diff --git a/.github/workflows/macOS.yml b/.github/workflows/macOS.yml index 38f080e62..35d57ae7c 100644 --- a/.github/workflows/macOS.yml +++ b/.github/workflows/macOS.yml @@ -120,7 +120,7 @@ jobs: -c ${{ matrix.configuration }} \ --enable-experimental-prebuilts \ --build-path .build-test-${{ matrix.configuration }} \ - --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|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)(/|$)' + --filter '\.(SymbolTestsCoreDumpSnapshotTests|SymbolTestsCoreInterfaceSnapshotTests|SymbolTestsCoreCoverageInvariantTests|STCoreE2ETests|STCoreTests|GenericSpecializationTests|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)(/|$)' - name: Run the SharedCache suites on a one-thread cooperative pool (${{ matrix.configuration }}) # The runner has 3 cores, so the Swift Concurrency cooperative pool is diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index a22926d26..e2d7482d7 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,7 +39,7 @@ jobs: - name: Verify Version.swift matches tag run: | set -euo pipefail - file="Sources/swift-section/Version.swift" + file="Sources/Executables/swift-section/Version.swift" value=$(grep -m1 -E 'static[[:space:]]+let[[:space:]]+value[[:space:]]*=[[:space:]]*"[^"]+"' "$file" | sed -E 's/.*"([^"]+)".*/\1/' || true) if [ -z "$value" ]; then echo "::error file=$file::Failed to extract BundledVersion.value" diff --git a/.github/workflows/version-check.yml b/.github/workflows/version-check.yml index 8cd21f100..41322971a 100644 --- a/.github/workflows/version-check.yml +++ b/.github/workflows/version-check.yml @@ -17,7 +17,7 @@ jobs: id: version run: | set -euo pipefail - file="Sources/swift-section/Version.swift" + file="Sources/Executables/swift-section/Version.swift" value=$(grep -m1 -E 'static[[:space:]]+let[[:space:]]+value[[:space:]]*=[[:space:]]*"[^"]+"' "$file" | sed -E 's/.*"([^"]+)".*/\1/' || true) if [ -z "$value" ]; then echo "::error file=$file::Failed to extract BundledVersion.value" @@ -39,7 +39,7 @@ jobs: fi changelog="Changelogs/$value.md" if [ ! -f "$changelog" ]; then - echo "::error file=Sources/swift-section/Version.swift::Missing $changelog — every stable BundledVersion.value must have a matching changelog. Either create $changelog or adjust Version.swift." + echo "::error file=Sources/Executables/swift-section/Version.swift::Missing $changelog — every stable BundledVersion.value must have a matching changelog. Either create $changelog or adjust Version.swift." exit 1 fi echo "Found $changelog" diff --git a/AGENTS.md b/AGENTS.md index 23285d0f6..fb8a575b5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -11,19 +11,20 @@ Requires Swift 6.2+ / Xcode 26.0+. ## Module dependency hierarchy ``` -swift-section (CLI; its `objc` subcommands also use MachOObjCSection's ObjC* products directly) - └── SwiftInterface (orchestrator) - └── SwiftIndexing, SwiftPrinting, SwiftSpecialization, SwiftAttributeInference - └── SwiftDeclaration (shared declaration model) - ├── 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) +swift-section (CLI — a wrapper: flags, error wording, stream routing, exit codes) + └── SwiftSectionKit (every subcommand as a request; its `objc` requests also use MachOObjCSection's ObjC* products) + └── SwiftInterface (orchestrator) + └── SwiftIndexing, SwiftPrinting, SwiftSpecialization, SwiftAttributeInference + └── SwiftDeclaration (shared declaration model) + ├── 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) SwiftInspection and everything above it also import MachOFoundation (umbrella = MachOBase + MachOSymbols + MachODependencies) @@ -33,6 +34,8 @@ SwiftInspection and everything above it also import `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` and `OutputTransformer` hang off the same level as the modules that use them. +**`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). + ## What each module does One or two lines each; the linked document is the authority. @@ -49,6 +52,7 @@ One or two lines each; the linked document is the authority. - **SwiftAttributeInference** — infers source-level attributes (`@propertyWrapper`, `@resultBuilder`, `@dynamicMemberLookup`, `@objc`, …). - **SwiftPrinting** — renders the model as Swift source: keywords the mangling does not carry (`class` vs `static`, `final`), bound rendering of specialized definitions, export-status annotation and `--exported-only` filtering. - **SwiftSpecialization** — runtime generic specialization (`GenericSpecializer`, `ConformanceProvider`); 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). @@ -64,9 +68,9 @@ One or two lines each; the linked document is the authority. - **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) 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. [Modules/MachODependencies.md](Documentations/Internal/Modules/MachODependencies.md). -- **MachOKitExtensions** (external sibling, `../MachOKitExtensions`) — MachOKit extensions. Three behaviors this repo's tests still pin live there: legacy `LC_DYLD_INFO` bind resolution (`LegacyDyldInfoBindTests`), ranked dyld-cache image name lookup (`DyldCacheImageSearchTests`), and whether an in-process image is in the shared cache — read from its header flag, never from its load address (`MachOImageCacheMembershipTests`). It cannot move back in-repo — `MachOObjCSection` depends on it, which would make a package-level cycle. +- **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. Printing and indexing are peers; neither depends on the other. @@ -85,6 +89,7 @@ swift test --filter MachOSwiftSectionTests swift test --filter SwiftDumpTests swift test --filter SwiftInterfaceTests swift test --filter SwiftSectionCommandTests +swift test --filter SwiftSectionKitTests # Run the CLI tool — the subcommands, in full swift run swift-section dump # types / protocols / conformances @@ -104,7 +109,8 @@ swift run swift-section objc dump # the Objective-C side: du # or a directory used as a system root. Without it, the thunk reader infers paths from # where the binary sits and everything falls back to the running system's cache, whose # images of another platform are never candidates: an iOS binary on a macOS host needs -# its runtime root named here. +# its runtime root named here. An image read out of a dyld cache resolves in that same +# cache first and needs no path named. # Build release executable ./build-executable-product.sh @@ -134,6 +140,7 @@ 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)). - **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. @@ -155,7 +162,7 @@ Rule out all three environment drifts **before** attributing red tests to a code - + That directory is exhaustively covered by `Tests/MachOSwiftSectionTests/Fixtures/`, and `MachOSwiftSectionCoverageInvariantTests` enforces it in both directions (every public method registered; every registered name real; sentinel-tagged suites actually sentinel; sentinel-behavior suites actually tagged). The procedure: @@ -183,6 +190,7 @@ Each of these fails **silently**, and several produce a real, fully-qualified, * - **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). - **Do not hold a lock across a demangle** — the large-stack hop can block. +- **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. Detail: [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.md), [NodeStoreMigrationPlan.md](Documentations/Internal/NodeStoreMigrationPlan.md), [SharedNodeStoreMigration.md](Documentations/Internal/SharedNodeStoreMigration.md). @@ -194,7 +202,9 @@ Detail: [Modules/MachOSymbols.md](Documentations/Internal/Modules/MachOSymbols.m - **`@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. - **`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:** `context.readElement(at:)` inferred at `Optional>` reads a different in-memory shape and silently answers nil — annotate the non-optional read and return it. +- **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 for one release and removed in 0.23.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. @@ -282,6 +292,8 @@ Keeping this file's module list and `Documentations/README.md`'s index in sync w +**The executable is a wrapper; a subcommand's logic lives in its `SwiftSectionKit` request.** `Sources/Executables/swift-section/` only declares flags (they ARE the `--help` text), rejects flag combinations in `validate()`, interprets command-line spellings (template names, comma lists, `a=b` replacements), maps the flags onto the request in `makeRequest()`, translates library errors back into the historical wording (`CommandLineErrorTranslation` — a usage mistake must stay a `ValidationError`, exit code 64), routes diagnostics to stdout or stderr (`StandardStreamOutput`) and decides the exit code. Anything else added there is untestable without spawning the binary. A new flag is a request field (with a default), a flag, a `makeRequest()` line, and a test on each side. All CLI output goes through `StandardStreamOutput` — `CommandLineStreamWriteScanTests` fails on a `print` / `fputs` / `FileHandle.standard*` anywhere else, and `PrintFailureEventTests` scans the library itself. [Modules/SwiftSectionKit.md](Documentations/Internal/Modules/SwiftSectionKit.md). + `AgentPlugins/swift-section/` is the agent plugin users install into Claude Code and Codex to learn this CLI; its skill (`skills/swift-section-cli/SKILL.md`, `references/objc.md`) is the only copy anywhere, so nobody else will fix it. - **A CLI change updates the skill in the same batch** — a new or renamed flag, a changed default, a new trap in the output. Check every flag it names still exists: `grep -ohE -- '--[a-z][a-z0-9-]+'` over the skill against the subcommands' `--help`. @@ -293,4 +305,4 @@ Keeping this file's module list and `Documentations/README.md`'s index in sync w ## Work in progress -**GenericSpecializer** (`Sources/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. +**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. diff --git a/AgentPlugins/swift-section/.claude-plugin/plugin.json b/AgentPlugins/swift-section/.claude-plugin/plugin.json index 11372e1ff..2a1d0e48b 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.21.0", + "version": "0.22.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 4ba31efea..e4844778e 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.21.0", + "version": "0.22.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 fa4c33067..fc18c43fc 100644 --- a/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md +++ b/AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md @@ -41,8 +41,9 @@ swift-section interface --help | grep -- --exported-only # empty ⇒ this bui Flags added comparatively late, and therefore worth checking: `--emit-header`, `--emit-export-status`, `--exported-only`, `--jobs`, `evolution --interface`, -`--supplementary-apinotes`, and from 0.20.0 `--dependency-search-path`, -`--infer-objc-overrides` and the whole `objc` subcommand group. When one is missing, say so +`--supplementary-apinotes`, from 0.20.0 `--dependency-search-path`, +`--infer-objc-overrides` and the whole `objc` subcommand group, and from 0.22.0 +`evolution --emit-available` / `--platform`. 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". @@ -103,8 +104,10 @@ swift-section dump --dyld-shared-cache --cache-image-path /System/Library/.../Sw macOS host needs `--dependency-search-path` (`dump`, `interface`, `snapshot`; repeatable) naming its runtime: a Mach-O file, a cache file (`dyld_shared_cache_*` / `dyld_sim_shared_cache_*`), or a directory used as a system root such as a simulator - runtime's `RuntimeRoot`. Named paths are consulted before the running system's cache. When - those facts are missing from an iOS binary's output, suspect this flag before the binary. + runtime's `RuntimeRoot`. Named paths are consulted before the running system's cache. An + image read out of a cache (`--dyld-shared-cache`) needs none: it resolves in that same cache + first, so an archived macOS 15 cache is laid out against its own Foundation, not the host's. + When those facts are missing from an iOS binary's output, suspect this flag before the binary. ## 3. Never redirect `interface`'s stdout — pass `-o` @@ -228,6 +231,7 @@ swift-section evolution 17.0.json 18.0.json /path/Foo --labels 17.0,18.0,26.0 snapshot JSON is rejected there, though it is fine for the change-list / lineage reports. - `evolution` needs ≥ 2 inputs **in version order, oldest first**; `--labels` is comma-separated and must have exactly one label per input. +- `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 diff --git a/Changelogs/0.20.0.md b/Changelogs/0.20.0.md index 17d510f5b..d21512bdb 100644 --- a/Changelogs/0.20.0.md +++ b/Changelogs/0.20.0.md @@ -1,54 +1,32 @@ # 0.20.0 -A minor release on top of `0.19.0`. `dump` and `interface` now read the types Swift hides behind accessor functions without running any code, and recover the `@objc`, `override`, `@objc @implementation` and property-wrapper spellings that stripped OS frameworks no longer carry. objc-section's commands ship inside `swift-section` as `swift-section objc`. Several rendered names change on purpose; see Compatibility before upgrading ABI baselines. - -## What's new - -- **Types behind accessor functions are read offline.** A field or associated type whose metadata sits behind an accessor function (availability-conditional `some View`, noncopyable payloads) used to print as `accessor function at 0x…`. `dump` and `interface` now decode the accessor's ARM64 code and print the type, with its availability branches as a comment — in macOS, iOS-device and simulator dyld caches and in standalone files. -- **`--dependency-search-path`** (`dump`, `interface`, `snapshot`, repeatable) — where a standalone binary's dependencies live: a Mach-O file, a dyld shared cache file, or a directory used as a system root (a simulator runtime's `RuntimeRoot`). Without it, paths are inferred from where the binary sits and the running system's cache is used; an iOS binary read on a macOS host needs its runtime named here. -- **`swift-section objc`** — `dump`, `interface`, `snapshot`, `diff` and `evolution` for Objective-C, moved from `objc-section` with the same output: `objc-section …` becomes `swift-section objc …`. The standalone `objc-section` is being retired after this release. -- **`@objc` members are recovered from the ObjC method table**, even where an OS framework stripped the thunk symbols: `@objc`, `@objc(selector:)` where the selector is not the one the compiler would derive, and `override` of members an ObjC ancestor implements — that chain is followed into the binary's dependencies. -- **`@objc @implementation` classes** print as `@objc @implementation extension X` with their stored properties; `dump` gains an `objcImplementationClasses` section. -- **`--infer-objc-overrides`** (`interface`, off by default) — also marks as `override` a method tied to a member by its selector's name alone. `dump` always shows these ties, marked `(selector name, no symbol evidence)`. -- **Property wrappers**: `interface` prints `@Wrapper var x` and hides the compiler-synthesized `_x` / `$x`, for wrappers from other images and for stripped declarations too. -- **Swift 6.4 binaries**: `Builtin.Borrow` metadata is read and laid out statically; a `@_rawLayout` type's artificial storage field is laid out, and hidden from `interface`, which prints `@_rawLayout(size:alignment:)` where only a builtin descriptor survives. An actor's `$defaultActor` storage is no longer printed in `interface`. -- **Private types in dyld caches keep their private discriminator**: `dump` prints `(Name in _…)` as it already did for binaries that keep their symbols, and two same-named private types no longer merge into one in `interface`. -- **Library**: models for key path components and property descriptors, async and coroutine function pointers, accessible functions (`__swift5_acfuncs`), capture descriptors (`__swift5_capture`), generic metadata patterns and function type metadata's trailing objects; type and protocol definitions know whether the image exports them; `NestedFieldOffset.byteWidth`, a nested field's proven value size; new library product `SwiftThunkAnalysis`. - -## Fixes - -- `dump` and `interface` crashed about one run in five on a dylib whose module declares no class (no `__DATA` segment) — including the dylib Homebrew's formula test builds. Present in `0.19.0`; fixed by MachOKit `0.52.103`. -- `interface` printed nothing for several node kinds in type positions — in SwiftUI, 201 `Predicate<>`, 8 bare `-> ` and 122 `init<>()`. -- A type declared in another module's extension lost the extended type: `Invalidations.Tuple` for `NSView.Invalidations.Tuple`. -- Specialized generic names that come from the runtime printed `(unknown context at $…)`, or dropped a private type argument's module and enclosing types. -- Opaque result types: an unresolvable reference printed the conforming type itself and now prints the legal `@_opaqueReturnTypeOf(…)` spelling; `some Base & P` kept only `P`; generic arguments inside a constraint were dropped (`some Sequence>` lost its ``). -- `interface --parse-opaque-return-type` (and RuntimeViewer's export) crashed with `Index out of range` on an opaque parameter that carries no runtime-visible constraint, seen on PhotosUIFoundation. -- A conformance to a `private` protocol had no type highlighting and no link in semantic output such as RuntimeViewer's. -- A method whose implementation pointer is null no longer drops its whole type from the index. -- A malformed symbol whose value is not an offset no longer crashes the process while an image is indexed. - ## Breaking -Source level — this package is distributed as source, so every downstream recompiles: - -- `MetadataReader` → `SymbolicDemangler` (SPI `Internals`). The old name remains as a deprecated alias for one release. -- `PrimitiveTypeMapping` and `PrimitiveTypeMappingCache` are removed; C-imported type names now come from each descriptor's own import info. -- `FieldLayoutRenderable` no longer refines `MachOSwiftSectionRepresentableWithCache`. Where a generic constraint needs both, write `MachOFieldLayoutRenderable`. -- `HeapLocalVariableMetadata.captureDescription` points at a `CaptureDescriptor` (was `String?`). -- `numUnderlyingTypeArugments` → `numUnderlyingTypeArguments`. The misspelling remains as a deprecated forward for one release. - -## Compatibility - -- **Rendered names change** in four deliberate places: types behind accessor functions (now read), private types in dyld caches (`dump` now shows their discriminators), C-imported type names (now follow each descriptor's import info, as the runtime does), and types declared in another module's extension. Anything keyed on these names changes with them — an ABI snapshot saved by `0.19.0` reports the affected types as removed and re-added, so regenerate baselines with `0.20.0`. Snapshot `formatVersion` is unchanged (5). -- **New dependency**: swift-capstone `6.0.0 ..< 7.0.0`, with only its `AARCH64` trait enabled; it is C source and builds for any host architecture. -- **Dependency floors**: MachOKit `0.52.103 ..< 0.53.0` (was `0.52.101`), swift-demangling `0.7.1 ..< 0.8.0` (was `0.6.3 ..< 0.7.0`), MachOObjCSection `0.8.106 ..< 0.9.0` (was `0.8.105`). All other pins are unchanged from `0.19.0`. -- The recoveries above are on by default; only the name-only override inference waits for `--infer-objc-overrides`. - -## Requirements - -- Swift 6.2+ -- Xcode 26.0+ - ---- - -Full design: evolution proposals [0021–0050](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.20.0/Documentations/Evolutions/README.md); the `objc` guide [ObjCCommandLine.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.20.0/Documentations/ObjCCommandLine.md); implementation notes [AccessorThunkResolutionExplained.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.20.0/Documentations/Internal/AccessorThunkResolutionExplained.md), [ObjCMemberRecovery.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.20.0/Documentations/Internal/ObjCMemberRecovery.md) and [SymbolicManglingSymbols.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.20.0/Documentations/Internal/SymbolicManglingSymbols.md). +- Some printed type names change, so ABI snapshots saved with 0.19.0 report those types as removed and re-added; regenerate your baselines. +- `MetadataReader` is renamed `SymbolicDemangler`, and `numUnderlyingTypeArugments` is renamed `numUnderlyingTypeArguments`; the old names stay deprecated for one release. +- Removed `PrimitiveTypeMapping` and `PrimitiveTypeMappingCache`. +- `FieldLayoutRenderable` no longer refines `MachOSwiftSectionRepresentableWithCache`; use `MachOFieldLayoutRenderable` where you need both. +- `HeapLocalVariableMetadata.captureDescription` is now a `CaptureDescriptor` instead of `String?`. +- Requires MachOKit 0.52.103, swift-demangling 0.7.1 and MachOObjCSection 0.8.106 or later, and adds a dependency on swift-capstone 6. + +## New + +- `swift-section objc` replaces `objc-section` with the same commands and output; the standalone `objc-section` is retired after this release. +- `dump` and `interface` now print types hidden behind accessor functions instead of `accessor function at 0x…`. +- `interface` recovers `@objc`, `@objc(selector:)`, `override` and `@objc @implementation` classes, even in stripped OS frameworks. +- `interface` prints property wrappers as `@Wrapper var x` and hides the synthesized `_x` and `$x`. +- New `--dependency-search-path` option tells `dump`, `interface` and `snapshot` where a binary's dependencies live. +- New `--infer-objc-overrides` option for `interface` also marks a method as `override` when only its selector name matches. +- Supports Swift 6.4 binaries, including `Builtin.Borrow` and `@_rawLayout` types. +- Private types in dyld caches keep their discriminator, so same-named private types no longer merge. +- New `SwiftThunkAnalysis` library product, and models for key paths, property descriptors, capture descriptors and accessible functions. + +## Fixed + +- Fixed `dump` and `interface` crashing intermittently on dylibs that declare no classes. +- Fixed `interface --parse-opaque-return-type` crashing with `Index out of range`. +- Fixed `interface` printing incomplete types such as `Predicate<>` and `init<>()`. +- Fixed wrong names for types in other modules' extensions, specialized generics and opaque result types. +- Fixed conformances to `private` protocols missing highlighting and links in semantic output. +- Fixed a type missing from the index when one of its methods has no implementation. +- Fixed a crash when indexing an image with a malformed symbol. diff --git a/Changelogs/0.21.0.md b/Changelogs/0.21.0.md index 95dd8e48e..811dff34d 100644 --- a/Changelogs/0.21.0.md +++ b/Changelogs/0.21.0.md @@ -1,36 +1,20 @@ # 0.21.0 -A minor release on top of `0.20.0`. `interface` now prints the class members that a stripped OS framework no longer names — 53 of them across AppKit — lists class methods in vtable order, and marks Swift classes renamed for the Objective-C runtime with `@objc(Name)`. ABI snapshots move to format version 6, so regenerate baselines saved by `0.20.0`. - -## What's new - -- **Class members named only by their method descriptor are recovered.** In an image stripped of its local symbols (AppKit in the OS dyld shared cache), a public class method's implementation has no name left, and `interface` dropped it: `NSTableViewDiffableDataSource` and `NSCollectionViewDiffableDataSource` printed only `init` and `deinit`. These members are now read from the class's vtable, and `diff`, `evolution` and snapshots see them too. -- **Class members print in vtable order.** `interface` lists a class's vtable methods first, in slot order — the source's declaration order, the way `dump` already walks them — then the remaining members by category as before. A slot nothing names is skipped. `--sort-members-by-offset` and the `diff` / `evolution` interfaces are unchanged. -- **`@objc(Name)` on renamed classes.** A Swift class whose source gave the Objective-C runtime its own name (`@objc(NSScrollPocket)`) prints that attribute in `interface`, `dump` and the `diff` / `evolution` headers, or `@_objcRuntimeName(Name)` where the class uses Swift's native object model and `@objc` would not compile. macOS 27's AppKit has 74 such classes. - -## Fixes - -- A renamed class lost every recovered `@objc` and `override` on its members, and in a stripped image its Objective-C members printed as `final`. With an Objective-C superclass, its static field offsets could be a few bytes off. -- `init` / `init?` was decided by the first closure in the signature: `NSCollectionViewDiffableDataSource.init(collectionView:itemProvider:)` printed as `init?` because its item provider returns an optional, and SwiftUI's failable `CoreDisplayLink.init?(displayID:handler:)` printed as `init`. -- Reading an in-process image that is not in the dyld shared cache but was loaded above the shared region's start printed wrong member and IMP addresses. Fixed by MachOKitExtensions `0.1.2`. - ## Breaking -- **The library no longer empties its per-image caches under memory pressure.** A host that relied on that calls `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()` (`@_spi(Internals) import MachOCaches`) when it wants memory back; it evicts every image no live `SwiftDeclarationIndexer` still owns. -- `SharedCache` (SPI `Internals`) is `final` and built by composition: `final class Foo: SharedCache { override func buildStorage(for:) … }` becomes `final class Foo { private let cache = SharedCache(evictionGroup: …) }`, looked up with `cache.storage(in: machO) { build($0) }`. `init()`, `buildStorage(for:)`, `buildStorage()`, `storage()`, `contains()` and `remove()` are removed. `SymbolIndexStore` and `InternedNodeReferenceCache` are no longer its subclasses; their instance API is unchanged. - -## Compatibility - -- **ABI snapshot `formatVersion` 5 → 6.** A snapshot saved by `0.20.0` is rejected with a format-version error rather than misreporting the recovered members as added; regenerate it with `0.21.0`. The key scheme is unchanged. -- **Rendered output changes** only where listed above: class member order in single-version `interface`, the recovered members, `@objc(Name)` and the renamed classes' members, and the `init` / `init?` corrections. -- **Dependency floors**: MachOKitExtensions `0.1.2` (was `0.1.1`), swift-capstone `6.0.1 ..< 7.0.0` (was `6.0.0`; `6.0.1` restores the AArch64 backend for packages still spelling the pre-v6 trait). All other pins are unchanged from `0.20.0`. -- The command line is unchanged: no flag was added, removed or given a new default. +- ABI snapshots move to format version 6; regenerate baselines saved with 0.20.0. +- The library no longer clears its per-image caches under memory pressure; call `SharedCacheRegistry.shared.evictImagesWithoutLiveOwners()` (SPI) to free them. +- `SharedCache` (SPI) is now `final`; hold one and call `storage(in:)` instead of subclassing it. +- Requires MachOKitExtensions 0.1.2 and swift-capstone 6.0.1 or later. -## Requirements +## New -- Swift 6.2+ -- Xcode 26.0+ +- `interface`, `diff`, `evolution` and snapshots now include class methods that stripped OS frameworks no longer name, such as those of `NSTableViewDiffableDataSource`. +- `interface` lists class methods in declaration order. +- Swift classes renamed for the Objective-C runtime now print with `@objc(Name)`. ---- +## Fixed -Full design: evolution proposals [0052–0054](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.21.0/Documentations/Evolutions/README.md); implementation notes [DescriptorOnlyVTableMembers.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.21.0/Documentations/Internal/DescriptorOnlyVTableMembers.md), [CustomObjCClassNames.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.21.0/Documentations/Internal/CustomObjCClassNames.md) and [Modules/MachOCaches.md](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/blob/0.21.0/Documentations/Internal/Modules/MachOCaches.md). +- Fixed members of renamed classes losing `@objc` and `override`, printing as `final`, or showing slightly wrong field offsets. +- Fixed `init` and `init?` being mixed up for initializers that take a closure. +- Fixed wrong member and IMP addresses for in-process images outside the dyld shared cache. diff --git a/Changelogs/0.22.0.md b/Changelogs/0.22.0.md new file mode 100644 index 000000000..c7a880dd4 --- /dev/null +++ b/Changelogs/0.22.0.md @@ -0,0 +1,31 @@ +# 0.22.0 + +## Breaking + +- Reading APIs that take a Mach-O or a raw pointer are deprecated until 0.23.0; pass `machO.context` or `.inProcess` instead. +- The deprecated pointer reads throw `UnsafeRawPointer.Error.initFailed` on a null or tagged pointer instead of crashing, and return `.symbol` instead of trapping on a symbol reference. +- A custom `MachOBindRebaseResolving` type now has rebases applied to indirect pointers, so reads return the target instead of the raw fixup. +- `NamedDumpable` and `ConformedDumpable` requirements now take a `ReadingContext`. +- `ResilientWitness.implementationAddress(in:)` taking a Mach-O is renamed `implementationAddressString(in:)`. +- Requires MachOKit 0.54.101, MachOKitExtensions 1.1.2, MachOObjCSection 0.8.110, swift-semantic-string 0.4.0 and swift-syntax 602 or later. + +## New + +- New `SwiftSectionKit` library product runs every `swift-section` subcommand as a request; `dump` results carry each declaration's kind and name. +- New `--emit-available` option for `evolution --interface` prints a real `@available` attribute on each declaration, with `--platform` to override the inferred platform. +- New `SwiftDeclarationPrintConfiguration.marksOptionalContent` prints all option-controlled content once, marking which option shows each part. + +## Improved + +- Reading dyld shared caches split into many files, such as macOS 27's, is much faster and uses far less memory. +- An image read from a dyld shared cache now finds its dependencies in that same cache, so archived caches are laid out against their own frameworks. +- Swift subclasses of Objective-C classes in iOS 26 and earlier simulator runtimes now get their field offsets, `override` and ancestors. +- `private` and `lazy` stored properties of `@objc @implementation` classes now print their types. + +## Fixed + +- Fixed `swift-section objc` crashing on macOS 14.4–15.3.2 dyld shared caches and losing protocol method names on older ones. +- Fixed `evolution` crashing when the same build appears in two of the given dyld shared caches. +- Fixed wrong addresses, unnamed vtable entries and unread accessor-function types in main executables. +- Fixed static properties printing `Address: 0x0` in binaries that carry debug symbols. +- `swift-section objc` no longer aborts when its output stream is closed. diff --git a/Documentations/Evolutions/0055-group-sources-by-layer.md b/Documentations/Evolutions/0055-group-sources-by-layer.md new file mode 100644 index 000000000..6faeb1363 --- /dev/null +++ b/Documentations/Evolutions/0055-group-sources-by-layer.md @@ -0,0 +1,47 @@ +# 0055 - `Sources/` 按层分组 + +- **状态**: Implemented +- **创建日期**: 2026-09-29 +- **最后更新**: 2026-09-29 +- **实现分支 / PR**: `refactor/group-sources`(worktree `.worktrees/MachOSwiftSection-SourcesGrouping`) + +## 摘要 + +`Sources/` 下平铺着 31 个 target,找一个模块要在一长串名字里翻。本提案按 AGENTS.md 里的依赖层级把它们分进 8 个目录,每个 target 在 `Package.swift` 里用 `path:` 指向新位置。target 名、product 名、模块名一个都不变,RuntimeViewer 等下游从源码重编译时感知不到这次改动;只是纯搬迁,dump / interface 输出不受影响。 + +## 方案 + +分组(组目录 → 其中的 target): + +| 目录 | target | +|------|--------| +| `Support/` | `Utilities`、`MachOMacros` | +| `MachO/` | `MachOReading`、`MachOResolving`、`MachOPointers`、`MachOBase`、`MachOSymbols`、`MachOCaches`、`MachODependencies`、`MachOFoundation` | +| `ABI/` | `MachOSwiftSection`、`MachOSwiftSectionC` | +| `Analysis/` | `SwiftInspection`、`SwiftLayout`、`SwiftThunkAnalysis` | +| `Declaration/` | `SwiftDeclaration`、`SwiftIndexing`、`SwiftAttributeInference`、`SwiftSpecialization`、`TypeIndexing` | +| `Output/` | `SwiftDeclarationRendering`、`SwiftOutputTransformer`、`SwiftPrinting`、`SwiftDump`、`SwiftInterface`、`SwiftDiffing` | +| `Executables/` | `swift-section`、`baseline-generator` | +| `TestSupport/` | `MachOFixtureSupport`、`MachOTestingSupport`、`MachOTestingSupportC` | + +目录多了一层,下面几处靠「源文件正好在 `Sources//` 下」算路径的代码要跟着改,否则测试变红: + +- **fixture 路径**:`MachOFileName` / `MachOImageName` 里 `SymbolTests*` 的 rawValue 是相对「解析它的源文件所在目录」的路径(`loadFromFile`、`MachOSwiftSectionFixtureTests.resolveFixturePath`、`InProcessMetadataPicker.resolveFixturePath` 三处用 `#filePath` 解析),`../../Tests/…` 改为 `../../../Tests/…`。 +- **源码扫描测试**:`PrintFailureEventTests` 把 `Sources` 下一层当模块名来豁免 CLI 与测试支持模块,改为取下两层;`MachOSwiftSectionCoverageInvariantTests` 的 `Models/` 路径加上 `ABI/`。`NodeStoreMigrationInvariantTests` 递归扫描整个 `Sources/`,不受影响。 +- **CI**:`release.yml` 与 `version-check.yml` 写死的 `Sources/swift-section/Version.swift`。 + +未经询问所作的假设: + +- `Tests/` 保持平铺,不在本次范围内。 +- 活文档(AGENTS.md、Glossary、`SwiftEnumLayout` 两份公开文档、`Internal/` 下的主题笔记)里的 `Sources/` 路径全部改成新路径;带日期的记录(TaskReports、Reviews、Roadmaps、已落地提案、ProjectEvolutionLog、Changelogs)保留当时的路径——它们记录的是当时的状态,而且都是纯文本、不是链接,不会断。 +- target 用字面量写 `path:`,不引入生成路径的 helper:字面量方便 grep,也不需要为新 target 多学一层抽象。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-09-29 | Created,用户要求「帮我分一下组,全部放在一个文件夹太杂了」 | — | +| 2026-09-29 | 选按层分 8 组,而不是粗分 4 组(MachO / Swift / 可执行 / 测试支持) | 用户选定;粗分方案里 `Swift/` 下仍有 16 个 target,没解决「太杂」 | +| 2026-09-29 | 修 fixture 路径时改 rawValue 的 `../` 层数,不改成以包根为锚 | 最小改动;三处解析器与 rawValue 的约定保持一致,AGENTS.md 记下这个深度假设 | +| 2026-09-29 | Implemented | `swift test --skip IntegrationTests` 原始退出码 0:19 批、2145 个测试、405 个套件全部通过,含三个依赖目录深度的扫描套件。纯搬迁、输出不可能变,不跑渲染 A/B 验证 | +| 2026-09-29 | 不写配套的使用指南 / 实现说明,不登记新术语 | 分组规则与深度假设一句话就说完,已写进 AGENTS.md;本次没有引入新词 | diff --git a/Documentations/Evolutions/0056-visibility-regions.md b/Documentations/Evolutions/0056-visibility-regions.md new file mode 100644 index 000000000..8c1ca324c --- /dev/null +++ b/Documentations/Evolutions/0056-visibility-regions.md @@ -0,0 +1,66 @@ +# 0056 - 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 + +- **状态**: Implemented +- **创建日期**: 2026-09-29 +- **最后更新**: 2026-09-30 +- **所属愿景**: 无 +- **关联提案**: swift-semantic-string 的设计记录 `docs/VisibilityRegions.md`(`VisibilityRegion`、区域表与投影); + MachOObjCSection 的提案 0011 `visibility-regions`;RuntimeViewer 的 `draft-find-navigator`(使用方) +- **实现分支 / PR**: `feature/visibility-regions` +- **配套文档**: 无 + +## 摘要 + +RuntimeViewer 的 Find 在引擎里给每个类型存一份打印好的 interface 供全文搜索,要求「只打印一次,搜索时按用户当前的 +显示选项只输出可见内容」,切换选项不重新打印(SwiftUI 打一遍约两分钟)。`SwiftDeclarationPrinter` 今天在输出点上 +看 `configuration.printX` 决定打不打,打出来的文本里已经没有「换一组选项会多出什么」的信息;而且偏移、地址、布局 +注释的文字可被 transformer 改写,一个成员有几行注释又取决于偏移、符号是否存在,调用方从文字和位置都认不出归属。 +本提案给打印器加一个**标记模式**:受选项控制的内容全部打印,并用 `VisibilityRegion` 标上它在什么选项下可见。 +调用方按任意选项组合投影这份输出,得到与该组合下普通打印逐字节相同的文本。 + +## 方案 + +- **开关**:`SwiftDeclarationPrintConfiguration.marksOptionalContent`(默认 `false`)。为 `true` 时下列选项不再决定 + 打不打,而是决定区域的条件;其余配置(transformer、`memberSortOrder`、不属于下列的开关)照常生效。布局注释经 + `DeclarationRenderConfiguration.marksOptionalContent` 同样标记,打印器在构造它时传下去。 +- **选项名**:`SwiftVisibilityOption`(`SwiftDeclarationRendering`,原始值 `swift.printFieldOffset` 这类): + `printStrippedSymbolicItem`、`printFieldOffset`、`printExpandedFieldOffsets`、`printMemberAddress`、 + `printVTableOffset`、`printPWTOffset`、`printTypeLayout`、`printEnumLayout`、`infersObjCOverridesFromSelectorNames`、 + `opaqueTypeResolution`。投影用的谓词是 `SwiftDeclarationPrintConfiguration.isVisibilityOptionEnabled(_:resolvesOpaqueTypes:)`; + opaque 那一项不是配置属性,而是「是否注册了 opaque 类型解析器」,由调用方在取谓词时给出。 +- **输出点**:打印器的 `optionalContent(_:content:)` 与 `DeclarationRenderConfiguration.optionalContent(_:content:)` + 在普通模式下按开关取舍、在标记模式下总是输出并包进区域;数据的计算(字段偏移、enum 布局、静态布局 provider) + 在标记模式下总是进行(`producesContent(for:)`)。覆盖: + - `renderMember` 的偏移 / vtable / 地址注释与 `protocol-extension default`,deinit 的两条地址注释; + - protocol 的 stripped symbolic item 整块(内层 PWT 偏移再嵌一层); + - 存储属性访问器的 vtable 注释;运行时与静态两个布局后端的字段偏移(展开偏移嵌在其内)、类型布局、enum 布局 + 与 enum 前导注释,两种布局注释之间「两者都开才有」的换行用嵌套区域表达; + - `@objc @implementation` 类的字段偏移注释; + - opaque 类型:`TypeNodePrintable.printOpaqueReturnType` 照常写入 ` <约束>`,写完用 + `SemanticString.markAtoms(from:visibleUnder:)` 给这几个原子补上条件(`NodePrintableDelegate.marksOptionalContent`); + - `infersObjCOverridesFromSelectorNames`:两种判定的 `ResolvedObjCMemberFacts` 不同时(`printUnderObjCVerdicts`), + 整条声明按两种判定各打一遍,分别包进「开」与「关」的区域——开时加 `@objc` / `override` / `class`、去掉 `final`, + 不是单纯的增删。 +- **容器**:不需要打印器处理。swift-semantic-string 的容器会把成员的条件带到自己打的换行、缩进与分隔符上(见其 + 设计记录 `docs/VisibilityRegions.md`)。 +- **不覆盖**:`printExportStatus`、`printExportedDeclarationsOnly`、`printSpareBitAnalysis`、 + `printConformancePWTAddress` 不是 RuntimeViewer 的选项,按配置原样处理;`memberSortOrder` 是重排,区域表达不了。 +- **正确性**:`VisibilityRegionProjectionTests`(`SwiftInterfaceTests`)对 SymbolTestsCore 的每个顶层类型、协议与 + 扩展断言「标记打印按某配置投影」与「按该配置直接打印」完全相等(文本、span、identifier):进程内打印(运行时布局, + RuntimeViewer 走的路径)覆盖全关、全开、每个选项单开与单关共 22 组,约 10 秒;从文件打印(静态布局)只变动四个 + 布局选项共 10 组,因为其余输出与进程内相同。漏标的新输出点会在这里现形。 +- **依赖**:需要 swift-semantic-string 带 `VisibilityRegion` 与 `markAtoms` 的版本;发布后抬远程依赖下限,此前本地 + 构建走 `USING_LOCAL_DEPENDENCIES` 或 SwiftPM 的 edit 模式。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-09-29 | Created as Accepted | RuntimeViewer 的用户要求 Find「语料要为所有可能出现的内容进行索引,但是只输出匹配当前options的内容」,且「可以动上游MachOSwiftSection,目前打印2次的方法可能会有性能问题」。两个会话分别设计后比较,都认为归属只能由打印器在输出时给出。用户:「可以改,上游都是我自己的库,写提案直接开工吧」。 | +| 2026-09-29 | 不用「每个选项各打一遍再 diff」 | 每个类型多打三到六遍,SwiftUI 这种镜像不可接受;注释文字又会被 transformer 改写,diff 出来也认不出归属。 | +| 2026-09-29 | `synthesizeOpaqueType` 与 `infersObjCOverridesFromSelectorNames` 纳入标记 | 用户指出前者「输出的结果是固定的,只是要改的地方是返回值」;核实后它关掉时只剩 `some`,是纯删减。后者核实为替换(加 `@objc` / `override` / `class`,去 `final`),用同一选项的开、关两种区域表达。 | +| 2026-09-29 | 容器不需要打印器另外处理;opaque 约束用 `markAtoms` 事后补标 | 容器由 swift-semantic-string 按成员条件自动带上装饰。opaque 约束是 NodePrinter 经泛型输出目标逐段写入的,写完后给这几个原子补标,文本与原子个数都不变,也保住了类型引用作用域盖上的 identifier。 | +| 2026-09-29 | Accepted → In Progress | 实现与测试完成于 `feature/visibility-regions`(基于 `next` 7ba306ed),未提交。与同一提交的临时基线比较 `SwiftInterfaceTests` / `SwiftPrintingTests` / `SwiftDumpTests` / `SwiftDeclarationRenderingTests`:基线 41 + 256 + 95 + 39 全过,本分支多出两条对照测试,唯一的失败是源码扫描测试把名为 `print` 的闭包参数当成了标准输出,改名为 `render` 后复跑。快照测试两边都过,普通打印的输出没有变化。 | +| 2026-09-30 | In Progress → Implemented,编号 0056,合入 `next` | rebase 到 `next`(4d93f328,抛错版 `init(bitPattern:)` 收回本仓库)无冲突。本地依赖模式(MachOKit `next` 0.53.101、MachOKitExtensions、已合入 `VisibilityRegion` 的 swift-semantic-string `next`、MachOObjCSection `next`)下`USING_LOCAL_DEPENDENCIES=1 swift test --skip IntegrationTests` 原始退出码 0:19 批、2146 个测试、406 个套件全部通过,唯一的 known issue 是既有的 `SymbolicManglingIndexTests`。远程依赖下限未抬:`from: "0.3.0"` 的 swift-semantic-string 没有 `VisibilityRegion`,带它的版本发布后同批抬下限;在此之前 `next` 只能以 `USING_LOCAL_DEPENDENCIES=1` 构建。 | +| 2026-09-30 | 不另写使用指南与实现说明;术语表登记「marking mode(标记模式)」,账本记第 71 节 | 用法与契约写在 `marksOptionalContent` 与 `SwiftDeclarationPrinter+VisibilityRegions.swift` 的文档注释和本提案「方案」里,包括两条不在签名里的约定:transformer、排序与导出选项照常生效(在打印时定死,投影改不了),以及 opaque 类型约束要先注册解析器才有内容可标。「可见性区域」「投影」由 swift-semantic-string 的设计记录定义。 | +| 2026-09-30 | swift-semantic-string 的远程下限抬到 `from: "0.4.0"` | swift-semantic-string 0.4.0 发布(带 `VisibilityRegion`)。不开本地依赖构建(MachOKit 0.52.103、MachOKitExtensions 1.0.0、MachOObjCSection 0.8.107、swift-semantic-string 0.4.0)通过,打印相关的五组测试通过;`next` 从此不必再靠 `USING_LOCAL_DEPENDENCIES=1` 构建。 | diff --git a/Documentations/Evolutions/0057-reading-context-migration.md b/Documentations/Evolutions/0057-reading-context-migration.md new file mode 100644 index 000000000..efe333385 --- /dev/null +++ b/Documentations/Evolutions/0057-reading-context-migration.md @@ -0,0 +1,342 @@ +# 0057 - 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-09-30 +- **最后更新**: 2026-10-01 +- **所属愿景**: 无 +- **关联提案**: [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) +- **配套文档**: [ReadingContextAbstraction.md](../Internal/ReadingContextAbstraction.md)「单一实现与废弃」一节(实现说明:旧形式为何原地保留、两个协议保留已废弃的 requirement、约束扩展的 guard 陷阱、修掉的分歧、缓存范围、已知缺口);术语表登记「cache scope」与「context / Mach-O / pointer form」 + +## 摘要 + +ABI 层几乎每个读取接口都有三份各自手写的实现:传 `machO` 的(按文件或镜像偏移读)、不传参直接用指针读本进程内存的、传 `some ReadingContext` 的。三份实现已经漂移:`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind 处理,指针版遇到空指针或带 tag 的指针直接崩。本提案把实现收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,传 `machO` 的旧接口改成一行转发到 `machO.context`,指针版改成一行转发到 `InProcessContext.shared`,两者在 0.22.0 标 `@available(*, deprecated)`、0.23.0 删除。范围是 ABI 层(`MachOSwiftSection`、`MachOPointers`、`MachOResolving` 的 `Resolvable`)的全部读取接口,外加上层模块里 61 个纯读取接口(`SymbolicDemangler`、`typeName` / `dumpName` 系列、`GenericContext+Dump` 等);为了让后者按镜像缓存照常生效,`ReadingContext` 新增一个「缓存范围」声明。仓库内全部调用点与测试同批迁到 `ReadingContext` 版,下游(RuntimeViewer、MachOKitUI、swift-decompiler)在删除前各提 PR 迁移。 + +## 动机 + +### 1. 三份实现已经漂移,而且错在 `ReadingContext` 那一份 + +`ReadingContext` 在 2026-01 落地时(`Documentations/Internal/ReadingContextAbstraction.md`)是「新增一条腿」:旧接口不动,新接口另写一份。2026-05 的覆盖补全把 `Models/` 下缺的 `ReadingContext` 版全部机械地补上,同样是另写一份。结果是同一个接口的三份函数体各自维护,改一份忘两份: + +- `Pointer.resolve`(`Sources/MachO/MachOPointers/Pointer.swift:15-29`):传 `machO` 的版本先查 `MachOFile` 的 rebase 表(`:16`),`ReadingContext` 版直接把槽里的原始字节读出来(`:28`)。chained fixup 的文件里,这些字节是 fixup 编码而不是地址。所有「间接指针的中转类型是 `Pointer<…>`」的字段都继承这个差异:`ProtocolRecord.protocol`、`TypeMetadataRecord` 的间接描述符、`GenericRequirementContent.conformance`、`RelativeProtocolDescriptorPointer`、`ExistentialTypeMetadata.superclassConstraint`。 +- `TypeMetadataRecord.contextDescriptor`(`Sources/ABI/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift:40-71`):传 `machO` 的版本跳过被 bind 的间接记录(`:48`),注释(`:32-39`)写明这是修过的真 bug——iOS 26.5 模拟器的 `libswiftSynchronization` 登记了一条指向 `libswiftCore` 里 `Swift.Optional` 的记录,读它会抛错并连带整张 `__swift5_types` 列表丢失。`ReadingContext` 版(`:58-71`)没有这个检查,这个 bug 在 `ReadingContext` 路径上还在。 +- `SymbolOrElementPointer`(`Sources/MachO/MachOPointers/SymbolOrElementPointer.swift`):可选元素的判空,指针版(`:110`)和 `machO` 版(`:121`)先 strip 再判 0,`ReadingContext` 版(`:132`)直接判 `address == 0`。指针版遇到 `.symbol` 直接 `fatalError()`(`:20-21`、`:108-109`),另外两版正常返回。 +- 指针版的底层读取(`Sources/MachO/MachOReading/Readable/UnsafeRawPointer+Readable.swift:60-85`)既不 strip pointer tag 也不判空,`InProcessContext`(`Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift:50-68`)两样都做。同一个本进程读取,走指针版遇到坏指针是崩溃,走 `ReadingContext` 版是抛错。 +- 同名不同义:`ResilientWitness.implementationAddress(in: machO)` 返回格式化好的十六进制字符串(`Sources/ABI/MachOSwiftSection/Models/Protocol/ResilientWitness.swift:36-38`),`implementationAddress(in: context)` 返回地址值(`:50-53`)。 + +这些分歧没有被测试抓到,因为 fixture 套件主要测传 `machO` 的版本,`ReadingContext` 版多是附带一条断言,而且只在 `imageContext`(`MachOContext`)上跑——镜像内存已经被 dyld 修正过,rebase / bind 的差异在那里不可见。 + +### 2. 惯例在让重复继续翻倍 + +[0025](0025-key-path-component-and-property-descriptor.md) 记下的惯例是「新接口三套都写」,每加一个读取接口就是三份函数体、三组测试。`ReadingContextAbstraction.md` 规划的第 4 阶段「给旧接口标 `@available(*, deprecated)`」一直写着 Future:2026-05 的补全 spec 把「重构旧接口」列为非目标,说上层迁移「留给后续分支」,这个后续分支从来没有发生。仓库内生产代码里,ABI 接口的调用约 229 处传 `machO`、约 104 处走指针、只有 28 处走 `ReadingContext`(其中 25 处在 `SymbolicDemangler.swift` 一个文件里)。 + +### 3. 上层模块把三份实现又复制了一遍 + +`SymbolicDemangler` 公开了传 `machO`、传 `ReadingContext`、什么都不传三套入口(`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift:42-263`),`SwiftDeclaration` 的 `typeName(in: machO)` / `typeName()`、`SwiftDeclarationRendering` 的 `typeNode(in: machO)` / `typeNode()` 也是成对的。这些接口只读数据,本可以只收一个 `ReadingContext`;它们没有这么做,是因为 `SymbolicDemangler` 的缓存按镜像分(`SymbolicDemanglerCache`,`:834-964`),而 `ReadingContext` 说不出自己读的是哪个镜像——`SymbolicDemangler` 现有的 `ReadingContext` 入口(`:246-263`)因此完全不走缓存。 + +## 前期调研 + +- **三份实现的规模**(2026-09-30 在 `next` @ `32feff36` 上统计):ABI 层传 `machO` 的声明 189 个、指针版 139 个、`ReadingContext` 版 143 个;`MachOPointers` / `MachOResolving` 另有一批协议 requirement 三套并列。已经转发的只有三处:`GenericContext.swift:144-150` 的两个 `init` 与 `TypeContextDescriptorProtocol.swift:110-113` 的 `typeImportInfo`。`Class` / `Enum` / `Struct` / `Protocol` / `ProtocolConformance` 的初始化在 `machO` 版与指针版之间共用一个 `initialize(… in reader: some Readable)`,`ReadingContext` 版另有一份。 +- **指针版能否无损转发到 `InProcessContext`**:能。本进程读出来的 wrapper,其 `offset` 就是指针的 bit pattern(`UnsafeRawPointer+Readable.swift:64-67`),`asPointer`(MachOKitExtensions `LocatableLayoutWrapper.swift:24`)与 `InProcessContext.addressFromOffset`(`InProcessContext.swift:78-81`)得到同一个地址。行为差别只在更安全的一侧:多了 strip 与判空,崩溃变成抛错;错误类型从 `NullPointerError` 变成 `UnsafeRawPointer.Error.initFailed`。 +- **`machO` 版能否无损转发到 `machO.context`**:能,前提是先把第 1 节的 rebase / bind / 判空差异补进 `ReadingContext` 版。每个 `machO` 参数都满足 `MachORepresentableWithCache & Readable`,`.context` 属性现成(`MachOContext.swift:97-112`)。bind / rebase 的判定统一走 `context.bindRebaseResolver`(`ReadingContext.swift:243-272`),它按协议而不是按 `MachOFile` 具体类型判定,所以 MachOKitUI 那种自己实现了 `MachOBindRebaseResolving` 的包装类型(`MachOKitUI/Sources/MachOKitUICore/Core/MachOFileSource+Traits.swift:131-139`)从此也能拿到正确的 rebase 处理,而它们今天在 `Pointer.resolve` 这类 `machO as? MachOFile` 的判定里是拿不到的。 +- **缺 `ReadingContext` 版的接口**:`GenericMetadataPatternProtocol.extraDataPattern`、`GenericClassMetadataPattern.immediateMembersPattern`、`AccessibleFunctionRecord.genericEnvironment`、`RelativeProtocolDescriptorPointer.protocolDescriptorRef`、`MetadataWrapper.metadata`、`TargetGenericContext.uniqueCurrentRequirementsInProcess()`(有改了名的对应版本 `uniqueCurrentRequirements(in:)`)、`SymbolicDemangler.demangleType(for: Symbol, in:)`、`SymbolicDemangler.demangleTypeUncached(for:)`,以及只有传 `machO` 版的 `AsyncResolvable`(整个仓库没有调用方)。 +- **天生离不开 Mach-O 或本进程的接口**:section 枚举入口(`MachOFile+Swift.swift` / `MachOImage+Swift.swift` 的 `machO.swift.*`,`SwiftSectionRepresentable`)、执行运行时代码的接口(`MetadataAccessorFunction.callAsFunction`、`RuntimeFunctions`、`MetadataProtocol.createInProcess` / `createInMachO` / `asMetatype`)、`MachOImage` 与指针之间的坐标换算(`asPointerWrapper(in:)`、`asMachOWrapper(in:)`)、地址格式化(`addressString`)、底层读原语(`Readable` 及其三个遵循、MachOKitExtensions 的 `asPointer` / `pointer(of:)`、`@Layout` 宏生成的 `pointer(from:of:)`)。它们不是「读取接口」而是入口、运行时调用或 `ReadingContext` 自身的实现基础。 +- **上层模块的接口分类**:上层模块自己有 287 个传 `machO` 的 public / package 接口。226 个要用读取以外的能力——符号索引(`SymbolIndexStore`)、ObjC section(MachOObjCSection)、依赖闭包、section 枚举、thunk 反汇编、执行 `MachOImage` 里的运行时函数——`ReadingContext` 按 [0018](0018-self-contained-abi-layer.md) 的定位不提供这些。61 个只读数据:`SymbolicDemangler` 的 `demangleType` / `demangleContext` / `buildGenericSignature` / `extendedTypeContextDescriptor`,`SwiftDeclaration` 的 `typeName` / `protocolName` / `demangledTypeNode` / `materialized*` / `memberJoinKey`,`SwiftDump` 的 `dumpName` / `dumpTypeName` / `dumpProtocolName`,`SwiftDeclarationRendering` 的 `GenericContext+Dump`(20 个)、`ResilientSuperclass+Dump`、`ContextDescriptorWrapper+Dump`、`ProtocolConformance+` 的 `typeNode` / `protocolNode`、`ResolvedTypeReference.node`、`ParentClassVTableCache.slotIndex`。其中大部分是 `package`。 +- **缓存怎么分层**:`SymbolicDemanglerCache` 与 `InternedNodeReferenceCache`(`Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift`)都分两层:按镜像的 `SharedCache` 条目(键是 `SharedCacheKey(machO)`,即 reader 的 `identifier`,随镜像驱逐),以及一份从不驱逐的全进程 `static` 存储,给本进程读取用。全进程那层按偏移做键(`nodeReferenceForContextOffset`),只对「偏移就是绝对地址」的 `InProcessContext` 安全;一个以文件偏移为地址的第三方 `ReadingContext` 如果落进这一层,两个镜像的偏移会撞在一起、互相串结果。`SharedCache` 已有按键取条目的 `resolve(key:build:)`(`Sources/MachO/MachOCaches/SharedCache.swift:179`)。 +- **下游**(调用 ABI 旧接口的地方,全部是传 `machO` 版,没有一处用指针版或 `ReadingContext` 版):RuntimeViewer `next` 3 处(`RuntimeSwiftSection.swift:713`、`RuntimeSwiftInterfaceIndexer.swift:208`,外加 `SymbolicDemangler.demangleType` 1 处;FindNavigator 分支另有 4 处);MachOKitUI 24 处(`MachOSwiftSectionDetailBuilder.swift`),它还自己遵循了 `Readable`、`MachOSwiftSectionRepresentableWithCache`、`MachOBindRebaseResolving`;swift-decompiler 9 处 + 3 处 `dumpName(using:in:)`;REAgent 与 RuntimeViewer `main` 钉死在 0.15.2,不受影响。没有一个下游开了「警告当错误」,本仓库也没有(`Package.swift` 只给测试 target 加 `SILENT_TEST`)。 +- **Swift 6.3 对废弃协议 requirement 的诊断**(`swiftc -typecheck` 探针实测):只给默认实现标 `deprecated`、requirement 不标,每个依赖该默认实现的遵循类型都报「deprecated default implementation is used to satisfy …」;requirement 与默认实现一起标,遵循处不报、只在调用处报;遵循类型自己写的实现也不报。仓库里依赖默认实现的遵循类型成百上千(64 个直接遵循 `ResolvableLocatableLayoutWrapper`、25 个直接遵循 `Resolvable`),所以旧 requirement 不能只废弃默认实现。 +- **分派是承重的**:`TypeContextDescriptorProtocol` 覆盖了 `genericContext`(`:17/38/52`),`any ContextDescriptorProtocol` 上的调用只有经过 requirement 才能落到这个覆盖;落不到时类型描述符会按 8 字节的 `GenericContextDescriptorHeader` 而不是 16 字节的 `TypeGenericContextDescriptorHeader` 解析(2026-04 的 `cc468e74` 就是为这个静态分派崩溃把 `ReadingContext` 版提成 requirement 的)。旧接口移出 requirement 列表之前,函数体必须已经转发到 `ReadingContext` requirement。 +- **覆盖率不变式**:`MachOSwiftSectionCoverageInvariantTests` 的 `PublicMemberScanner` 只扫 `Sources/ABI/MachOSwiftSection/Models`,函数按「类型名 + 裸名字」建键、忽略标签与参数类型(`Sources/TestSupport/MachOFixtureSupport/Coverage/PublicMemberScanner.swift:127-145`),初始化器保留标签(`:147-156`),不看 `@available`。所以标废弃对它没有影响;0.23.0 删除时,只有指针版初始化器 `init(descriptor:)` / `init(contextDescriptor:)` 这 13 个键会从登记表里消失,要同步改 baseline 生成器的登记列表。另有一个陷阱:测试里用 `InProcessContext.shared` / `.inProcess` 而不是 fixture 的 `inProcessContext` 属性,会被 `SuiteBehaviorScanner` 判成 sentinel(它按大小写敏感的子串 `inProcessContext` 识别)。 +- **仓库的废弃惯例**:[0018](0018-self-contained-abi-layer.md) 定过「能转发的废弃保留一个版本,否则在 minor 版本直接破坏」,0.x 阶段不升大版本,理由是下游都在本人控制之下;0.20.0 的两个废弃别名就是这么处理的。当前版本 0.21.0,本提案随 0.22.0 发布。 +- **并行工作**:2026-09-30 另有会话在 `feature/offline-generic-specialization`(worktree `.worktrees/MachOSwiftSection-OfflineGenericSpecialization`)起草离线泛型特化,它会动 `SwiftSpecialization/GenericSpecializer.swift`,而那里有本提案要迁的约 50 处调用。两边谁后合,谁解冲突。 + +## 提议方案 + +**一份实现**:每个读取接口只保留 `ReadingContext` 版的函数体。传 `machO` 的旧接口写成 `try x(in: machO.context)`,指针版写成 `try x(in: InProcessContext.shared)`,两者标 `@available(*, deprecated)`,不再有自己的逻辑。 + +**废弃的**: + +- ABI 层全部读取接口的传 `machO` 版与指针版:`Sources/ABI/MachOSwiftSection` 下的描述符、metadata、wrapper 初始化器与指针类型,`MachOPointers` 的相对 / 间接指针协议,`MachOResolving` 的 `Resolvable.resolve(from:in:)` / `resolve(from:)` 与 `AsyncResolvable`。 +- 上层 61 个纯读取接口中的 `public` 者的传 `machO` 版与指针版(`SymbolicDemangler`、`SwiftDump` 的 `NamedDumpable.dumpName` / `ConformedDumpable.dumpTypeName` / `dumpProtocolName`、`SwiftDeclaration` 的 `materialized*`)。其中 `package` 级别的外部看不到,直接改签名,不走废弃。 + +**保留、不废弃的**:section 枚举入口、执行运行时代码的接口、`MachOImage` 与指针之间的坐标换算、地址格式化、底层读原语(清单见前期调研),以及上层那 226 个要用读取以外能力的接口。它们内部对 ABI 读取接口的调用照样改走 `ReadingContext`。 + +**`ReadingContext` 新增缓存范围**:一个带默认值的 requirement,回答「这个 context 读出来的东西,按镜像缓存、按进程缓存、还是不缓存」。`MachOContext` 回答按镜像(给出 reader 的 `identifier`),`InProcessContext` 回答按进程,其余一律不缓存。只暴露缓存身份,不暴露 Mach-O 本身。 + +**迁移**:仓库内全部调用点——`Sources/` 与测试、baseline 生成器——在废弃落地的同一个 PR 里改走 `ReadingContext` 版,每个 PR 合入时不新增任何废弃警告。下游在 0.22.0 发布后、0.23.0 之前各提 PR。 + +**惯例**:AGENTS.md 加一条——新读取接口只写 `ReadingContext` 版。 + +### 非目标 + +- 不改上层那 226 个要用符号索引、ObjC、依赖、section 枚举或运行时能力的接口,也不改 36 个按 `MachO` 泛型化的上层类型(`SwiftDeclarationIndexer`、各 `Dumper`、`SwiftInterfaceBuilder` 等)。`ReadingContext` 不变成「镜像」抽象,不带符号服务。 +- 不废弃、不收紧底层读原语(`Readable`、`UnsafeRawPointer: Readable`、`asPointer`、`pointer(of:)`、`pointer(from:of:)`)。MachOKitUI 自己实现了 `Readable`。 +- 不动 MachOKitExtensions,不发它的新版本。 +- 不改变任何 dump / interface 输出:三条读取路径的渲染 A/B 必须逐字节一致。 +- 不支持 32 位 Mach-O(`MachOContext.Runtime` 仍是 `RuntimeTarget64`)。 +- 不迁 REAgent、RuntimeViewer `main`(都钉死在 0.15.2)。 + +## 详细设计 + +### 1. 先修 `ReadingContext` 版,再切转发 + +每处修复先写一个修复前失败的测试(对 `MachOContext` 断言与传 `machO` 版的结果一致,或直接断言正确值),修复后转绿,测试永久保留。 + +- **`Pointer.resolve(at:in:)`**:先问 `context.bindRebaseResolver?.resolveRebase(fileOffset:)`,有结果用它,否则再读字节。与 `SymbolOrElementPointer.resolve(at:in:)`(`:91-102`)现有的写法一致。 +- **`TypeMetadataRecord.contextDescriptor(in:)`**:间接记录先问 `context.bindRebaseResolver?.resolveBind(fileOffset:)`,被 bind 的返回 `nil`。 +- **`SymbolOrElementPointer` 可选元素**:判空改成 strip 之后判 0。 +- **其它 `machO as? MachOFile` / `context as? MachOContext` 的 bind 判定**(`SymbolOrElement.swift:37/45/57/65`)统一改走 `bindRebaseResolver`。 + +### 2. 转发与废弃的写法 + +```swift +extension NamedContextDescriptorProtocol { + public func name(in context: some ReadingContext) throws -> String { + let baseAddress = try context.addressFromOffset(offset + layout.offset(of: .name)) + return try layout.name.resolve(at: baseAddress, in: context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: machO.context for a Mach-O, .inProcess for process memory.") + public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try name(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: .inProcess for process memory.") + public func name() throws -> String { + try name(in: InProcessContext.shared) + } +} +``` + +- **协议 requirement**:`Resolvable`、`PointerProtocol`、`RelativePointerProtocol`、`RelativeIndirectType`、`RelativeIndirectPointerProtocol`、`RelativeIndirectablePointerProtocol`、`ContextDescriptorProtocol` 里的传 `machO` 版与指针版 requirement 移出协议声明,只作为废弃的扩展方法保留、转发到 `ReadingContext` requirement。具体遵循类型里手写的旧版本实现(`String` / `Optional` / `LocatableLayoutWrapper` 的 `resolve`、`Pointer.resolve`、`SymbolOrElementPointer.resolve` 等)一并删除,它们的 `ReadingContext` 版就是唯一实现。 +- **不抛错的 `resolveOffset(in: machO) -> Int`**:转发到 `MachOContext` 自己的地址换算。`MachOContext.addressFromVirtualAddress` 的实现本来就不会抛错,把这个具体方法声明成不抛错(仍满足协议里的 `throws` requirement),转发处就不需要 `try!`。 +- **`ResilientWitness.implementationAddress(in: machO) -> String?`** 属于地址格式化,保留,但改名为 `implementationAddressString(in:)`,旧名字标 `@available(*, deprecated, renamed:)`,免得和 `ReadingContext` 版同名、返回的却是另一种东西。 +- **`AsyncResolvable`** 整个废弃,提示改用同步的 `resolve(at:in:)`。 +- **补齐缺口**:前期调研列出的缺 `ReadingContext` 版的接口逐个补上,旧版本转发过去。`uniqueCurrentRequirementsInProcess()` 标 `deprecated`,提示 `uniqueCurrentRequirements(in: .inProcess)`。 + +### 3. `ReadingContext` 的缓存范围 + +```swift +/// Where the memo caches built on top of reading — demangling, node +/// interning — may file what they compute from a context. +public enum ReadingContextCacheScope: Sendable { + /// Per image: entries are keyed on the reader's identifier and are + /// evicted with the image. + case image(identifier: AnyHashable) + /// Process-wide: addresses are absolute, so two images never collide. + case process + /// The context gives no identity; nothing may be memoized. + case uncached +} + +public protocol ReadingContext: Sendable { + // Existing requirements unchanged. + + /// The scope a memo cache uses for what it computes from this context. + var cacheScope: ReadingContextCacheScope { get } +} + +extension ReadingContext { + public var cacheScope: ReadingContextCacheScope { .uncached } +} +``` + +- `MachOContext` 返回 `.image(identifier: AnyHashable(machO.identifier))`,`InProcessContext` 返回 `.process`。默认值 `.uncached` 保证第三方 context 永远不会落进全进程那层。 +- `MachOCaches` 的 `SharedCacheKey` 增加从 identifier 构造的入口,与 `SharedCacheKey(machO)` 共用同一段表示逻辑,保证同一个镜像经 `machO` 与经 context 得到同一个键,驱逐注册表([0053](0053-shared-cache-composition-and-eviction-registry.md))照常认领与驱逐。 +- (实现时修订,见决策日志 2026-09-30「`.image` 的载荷改为 `MachOTargetIdentifier`」:`.image` 不带 `AnyHashable`,`SharedCacheKey` 也不加新入口,两个缓存用现成的 `SharedCacheKey(identifier:)`。) +- `SymbolicDemanglerCache` 与 `InternedNodeReferenceCache` 按 `cacheScope` 选层:`.image` 走按镜像的 `SharedCache` 条目,`.process` 走现有的全进程存储,`.uncached` 不查不存。`SymbolicDemangler.isCacheEnabled` 照旧是总开关。 +- `SymbolicDemangler` 查符号用的私有 `SymbolLookupContext` 转型(`SymbolicDemangler.swift:184-231`)不变——那是符号服务,不是缓存身份。 + +### 4. 上层 61 个纯读取接口 + +- `public` 的:新增 `ReadingContext` 版作为唯一实现,旧版本废弃转发。`NamedDumpable` / `ConformedDumpable` 的 `dumpName` / `dumpTypeName` / `dumpProtocolName` 改成以 `some ReadingContext` 为参数的 requirement;取名逻辑从 `Dumper.name` 里抽成一个只读 context 的函数,`Dumper` 自己的 `name` 也调它(传 `machO.context`),保持一份实现。`ExtensionDefinition.init(extensionName:…:in:)` 的 `machO` 参数从未被使用,新增不带 reader 的初始化器,旧的废弃。 +- `package` 的:直接改成 `some ReadingContext` 参数,调用方同批改。 + +### 5. 调用点迁移规则 + +- `x.f(…, in: machO)` → `x.f(…, in: machO.context)`;持有 `machO` 的上层类型在热点处可以存一份 `MachOContext`,其余就地写 `.context`。 +- 指针版 `x.f()` → `x.f(in: .inProcess)`(生产代码);测试里用 fixture 的 `inProcessContext` 属性。 +- `T.resolve(from: offset, in: machO)` → `T.resolve(at: offset, in: machO.context)`;`pointer.resolve(from: ptr)` → `pointer.resolve(at: ptr, in: .inProcess)`。 +- 以编译器的废弃警告为工作清单:先加废弃,再逐个清掉警告,直到构建零新增警告。 + +### 6. 测试 + +- fixture 套件与 baseline 生成器改调 `ReadingContext` 版,`acrossAllReaders` 改成 `acrossAllContexts`,按 `MachOContext`、`MachOContext`、本进程三种 context 各验一遍。baseline 的值不变(它们本来就由 `MachOFile` 上的传 `machO` 版生成,而那一版的正确行为已经补进 `ReadingContext` 版)。 +- 新增一个转发套件:对每一类旧接口抽代表,断言旧接口与 `ReadingContext` 版结果相同。套件本身标 `@available(*, deprecated)` 以免报警,0.23.0 随旧接口一起删除。 +- 第 1 节每处修复各带一个修复前失败的回归测试,永久保留。 + +### 7. 性能 + +`MachOFile`、`MachOImage`、本进程三条路径的 dump 与 interface 都和改动前对比耗时(同一份 `Package.resolved`、同一个 fixture 与系统镜像集),慢出测量噪声即视为回归,修到持平才合入。预期的风险点是原来走指针版的本进程路径(`RuntimeMetadataTypeBuilder`、`GenericSpecializer`、`RuntimeFieldLayoutBackend`):每次读取多了 strip 与判空,调用从具体函数变成跨模块的泛型函数。手段按代价从低到高:在调用处持有具体的 `InProcessContext` 类型而不是存在类型、热点函数标 `@inlinable`、必要时对 `InProcessContext` 手动特化。 + +## 替代方案考量 + +- **只加废弃、三份实现不动**:改动最小,但漂移继续存在,第 1 节的 bug 也不会被修。用户明确要求「实现只有一份」。 +- **旧接口直接删除**:一步到位,但会让 MachOKitUI、swift-decompiler、RuntimeViewer 在升级时直接编译失败。按 0018 定的惯例保留一个版本。 +- **只迁 ABI 层**:不需要改 `ReadingContext` 协议,改动面约小一半;但 `SymbolicDemangler` 等上层只读接口会继续三套并存。用户选择把 61 个纯读取接口一起迁。 +- **上层全部迁移,把 `ReadingContext` 扩成「镜像」抽象**:符号表、ObjC、依赖都经 context 走,226 个接口与 36 个泛型类型全部改写。工作量是本方案的数倍,而且推翻 0018「`ReadingContext` 不带符号服务」的决定。 +- **`ReadingContext` 直接暴露底层 Mach-O**:一个可选的 `machO` 属性就能当缓存键,将来也方便更多上层接口改收 context。代价是调用方可以悄悄 `as? MachOFile`,把对 Mach-O 的依赖藏进 context 里,正是 0018 想避免的。 +- **不改协议,缓存内部识别 `MachOContext` / `InProcessContext`**:公开面最小,但这个能力在协议上不可见,第三方 context 也无法选择加入。 +- **运行时调用类接口也改收 `ReadingContext`**:这些接口只对本进程或 `MachOImage` 有意义,改成 context 形式只会得到一个传 `MachOContext` 就报错的假泛型。 +- **底层读原语一起收紧**:MachOKitUI 自己实现了 `Readable`,收紧会直接破坏它;而且 `ReadingContext` 本身就建在这些原语上。 +- **测试保持调用旧接口**:靠转发间接覆盖唯一实现,测试构建会冒上千条废弃警告,0.23.0 删除时还得回头改一遍。 + +## 影响 + +### 源码兼容性(source compatibility) + +0.22.0 对外是**纯新增 + 废弃警告**,另有三处行为变化与一处协议形状变化: + +- 废弃:传 `machO` 版与指针版的调用照常编译,只多一条警告。改法: + + ```swift + // Before + let name = try descriptor.name(in: machO) + let fields = try metadata.fieldOffsets() + + // After + let name = try descriptor.name(in: machO.context) + let fields = try metadata.fieldOffsets(in: .inProcess) + ``` + +- 行为变化(写进 0.22.0 Changelog): + - 原来走指针版的调用,遇到空指针或带 tag 的指针改为抛错,不再崩溃;错误类型从 `NullPointerError` 变成 `UnsafeRawPointer.Error.initFailed`。 + - 指针版遇到符号引用时返回 `.symbol`,不再 `fatalError()`。 + - 自己实现了 `MachOBindRebaseResolving` 的包装类型(MachOKitUI 的 `MachOFileSource`)在间接指针上开始走 rebase 表,读出的是正确的目标,而不是 fixup 编码。 +- 协议形状:旧 requirement 移出协议声明。外部类型如果遵循了这些协议并**只**实现了旧 requirement(仓库外没有已知实例),它的实现不再参与分派;`ReadingContext` 新增的 `cacheScope` requirement 带默认值,外部 context 不需要改。 +- `NamedDumpable` / `ConformedDumpable` 的 requirement 换成 `ReadingContext` 参数:外部遵循者需要改(仓库外没有已知实例);外部调用者走废弃转发,不受影响。 +- `ResilientWitness.implementationAddress(in: machO)` 改名,旧名字带 `renamed:`,Xcode 可以一键修复。 + +0.23.0 删除旧接口,属于破坏性变更,届时下游应已迁完。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +本仓库内:几乎所有 target。生产代码约 333 处 ABI 调用、上层 61 个接口的调用方,测试约 1000 处调用、baseline 生成器约 190 处。 + +下游仓库: + +- **RuntimeViewer**(`next` 分支跟随 MachOSwiftSection `next`):3 处 ABI 调用 + `SymbolicDemangler` 1 处;FindNavigator 分支另 4 处。0.22.0 进入 `next` 之后即可迁。 +- **MachOKitUI**(`from: "0.19.0"`):24 处,需要 0.22.0 发布后迁。它遵循的 `Readable` / `MachOSwiftSectionRepresentableWithCache` / `MachOBindRebaseResolving` 不受影响。 +- **swift-decompiler**(跟随 `main`):9 处 + 3 处 `dumpName(using:in:)`,0.22.0 发布后迁。 +- REAgent、RuntimeViewer `main`:钉死在 0.15.2,不受影响,也不在本次范围。 + +### 文档与示例 + +- `Documentations/Internal/ReadingContextAbstraction.md`:第 4 阶段落地;缓存范围一节;更正「`runtimePointer(at:)` 不是 requirement」的过时说法;用法示例改成 `ReadingContext`。 +- `AGENTS.md`:新读取接口只写 `ReadingContext` 版;模块描述里提到的接口形态同步。 +- `Documentations/Internal/Modules/` 下涉及的模块页、`Documentations/README.md` 索引、`Documentations/Glossary.md`(登记「缓存范围 / cache scope」)、`Documentations/Internal/ProjectEvolutionLog.md`、`Changelogs/0.22.0.md`。 +- `AgentPlugins/swift-section/`:CLI 不变,不需要改。 + +## API 演进与废弃策略 + +- 被替代的旧 API 标 `@available(*, deprecated, message:)` 保留,函数体只转发,不再有自己的逻辑。改名的一处用 `renamed:`。 +- 废弃期一个版本:0.22.0 标废弃,0.23.0 删除。删除前在各下游仓库提 PR 迁移调用点。 +- 不需要 semver major 跃迁:0.x 阶段按惯例在 minor 版本做破坏性变更。 + +## 落地步骤 + +**PR 1:ABI 层**(进 `next`) + +1. 第 1 节的四处修复,各带一个修复前失败的回归测试。 +2. 补齐缺 `ReadingContext` 版的接口。 +3. 旧接口改成转发并标废弃;旧 requirement 移出协议声明;删除具体类型里手写的旧实现。 +4. 以废弃警告为清单,迁移 `Sources/` 里全部 ABI 调用点,直到零新增警告。 +5. 迁移测试与 baseline 生成器,新增转发套件。 +6. 验证:`swift test --skip IntegrationTests` 原始退出码为 0;`regen-baselines` 之后 `__Baseline__/` 零 diff;渲染 A/B 三条路径逐字节一致;三条路径耗时不劣于基线。 + +**PR 2:缓存范围与上层 61 个接口**(进 `next`) + +7. `ReadingContextCacheScope`、`MachOContext` / `InProcessContext` 的实现、`SharedCacheKey` 的 identifier 入口;两个缓存按 scope 选层,带测试(同一镜像经 `machO` 与经 context 命中同一条目、驱逐一致、第三方 context 不缓存)。 +8. 上层 61 个接口:`public` 的加 `ReadingContext` 版并废弃旧版,`package` 的直接改签名;迁移调用点。 +9. 同第 6 步的验证。 + +**文档**:随各自 PR 同批更新第「文档与示例」节列出的文件,本提案原地更新。 + +**发布与下游** + +10. 0.22.0 发布(Changelog 写明废弃清单与三处行为变化)。 +11. RuntimeViewer、MachOKitUI、swift-decompiler 各提迁移 PR。 +12. 0.23.0:删除全部废弃转发与转发套件,更新覆盖率登记表(13 个指针版初始化器键),本提案决策日志补一行。 + +**收尾判断**(落地时写进决策日志):是否需要配套实现说明(预期更新 `ReadingContextAbstraction.md` 即可,不另写);新术语「缓存范围」登记进术语表。 + +## 当前进度(2026-09-30) + +**一句话**:实现、正确性验收与性能验收都已完成(落地步骤 1–9),分支 `refactor/reading-context-migration` 已推送,基于 `next` @ `f7c189b8`,以一个 PR 合入 `next`。 + +| commit | 内容 | +|---|---| +| `b00fda81` | 本提案 | +| `a23d52b6` | ABI 层:`ReadingContext` 形式成为唯一实现,传 `machO` 与指针的形式改为废弃转发;五处分歧修复及回归测试 | +| `9c75c40f` | `Sources/` 与测试、baseline 生成器的全部调用点改走 context 形式 | +| `9827e1d0` | 删掉迁移后变成「自己比自己」的 fixture 断言 | +| `17d101e6` | `ReadingContext.cacheScope`;上层 61 个只读接口迁移;AGENTS.md、实现说明、术语表 | +| `3d84ee05` | 缓存范围的镜像身份不装箱(`SharedCacheKey` 恢复原样) | +| `1cf72537` 及之后 | 验证数据与本节 | + +这些 commit 是在 JHs-Mac-Studio-Ultra 上按会话记录重建的:原分支(`bd670206` 到 `b7c99dbf`)只存在于公司那台机器上,没有推送。重建时按时间顺序重放记录里的每次编辑,并逐一核对记录中「编辑前的完整文件」;重建后各 commit 的文件清单与行数统计和原 commit 一致(例如 ABI 那次 86 个源文件 +1959 / −2800、测试去重那次 24 个文件 +75 / −206)。 + +**正确性验收**: +- 全量测试:公司机器(Xcode 26 工具链)2157 个 / 410 个套件,只有那台机器既有的两条 `MultiPayloadEnumDescriptorCacheTests` 失败;Ultra(Swift 6.4,fixture 用 Xcode 26.6 编)同样 2157 个 / 410 个,全部通过,原始退出码 0。零新增警告。 +- 渲染 A/B:公司机器 90 对、Ultra 96 对逐字节一致。Ultra 的 96 对是:脚本跑的 CLI 两条腿 60 对;26.6 归档 cache 手动补跑 12 对(Ultra 上没有脚本写死的 26.6.2 目录,脚本会静默跳过这条腿);MachOImage 腿 24 对。 + +**性能验收**(Ultra,release,每组按「基线、候选、候选、基线」运行,SwiftUI):三条路径都没有变慢。 + +| 路径 | 基线 | 候选 | 结论 | +|---|---|---|---| +| dyld cache 里的 `MachOFile`(26.6)`dump` | 580.42G 条指令,user 31.82 秒 | 577.63G,31.62 秒 | 指令 −0.48% | +| 同上 `interface` | 740.22G,40.81 秒 | 738.64G,40.85 秒 | 指令 −0.21% | +| 磁盘上的 `MachOFile`(iOS 26.5 模拟器)`dump` | user 30.51 秒 | 30.57 秒 | +0.2% | +| 同上 `interface`(各 4 次) | user 38.75 秒(38.57–38.93) | 38.97 秒(38.62–39.45) | +0.57%,区间重叠 | +| MachOImage 与本进程(`RenderingVerificationTests`) | user 504.2 秒 | 498.2 秒 | −1.2% | + +指标以 `/usr/bin/time -l` 的退休指令数为主(同一侧两次相差 0.03%–0.3%),模拟器路径的内核时间占一半、指令数跟着抖,改看 user 时间;MachOImage 腿的指令数只统计了 `swift test` 驱动进程本身,也只看 user 时间。公司那台机器上测出的 MachOImage 腿「多 2.5%」是噪声(那台机器上基线两次之间就差 3%)。 + +**换机器时的注意事项**: +- Xcode 27 的机器上,SymbolTestsCore fixture 要用 Xcode 26.6 编(`DEVELOPER_DIR=…/Xcode-26.6.0.app/Contents/Developer`,ad-hoc 签名),否则 `MachOSwiftSectionTests` 会有约 195 个 offset / layout 与 baseline 不符,那是编译器版本带来的漂移,不是回归。 +- 渲染 A/B 脚本的归档 cache 目录写死为 `26.6.2` 与 `15.5`,缺哪个就静默少一条腿(Ultra 上只有 `15.5`)。脚本自己会跑 `swift build -c release` 与 `swift test -c release`,不经 `queued-build`;在限流的 10 核 Mac Studio 上,`queued-build` 给预构建加的 `--jobs 8` 会变成编译器参数 `-num-threads 8`,脚本的那次构建于是两侧并行、绕过队列地全量重编。 + +**不在本 PR、另开分支处理**(用户已决定): + +1. 本批发现的既有问题:`FunctionTypeMetadata.extendedFlags(in:)` 与 `EnumMetadataProtocol.payloadSize(descriptor:in:)` 从泛型 `readElement` 直接返回 Optional,按 Optional 的内存形状多读一个字节,`FunctionTypeMetadataTests` 时好时坏就是它;`ContextDescriptorWrapper.resolve(at:in:) -> Self?` 出错时用 `print` 写 stdout,违反日志规则,也会弄脏 CLI 的输出。**已修复**:分支 `fix/optional-read-and-stdout-print`,[PR #130](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/130)(本 PR 合入后直接对 `next`);另查出并修了 `SwiftClassObjectIndex` 读 class flags 的一处同类写法,同批清掉的还有 `SubstitutionMap` 的 `print`。 +2. 渲染 A/B 脚本加 `--skip-build`:直接使用预先经 `queued-build` 构建好的产物,脚本自己不再构建。**已合入**:分支 `chore/rendering-harness-skip-build`,合并提交 `01b57f74`(2026-10-01 直接合入 `next`,没有开 PR);用法见 [SystemFrameworkRenderingVerification.md](../Internal/SystemFrameworkRenderingVerification.md)「关键调用细节」。 + +**合入之后**(编号与状态已在合入时完成):0.22.0 的 Changelog 写明废弃清单与三处行为变化;给 RuntimeViewer(`next`)、MachOKitUI、swift-decompiler 提迁移 PR;0.23.0 删除全部废弃转发、`DeprecatedReadingFormsTests`,以及覆盖率登记表里 13 个指针版初始化器的键。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-09-30 | Created as Draft | 用户原话:「把传递machO和直接用指针解析的接口全部迁移至ReadingContext,旧接口全部弃用」 | +| 2026-09-30 | 旧接口废弃后转发到 `ReadingContext` 版,实现只留一份 | 用户:「弃用旧接口后旧接口的实现直接调用ReadingContext接口,确保实现只有1份」 | +| 2026-09-30 | 范围:ABI 层 + 上层 61 个纯读取接口 | 用户选定;否决「只迁 ABI 层」与「上层全部迁移」(后者要推翻 0018 的定位) | +| 2026-09-30 | 0.22.0 标废弃,0.23.0 删除,删除前迁下游 | 用户选定,与 0018 的废弃惯例一致;否决「只废弃不定删除时间」「下游迁完再删」 | +| 2026-09-30 | 测试与 baseline 生成器全部改走 `ReadingContext`,另留转发套件 | 用户选定;否决「测试保持不动」 | +| 2026-09-30 | 天生离不开 Mach-O / 本进程的接口保留不废弃 | 用户选定;否决「运行时调用类也改 context 版」「连底层原语一起废弃」 | +| 2026-09-30 | `ReadingContext` 新增缓存范围声明,只暴露缓存身份 | 用户选定;否决「直接暴露底层 Mach-O」「不改协议、内部转型」 | +| 2026-09-30 | 性能:三条路径都不许变慢,修到持平才合入 | 用户选定;否决「本进程路径允许 10% 开销」「只验正确性」 | +| 2026-09-30 | 自定:先修 `ReadingContext` 版再切转发;旧 requirement 移出协议;`package` 接口直接改签名;`implementationAddress(in: machO)` 改名;`AsyncResolvable` 废弃;分两个 PR;AGENTS.md 改惯例 | 列在收尾确认清单里,用户确认 | +| 2026-09-30 | Accepted | 用户确认决策清单:「可以,然后开一个worktree开工」 | +| 2026-09-30 | In Progress | worktree `.worktrees/MachOSwiftSection-ReadingContextMigration`,分支 `refactor/reading-context-migration` | +| 2026-09-30 | 旧形式原地保留成转发,不集中到协议扩展 | 集中之后 `Pointer.resolve(from:in:).descriptor()` 这类链式调用在 `-> Self` 与 `-> Self?` 之间二义(实际撞上);原地保留使重载解析与原来一致 | +| 2026-09-30 | 不用 `@_disfavoredOverload` 压 `-> Self?` 形式 | `ContextDescriptorWrapper` 等类型的 `-> Self?` 遇非法 kind 返回 nil,一律压成 `-> Self` 会改变旧调用方的结果 | +| 2026-09-30 | `PointerProtocol` 与 `RelativeIndirectType` 保留已废弃的旧 requirement,其余协议移除 | `Pointer` 同时遵循两者,两个协议扩展各给一份转发会让对 `Pointer` 的调用二义;requirement 与默认实现一起废弃只在调用处报警(Swift 6.3 探针实测) | +| 2026-09-30 | 约束扩展里的空指针 guard 放进私有 helper | 约束扩展内按名字调用同名 requirement 绑定到无约束 witness(探针实测),直接写成一行转发会跳过 guard | +| 2026-09-30 | 分歧修复:`Pointer` 查 rebase、`TypeMetadataRecord` 跳过 bind、`SymbolOrElementPointer` 剥 tag 后判空、`MangledName` 偏移统一基准、metadata 地址为 0 时抛错 | 以传 `machO` 版为准补进 `ReadingContext` 版;前三处各带修复前确认红过的回归测试 | +| 2026-09-30 | `InProcessContext` 的 tag 掩码只算一次、`advanceAddress` 剥 tag;`MachOContext` 去掉多余的预剥并改为不抛错 | 性能:避免每次读取都查当前镜像、遍历 load command;与旧的传 `machO` 版做完全相同的事 | +| 2026-09-30 | `NamedDumpable` / `ConformedDumpable` 的 requirement 换成收 `ReadingContext` 的形式,取名逻辑从各 Dumper 抽成被 dump 类型上的一份实现 | 取名只读数据;Dumper 自己的 `name` 与 `dumpName` 共用同一份,保持单一实现 | +| 2026-09-30 | `ProtocolConformance.typeName` 遇只剩 `typeAlias` 的符号时按 struct 处理(原指针版返回 nil) | 以传 `machO` 版(`Node.typeKind`)为准 | +| 2026-09-30 | 测试去重:改写后与已有 context 断言等价的重复断言删除,保留更强的一条 | 旧形式只是转发,改写后两边走同一路径,对比永远成立 | +| 2026-09-30 | `.image` 的载荷改为 `MachOTargetIdentifier`(原设计为 `AnyHashable`),`SharedCacheKey` 不加新入口;identifier 不是这个类型的读者经 context 读时不缓存 | 按原设计实现后,`SharedCacheKey(machO)` 被改成先装箱再拆箱,退回了 0053 专门去掉的每次查找一次堆分配(文件的 identifier 放不进 existential 内联缓冲),context 路径每次 memo 查找也要装箱一次。今天所有读者(含 MachOKitUI 的包装类型)都用 `MachOTargetIdentifier`,不缓存只影响假想中的读者,且只慢不错 | +| 2026-09-30 | 性能验收暂缓,换性能更好的机器再测 | 用户:「差不多先停下来,基准测试在这台电脑上可能不准,得换另一台性能更好的设备才看的出来,这台电脑内存不足和cpu占用过高了」。已有结果:cache 路径按退休指令数与 user 时间持平;模拟器文件路径 user 时间持平;MachOImage 腿 CPU 时间候选平均多 2.5%,而基线两次之间就差 3%,未定论。正确性验收(全量测试、90 对渲染 A/B)已完成,数据见 ProjectEvolutionLog。接手步骤见「当前进度」一节 | +| 2026-09-30 | 分支在 JHs-Mac-Studio-Ultra 上按会话记录重建并推送 | 原分支没有推送,公司那台机器随后关机。用户:「你在我这台设备重新写吧,自己对着对话记录抄」。重建后各 commit 的文件清单与行数统计与原 commit 一致,全量测试与渲染 A/B 在 Ultra 上重跑通过 | +| 2026-09-30 | 性能验收完成:三条路径都没有变慢 | 在 Ultra(28 核,负载低)上测:dyld cache 路径退休指令数 −0.48% / −0.21%,模拟器文件路径 user 时间 +0.2% / +0.57%(两侧区间重叠),MachOImage 与本进程路径 user 时间 −1.2%。公司机器上「多 2.5%」的读数判为噪声 | +| 2026-09-30 | 改为一个 PR 合入(原计划拆成 ABI 层与缓存范围加上层接口两个) | 用户选定。ABI 层的文档改动是和第二部分一起提交的,拆开要重排 commit;现有 commit 已按逻辑分开,评审时可逐个看 | +| 2026-09-30 | 既有的 Optional 读取陷阱与 `print` 写 stdout 另开分支修,A/B 脚本加 `--skip-build` 也另开分支 | 用户选定;本 PR 只做迁移,保持聚焦 | +| 2026-10-01 | In Progress → Implemented,编号 0057,经 [PR #129](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/129) 合入 `next` | 用户:「继续合并吧」。各共享分支上的最大编号是 0056(`next`)。分支基于 `next` @ `f7c189b8`,此后 `next` 没有新提交,合入无冲突。最后一次代码改动之后只有文档 commit,验收数据沿用「当前进度」一节:全量测试 2157 个 / 410 个套件原始退出码 0,渲染 A/B 96 对逐字节一致,三条路径性能持平 | +| 2026-10-01 | 收尾判断:不另写使用指南,实现说明是 `ReadingContextAbstraction.md`「单一实现与废弃」一节;术语表的「cache scope」与「context form / Mach-O form / pointer form」已在实现批次登记;账本记第 73 节 | 迁移写法只有三种替换(`x(in: machO)` → `x(in: machO.context)`,`x()` → `x(in: .inProcess)`,`resolve(from:in:)` → `resolve(at:in:)`),废弃消息本身就给出了替代写法,0.22.0 的 Changelog 再列一遍 | diff --git a/Documentations/Evolutions/0058-swift-section-kit.md b/Documentations/Evolutions/0058-swift-section-kit.md new file mode 100644 index 000000000..33dce0871 --- /dev/null +++ b/Documentations/Evolutions/0058-swift-section-kit.md @@ -0,0 +1,672 @@ +# 0058 - 把 swift-section 的功能抽成 SwiftSectionKit 库,CLI 只剩一层包装 + +- **状态**: Implemented +- **作者**: JH +- **创建日期**: 2026-10-03 +- **最后更新**: 2026-10-03 +- **所属愿景**: 无 +- **关联提案**: [0036](0036-objc-subcommands.md)(`objc` 子命令组并入 swift-section;本提案把它一起抽进库)、[0055](0055-group-sources-by-layer.md)(`Sources/` 按层分组;本提案新增 `Commands/` 一组) +- **实现分支 / PR**: `refactor/swift-section-kit`(worktree `.worktrees/MachOSwiftSection-SwiftSectionKit`,基于 `next`),按本仓库惯例在本地合并进 `next` +- **配套文档**: 使用指南 [SwiftSectionKit.md](../SwiftSectionKit.md) / [SwiftSectionKit_zh.md](../SwiftSectionKit_zh.md);模块文档 [Modules/SwiftSectionKit.md](../Internal/Modules/SwiftSectionKit.md) + +## 摘要 + +新增一个对外发布的 library product `SwiftSectionKit`,把 `swift-section` 每个子命令真正干活的部分搬进去:加载二进制、组装配置、遍历要输出的内容、写文件、决定输出的先后顺序、算出 diff 有没有破坏性变更。每个子命令对应一个按用途建模的请求类型(`DumpRequest`、`ABIDiffRequest`……),输出交给调用方注入的输出端,测试时换成内存记录器即可断言。`swift-section` 可执行文件只剩一层包装:声明 flag、校验 flag 组合、把 flag 映射成请求、把库的错误翻译回原来的文案、把输出写到 stdout / stderr、决定退出码。范围覆盖全部子命令(含 `objc` 下五个)。输出逐字节保持不变,只有两处有意的偏差(见「两处行为偏差」)。 + +## 动机 + +**CLI 的执行逻辑完全没有测试。** `Tests/SwiftSectionCommandTests` 现有 79 个测试,没有一个调用过任何命令的 `run()`(`grep -rn '\.run()'` 结果为 0)。这些测试只验证参数能不能解析(`DumpCommand.parse([...])`),外加两个纯函数(`ObjCDumpCommand.diagnosticNotes(for:)`、`TransformerOptionGroup.buildTransformerConfiguration()`)。下面这些行为今天只能靠手动跑命令来确认: + +- `dump` 默认输出全部 section 时吞掉读取失败、显式指定时才报错(`Sources/Executables/swift-section/Commands/DumpCommand.swift:153-281`),以及 `--preferred-binary-order` 的排序规则。 +- 写文件和打到终端的细微差别:`interface -o` 写出的文件末尾没有换行,打到终端时有(`InterfaceCommand.swift:204-210`);`diff` 同样如此,`evolution` 则两边一致(`DiffCommand.swift:212-219`、`EvolutionCommand.swift:103-108`)。 +- `interface` 进度行的先后顺序:带 `--emit-header` 时 "Preparing…" 打在建索引之前,否则打在挂完 provider 之后(`InterfaceCommand.swift:120-131`、`192-194`)。 +- snapshot 输入的识别与重贴标签(`Utilities/ABISnapshotInputLoader.swift:16-79`)、`--fail-on-breaking` 的退出码(`DiffCommand.swift:144-146`、`EvolutionCommand.swift:110-112`)、annotated interface 的逐行着色规则(`DiffCommand.swift:223-251`、`EvolutionCommand.swift:174-204`)。 + +**测不了的原因是逻辑和进程缠在一起。** `run()` 里直接 `print` / `fputs` / `FileHandle.write`,直接写文件系统;中途抛 ArgumentParser 的 `ValidationError` 和 `ExitCode`;还把 `Date()` 和 `BundledVersion.value` 盖进输出(`ABISnapshotInputLoader.swift:72-77`),同一输入两次运行的结果都不一样。 + +**两套命令已经各写各的,开始漂移。** Swift 侧的 `snapshot` 早就因为 `swift-section snapshot … | head` 会让进程 abort,把 `FileHandle.standardOutput.write` 换成了 `fwrite`(`SnapshotCommand.swift:40-49` 的注释)。0036 搬进来的 `objc` 子命令却还在用这个写法(`ObjC/Commands/ObjCSnapshotCommand.swift:37-38`、`ObjC/Utilities/StandardErrorLog.swift:10`):stderr 被关闭时,`objc` 的任何一条进度行都会让进程 abort。`ABISnapshotInputLoader` 和 `ObjCSnapshotInputLoader` 的嗅探与加载代码几乎逐行相同。输出统一走一个有测试的输出端之后,这类漂移就没有地方藏了。 + +**做成对外 product,其他宿主也能拿到同一套行为。** 仓库里的 `MCP/swift-section-mcp` 自己重写了一套加载逻辑,已经和 CLI 走岔:它用 `DyldCache` 而不是 `FullDyldCache`(0036 动机里写过,只覆盖主缓存文件的 `DyldCache` 会把落在子缓存里的镜像读到映射范围之外),还按文件名而不是 install name 找 cache 镜像(`MCP/Sources/swift-section-mcp/BinarySession.swift:12-80`)。有了 `SwiftSectionKit`,它以后可以直接复用(本提案不迁移它,见「后续工作」)。 + +## 前期调研 + +- **CLI 的构成**:`Sources/Executables/swift-section/` 共 35 个文件、3,476 行。最大的几个是 `DumpCommand.swift`(370 行)、`TransformerOptionGroup.swift`(314 行)、`TransformerCommand.swift`(276 行)、`DiffCommand.swift`(260 行)、`EvolutionCommand.swift`(240 行)、`InterfaceCommand.swift`(212 行)。`objc` 子树约 1,000 行。 +- **现有测试**:`DiffCommandValidationTests`、`EvolutionCommandValidationTests`、`HeaderAndExportStatusFlagTests`、`InferObjCOverridesFlagTests`、`DumpSectionsOptionTests`、`ExportedOnlyFlagTests`、`ObjCSectionCommandTests`、`ObjCAPICommandParsingTests` 只测解析与 `validate()`;`TransformerOptionGroupTests` 测模板选项到配置的映射;`ObjCDumpDiagnosticsTests` 测空结果提示的文案。测试目标通过 `@testable import swift_section` 直接依赖可执行目标(`Package.swift:1053-1066`)。 +- **每个命令写到哪里**(逐字节保持的依据): + + | 命令 | stdout | stderr | + |---|---|---| + | `dump` | 产物;**每个声明的读取错误**(红色,`DumpCommand.swift:343-345`),带 `-o` 时也照样打到 stdout | 无 | + | `interface` | **进度行** "Preparing… / Building… / built successfully. / Writing… to X..."(`InterfaceCommand.swift:125`、`193-205`);不带 `-o` 时产物 | `--resolve-c-module-names` 相关警告(`fputs`);`ConsoleEventHandler` 的索引事件 | + | `snapshot` | 产物(`fwrite` + 换行) | 进度行(`fputs`);索引事件 | + | `diff` / `evolution` | 产物;`--summary-only` 的结论行 | 进度行(`fputs`);索引事件(按 old / new 或版本标签分开) | + | `transformer` | 列表或 JSON | 无 | + | `objc dump` / `interface` | 产物(`dump` 每个声明后空一行) | 空结果提示、`--verbose` 进度(`FileHandle.standardError.write`) | + | `objc snapshot` | 产物(`FileHandle.standardOutput.write`) | 进度行(同上) | + | `objc diff` / `evolution` | 产物 | 进度行(同上) | + + `interface` 进度行混进 stdout 是插件 skill 专门警告过的已知怪癖(`AgentPlugins/swift-section/skills/swift-section-cli/SKILL.md:109-126`)。 +- **ArgumentParser 怎么处理 `run()` 抛出的错误**(读 swift-argument-parser 源码 `Sources/ArgumentParser/Usage/MessageInfo.swift:96-118`、`Utilities/Foundation.swift:19-31` 核实):`ValidationError` 打印报错加用法、退出码 64;`ExitCode` 什么都不打印、按给定码退出;其余错误打印 `LocalizedError.errorDescription`(没有就是 `String(describing:)`)、退出码 1。所以库里的错误一旦换了措辞或类型,CLI 必须翻译回原样。 +- **源码扫描会自动覆盖新模块**:`Tests/SwiftInterfaceTests/PrintFailureEventTests.swift:165-280` 禁止库模块写进程流(`print` / `fputs` / `FileHandle.standardOutput` / `FileHandle.standardError`),只豁免 `hostModules = ["swift-section", "MachOTestingSupport"]`,模块名取 `Sources` 下第二层目录。`Sources/Commands/SwiftSectionKit/` 不在豁免名单里,扫描会从机制上保证只有 CLI 层碰 stdout / stderr。 +- **请求类型可以做成 `Equatable`**:请求要携带的库类型都已经是值类型且可比较——`Transformer.SwiftConfiguration`(`Sendable, Equatable, Hashable, Codable`)、`ObjCGenerationOptions`(同上)、`ObjCPrimitiveTypePattern`(`Hashable`)、`DependencySearchPath`(`Hashable`)、`SwiftDeclarationMemberSortOrder`(`Hashable`)、`Transformer.Module`(`Hashable`)、`ABISnapshotDocument`(`Equatable`)。这让 CLI 包装层可以用「解析 flag → 生成请求 → 与期望值比较」来测。 +- **CI 与版本号**:`.github/workflows/version-check.yml:20` 与 `release.yml:42` 写死了 `Sources/Executables/swift-section/Version.swift`;`release.yml:55-58` 按 product 名 `swift-section` 构建。`macOS.yml:123` 的 `--filter` 白名单只跑点名的套件,`ContinuousIntegrationTestFilterTests` 校验名单里的每个名字都真实存在。 +- **A/B 对比脚本的覆盖面**:`Scripts/run-rendering-ab-verification.py:397-444` 对系统框架跑默认参数的 `dump` 与 `interface`,覆盖归档 cache、模拟器 runtime 文件两条 CLI 路径(第三条进程内 `MachOImage` 路径走 `RenderingVerificationTests`,不经过 CLI)。`snapshot` / `diff` / `evolution` / `transformer` / `objc` 与各子命令的 `--help` 都不在它的覆盖范围内。 +- **`IgnoreCoding.swift` 没有任何调用方**(`grep -rn IgnoreCoding Sources Tests` 只有定义本身)。 +- **`package` 访问级别在本仓库已大量使用**(340 个文件)——只与被否的「仅包内可见」方案有关,见「替代方案考量」。 + +## 提议方案 + +``` +swift-section(可执行文件) flag 声明与 --help、validate()、命令行拼写的解释、flag → 请求、 + 错误翻译回原文案、诊断写哪个流、终端着色(Rainbow)、退出码、BundledVersion + └── SwiftSectionKit(新 product) 每个子命令一个请求类型、Mach-O 加载、snapshot 输入加载、 + 输出端协议、全部编排逻辑 + └── SwiftInterface、SwiftDump、SwiftDiffing、TypeIndexing、MachOObjCSection 的 ObjC 产品…… +``` + +- **每个子命令一个请求类型**,`run(output:environment:)` 执行。互斥选项用 enum 表达,非法组合在类型上写不出来;例如 `diff` 的输出只能是 change list / summary / JSON / annotated interface 之一。 +- **输出端**是调用方注入的 `SwiftSectionOutput`,分三路:产物(`write`)、诊断(`report`)、索引事件 handler(`indexEventHandlers(forInputLabeled:)`)。`dump` 照旧边算边输出,错误与正文的先后顺序不变。 +- **诊断 = 级别 + 原文**。级别是 progress / warning / note / error,原文就是 CLI 现在打出来的那句话。产物那一路只放真正的产物。哪一级写哪个流由 CLI 决定:`interface` 的 progress 和 `dump` 的 error 写 stdout,其余写 stderr。两个怪癖因此只留在 CLI 包装层,以后修只改一处。 +- **环境**(`SwiftSectionEnvironment`)注入生成器名、版本和当前时间。CLI 传 `swift-section` 和 `BundledVersion.value`,测试传固定值。 +- **库不依赖 ArgumentParser 和 Rainbow。** 库里的 enum(`Architecture`、`DumpSection`……)在 CLI 里用 `@retroactive` 补上 `ExpressibleByArgument`。 +- **CLI 保留的只有**:flag 声明(`--help` 文本逐字不变)、`validate()`(报错文案不变)、命令行拼写的解释(模板名或字面模板、`--transformer-config` JSON 文件、逗号分隔的列表、`--c-type-replacement` 的 `a=b` 串、demangle 覆盖开关)、flag → 请求的映射、库错误翻译回历史文案、诊断的流路由、着色、退出码。 +- **测试**:库这一侧,每个请求对 SymbolTestsCore fixture 端到端跑一遍,再加纯逻辑测试;CLI 这一侧,测 flag → 请求映射、错误翻译、流路由。新套件加进 CI 白名单。 + +### 两处行为偏差 + +除这两处外,stdout、stderr、退出码、每个子命令的 `--help` 全部逐字节不变。 + +1. **写流统一走 `fputs` / `fwrite`。** 只在流已经被关闭时有区别:`objc` 子命令不再因此 abort(Swift 侧本来就是这样)。 +2. **参数层面的错误改在打开二进制之前报出。** 命令行拼写现在由 CLI 解释,并且发生在调用库之前。受影响的错误有:输入 flag 的组合错误(缺文件路径、`-n` 与 `-p` 同时给、`--dyld-shared-cache` 缺镜像名)、模板名 / `--transformer-config`、C type 替换串。只写错一处时,报错文案和退出码不变,只是不必等二进制加载完;同时写错二进制路径和这类参数时,现在先报后者;`objc --verbose` 下,C type 替换串的错误前面不再有进度行。实现时又确认了同一原因的三个边角:`interface` 的「--supplementary-apinotes has no effect」警告在加载前发出;`snapshot` 给 snapshot JSON 输入时乱写 `--dyld-shared-cache` 现在报错;`snapshot` 对普通文件给 `-n` / `-p` 时 provenance 不再带上那个被忽略的镜像名(见决策日志)。 + +### 非目标 + +- **不改 CLI 行为**,上面两处偏差除外。`interface` 进度行与 `dump` 错误行打到 stdout 的怪癖原样保留。 +- **不迁移 MCP server**,见「后续工作」。 +- **不给库加 CLI 没有的能力**,例如以进程内 `MachOImage` 为输入、snapshot 输入直接给内存中的 document。`SnapshotSource` 是 enum,为后者留了位置。 +- **不动现有 product 的公开 API**,不动 `baseline-generator`。 +- **不在本提案里发版**。0.22.0 的发版说明到时补一条新 product。 + +### 后续工作 + +- 修掉两个输出怪癖:`interface` 进度行与 `dump` 错误行改到 stderr,同步改插件 skill 第 3 节。届时库里也不再有「写 stdout 的诊断」。 +- `MCP/swift-section-mcp` 改用 `SwiftSectionKit` 的 `MachOSource` 加载与各请求。 +- 诊断原文里还有 CLI 的 flag 名(例如 "warning: --resolve-c-module-names …"),可以随第一条一起改成中性措辞。 + +## 详细设计 + +### 模块与目录 + +```swift +// Package.swift +static let SwiftSectionKit = Target.target( + name: "SwiftSectionKit", + dependencies: [ + .target(.MachOFoundation), + .target(.SwiftDump), + .target(.SwiftInspection), + .target(.SwiftOutputTransformer), + .target(.SwiftDeclaration), + .target(.SwiftDeclarationRendering), + .target(.SwiftIndexing), + .target(.SwiftPrinting), + .target(.SwiftDiffing), + .target(.SwiftInterface), + .target(.TypeIndexing), + .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), + .product(name: "ObjCDiffing", package: "MachOObjCSection"), + .product(name: "ObjCIndexing", package: "MachOObjCSection"), + .product(name: "ObjCInterface", package: "MachOObjCSection"), + .product(name: "ObjCMetadataSource", package: "MachOObjCSection"), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), + // plus the products its sources import directly (Semantic, MachOKit, …) + ], + path: "Sources/Commands/SwiftSectionKit", +) + +static let swift_section = Target.executableTarget( + name: "swift-section", + dependencies: [ + .target(.SwiftSectionKit), + // what the wrapper itself names while mapping flags to requests + .target(.SwiftDump), + .target(.SwiftOutputTransformer), + .target(.SwiftIndexing), + .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), + .product(name: "Rainbow", package: "Rainbow"), + .product(name: "ArgumentParser", package: "swift-argument-parser"), + ], + path: "Sources/Executables/swift-section", +) +``` + +`products:` 加 `.library(.SwiftSectionKit)`;新增测试目标 `SwiftSectionKitTests`。`Sources/Commands/` 是新的一层分组:这个库是可执行文件背后那一层,放进 `Executables/` 名不副实。 + +### 输出端 + +```swift +// Sources/Commands/SwiftSectionKit/Output/SwiftSectionOutput.swift +import Foundation +import Semantic +import SwiftDeclaration + +/// Where a request's output goes. `swift-section` writes it to stdout and +/// stderr; a test records it. +/// +/// A request that indexes several inputs side by side calls this from several +/// tasks at once, so an implementation must be safe to call concurrently. +public protocol SwiftSectionOutput: Sendable { + /// One piece of the product, in order. Printed, every piece is followed + /// by a newline. + func write(_ product: SwiftSectionProduct) + + /// A progress line, warning, note or per-declaration error. + func report(_ diagnostic: SwiftSectionDiagnostic) + + /// The indexing-event handlers for one indexed input. `label` names the + /// input when a request indexes several ("old", "new", a version label), + /// and is `nil` for a single-input request. + func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] +} + +extension SwiftSectionOutput { + /// No handler: indexing degradations fall to `Dispatcher`'s os_log floor. + public func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] { + [] + } +} + +public enum SwiftSectionProduct: Sendable { + /// Rendered declarations (`dump`, `interface`, `objc dump`, + /// `objc interface`), carrying the semantic types a terminal colors by. + case declarations(SemanticString) + /// Plain text: reports, JSON, listings. + case text(String) + /// An annotated interface, whose lines a terminal colors by annotation. + case annotatedInterface(String, style: InterfaceAnnotationStyle) + /// Raw bytes: a snapshot document's JSON. + case data(Data) +} + +public enum InterfaceAnnotationStyle: Sendable, Hashable { + /// `diff --interface`. A unified diff also has two file-header lines and + /// `@@` hunk headers. + case diff(isUnifiedDiff: Bool) + /// `evolution --interface`: trailing `// [...]` lifecycle annotations and + /// column-0 legend comments. + case evolution +} + +/// What a terminal colors one annotated line as. +public enum AnnotatedLineKind: Sendable, Hashable { + case added + case removed + case modified + case header + case plain +} + +extension InterfaceAnnotationStyle { + /// The rule `swift-section` colors by, public so that every host colors + /// alike: one kind per line of `text`, split on "\n" keeping empty lines. + public func lineKinds(of text: String) -> [AnnotatedLineKind] +} + +public struct SwiftSectionDiagnostic: Sendable, Hashable { + public enum Severity: Sendable, Hashable, CaseIterable { + case progress + case warning + case note + case error + } + + public var severity: Severity + /// The line exactly as `swift-section` prints it. + public var message: String + + public init(severity: Severity, message: String) +} + +/// Where the product goes. +public enum ProductDestination: Sendable, Hashable { + /// To the request's `SwiftSectionOutput`. + case output + /// Into this file; the output then receives diagnostics only. + case file(URL) +} +``` + +「每块产物后面跟一个换行」这条语义是盘点出来的:现有的每处 stdout 写入都等于「内容 + 换行」。`print(x)` 如此;annotated interface 按行着色后逐行补换行,拼起来恰好也是「全文 + 换行」;`snapshot` 的 `fwrite` 加 `fputs("\n")` 同样如此。写文件时各命令的老规矩(`interface` / `diff` 不补换行、`evolution` 补、`dump` 每块补)由库自己处理,`.file` 目的地下不经过输出端。 + +### 输入 + +```swift +public enum Architecture: String, CaseIterable, Sendable, Hashable { + case x86_64 + case arm64 + case arm64e +} + +public enum DyldSharedCacheImage: Sendable, Hashable { + case name(String) + case path(String) +} + +/// Where a Mach-O image comes from. +public enum MachOSource: Sendable, Hashable { + /// A thin or fat Mach-O file; `architecture` picks a fat binary's slice. + case file(path: String, architecture: Architecture?) + /// One image of the dyld shared cache at `cachePath`. + case dyldSharedCache(cachePath: String, image: DyldSharedCacheImage) + /// One image of the running system's dyld shared cache. + case systemDyldSharedCache(image: DyldSharedCacheImage) +} + +extension MachOSource { + /// The loader every request shares (today's `MachOFile.load`). + public func load() throws -> MachOFile +} + +public enum MachOSourceError: Error, LocalizedError, Sendable, Equatable { + case fatBinaryRequiresArchitecture(availableArchitectures: [String]) + case architectureNotFound(Architecture) + case dyldSharedCacheImageNotFound(DyldSharedCacheImage) + case systemDyldSharedCacheUnavailable +} + +/// Where a snapshot comes from. +public enum SnapshotSource: Sendable, Hashable { + /// A snapshot document (JSON) or a binary, told apart by the file's first + /// non-whitespace byte, as the command line always has. + case path(String) +} + +public enum SnapshotSourceError: Error, LocalizedError, Sendable, Equatable { + /// An annotated interface renders from the live models; a snapshot + /// document carries none. + case binaryRequired(path: String) +} + +/// How `snapshot` / `diff` / `evolution` load a binary input. A snapshot +/// document input ignores it. +public struct BinaryLoadingOptions: Sendable, Hashable { + public var architecture: Architecture? + /// When set, every binary input is a dyld shared cache and this image is + /// extracted from each. + public var dyldSharedCacheImage: DyldSharedCacheImage? + + public init(architecture: Architecture? = nil, dyldSharedCacheImage: DyldSharedCacheImage? = nil) +} +``` + +今天的 `SwiftSectionCommandError` 里,缺文件路径、`-n` 与 `-p` 同时给、缺镜像名这三种在 `MachOSource` 上写不出来,留在 CLI,由 flag → `MachOSource` 的映射抛出,文案不变。`failedFetchFromSystemDyldSharedCache` 从来没有被抛出过,删掉。 + +### 环境 + +```swift +public struct GeneratorIdentity: Sendable, Hashable { + public var name: String + public var version: String + + public init(name: String, version: String) +} + +public struct SwiftSectionEnvironment: Sendable { + /// Stamped into interface headers and snapshot provenance. + public var generator: GeneratorIdentity + /// Stamped into snapshot provenance as `createdAt`. + public var currentDate: @Sendable () -> Date + + public init(generator: GeneratorIdentity, currentDate: @escaping @Sendable () -> Date = { Date() }) +} +``` + +`BundledVersion` 留在 `Sources/Executables/swift-section/Version.swift`,CI 两个 workflow 不用改。版本号标识的是工具而不是库,其他宿主应该盖上自己的名字。 + +### 请求类型 + +两个写全的例子: + +```swift +public struct DumpRequest: Sendable, Equatable { + public enum SectionSelection: Sendable, Hashable { + /// Every section; one the binary does not carry is skipped silently. + case all + /// These sections, in this order; one that fails to read is reported. + case only([DumpSection]) + } + + public enum Ordering: Sendable, Hashable { + /// Section by section. + case bySection + /// Types, protocols and `@objc @implementation` classes interleaved + /// by their offset in the binary, then conformances, then associated + /// types. + case binaryOrder + } + + public enum FieldOffsetComments: Sendable, Hashable { + case none + case flat + /// Nested struct fields expanded with their absolute offsets. + case expanded + } + + public var source: MachOSource + public var dependencySearchPaths: [DependencySearchPath] + public var sections: SectionSelection + public var ordering: Ordering + public var demangleOptions: DemangleOptions + public var fieldOffsetComments: FieldOffsetComments + public var emitsMemberAddresses: Bool + public var emitsVTableOffsets: Bool + public var emitsProtocolWitnessTableAddresses: Bool + public var emitsTypeLayout: Bool + public var emitsEnumLayout: Bool + public var emitsExportStatus: Bool + public var emitsHeader: Bool + public var commentTransformers: Transformer.SwiftConfiguration? + public var destination: ProductDestination + + public init(source: MachOSource) + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws +} + +public struct ABIDiffRequest: Sendable, Equatable { + public enum Report: Sendable, Hashable { + /// The change list followed by the verdict line. + case changeList + /// The verdict line alone. + case summary + /// The diff with provenance, as JSON. + case json + /// The full interface annotated with diff markers; both sides must be + /// binaries. With `includesBreakingChangeVerdict`, the outcome also + /// says whether the diff breaks the ABI, at the cost of a change-list + /// diff on top. + case annotatedInterface(format: AnnotatedDiffFormat, includesBreakingChangeVerdict: Bool) + } + + public var old: SnapshotSource + public var new: SnapshotSource + public var binaryLoading: BinaryLoadingOptions + public var report: Report + public var destination: ProductDestination + /// How many inputs index at once: `nil` is the processor count, and `1` + /// indexes the old side before the new one. + public var maximumConcurrentPreparations: Int? + + public init(old: SnapshotSource, new: SnapshotSource, report: Report) + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ABIDiffOutcome +} + +public enum AnnotatedDiffFormat: Sendable, Hashable { + case inline + case unified + case markdownFenced +} + +public struct ABIDiffOutcome: Sendable { + /// `nil` only for an annotated interface requested without the verdict. + public var diff: ABIDiff? + + public var hasBreakingChange: Bool? { + diff?.hasBreakingChange + } +} +``` + +其余请求: + +| 请求 | 对应子命令 | 字段(按用途建模之处加粗) | 返回 | +|---|---|---|---| +| `InterfaceRequest` | `interface` | `source`、`dependencySearchPaths`、`showsCImportedTypes`、`parsesOpaqueReturnTypes`、**`cModuleNameResolution: .disabled / .enabled(supplementaryAPINotesPaths:)`**、**`fieldOffsetComments: .none / .flat / .expanded`**、`emitsMemberAddresses`、`emitsVTableOffsets`、`emitsTypeLayout`、`emitsEnumLayout`、`emitsExportStatus`、`printsExportedDeclarationsOnly`、`memberSortOrder: SwiftDeclarationMemberSortOrder`、`infersObjCOverridesFromSelectorNames`、`emitsHeader`、`commentTransformers`、`destination` | — | +| `ABISnapshotRequest` | `snapshot` | `source: SnapshotSource`、`binaryLoading`、`dependencySearchPaths`(今天只交给 accessor thunk 读取器,索引器不用;照旧)、`label`、`destination` | `ABISnapshotDocument` | +| `ABIEvolutionRequest` | `evolution` | `inputs: [SnapshotSource]`、`labels: [String]?`、`binaryLoading`、**`report: .lineage / .summary / .json / .annotatedInterface`**、`destination`、`maximumConcurrentPreparations` | `ABIEvolutionOutcome`(`evolution`、`hasBreakingChange`) | +| `TransformerTokensRequest` / `TransformerTemplatesRequest` | `transformer tokens` / `templates` | `module: TransformerModule?`(`nil` 列出全部) | — | +| `TransformerConfigurationRequest` | `transformer config` | `configuration: Transformer.SwiftConfiguration`、`destination` | — | +| `ObjCDumpRequest` | `objc dump` | `source`、**`kinds: [ObjCDeclarationKind]?`**(`nil` 为全部,此时空的 kind 不提示)、`nameFilter`、`generation: ObjCGenerationOptions`、`cTypeReplacements: [ObjCPrimitiveTypePattern: String]`、`ivarOffsetComment: Transformer.ObjCIvarOffset?`(给了就隐含打开 ivar offset 注释)、`reportsIndexingProgress`、`imageDescription: String?`、`destination` | — | +| `ObjCInterfaceRequest` | `objc interface` | `declarationName`、`kind: ObjCDeclarationKind?`、`source`、`generation`、`cTypeReplacements`、`ivarOffsetComment`、`reportsIndexingProgress`、`destination` | — | +| `ObjCAPISnapshotRequest` | `objc snapshot` | `source: SnapshotSource`、`binaryLoading`、`label`、`destination`(ObjC 侧没有 `--dependency-search-path`) | `ObjCAPISnapshotDocument` | +| `ObjCAPIDiffRequest` | `objc diff` | `old`、`new`、`binaryLoading`、**`report: .changeList / .summary / .json`**、`destination` | `ObjCAPIDiffOutcome` | +| `ObjCAPIEvolutionRequest` | `objc evolution` | `inputs`、`labels`、`binaryLoading`、**`report: .lineage / .summary / .json`**、`destination` | `ObjCAPIEvolutionOutcome` | + +几处说明: + +- `DumpSection` 是今天的 `SwiftSection` 改名,`ObjCDeclarationKind` 是 `ObjCSectionKind` 改名。作为公开类型,旧名分别容易和包名、和 section 的概念混淆。rawValue 不变,所以 `--help` 里列出的取值不变。 +- `labels` 的个数校验在库里,抛出的仍是 `ABIEvolutionError.labelCountMismatch` / `ObjCAPIEvolutionError.labelCountMismatch`,文案和退出码不变;逗号拆分属于命令行拼写,留在 CLI。 +- `objc dump` 提示文案里的镜像名今天取「用户敲的写法」:`-n` → `-p` → 文件路径。`imageDescription` 让 CLI 照旧传这个值;不传时按 `source` 推导。 +- `--supplementary-apinotes` 不带 `--resolve-c-module-names` 时,在 `cModuleNameResolution` 上写不出来,所以那条 "has no effect" 警告改由 CLI 发出,原文不变。 +- `objc` 的 `diff` / `evolution` 今天逐个加载输入,库里保持不变。 + +### 错误 + +库抛出的错误用中性措辞(不提 flag 名)。CLI 在 `run()` 里捕获,翻译回历史文案: + +| 库错误 | CLI 打印(不变) | +|---|---| +| `MachOSourceError.fatBinaryRequiresArchitecture` | "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). …"(退出码 1) | +| `.architectureNotFound` / `.dyldSharedCacheImageNotFound` / `.systemDyldSharedCacheUnavailable` | `invalidArchitecture` / `imageNotFound` / `unsupportedSystemVersionForDyldSharedCache` 的原文(退出码 1) | +| `diff` 里的 `SnapshotSourceError.binaryRequired` | `ValidationError("--interface needs two binaries; snapshot JSON inputs only support the change-list report.")`(退出码 64) | +| `evolution` 里的 `SnapshotSourceError.binaryRequired(path:)` | `ValidationError("--interface needs binaries; snapshot JSON inputs () only support the lineage report.")`(退出码 64) | + +其他错误原样透传:snapshot 解码、写文件、MachOKit 读文件、`labelCountMismatch`,以及 `objc interface` 找不到声明("No class, protocol, category, struct or union named '…' in this binary.",本来就是中性措辞,库里保留原文)。 + +诊断不翻译:原文就是 CLI 的措辞,有些含 flag 名(例如 "warning: --supplementary-apinotes path does not exist: …")。这是选定「诊断 = 级别 + 原文」的直接结果,列在「后续工作」里。 + +### CLI 包装层长什么样 + +```swift +// Sources/Executables/swift-section/Commands/DiffCommand.swift (after) +struct DiffCommand: AsyncParsableCommand { + // every @Argument / @Option / @Flag declaration unchanged + + func validate() throws { + // unchanged + } + + /// The library request these flags describe. + func makeRequest() -> ABIDiffRequest { + let report: ABIDiffRequest.Report + if interface { + report = .annotatedInterface( + format: (format ?? .inline).annotatedDiffFormat, + includesBreakingChangeVerdict: failOnBreaking + ) + } else if json { + report = .json + } else if summaryOnly { + report = .summary + } else { + report = .changeList + } + // validate() has already required exactly one of -n / -p with --dyld-shared-cache + let cacheImage: DyldSharedCacheImage? = cacheImageName.map { .name($0) } ?? cacheImagePath.map { .path($0) } + var request = ABIDiffRequest(old: .path(oldPath), new: .path(newPath), report: report) + request.binaryLoading = BinaryLoadingOptions( + architecture: architecture, + dyldSharedCacheImage: isDyldSharedCache ? cacheImage : nil + ) + request.destination = outputPath.map { .file(URL(fileURLWithPath: $0)) } ?? .output + request.maximumConcurrentPreparations = jobs + return request + } + + func run() async throws { + let outcome = try await CommandLineErrorTranslation.translating(for: Self.self) { + try await makeRequest().run(output: StandardStreamOutput(), environment: .commandLine) + } + if failOnBreaking, outcome.hasBreakingChange == true { + throw ExitCode.failure + } + } +} +``` + +```swift +// Sources/Executables/swift-section/Output/StandardStreamOutput.swift +/// Writes a request's output where `swift-section` has always written it: +/// the product to stdout, diagnostics to stderr, except the severities a +/// command lists in `standardOutputSeverities`. +struct StandardStreamOutput: SwiftSectionOutput { + var colorScheme: SemanticColorScheme = .none + /// `interface` prints its progress lines on stdout and `dump` its + /// per-declaration errors. Both are historical and kept for byte-identical + /// output; see the proposal's follow-up work. + var standardOutputSeverities: Set = [] + + func write(_ product: SwiftSectionProduct) { + // fputs / fwrite to stdout, every piece followed by "\n"; + // declarations colored by colorScheme, annotated lines by lineKinds(of:) + } + + func report(_ diagnostic: SwiftSectionDiagnostic) { + // stdout when standardOutputSeverities contains the severity, else stderr; + // an .error on stdout is red, as dump's error lines are today + } + + func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] { + [ConsoleEventHandler(label: label)] + } +} +``` + +`StandardStreamOutput` 写入的两个 `FILE*` 可以注入,测试拿 `open_memstream` 读回字节。 + +### 文件去向 + +| 现在 | 去向 | +|---|---| +| `Commands/*.swift` 与 `ObjC/Commands/*.swift` 的 `run()` 主体 | `SwiftSectionKit/Swift/*Request.swift`、`SwiftSectionKit/ObjC/*Request.swift`;命令文件只留 flag、`validate()`、`makeRequest()`、`run()` 的三五行 | +| `Utilities/Extensions.swift` 的 `MachOFile.load` | `SwiftSectionKit/Inputs/MachOSource.swift` | +| `Utilities/Extensions.swift` 的配色与 `printColorfully` | `swift-section/Output/StandardStreamOutput.swift` | +| `Utilities/ABISnapshotInputLoader.swift`、`ObjC/Utilities/ObjCSnapshotInputLoader.swift` | `SwiftSectionKit/Inputs/`,两份嗅探代码合成一份 | +| `ObjC/Utilities/ObjCInterfaceSession.swift` | `SwiftSectionKit/ObjC/`(internal) | +| `ObjC/Utilities/StandardErrorLog.swift` | 删除,由 `StandardStreamOutput` 取代 | +| `Utilities/IgnoreCoding.swift` | 删除(没有调用方) | +| `ObjCDumpCommand.diagnosticNotes(for:)` 与 `Outcome` | `SwiftSectionKit/ObjC/`,`ObjCDumpDiagnosticsTests` 随之搬进 `SwiftSectionKitTests` | +| `TransformerCommand.swift` 的 `TransformerModuleSelector` 与列表格式化 | `SwiftSectionKit/Swift/`(`TransformerModule` 与三个请求) | +| `Models/Architecture.swift`、`SwiftSection.swift`、`ObjC/Models/ObjCSectionKind.swift` | `SwiftSectionKit`(`Architecture`、`DumpSection`、`ObjCDeclarationKind`),`ExpressibleByArgument` 留在 CLI | +| `Models/*OptionGroup.swift`、`ObjC/Models/*OptionGroup.swift`、`ObjCSectionKindList.swift`、`SemanticColorScheme.swift`、`Version.swift` | 留在 CLI | +| `Models/SwiftSectionCommandError.swift`、`ObjC/Models/ObjCSectionCommandError.swift` | 留在 CLI,只装历史文案(翻译目标、C type 替换串错误);`declarationNotFound` 移到库 | + +`DumpCommand` 里逐类型 dump 的辅助函数标着 `@MainActor`,搬进库时去掉:循环本来就是顺序执行,去掉不影响输出顺序,而且库的入口不该要求调用方在 main actor 上。 + +### 测试 + +- **`SwiftSectionKitTests`(新)**:内存记录器 `RecordingOutput` 按调用顺序记下产物和诊断。对 SymbolTestsCore fixture 跑每个请求: + - `dump`:默认 section 与显式 section 的报错差异、两种排序、`.file` 目的地写出的字节、固定生成器下的 header、注释开关与模板配置生效、`objcImplementationClasses` 为空时的提示。 + - `interface`:带与不带 header 时的 progress 顺序、`.file` 目的地。 + - `snapshot`:返回的 document、固定时间与版本的 provenance、重贴 snapshot JSON 的标签。 + - `diff` / `evolution`:fixture 对自身无变化、snapshot 与二进制混用、四种报告、annotated interface 遇到 snapshot 输入抛 `SnapshotSourceError`、标签个数不符。 + - `transformer` 的三个列表;`objc` 五个请求。 + - 纯逻辑:`MachOSource` 的各个错误路径、`lineKinds(of:)` 的着色分类、合并后的 snapshot 嗅探。 + - fixture 的 `ExclusiveImageAccess` 声明照现有 fixture 套件的做法来。 +- **`SwiftSectionCommandTests`(保留并补充)**:现有解析测试不动(类型改名处随改)。新增:每个命令「解析 flag → `makeRequest()` → 与期望请求比较」、错误翻译(库错误 → 历史文案与退出码)、`StandardStreamOutput` 的流路由与换行语义、流已关闭时不 abort。 +- **源码扫描**:`PrintFailureEventTests` 不改豁免名单,靠它保证 `SwiftSectionKit` 里没有任何进程流写入。 +- **CI**:新套件名加进 `macOS.yml` 的白名单。 + +### 验收 + +1. `swift test --skip IntegrationTests` 的原始退出码为 0(全量,不只 CI 子集)。 +2. A/B 对比脚本:基准为 `next`,候选为本分支,`dump` 与 `interface` 逐字节一致。 +3. 新旧两个二进制逐字节对比 A/B 脚本覆盖不到的部分:根命令与每个子命令的 `--help` 和 `--version`;`snapshot` / `diff` / `evolution` 的各种报告(JSON 去掉 `createdAt` 后比);`transformer` 三个子命令;`objc` 五个子命令;若干错误路径(文件不存在、胖二进制没给 `-a`、flag 组合错误)。比较 stdout、stderr 和退出码,凡有差异逐条解释,只允许出现「两处行为偏差」里的那两类。这个对比脚本写完先给用户看再跑。 +4. `SwiftSectionKit` 能为包声明的每个平台编译(macOS、iOS、tvOS、watchOS、visionOS),因为它现在是对外 product。 +5. 插件 skill 里点名的每个 flag 在 `--help` 里都还在(`grep -ohE -- '--[a-z][a-z0-9-]+'`)。CLI 行为不变,skill 本身不用改。 + +## 替代方案考量 + +- **仅包内可见的 target(`package` 访问级别,不进 products)**:不新增对外契约,以后要复用再升格。**用户否决**,选择直接做成对外 product。 +- **只抽 Swift 侧、`objc` 以后再说**:**用户否决**,要一次性让整个 CLI 层变薄。 +- **请求返回完整结果值、CLI 再打印**:测试最直接,但 `dump` 大框架要等全部算完才出第一行,错误与正文的穿插顺序也要另外记录。**用户否决。** +- **请求字段一比一镜像 flag**(`json: Bool`、`summaryOnly: Bool`,校验和报错一起搬进库):搬迁最省事,但库的 API 带着命令行的味道,非法组合写得出来,程序调用方还会收到提到 `--json` 的报错。**用户否决。** +- **结构化诊断事件**(每种诊断一个带数据的 enum case):调用方能按数据处理,但 public enum 每加一个 case 对下游都是源码破坏。**用户否决。** +- **输出端照搬两个流**(`standardOutput` / `standardError`):最简单,但程序调用方拿到的产物里会混进 `interface` 的进度行。**用户否决。** +- **在这次改动里顺手修掉输出怪癖**:重构和行为变化混在一起,A/B 对比就没法当验收证据了。**用户否决**,列为后续工作。 +- **不重构,测试时启动编好的可执行文件、抓它的输出**:测试拿不到可靠的二进制路径,每个用例起一个进程很慢,没法注入时间和版本,也给不出程序化 API。不采用。 +- **把 `BundledVersion` 搬进库**:要改两个 CI workflow 里写死的路径,而且版本号标识的是工具。不采用。 +- **把命令行拼写的解释(模板名、C type 替换串等)也搬进库**:好处是「参数错误先于加载报出」这处偏差不会出现。代价是要么让请求携带未解析的字符串(又回到镜像 flag),要么在公开 API 里带上 CLI 的 option 名作报错文案。不采用,偏差留档在「两处行为偏差」。 +- **迁移 MCP server**:**用户选定不在本次范围**,列为后续工作。 + +## 影响 + +### 源码兼容性(source compatibility) + +- **库 API:纯新增。** 新增 product `SwiftSectionKit`;现有 product 的公开 API 一个都不变。 +- **命令行:除「两处行为偏差」外不变。** flag、`--help`、stdout、stderr、退出码保持原样。 + +### ABI 兼容性(条件项) + +不适用 —— 本库以 SPM 源码分发,使用方每次重新编译。 + +### 下游影响 + +- 本仓库内:`swift-section` 可执行目标、`SwiftSectionCommandTests`、新增的 `SwiftSectionKit` 与 `SwiftSectionKitTests`、`Package.swift`、`macOS.yml` 的白名单。`release.yml` / `version-check.yml` 不变。 +- 下游仓库:没有一个必须改。RuntimeViewer、MachOKitUI、SymbolViewer 不依赖新 product。`MCP/swift-section-mcp` 以后可以改用它(后续工作)。 + +### 文档与示例 + +- 新增使用指南 `Documentations/SwiftSectionKit.md`(英文)与 `SwiftSectionKit_zh.md`。调用方要遵守的约定从签名上看不出来,所以要写指南:输出端会被并发调用;每块产物后跟换行的语义;诊断原文是 CLI 措辞;哪些错误该由宿主自己翻译。 +- 新增模块文档 `Documentations/Internal/Modules/SwiftSectionKit.md`。 +- `AGENTS.md`:模块依赖图加上 `swift-section → SwiftSectionKit`、模块说明加一条、`Sources/` 分组清单加 `Commands/`;再写一条 agent 默认会做错的规矩——命令的新逻辑写进 `SwiftSectionKit`,CLI 只做 flag 映射、错误翻译和流路由。 +- README:product 表加一行,并给一段用法示例。 +- `Documentations/README.md` 索引、`Evolutions/README.md` 状态表、`ProjectEvolutionLog`。 + +## API 演进与废弃策略 + +- 没有被替代的旧 API,不需要 `@available(*, deprecated)`,也不需要 semver major 跃迁。 +- 以后给请求加字段一律带默认值,保持源码兼容。`Report` 这类调用方会构造的 enum 加 case,对 `switch` 它们的下游是源码破坏。指南里写明这类 enum 是「供构造的」,不承诺可以穷举 `switch`。 + +## 落地步骤 + +每一步都单独构建通过,现有测试保持绿色。 + +1. **骨架**:`Package.swift` 加 target、product 与测试目标;搬入 `Architecture` / `DumpSection` / `ObjCDeclarationKind`,CLI 补 `@retroactive ExpressibleByArgument`。 +2. **地基**:输出端、诊断、环境、`MachOSource` 与 snapshot 输入加载;CLI 侧的 `StandardStreamOutput` 与错误翻译。 +3. **逐个搬命令**:`transformer` → `snapshot` → `diff` → `evolution` → `dump` → `interface` → `objc` 五个。每搬一个,构建并跑 `SwiftSectionCommandTests`。 +4. **测试**:`SwiftSectionKitTests` 全部套件,CLI 侧的映射、翻译与路由测试;CI 白名单。 +5. **验收**:按「验收」一节逐条做,结果记进决策日志。 +6. **文档**:按「文档与示例」一节写齐。 +7. **落地**:分配编号、状态改为 Implemented、写演进账本,合进 `next`(推送与否由用户定)。 + +**收尾时必须判断两件事**(判断结果写进决策日志,不允许沉默跳过): + +- **要不要配套专题文章** —— 计划中的使用指南已经满足「有从签名看不出来的调用方契约」这一判据;实现过程中若出现代码里看不出来的决策,另写实现说明或并入模块文档。 +- **有没有引入新术语** —— 预计没有;落地时确认。 + +## 决策日志 + +| 日期 | 变更 | 说明 | +|------|------|------| +| 2026-10-03 | Created as Draft | 用户原话:「把swift-section CLI的功能抽出来,方便进行测试,CLI层只是一层包装」 | +| 2026-10-03 | 定为完整档(大型重构),三轮澄清提问(最后一轮含收尾确认)后成稿 | — | +| 2026-10-03 | 做成对外发布的 product | 用户选定(推荐的是仅包内可见 + `package` 访问级别) | +| 2026-10-03 | 范围:全部子命令,含 `objc` 五个 | 用户选定 | +| 2026-10-03 | 输出逐字节保持,只统一写流方式;怪癖记为后续 | 用户选定 | +| 2026-10-03 | 输出走注入的输出端,不用返回值 | 用户选定;`dump` 要边算边输出 | +| 2026-10-03 | 模块名 `SwiftSectionKit`,放 `Sources/Commands/` | 用户选定 | +| 2026-10-03 | 公开 API 按用途建模;flag 组合的校验与原报错留在 CLI 的 `validate()` | 用户选定 | +| 2026-10-03 | 测试:每个子命令端到端 + 纯逻辑,新套件进 CI | 用户选定 | +| 2026-10-03 | MCP server 不在本次范围 | 用户选定,列为后续工作 | +| 2026-10-03 | 诊断 = 级别 + CLI 原文 | 用户选定 | +| 2026-10-03 | 版本号留在 CLI、经环境注入;库错误用中性措辞、由 CLI 翻译回原文;退出码由 CLI 决定;索引事件 handler 注入;源码扫描覆盖新模块;删 `IgnoreCoding.swift`;验收方式;文档清单;worktree 与分支 | 我提出,用户确认 | +| 2026-10-03 | 成稿时细化、待评审确认的四处:(1) 命令行拼写的解释留在 CLI,库只收解析好的值,由此带来第二处行为偏差「参数错误先于加载报出」;(2) 预览里的 `failsOnBreakingChange` 改为 `.annotatedInterface(format:includesBreakingChangeVerdict:)`,库只报告结论,退出码由 CLI 定;(3) 诊断原文保留 CLI 措辞(部分含 flag 名),只有抛出的错误用中性措辞;(4) `SwiftSection` / `ObjCSectionKind` 作为公开类型改名为 `DumpSection` / `ObjCDeclarationKind`,`objc dump` 的 `imageDescription` 改为显式字段 | 写详细设计时发现;(1)(3) 是「逐字节保持」与「按用途建模」两条选定碰到一起的结果 | +| 2026-10-03 | Draft → Accepted → In Progress | 用户回复「开工」,批准提案(含上一行四处细化) | +| 2026-10-03 | 实现偏差:`ProductDestination.file(URL)` 改为 `.file(path: String)` | 「Report written to …」这类诊断要逐字复述调用方的拼写;实测 `URL(fileURLWithPath:)` 把 `dir/` 规整成 `dir`、把 `~/x` 展开成家目录路径。写文件时照旧经 `URL(fileURLWithPath:)`,行为不变 | +| 2026-10-03 | 实现偏差:偏差 2 比提案写的多出三个边角,另有一处怪癖随之消失 | 都来自「命令行拼写在调用库之前解释」:`interface` 的「--supplementary-apinotes has no effect」警告在加载前发出(加载失败时也会出现);`snapshot` 给 snapshot JSON 输入时乱写 `--dyld-shared-cache`(缺镜像名或 `-n` / `-p` 同给)现在报错,以前因为没走到加载而被忽略;`objc --verbose` 下 C type 替换串的错误前不再有进度行。`snapshot` 对普通文件给 `-n` / `-p`(帮助里写明会被忽略)时,provenance 的 `binaryPath` 不再带上那个没用到的镜像名。全部是误用或一条命令行里两处写错的情形,正文「两处行为偏差」已同步 | +| 2026-10-03 | 实现细节:`transformer` 的三个请求 `run(output:)` 不收环境;`ObjCDumpRequest.run` 返回 `Outcome`,`diagnosticNotes(for:)` 公开 | 前者不往产物里盖任何东西;后者让宿主拿到「找到了什么」,测试也直接用它(`ObjCDumpDiagnosticsTests` 从 CLI 测试目标搬到 `SwiftSectionKitTests`) | +| 2026-10-03 | 实现细节:`ExpressibleByArgument` 不加 `@retroactive` | 编译器指出库与可执行文件同包,不算 retroactive conformance | +| 2026-10-03 | 偏差 1 的实测证据 | 旧二进制 `swift-section objc dump --sections unions 2>&-` 退出码 134(写 stderr 时 abort),新的是 0。`CommandLineStreamWriteScanTests` 在 `next` 的源码上会命中 `ObjCSnapshotCommand.swift:37-38`、`StandardErrorLog.swift:10` 三处 `FileHandle` 写入和几十处直接 `print`,在本分支上为空——整类挡住,不只修已发现的几处 | +| 2026-10-03 | 测试落地 | `SwiftSectionKitTests` 52 个(`MachOSourceTests`、`InterfaceAnnotationStyleTests`、`TransformerRequestTests`、`ABIRequestTests`、`DumpAndInterfaceRequestTests`、`ObjCRequestTests`,加搬来的 `ObjCDumpDiagnosticsTests`),`SwiftSectionCommandTests` 新增 `CommandRequestMappingTests`、`CommandLineErrorTranslationTests`、`StandardStreamOutputTests`、`CommandLineStreamWriteScanTests`,两个目标合计 151 个,原始退出码 0;新套件全部加进 `macOS.yml` 白名单。`ABIRequestTests` 整个套件共用一份 fixture 的 snapshot 文档,耗时 32 秒 → 17 秒;「模板打开注释种类」改用 member address 模板,避开静态布局引擎(单条 46 秒 → 约 1 秒)。胖二进制测试用 fixture 现场拼单切片胖文件,不依赖宿主 | +| 2026-10-03 | 抽查:`--help` 与 fixture 上的 dump / interface | 根命令与 15 个子命令的 `--help` 新旧逐字节一致;fixture 上 `dump`(默认、带 header 与注释开关)、`interface`(默认、带 header 与 offset 注释)stdout 一致,stderr 只差 `ConsoleEventHandler` 行首时间戳 | +| 2026-10-03 | 验收 1:全量测试 | `swift test --skip IntegrationTests`(Ultra,Xcode 27 / Swift 6.4,`USING_LOCAL_DEPENDENCIES=1`)原始退出码 0:20 批、2240 个测试、422 个套件全部通过,含覆盖新模块的 `PrintFailureEventTests` 源码扫描与 `ContinuousIntegrationTestFilterTests` | +| 2026-10-03 | 验收 2:A/B 对比 | `run-rendering-ab-verification.py --skip-build --skip-image-part`,两侧都是从源码编出的 release 二进制(基准为 `next` 5ec73b2e):归档 cache 15.5 / 26.6 与模拟器 iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5,68 对 dump / interface 逐字节一致;iOS 15.5 模拟器的 SwiftUI、WidgetKit 共 4 对两侧同样以信号 5 退出,是 `next` 上原有的问题,脚本按「两侧同败」跳过。MachOImage 一腿不经过 CLI、走的库代码这次没动,跳过 | +| 2026-10-03 | 验收 4:各平台编译 | `SwiftSectionKit` 能为 iOS 15.0、tvOS 15.0、watchOS 9.0(原生构建系统交叉编译)与 visionOS 2.0(Swift Build)编译,新模块零警告。Xcode 27 的 Swift Build 拒绝包声明的 iOS 13.0 下限(只支持 15.0 起),原生构建系统又不认 xros triple,所以平台版本按工具链能接受的取——这是整个包的部署下限问题,与本改动无关,未在此处理 | +| 2026-10-03 | 验收 5:插件 skill 的 flag | skill 与 `references/` 里点名的每个 flag 都出现在新二进制的 `--help` 里;CLI 行为不变,skill 不需要改 | +| 2026-10-03 | 验收 3:新旧二进制逐字节对比 | 用户批准后跑一次性脚本(仓库外,不提交),93 条命令行(覆盖全部子命令的主要 flag、`-o`、各种报告、`objc` 五个子命令、错误路径与每个子命令的 `--help`),比较 stdout、stderr、退出码与 `-o` 写出的文件,抹掉时间戳与 `createdAt`。83 条一致;7 条只差 stderr 上 `[old]` / `[new]` 事件行的先后与「symbol index」计数落在哪一侧——旧二进制自己连跑四次也各不相同(两侧并发索引,谁先建好共享的符号索引不定),加 `--jobs 1` 让两侧按顺序索引后 7 条全部一致;剩下 3 条都属偏差 2:`dump-two-mistakes`(故意写错两处,退出码 1 → 64,先报模板名)、`dump-missing-image-name` 与 `snapshot-cache-without-image`(对不是 cache 的文件加 `--dyld-shared-cache` 又不给镜像名:旧版先打开文件报 `invalidMagic`,新版先报缺镜像名,`snapshot` 也不再先打出「Indexing …」) | +| 2026-10-03 | rebase 到 `next` 9eb05245 | 开工后 `next` 多了一个提交(MachOObjCSection 下限抬到 0.8.108),改的是依赖声明与演进账本,与本改动不重叠,rebase 无冲突 | +| 2026-10-03 | 收尾判断:配套文档与术语 | 使用指南已写(`SwiftSectionKit.md` / `_zh`,输出端契约从协议签名上看不出来,符合写指南的判据),模块文档已写,均登记在头部;实现上的决策都记在本日志与模块文档里,不另写实现说明。没有引入需要登记的新术语:「请求」「输出端」是普通说法,`SwiftSectionKit` 是模块名 | +| 2026-10-03 | In Progress → Implemented,落地编号 0058 | 取 `origin/next`(0057)与 `origin/main`(0054)的最大号加一;同批写演进账本第 77 节,合进 `next` | diff --git a/Documentations/Evolutions/0059-dump-declaration-identity.md b/Documentations/Evolutions/0059-dump-declaration-identity.md new file mode 100644 index 000000000..24d27c10a --- /dev/null +++ b/Documentations/Evolutions/0059-dump-declaration-identity.md @@ -0,0 +1,79 @@ +# 0059 - SwiftSectionKit:dump 把每个声明的种类与名字一并交给输出端 + +- **状态**: Implemented +- **创建日期**: 2026-10-04 +- **最后更新**: 2026-10-04 +- **关联提案**: [0058](0058-swift-section-kit.md)(SwiftSectionKit 本身;本提案只给它的输出端加一条通道) +- **实现分支 / PR**: `feature/dump-declaration-identity`(worktree `.worktrees/MachOSwiftSection-DumpDeclarationIdentity`,基于 `next`),按本仓库惯例在本地合并进 `next` +- **配套文档**: 使用指南 [SwiftSectionKit.md](../SwiftSectionKit.md) / [SwiftSectionKit_zh.md](../SwiftSectionKit_zh.md) 的「输出端契约」;模块文档 [Modules/SwiftSectionKit.md](../Internal/Modules/SwiftSectionKit.md) 的「1. 输出端」 + +## 摘要 + +`DumpRequest` 和 `ObjCDumpRequest` 把每个顶层声明当作一块 `.declarations` 产物交给输出端,却不说这块是什么、叫什么。宿主要按声明拆文件就做不到,只能自己再建一遍索引、重写一遍 dump 的编排——这正是 SwiftSectionKit 要消灭的重复。第一个撞上的宿主是 ReverseEngineeringToolbox:它的 dump 服务要改用 SwiftSectionKit,而它默认「每个类型一个文件」(`NSView.h`、`NSView+Animation.h`、`NSObject+Protocol.h`,Swift 的 conformance 并进它所扩展的类型的文件)。本提案让这两个请求交出声明时附上种类与名字:`SwiftSectionOutput` 新增一个带默认实现的方法来接收,默认实现转给 `write(_:)`,所以 `swift-section` 和只实现 `write(_:)` 的宿主,输出逐字节不变。 + +## 方案 + +**新类型**(`Sources/Commands/SwiftSectionKit/Output/`): + +```swift +/// What one top-level piece of a `dump` or `objc dump` product declares. +public enum DumpedDeclaration: Sendable, Hashable { + /// A Swift declaration, from `section`. A conformance and an associated + /// type are named after the type they extend. `name` is `nil` when the + /// name could not be rendered although the declaration itself was. + case swift(DumpSection, name: String?) + /// An Objective-C declaration. A category is named + /// `ClassName(CategoryName)`, as the index names it. + case objc(ObjCDeclarationKind, name: String) +} +``` + +**输出端**:`SwiftSectionOutput` 加一条协议要求,扩展里给默认实现(转给 `write(_:)`)。做成协议要求而不是只放在扩展里,是为了经 `some SwiftSectionOutput` 调用时动态派发到宿主的实现。 + +```swift +/// One top-level declaration of a `dump` or `objc dump`, with what it +/// declares. The default hands `product` to `write(_:)`. +func write(_ product: SwiftSectionProduct, declaring declaration: DumpedDeclaration) +``` + +**两个请求怎么交**(只在 `destination: .output` 时;写文件时产物不经过输出端,照旧): + +- `DumpRequest`:每个 dump 成功的顶层声明改走 `write(.declarations(…), declaring: .swift(section, name:))`。名字就是 dump 打印的那个:type、protocol、`@objc @implementation` 类取 `dumpName`;conformance 取它 `extension` 那一行的完整拼法(`dumpedTypeName(isFull: true, …)`),associated type 取 `dumpTypeName`(与它的 `extension` 行同一个函数);都用和 dump 同一份 `DumperConfiguration`。名字在 dump 成功之后才算;算名字失败只把 `name` 置 `nil`,不报诊断(否则 CLI 的 stdout 会多出错误行)。header 与「No @objc @implementation classes recognized」那行注释不是声明,照旧走 `write(_:)`。`.bySection` 与 `.binaryOrder` 都覆盖。 +- `ObjCDumpRequest`:每个声明改走 `write(.declarations(interface), declaring: .objc(kind, name: name))`;后面那个 `.text("")` 空行照旧走 `write(_:)`。 +- `InterfaceRequest`、`ObjCInterfaceRequest` 不动:产物只有一块。 + +**假设(未问)**: + +- 名字一律算,不加开关。代价是每个 Swift 声明多解析一次名字(dumper 内部本来就解析一次),CLI 用不上也要付。落地前用 `swift-section dump` 跑一个大镜像(宿主 cache 里的 `SwiftUICore`)比较前后耗时,差别明显就改成请求上的开关,并记进决策日志。 +- 名字用 `String` 而不是 `SemanticString`:它是给宿主认声明用的,不是用来显示的。 +- 只覆盖 `dump` 与 `objc dump`。`snapshot` / `diff` / `evolution` 的产物不是按声明分块的,不在范围内。 + +**源码兼容性**:纯新增。协议新要求带默认实现,现有 conformer(`StandardStreamOutput`、测试里的 `RecordingOutput`、下游宿主)不改照样编译;`SwiftSectionProduct` 不加 case,`switch` 它的宿主不受影响。`DumpedDeclaration` 是宿主消费的 enum,以后加 case 对穷举 `switch` 它的宿主是源码破坏——使用指南里写明不承诺可穷举,与 `DumpSection` 等一致。 + +**测试**(`SwiftSectionKitTests`,SymbolTestsCore fixture): + +- `RecordingOutput` 记下每块产物附带的声明。 +- `DumpRequest`:每块 `.declarations` 都带声明,且与只实现 `write(_:)` 的输出端收到的那些块逐一相同;类型与它的 conformance 同名(一个枚举、一个泛型结构体、一个文件级 private 结构体);protocol 按声明命名;associated type 以见证它的类型命名;`.binaryOrder` 下声明集合与 `.bySection` 相同;header 那块不带声明。 +- `ObjCDumpRequest`:桥接类以 `.objc(.classes, name: "SymbolTestsCoreObjCBridgeClass")` 交出;声明顺序与产物顺序一致。 +- 默认实现:一个只实现 `write(_:)` 的输出端收到的 `printedProduct` 与改动前相同(现有的 dump / objc 测试原样保留并通过即证明)。 +- `SwiftSectionCommandTests` 全绿,CLI 输出不变。 +- 先写测试、确认在改动前编译失败或断言失败,再实现。 + +**文档**:使用指南 `SwiftSectionKit.md` / `SwiftSectionKit_zh.md` 的「输出端契约」加一条;模块文档 `Internal/Modules/SwiftSectionKit.md` 的「1. 输出端」与「6. 测试锚点」;`Evolutions/README.md` 状态表;落地时演进账本。 + +**不做**:给 `swift-section` 加按声明拆文件的 flag;`Architecture` 补 `arm64e.x1`(本仓库要求的 MachOKit 0.52.x 不认这个子类型)。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-04 | Created as Draft | ReverseEngineeringToolbox 改用 SwiftSectionKit 时,用户:「不要自己重写dump逻辑」;被问到按类型拆文件怎么办时,用户选「先补 SwiftSectionKit」 | +| 2026-10-04 | 走轻量档 | 公开 API 纯新增,不改现有行为 | +| 2026-10-04 | 新增带默认实现的输出端方法,不给 `SwiftSectionProduct` 加 case | 加 case 会让每个穷举 `switch` 它的宿主编不过(CLI 的 `StandardStreamOutput`、测试的 `RecordingOutput` 都是);默认实现转给 `write(_:)`,不关心声明的宿主一行不改 | +| 2026-10-04 | Draft → Accepted | 用户批准:「开工」 | +| 2026-10-04 | Accepted → In Progress | 开始实现 | +| 2026-10-04 | conformance 的名字取 `extension` 行的完整拼法,不用公开的 `dumpTypeName` | 实测:文件级 private 类型 `AlphaProtocolWitness` 的类型名是 `SymbolTestsCore.(AlphaProtocolWitness in _82F1…)`,`dumpTypeName` 按 interface-type 选项打印、去掉了判别符,得到 `SymbolTestsCore.AlphaProtocolWitness`,宿主会把类型和它的 conformance 分进两个文件。`filePrivateTypeAndConformanceShareName` 钉住;换回 `dumpTypeName` 的单点变异实测变红 | +| 2026-10-04 | 名字一律算,不加开关 | 实测(release,JHs-Mac-Studio-Ultra,macOS 27.0 宿主 cache 的 SwiftUICore,输出 8.5 MB,两侧交替各跑三次):改动前 53.02 / 53.43 / 52.83 秒,改动后 55.48 / 53.49 / 54.50 秒,中位数慢 2.8%(约 1.5 秒)。为这点差别再加一个必须和 `write(_:declaring:)` 配对打开的开关不值得;三次的 stdout 两侧逐字节相同 | +| 2026-10-04 | 验证 | `SwiftSectionKitTests` 60 个(新增 8 个)、`SwiftSectionCommandTests` 99 个、`PrintFailureEventTests` / `ContinuousIntegrationTestFilterTests` / `CommandLineStreamWriteScanTests` 全部通过,原始退出码 0。新增的 Swift 测试先在只加了类型与默认实现时运行,7 个全红、原有测试全绿,实现后转绿;ObjC 那条同样先红后绿。命令行逐字节对照(`git archive` 导出的 `next` 与本分支,各自 release 编译):`dump` libswiftObservation、SwiftUICore,`objc dump` AppKit(5.9 MB),stdout 与 stderr 全部一致 | +| 2026-10-04 | In Progress → Implemented,编号 0059 | 按共享分支编号(origin/next 最大为 0058,origin/main 为 0054),合入 `next`;演进账本第 78 节 | +| 2026-10-04 | 收尾判断:不另写专题文档;无新术语 | 调用方要遵守的约定(默认实现、只在 `.output` 时给名字、conformance 的拼法)已写进使用指南的「输出端契约」与模块文档,没有再值得单列的实现决策;`DumpedDeclaration` 是标识符,不是自造词,术语表不登记 | diff --git a/Documentations/Evolutions/0060-evolution-interface-available-annotations.md b/Documentations/Evolutions/0060-evolution-interface-available-annotations.md new file mode 100644 index 000000000..4aff12f14 --- /dev/null +++ b/Documentations/Evolutions/0060-evolution-interface-available-annotations.md @@ -0,0 +1,50 @@ +# 0060 - evolution 联合接口的 @available 生命周期标注 + +- **状态**: Implemented +- **创建日期**: 2026-08-31 +- **最后更新**: 2026-10-05 +- **关联提案**: [0013](0013-swift-evolution-interface-builder.md)(evolution 联合接口本身,以及它否决过的伪 `@available` 形态)、[0058](0058-swift-section-kit.md)(命令行逻辑所在的 SwiftSectionKit) +- **实现分支 / PR**: `feature/evolution-interface-available-annotations`(worktree `.worktrees/MachOSwiftSection-EvolutionAvailableAnnotations`,基于 `next`),按本仓库惯例在本地合并进 `next` +- **配套文档**: 模块文档 [Modules/SwiftInterface.md](../Internal/Modules/SwiftInterface.md)「子系统 5」与「消费入口速查」、[Modules/SwiftSectionKit.md](../Internal/Modules/SwiftSectionKit.md);使用指南 [SwiftSectionKit.md](../SwiftSectionKit.md) / [SwiftSectionKit_zh.md](../SwiftSectionKit_zh.md) 的「Errors / 错误」;任务报告 [TaskReports/2026-08-31-evolution-interface-available-annotations.md](../Internal/TaskReports/2026-08-31-evolution-interface-available-annotations.md) + +## 摘要 + +`swift-section evolution --interface` 的联合接口目前用位图注释(`// [○●●] added in 18.0`)承载每条声明的生命周期。本案在此之上增加**真实、语法合法的 `@available` 属性行**:当一条声明的生命周期能被一条 `@available` 完整表达时,在声明上方渲染 `@available(iOS, introduced: 18.0, obsoleted: 26.0)`;位图注释原样保留,继续承载属性表达不了的事实(modified 事件、多区间形状等)。flag 门控、默认关,默认输出逐字节不变。 + +## 方案 + +**事实层零改动**:属性只从 `EvolutionAnnotation`(presence 位图 + `LineageEvent`)派生,与位图注释同一事实源(`EvolutionAnnotationIndex`),两种呈现永不打架。 + +**可表达性判据**(不满足任一条即整条声明不发属性,注释兜底): + +- presence 位图必须是单一在场区间 `○ᵃ●ᵇ○ᶜ`(a、c ≥ 0,b ≥ 1);`●○●` 这类多区间不发。 +- `introduced:` 事实仅在 a ≥ 1 时存在(首版就在场 = 早于轴起点,没有 introduced 事实,不发);`obsoleted:` 事实仅在 c ≥ 1 时存在(removal 映射为 `obsoleted:`)。两个事实都不存在(全程在场,只有 modified)→ 不发。 +- 涉及的版本标签必须能解析为 1–3 段数字版本号(`26.0` / `18.5.1`);文件名回退标签解析不了 → 不发。 +- modified 事件永不进属性(`@available` 无此语义),始终留在注释短语里。 + +**平台名从哪来**:由 SwiftSectionKit 的 `ABIEvolutionRequest.AvailabilityAttributes` 决定,它是 `Report.annotatedInterface(availabilityAttributes:)` 的关联值,所以「只有 annotated interface 才有属性」在类型上写不出反例。三种取值:`.none`(不发属性,即原来的输出);`.inferredPlatform`(读每个输入的 `LC_BUILD_VERSION`,模拟器算作对应的设备平台,映射成 `@available` 的拼写 macOS / iOS / tvOS / watchOS / visionOS / macCatalyst);`.platform(String)`(调用方直接给拼写)。推断在加载之后、索引之前做,失败就抛 `AvailabilityPlatformInferenceError`:某个输入没有 `LC_BUILD_VERSION`、或者它的平台在 `@available` 里没有名字(DriverKit、bridgeOS),抛 `.noPlatform(path:)`;输入之间平台不一致,抛 `.conflictingPlatforms(_:)`。响亮失败,不悄悄地退回不发属性。`LC_BUILD_VERSION` 用 MachOKitExtensions 公开的 `buildVersionCommand` 读,TypeIndexing 按同一条 load command 选 SDK(`Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift`)。 + +**命令行**:`evolution --emit-available` 打开属性,只能和 `--interface` 一起用;`--platform <拼写>` 覆盖推断,只能和 `--emit-available` 一起用,两条组合规则在 `validate()` 里拒绝。`makeRequest()` 把这两个 flag 映射成上面三种取值。库的两种推断错误由 `CommandLineErrorTranslation` 译成指向 `--platform` 的 `ValidationError`(退出码 64)。 + +**渲染位置**:属性是独立的一行 `EvolutionLine`(自身不带 annotation),成员单元插在声明行上方、容器单元插在 header 首行上方(header 的属性行本就先于声明行,锚点规则不变);位图注释与逐块列对齐逻辑不动。生成属性文本的是格式层纯函数(`EvolutionMarking` 新增,遵循既有可单测形态);`SwiftEvolutionInterfaceRenderer` 持配置(平台名,optional,`nil` = 关闭),经 `AnySwiftEvolutionInterfaceBuilder` / pack façade 透传。启用时 `@_spi(Support) annotatedBlocks()` 结构流同样包含属性行;未配置时全链路行为逐字节不变。启用时图例区加一行说明语义分辨率:introduced/obsoleted 指「该轴点首次/末次观测到」,不保证是精确的引入/移除 OS 版本。着色规则 `InterfaceAnnotationStyle.lineKinds(of:)` 不用改:图例第三行以 `//` 开头,算 header;属性行不带 `// [`,算 plain,着色的仍是它下面那行声明。 + +**范围**:仅 evolution 联合接口。`diff --interface` 的 `-`/`+` 标记已表达增删,不做。 + +**测试**:`EvolutionMarkingTests` 可表达性矩阵单测(introduced-only / obsoleted-only / 双端 / `●○●` 跳过 / 非版本标签跳过 / 全程在场不发 / modified-only 不发);`SwiftEvolutionInterfaceBuilderTests` 渲染器级属性落位测试(成员与容器两种锚点、注释保留)。`SwiftSectionKitTests` 的 `ABIRequestTests` 端到端跑请求:三种取值下图例第三行有没有、写的是哪个平台;平台冲突(模拟器按设备算)与平台没有拼写两种推断错误,并确认它们在索引之前抛出——不同平台的输入是测试里现场改写了 `LC_BUILD_VERSION` 的 fixture 副本。`InterfaceAnnotationStyleTests` 钉住属性行与图例第三行的着色。`SwiftSectionCommandTests` 钉 flag 组合校验、flag 到请求的映射与错误译文。默认输出逐字节不变由现有快照测试兜底。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-08-31 | Created as Draft | 用户提出:基于既有 ABI 演进功能实现 @available 标注 | +| 2026-08-31 | 形态定为「真属性 + 保留位图注释」 | 一轮提问定案。前案 [0013(SwiftEvolutionInterfaceBuilder)](0013-swift-evolution-interface-builder.md) 否决过「伪 @available 属性形态」,理由是①似 Swift 而语义不符、②modified 塞不进该形状;本案只发语法合法的真属性、只在事实完整可表达时发、注释继续承载全部真相,两条否决理由均不复现,不构成翻案 | +| 2026-08-31 | 不可表达时不发属性、注释兜底 | 同轮定案;与项目一贯的「算不出就诚实标注、宁缺勿假」渲染原则一致 | +| 2026-08-31 | 范围仅 evolution --interface | 同轮定案;diff 双侧渲染的 -/+ 标记已表达增删,属性放入语义重复 | +| 2026-08-31 | 平台名自动推断 + `--platform` 覆盖,解析失败响亮报错 | 未提问自定:`LC_BUILD_VERSION` 仓内已有读取先例,推断可靠;静默不发属性会让用户以为没有生命周期事实,报错才诚实 | +| 2026-08-31 | 用户批准(Accepted → In Progress) | 方案与全部假设照单通过,随即开始实现 | +| 2026-08-31 | 实现完成,实施偏差:无 | 定向套件 47 tests 绿、`SwiftInterfaceTests` + `SwiftSectionCommandTests` 全量 168 tests 绿(`--skip IntegrationTests`)、CLI 冒烟通过(推断 macOS、`--platform iOS` 覆盖、默认输出零属性)。落地文件:`EvolutionMarking`(属性纯函数 + 图例第三行)、`SwiftEvolutionInterfaceRenderer`(前插属性行)、两个 builder(`availabilityAnnotationPlatform` 配置)、`EvolutionCommand`(`--emit-available` / `--platform` + `LC_BUILD_VERSION` 推断)。过程复盘见 [TaskReports/2026-08-31-evolution-interface-available-annotations.md](../Internal/TaskReports/2026-08-31-evolution-interface-available-annotations.md) | +| 2026-10-01 | rebase 到 `next`(`514bb4bd`) | 分支写成时落后 `next` 271 个提交。`printAnnotatedInterface` 的冲突把 `next` 的 `LargeStackTaskExecution.run` 包裹与本分支的平台参数合在一起;原本写进 `AGENTS.md` 模块条目的三处说明,因为 `next` 已把模块细节移出 `AGENTS.md`,改写进 `Modules/SwiftInterface.md` | +| 2026-10-05 | 命令行逻辑搬进 SwiftSectionKit(实施偏差) | 落地前 `next` 已把每个子命令的逻辑移进 SwiftSectionKit([0058](0058-swift-section-kit.md)),CLI 只剩包装层,原 `EvolutionCommand` 里的平台推断与报错没法照原样合入。用户在「搬进 SwiftSectionKit 再合」与「这次只合另一个分支」之间选了前者。按 0058 的约定重做:只对 annotated interface 有意义的选项并进已有 enum,`Report.annotatedInterface` 带上 `availabilityAttributes`,与 `ABIDiffRequest.Report.annotatedInterface(format:includesBreakingChangeVerdict:)` 同形;库的错误不提 flag 名,CLI 再译回原分支的报错文案。`.annotatedInterface` 改成带关联值对调用方是源码不兼容的改动,但 SwiftSectionKit 还没发过版本,受影响的只有本仓库里的调用处 | +| 2026-10-05 | 验证 | rebase 后只含 SwiftInterface 部分的那个提交单独编译通过(含测试)。定向套件全部通过,原始退出码 0:`SwiftSectionKitTests` 64 个(新增 4 个)、`SwiftSectionCommandTests` 103 个(新增 4 个)、`EvolutionMarkingTests` / `SwiftEvolutionInterfaceBuilderTests` / `EvolutionAnnotationIndexTests` / `PrintFailureEventTests` 49 个。变异检验:同时注入「模拟器不算 iOS」「DriverKit 有拼写」「`.platform` 被忽略」三处,`ABIRequestTests` 正好对应的 3 个用例变红(原始退出码 1),其余照旧通过,还原后转绿。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,远端依赖)2268 个测试 / 422 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。CLI 冒烟(现编的三版 dylib,`Added` 在 2.0 加入、`Removed` 在 3.0 删除):推断出 macOS,两者分别带 `introduced: 2.0` / `obsoleted: 3.0`,`--platform iOS` 覆盖生效,不加 `--emit-available` 时输出里没有 `@available`;用 `vtool` 改成 iOS 模拟器 / DriverKit 平台的副本分别报冲突(`iOS, macOS`)与推不出,退出码都是 64;两条 flag 组合规则也是 64。插件 skill 提到的每个 flag 都在新 CLI 的 `--help` 里,`claude plugin validate` 两项通过。没有跑渲染 A/B:改动全在开关后面,默认输出由现有快照测试兜底 | +| 2026-10-05 | In Progress → Implemented,编号 0060 | 按共享分支编号(`next` 最大为 0059),合入 `next`;演进账本第 79 节 | +| 2026-10-05 | 收尾判断:不另写专题文档;无新术语 | 规则与边界已写进 `Modules/SwiftInterface.md` 子系统 5 与本提案;`AvailabilityAttributes` 等是标识符,不是自造词。术语表「lifecycle annotation」条目补一句指向本提案 | diff --git a/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md b/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md new file mode 100644 index 000000000..a2be7dcec --- /dev/null +++ b/Documentations/Evolutions/0061-dyld-shared-cache-path-versions.md @@ -0,0 +1,33 @@ +# 0061 - 测试用的 dyld shared cache 路径按版本取 + +- **状态**: Implemented +- **创建日期**: 2026-10-05 +- **最后更新**: 2026-10-06 + +## 摘要 + +测试支撑代码里的 `DyldSharedCachePath`(`Sources/TestSupport/MachOFixtureSupport/DyldSharedCachePath.swift`)原是一个以 `String` 为原始值的 enum,每用一个归档 cache 就得手写一个 case 和它的完整路径。本次把它改成用静态成员充当 case 的结构体,带路径(`rawValue`)和版本标签(`versionLabel`)两个字段,新增按版本号拼出路径、并拿这个版本当标签的 `macOS(_:)` / `iOS(_:)`;evolution 的 IntegrationTests 因此直接用每个 cache 的标签当轴标签,不必再另写一份标签数组。另在 IntegrationTests 的单版本、diff、evolution 三个套件里各加一个只需填版本号的 `ArchivedDyldCacheTests`;evolution 用的多版本基类会跳过 cache 里没有该镜像、或镜像不含 Swift 的版本。 + +## 方案 + +- **类型**:`DyldSharedCachePath: Hashable, Sendable`,`rawValue` 是路径,`versionLabel` 是它在版本轴上的标签,两者都在构造时给出。`macOS("26.6")` 得到 `/Volumes/DyldSharedCaches/macOS/26.6/dyld_shared_cache_arm64e`、标签 `26.6`,`iOS("27.0")` 同理。版本就是卷上的目录名,原样拼进路径、原样当标签(`14.0(Internal)` 也行);不检查文件在不在,和以前一样由调用方判断——卷上有的目录只放导出的头文件,没有 cache(例如 26.4.1、26.5.1)。不再遵循 `RawRepresentable`:它要求只凭路径就能构造出值,而每个值都必须带标签。 +- **原有常量**:8 个 case 变成同名的 `static let`,调用点一处不改。四个 macOS 常量改由 `macOS(_:)` 生成;其余四个直接写明标签:`current` 标为 `current`(标签不一定是系统版本),`iOS_18_5`、`iOS_26_1`、`iOS_27_0_Simulator` 分别标为 `18.5`、`26.1`、`27.0`。`MachOTestingSupportTests` 的 `DyldSharedCachePathTests` 钉住四个 macOS 常量的路径与原来写死的完全相同、标签与 evolution 测试原来手写的相同——这些常量只在不会自动运行的 IntegrationTests 里用,拼错了平时没人发现。 +- **版本标签**:evolution 的 `MultiVersionDyldCacheImageTests` 只列 `cachePaths`,轴标签取每个 cache 的 `versionLabel`,原来与路径一一对应的 `cacheLabels` 数组删掉;默认三个 cache 给出的标签仍是 `15.5`、`26.5.2`、`27.0`,现有 evolution 输出不变。标签手动给,不从 cache 文件里解析:cache 头的 `osVersion` 只记主、次版本号,补丁号总是 0(26.5.2 的头里是 26.5.0,15.8.1 是 15.8.0),macOS 11 的 cache 干脆是 0.0.0,解析出来会让两个补丁版本撞成同一个标签。 +- **只给 macOS 与 iOS 出版本函数**:卷上的 `iOS-Simulator/` 目录里只有导出的头文件,没有 cache;模拟器 runtime 的 cache 在 CoreSimulator 卷里,卷名带 build 号(`iOS_24A434`),从版本号推不出路径,所以 `iOS_27_0_Simulator` 仍然写死。 +- **IntegrationTests**:`SwiftInterfaceBuilderTestSuite`、`SwiftDiffableInterfaceBuilderTestSuite`、`SwiftEvolutionInterfaceBuilderTestSuite` 各加一个 `ArchivedDyldCacheTests`,分别只填 `cacheVersion`、`oldCacheVersion` / `newCacheVersion`、`cacheVersions`,镜像默认 AppKit,各自沿用所在套件现有的基类。evolution 那个的 `cachePaths` 由 `cacheVersions` 生成,标签就是这些版本号,全是数字,于是打开 `@available(macOS, …)` 输出(提案 [0060](0060-evolution-interface-available-annotations.md));为此 `SwiftEvolutionInterfaceDumpTests` 的两个辅助函数加了一个默认 `nil` 的 `availabilityAnnotationPlatform` 参数,现有调用不受影响。evolution 那个起初只列 15.8.1、26.6、27.0,后续改为卷上 macOS 11.0.1 → 27.0 每个次版本一个(共 51 个;11.0、12.0 在卷上只有 `11.0.1`、`12.0.1`),镜像换成 SwiftUI。这些目录在卷上都有 cache。 +- **跳过没有 Swift 的版本**:`MultiVersionDyldCacheImageTests` 打开每个 cache 后,cache 里没有这个镜像、或镜像没有任何 `__swift5_*` 节的,这个版本就不上轴,也不报错;打不开的 cache 照旧抛错。起因是 AppKit 在 macOS 14 之前把 Swift API 放在 `/usr/lib/swift/libswiftAppKit.dylib`,AppKit 本体在 11.0.1–13.7 一个 Swift 节都没有。索引这样的镜像时,索引器对类型、协议、conformance、associated type 各报一次提取失败;测试没挂事件处理器,这四条失败都会以 error 级别写进日志。 + +## 决策日志 + +| 日期 | 决定 | 理由 | +|------|------|------| +| 2026-10-05 | Created | 用户:「DyldSharedCachePath改成String Type Enum结构体,支持传递版本返回路径」 | +| 2026-10-05 | 三个套件各加一个按版本号取 cache 的类 | 用户:「再加一个SwiftInterfaceBuilderTests加上Diff和Evolution版本」。三个套件本来就有,问过一轮,用户选「每个套件加一个按版本号的类」 | +| 2026-10-05 | 顺带发现的两处先不改 | `macOS_26_5_1` 指向的目录是空的,diff 套件里两处拿它当旧版本,一跑就失败;`iOS_18_5` / `iOS_26_1` 指向没挂载的 `/Volumes/Generic`,全仓没有调用。用户选「都先不动」 | +| 2026-10-05 | 验证 | 全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,远端依赖)2270 个测试 / 423 个套件全部通过,原始退出码 0,比改动前多出的正是新加的 1 个套件、2 个测试;只有早已登记的 `SymbolicManglingIndexTests` known issue。IntegrationTests 按项目规矩只编译、不运行:三个新类与改过的辅助函数编译通过,没有新警告。默认的 15.8.1、26.6、27.0 在卷上都有 cache 文件 | +| 2026-10-05 | Implemented,编号 0061 | 按共享分支编号(`next` 最大为 0060),合入 `next`;演进账本第 80 节。不另写专题文档,无新术语 | +| 2026-10-05 | 后续:加 `versionLabel`,evolution 测试不再另写标签 | 用户:「DyldSharedCachePath这里再嵌入或者解析dyld cache的系统版本,evolution那边就不用再写一次label了」。查到 cache 头的 `osVersion` 不带补丁号、macOS 11 没有这个值,解析会丢信息;用户随后定为「手动传吧,静态常量直接写上,调方法的就拿那个作为版本label,这个不是一定得是系统版本,应该叫versionLabel」。`RawRepresentable` 因此去掉,`cacheLabels` 删掉 | +| 2026-10-05 | 后续的验证 | 按用户「不用全部跑一遍,编译过了就行」,只编译:全部测试目标(含 IntegrationTests)编译通过,改动的文件没有新警告;没有运行测试,`DyldSharedCachePathTests` 新加的标签断言也没有跑过 | +| 2026-10-06 | 后续:evolution 的归档套件改列 51 个版本 | 用户:「SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.cacheVersions,把这个属性填完……只写x.y版本,忽略x.y.z版本」。每个次版本取 x.y 目录;11.0、12.0 在卷上只有 x.0.1 目录,照用户写下的第一项 `11.0.1`,12.0 取 `12.0.1`;`14.0(Internal)` 不收。`cachePaths` 改由 `cacheVersions` 生成、镜像换成 SwiftUI,这两处是用户自己改的 | +| 2026-10-06 | 后续:没有 Swift 的版本跳过,不报错 | 用户:「没有swift信息不报错,跳过」。用 `ipsw dyld macho … --loads` 核对过:AppKit 本体在 11.0.1、12.0.1、13.7 没有 `__swift5_*` 节,14.0 起才有;同期 `libswiftAppKit.dylib` 里有 7 个(11.0.1)到 43 个(13.7)类型,14.0 起为 0。判断放在基类,看节名前缀;cache 里没有这个镜像也算没有 Swift,一并跳过 | +| 2026-10-06 | 后续的验证 | 全部测试目标(含 IntegrationTests)编译通过,没有新警告。按用户「测试一下SwiftUI会不会爆内存」运行过一次 `evolutionInterfaceFile`,第 140 秒在 13.5 上因 MachOKit 的整数下溢崩溃,内存没到 5 GB 的上限;其余测试没有运行。实测数字见演进账本第 80 节,崩溃的根因与修复见第 81 节 | diff --git a/Documentations/Evolutions/README.md b/Documentations/Evolutions/README.md index 88a96654c..68af29318 100644 --- a/Documentations/Evolutions/README.md +++ b/Documentations/Evolutions/README.md @@ -63,4 +63,11 @@ | [0052](0052-objc-custom-class-name.md) | 改过 ObjC 运行时名的 Swift 类:打印 `@objc(Name)`,并按描述符指针配对它的类对象 | Implemented | | [0053](0053-shared-cache-composition-and-eviction-registry.md) | 按镜像缓存整治:`SharedCache` 去继承、键去装箱、驱逐收口到注册表 | Implemented | | [0054](0054-interface-descriptor-only-vtable-members.md) | interface 按 vtable 槽位顺序打印类成员,补上只剩 method descriptor 符号的成员 | Implemented | +| [0055](0055-group-sources-by-layer.md) | `Sources/` 按层分组 | Implemented | | draft | [静态布局引擎读取 accessor thunk 背后的字段类型](draft-static-layout-through-accessor-thunks.md) | Draft | +| [0056](0056-visibility-regions.md) | 标记模式:一次打印全量 interface,并标出每段内容受哪个开关控制 | Implemented | +| [0057](0057-reading-context-migration.md) | 读取接口统一到 ReadingContext:传 machO 与直接用指针的旧接口废弃 | Implemented | +| [0058](0058-swift-section-kit.md) | 把 swift-section 的功能抽成 SwiftSectionKit 库,CLI 只剩一层包装 | Implemented | +| [0059](0059-dump-declaration-identity.md) | SwiftSectionKit:dump 把每个声明的种类与名字一并交给输出端 | Implemented | +| [0060](0060-evolution-interface-available-annotations.md) | evolution 联合接口的 @available 生命周期标注(真属性 + 位图注释保留) | Implemented | +| [0061](0061-dyld-shared-cache-path-versions.md) | 测试用的 dyld shared cache 路径按版本取 | Implemented | diff --git a/Documentations/Glossary.md b/Documentations/Glossary.md index af1db1d95..11a63e71f 100644 --- a/Documentations/Glossary.md +++ b/Documentations/Glossary.md @@ -49,35 +49,49 @@ 一条 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 尖括号参数的归属裁决以它为第一信号。 -- **主要出现在**:`Sources/SwiftInterface/OpaqueSameTypeConstraint.swift`、`SwiftInterfaceBuilderOpaqueTypeProvider` +- **主要出现在**:`Sources/Output/SwiftInterface/OpaqueSameTypeConstraint.swift`、`SwiftInterfaceBuilderOpaqueTypeProvider` - **延伸阅读**:[提案 0011](Evolutions/0011-opaque-primary-associated-type-attribution.md)、[OpaqueReturnTypeResolution.md](Internal/OpaqueReturnTypeResolution.md) §2.2 ### bare image name(裸镜像名) 一个 dylib load name(`@rpath/Foo.framework/Versions/A/Foo`、`/usr/lib/libobjc.A.dylib`)归约成的镜像名:末段路径去**第一个**扩展名(`Foo`、`libobjc`)。这是与 MachOKit 的契约——`MachOImage(name:)` 对进程内每个镜像的路径做同一归约再比较,把未归约的 load name 喂给它永远匹配不到。它也是所有依赖集合的去重键:同一个库会被不同镜像以不同拼写链接,只有裸名跨拼写稳定。 -- **主要出现在**:`Sources/MachODependencies/DependencyLoadName.swift`、`DependencyClosure`、`FileDependencyLocator` +- **主要出现在**:`Sources/MachO/MachODependencies/DependencyLoadName.swift`、`DependencyClosure`、`FileDependencyLocator` - **延伸阅读**:[Modules/MachODependencies.md](Internal/Modules/MachODependencies.md) §2 ### bucket(桶) 分类索引里「一个键对应的一组符号表行号」(如 `symbolRowsByOffset` 的值、`MemberSymbolRows` 的叶子)。旧形态是 `[UInt32]` 小数组——绝大多数桶只有一个元素,却各付一次堆分配;提案 0003 落地后值形态为 `SymbolRowBucket`(单元素内联于字典槽,第二个元素起才落堆数组),迭代序保持插入序。 -- **主要出现在**:`Sources/MachOSymbols/SymbolIndexStore.swift`、`Sources/MachOSymbols/SymbolRowBucket.swift` +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift`、`Sources/MachO/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` +- **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.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.23.0 删除的一行转发(`machO.context` / `.inProcess`)。 + +- **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`、`Sources/MachO/MachOPointers/`、`Sources/MachO/MachOResolving/Resolvable.swift` +- **延伸阅读**:[提案 0057](Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.md) + ### dependency closure(依赖闭包) 一个 root 二进制经 `LC_LOAD_DYLIB` 家族 load command 解析出的依赖镜像集合(`MachODependencies.DependencyClosure`)。本项目里的「闭包」默认指**传递**闭包:BFS 递归、按裸镜像名去重、root 排除、解析顺序是契约的一部分(`SwiftLayout.ImageUniverse` 按此顺序惰性索引、命中即停)。同一类型也承载 `.direct` 遍历(只取 root 自己的一层),`SwiftInterfaceBuilderDependencies` 用的是这一种——名字里的「闭包」在那里只是复用同一个结果类型。定位不到的依赖记入 `unresolvedLoadNames`,不算失败。 -- **主要出现在**:`Sources/MachODependencies/DependencyClosure.swift`、`Sources/SwiftLayout/ImageUniverse+DependencyClosure.swift` +- **主要出现在**:`Sources/MachO/MachODependencies/DependencyClosure.swift`、`Sources/Analysis/SwiftLayout/ImageUniverse+DependencyClosure.swift` - **延伸阅读**:[Modules/MachODependencies.md](Internal/Modules/MachODependencies.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/MachOSymbols/SymbolIndexStore.swift` +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` - **延伸阅读**:[提案 0008](Evolutions/0008-interface-header-and-export-status-annotations.md)、[InterfaceHeaderAndExportStatusAnnotations.md](Internal/InterfaceHeaderAndExportStatusAnnotations.md) ### descriptor-only member(只剩 method descriptor 符号的成员) @@ -93,7 +107,7 @@ class 的 vtable 成员里,实现函数没有符号、只剩它自己 method d 把一个查询期 vend 出来的 `DemangledSymbol` 从共享 `SymbolTable` 上摘下来、换成自带单行表的独立值。共享表对「vend 十万个、随手丢弃」是正确的取舍,但**存进声明模型的长命值必须先 detach**——一个存活值会把整张表(几十万行 + 对镜像映射内存的引用)钉在内存里,让按镜像回收失效。六个存储点由 `SymbolTableRetentionTests` 钉住;查询路径**不要** detach。 -- **主要出现在**:`Sources/MachOSymbols/DemangledSymbol.swift`、AGENTS.md「Symbol indexing」段 +- **主要出现在**:`Sources/MachO/MachOSymbols/DemangledSymbol.swift`、AGENTS.md「Symbol indexing」段 - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) ### 等价类塌缩(equivalence-class collapse) @@ -108,28 +122,28 @@ Requirement Machine 最小化泛型签名时,把 pin 到同一具体类型的 按镜像缓存的三个所有权概念(`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)在登记之前填的条目永远不被认领。 - **不要混淆**:`evict(groups:for:)` 是显式驱逐,只清点名的家族、不展开 followers;followers 只在最后一个持有者注销时展开。「内存压力驱逐」已不存在,宿主要清就调 `evictImagesWithoutLiveOwners()`。 -- **主要出现在**:`Sources/MachOCaches/SharedCacheRegistry.swift`、`Sources/MachOCaches/SharedCacheEvictionGroup.swift`、各模块的 `SharedCacheEvictionGroup+<模块>.swift`、`Sources/SwiftIndexing/SwiftDeclarationIndexer.swift`(`prepare()` 与 `deinit`) +- **主要出现在**:`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) ### export status(导出状态标注,`// not exported`) `--emit-export-status` 门控的成员标注:成员的**所有**符号(含派生形态)都不在 export trie 时打 `// not exported`。语义是**符号表事实**而非访问级别猜测(`internal`/`fileprivate`/`private` 不可恢复,见 roadmap L-16);`override` 与 `@objc` 成员豁免(分别经父类 thunk / objc_msgSend 可达,自有符号零导出是编译器常态);镜像无导出信息时三态查询答 `nil`、不发射。 -- **主要出现在**:`Sources/SwiftPrinting/SwiftDeclarationPrinter.swift`(`renderMember`)、三个 Dumper 的 member-symbol 循环 +- **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift`(`renderMember`)、三个 Dumper 的 member-symbol 循环 - **延伸阅读**:[提案 0008](Evolutions/0008-interface-header-and-export-status-annotations.md)、[InterfaceHeaderAndExportStatusAnnotations.md](Internal/InterfaceHeaderAndExportStatusAnnotations.md) ### exported-only 过滤(`--exported-only`,`printExportedDeclarationsOnly`) export status 的**过滤形态**:interface 只输出镜像导出的声明。类型 / 协议按描述符符号(`…Mn` / `…Mp`,优先取描述符 offset 处的符号,重整名只兜底)裁决,成员沿用 export status 的派生形态判定,扩展按「被扩展类型 / 遵循协议是否为本镜像内未导出声明」裁决(依据 **`ExportFilterScope`**——`printRoot` 从索引器表算出的本镜像内未导出 `TypeName` / `ProtocolName` 集合)。只在判定为 `false` 时删,`nil` 一律保留(绝不靠猜删);普通扩展被清空则整块删,conformance 扩展留 `{}`。与 export status 是同一个事实的两种呈现:删除条件即标注条件,两开关同开输出零标注。 -- **主要出现在**:`Sources/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift`、`SwiftInterfaceBuilder.printRoot()` +- **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift`、`SwiftInterfaceBuilder.printRoot()` - **延伸阅读**:[提案 0016](Evolutions/0016-exported-only-interface.md)、[ExportedOnlyInterfaceFiltering.md](Internal/ExportedOnlyInterfaceFiltering.md) ### emission strategy(发射策略) diff / evolution 两条对比渲染路共享结构遍历核心(`InterfaceUnionWalker`)之后各自剩下的那一半:遍历器负责**结构**(N 路匹配与并集排序、extension 容器拆分、成员构造、类别调度、body 组合序),策略(`InterfaceUnionEmitting`)负责**呈现**——同一个匹配结果如何变成行(`+`/`-` 标记 vs 生命周期注解)、容器 header 如何裁决(两侧配对 vs 最新可渲染)、容器如何装配。真正语义不同的部分(`HeaderOutcome` 配对、注解锚点、两套格式层)只住在策略里,绝不上浮进遍历器。 -- **主要出现在**:`Sources/SwiftInterface/InterfaceUnionWalker.swift`(协议与遍历器)、`SwiftDiffableInterfaceRenderer.swift`(`DiffUnionStrategy`)、`SwiftEvolutionInterfaceRenderer.swift`(evolution 策略) +- **主要出现在**:`Sources/Output/SwiftInterface/InterfaceUnionWalker.swift`(协议与遍历器)、`SwiftDiffableInterfaceRenderer.swift`(`DiffUnionStrategy`)、`SwiftEvolutionInterfaceRenderer.swift`(evolution 策略) - **延伸阅读**:[提案 0014](Evolutions/0014-unify-interface-renderers.md) ### identical code folding(ICF,相同代码折叠) @@ -143,27 +157,34 @@ linker 把字节相同的函数体合并到同一地址的优化。后果是「 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,会占线程上百秒,不能挤占同步跳转的额度。 -- **主要出现在**:`Sources/MachOSymbols/LargeStackTaskExecution.swift`、各 async 入口的 `LargeStackTaskExecution.run { … }` +- **主要出现在**:`Sources/MachO/MachOSymbols/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/MachOSymbols/SymbolIndexStore.swift` +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` ### leg(腿,reader-split) 同一逻辑按 reader 类型分出的并行实现路径,口语记作「镜像腿 / 文件腿」:`MachOImage`(进程内映射,符号名可直指 LINKEDIT 字符串表、零拷贝)与 `MachOFile`(离线文件,名字须读进私有缓冲)。0001 的 sweep 收集与名字来源都是按腿分叉的。 -- **主要出现在**:`Sources/MachOSymbols/SymbolIndexStore.swift`(`buildStorageSweep`)、`Sources/MachOSymbols/SymbolTable.swift` +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift`(`buildStorageSweep`)、`Sources/MachO/MachOSymbols/SymbolTable.swift` ### lifecycle annotation(生命周期注解) -演进并集接口里每条「变过的」声明行尾的注释:`// [●●○] removed in 26.0` —— 存在位图(每版本一位,文件头图例映射位置到版本标签)+ 按 ` · ` 连接的事件短语(added / removed / modified in 版本;modified 带 `旧签名 → 新签名`,两侧文本相同时省略箭头段)。**没有注解本身就是信息**:全程存在且从未变化。注解事实唯一来源是 `ABIEvolution` 的 lineage 查表,渲染器不自行推导。 +演进并集接口里每条「变过的」声明行尾的注释:`// [●●○] removed in 26.0` —— 存在位图(每版本一位,文件头图例映射位置到版本标签)+ 按 ` · ` 连接的事件短语(added / removed / modified in 版本;modified 带 `旧签名 → 新签名`,两侧文本相同时省略箭头段)。**没有注解本身就是信息**:全程存在且从未变化。注解事实唯一来源是 `ABIEvolution` 的 lineage 查表,渲染器不自行推导。打开 `--emit-available` 时,生命周期能完整写成一条 `@available` 的声明上方还会多一行真属性,它由同一份事实派生,是补充不是替代,注解照旧都在。 -- **主要出现在**:`Sources/SwiftInterface/EvolutionMarking.swift`、`EvolutionAnnotationIndex.swift` -- **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md) +- **主要出现在**:`Sources/Output/SwiftInterface/EvolutionMarking.swift`、`EvolutionAnnotationIndex.swift` +- **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md)、[提案 0060](Evolutions/0060-evolution-interface-available-annotations.md)(`@available` 属性) + +### 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)。 + +- **主要出现在**:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+VisibilityRegions.swift`、`SwiftDeclarationPrintConfiguration.swift`、`Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift`、`SwiftVisibilityOption.swift` +- **延伸阅读**:[提案 0056](Evolutions/0056-visibility-regions.md) ### materialize(物化) @@ -182,7 +203,7 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 `SymbolTable` 里一行的名字字节从哪里读:**mapped 字符串表**(`MachOImage` 行直指镜像 mmap 的 LINKEDIT 字符串表,clean 页、零拷贝,代价是要求镜像保持加载)或**私有缓冲**(`MachOFile` 行与 export-trie 解码名,字节存进表自有的连续缓冲)。`PackedNameReference` 用 1 个 bit 区分两者。 -- **主要出现在**:`Sources/MachOSymbols/SymbolTable.swift` +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift` - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) ### NodeStore / NodeReference @@ -224,7 +245,7 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 不给数据本体排序,而是另存一条「按某序排列的下标数组」(permutation),查询时在这条下标序列上二分。`SymbolTable.rowsSortedByName` 即名字序 permutation:行本体保持插入序不动,名字查找二分这条 `[UInt32]`。替代了被退役的名字键字典 `tableRowByName`。 -- **主要出现在**:`Sources/MachOSymbols/SymbolTable.swift`(`row(forName:)`) +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift`(`row(forName:)`) - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md) ### renamed class(改名类,`@objc(Name)` / `@_objcRuntimeName(Name)`) @@ -238,26 +259,26 @@ opaque 尖括号参数归属的第三条规则:协议无任何 anchor 命中 `SymbolTable` 的最小单位:每个唯一符号名一行,16 字节(canonical offset + `PackedNameReference`),行号(`UInt32`)是全部分类索引引用符号的方式。「一名一行」意味着按名字查询的语义是纯函数——同名必同行。 -- **主要出现在**:`Sources/MachOSymbols/SymbolTable.swift` +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolTable.swift` ### 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/MachOSymbols/StructuralNodeReferenceKey.swift`;键位清单见 AGENTS.md「Symbol indexing」段 +- **主要出现在**:`Sources/MachO/MachOSymbols/StructuralNodeReferenceKey.swift`;键位清单见 AGENTS.md「Symbol indexing」段 ### supplementary APINotes(补充映射) -TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备**类型映射文件,为 **SDK 里没有模块的私有框架**(AttributeGraph 等)提供 `__C` 类型的归属与改名——这类框架的 `swift_name` 改名只活在头文件里、二进制零残留,原理上不可恢复,只能靠外部知识。库自身不内置任何映射(首版的内置 SPM resource bundle 因 `Bundle.module` 分发即崩问题在 review 后移除);宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes` 传入,覆盖顺序 SDK APINotes → 用户文件按传入序,后写覆盖同名。CF-bridged 类型须登记两个 C 拼写(typedef 名进 Typedefs、storage tag 名进 Tags),第三种 mangling 形态(导入名直出)由 SwiftName 自动派生。 +TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备**类型映射文件,为 **SDK 里没有模块的私有框架**(AttributeGraph 等)提供 `__C` 类型的归属与改名——这类框架的 `swift_name` 改名在二进制里只剩类型记录里的最后一截(`Graph`),所属模块与嵌套关系都不记录,完整名字只能靠外部知识。库自身不内置任何映射(首版的内置 SPM resource bundle 因 `Bundle.module` 分发即崩问题在 review 后移除);宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes` 传入,覆盖顺序 SDK APINotes → 用户文件按传入序,后写覆盖同名。CF-bridged 类型须登记两个 C 拼写(typedef 名进 Typedefs、storage tag 名进 Tags)。描述符按 import info 里的 ABI name 打印(提案 0023),不会再出现 Swift spelling 的 `__C.Graph`;SwiftName spelling 仍会登进归属表,让改名条目所在的模块胜过只做标注的其它模块(`NSObject` 归 ObjectiveC,不归同样列出它的 Foundation)。 -- **主要出现在**:`Sources/TypeIndexing/SupplementaryAPINotes.swift` +- **主要出现在**:`Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift` - **延伸阅读**:[提案 0010](Evolutions/0010-community-type-mapping-bundles.md)、[SupplementaryTypeMappings.md](SupplementaryTypeMappings.md)(公开使用指引)、[TypeIndexingPipeline.md](Internal/TypeIndexingPipeline.md) ### sweep(构建扫描) 对一个镜像的**全量符号一遍扫过**的批处理构建过程:`SymbolIndexStore` 首次索引某镜像时,`buildStorageSweep` 遍历整张符号表 + export trie,收集行、对每个 Swift 符号 demangle 一次、把结果分类进各查询索引——与之相对的是查询期的按需单点操作。RuntimeViewer 语境里「按需索引 sweep」指用户打开某镜像才触发这一遍构建;sweep 期的临时缓冲是瞬态内存峰值的来源(完即释放)。 -- **主要出现在**:`Sources/MachOSymbols/SymbolIndexStore.swift`(`buildStorageSweep`) +- **主要出现在**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift`(`buildStorageSweep`) - **延伸阅读**:[提案 0001](Evolutions/0001-symbol-name-offsetization.md)、[SymbolIndexStoreMemoryOptimization.md](Internal/SymbolIndexStoreMemoryOptimization.md) ### symbolic-mangling symbol(`_symbolic` 符号)与被引用者(referent) @@ -268,28 +289,28 @@ TypeIndexing 的外部知识入口:标准 `.apinotes` 格式的**用户自备* 名字的地方,dyld shared cache 也保留着。被引用者不能单独 demangle:同一个 mangler 依次写出它们,后面的会借用前面的 substitution,必须连在一个 `$s` 后面一起 demangle。 -- **主要出现在**:`Sources/MachOSymbols/SymbolicManglingSymbols.swift`(收集)、`Sources/SwiftInspection/SymbolicManglingIndex.swift`(配对与解码) +- **主要出现在**:`Sources/MachO/MachOSymbols/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) `SwiftInspection` 里带镜像上下文的 demangler:mangled name 里的 symbolic reference(指向 context descriptor、opaque type descriptor、protocol descriptor、existential shape 的相对指针)要回到镜像里解析,它读出被引用的描述符、建出编译器本来会 mangle 进去的那棵子树,对应运行时的 `ResolveAsSymbolicReference` 加 `_swift_buildDemanglingForContext`。另外直接为 context descriptor 和 generic requirement 列表建 demangling(`demangleContext(for:)`、`buildGenericSignature(for:)`)。它从不读 `Metadata` 记录,metadata 指针变类型那个方向是 `RuntimeMetadataTypeBuilder`。2026-09-09 之前叫 `MetadataReader`,名字抄自上游 `swift/Remote/MetadataReader.h`,但上游那个类型的主业正是「从远程进程内存读 metadata 记录再交给 Builder」,我们只对应它 demangle 那一半;带日期的旧文档里仍用旧名。 -- **主要出现在**:`Sources/SwiftInspection/SymbolicDemangler.swift` +- **主要出现在**:`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift` - **延伸阅读**:[提案 0022](Evolutions/0022-rename-metadata-reader-to-symbolic-demangler.md)、[ReadingContextAbstraction.md](Internal/ReadingContextAbstraction.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`。 -- **主要出现在**:`Sources/MachOSwiftSection/Models/Type/TypeImportInfo.swift`、`SymbolicDemangler.cImportedTypeIdentity` +- **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/Type/TypeImportInfo.swift`、`SymbolicDemangler.cImportedTypeIdentity` - **延伸阅读**:[提案 0023](Evolutions/0023-type-import-info-identity.md)、上游 `swift/ABI/TypeIdentity.h` ### trailing objects Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可变数量的附加记录(vtable 方法描述符、resilient witnesses、泛型上下文等),源自 C++ 侧的 `TrailingObjects` 模板。本仓库的高层 wrapper 构造时把它们全部解析成 Swift 数组——0002 要治理的驻留正是这些解析产物。 -- **主要出现在**:`Sources/MachOSwiftSection/Models/`(各 wrapper 的 `initialize` 尾部解析) +- **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/`(各 wrapper 的 `initialize` 尾部解析) ### system root(系统根目录搜索路径) @@ -302,19 +323,19 @@ Swift runtime 的 descriptor 布局惯例:固定头之后按 flags 跟着可 离线读 kind-9 accessor thunk 的方法:不执行 thunk,按指令顺序做符号求值——寄存器和栈槽里放「类型表达式」(参数缓冲区第 k 个词、某 descriptor 的 accessor 以若干实参调用的结果、常量 metadata 地址、mangled name 实例化)而不是数值。thunk 只用几种运行时入口(泛型类型的 metadata accessor、`swift_getWitnessTable`、`__swift_instantiateConcreteTypeFromMangledName`)构造类型,每一种的语义都是类型层面的,所以函数返回时 `x0` 里的表达式就是答案。条件跳转能判定的(运行时能力标志、已知立即数)直接判定,判定不了的(版本检查的结果)按「假设为假 / 假设为真」各跑一遍,两次结果即 `if #available` 的两支。与「查表」读法(只认 `csel` 的两个操作数或分支里唯一一次调用)的区别:后者忽略了尾调用,会把 `ModifiedContent<…, X>` 读成 `X`、把中间调用的结果当答案。 -- **主要出现在**:`Sources/SwiftThunkAnalysis/Analysis/ThunkTypeEvaluator.swift`、`AccessorThunkAnalyzer.swift` +- **主要出现在**:`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) ### union interface(并集接口) `evolution --interface` 的输出形态:N 个版本所有声明的**并集**只渲染一次的 Swift 接口——每条声明由「最后一个拥有它的版本」的模型与 printer 渲染文本,变化写进生命周期注解,同一成员改签名不裂成多行。与「逐 transition 串联 diff」(同一声明重复出现 N−1 次)和「只渲染最新版 + since 注解」(丢中间版本细节)相对。排序规则:最新版本声明序为脊柱,不在最新版的声明按其最后存在版本的顺序追加。 -- **主要出现在**:`Sources/SwiftInterface/SwiftEvolutionInterfaceRenderer.swift`(`matchAcrossVersions`) +- **主要出现在**:`Sources/Output/SwiftInterface/SwiftEvolutionInterfaceRenderer.swift`(`matchAcrossVersions`) - **延伸阅读**:[提案 0013](Evolutions/0013-swift-evolution-interface-builder.md) ### wrapper vs descriptor(高层包装 vs 描述符) 同一个二进制实体的两级表示,易混淆:**descriptor**(`ClassDescriptor`、`ProtocolConformanceDescriptor` 等)是原始布局 + 位置的薄值(几十字节,可随时重读);**wrapper**(`Class` / `Struct` / `Enum` / `ProtocolConformance` / `Protocol` / `TypeContextWrapper`)是构造时急切解析全部 trailing objects 的完整值(内联数百字节 + 堆数组)。规则口诀:descriptor 可驻留,wrapper 应物化。 -- **主要出现在**:`Sources/MachOSwiftSection/Models/` +- **主要出现在**:`Sources/ABI/MachOSwiftSection/Models/` - **延伸阅读**:[提案 0002](Evolutions/0002-declaration-model-descriptor-slimming.md) diff --git a/Documentations/Internal/ABIEvolutionDesign.md b/Documentations/Internal/ABIEvolutionDesign.md index 9623cd960..8f3e5b654 100644 --- a/Documentations/Internal/ABIEvolutionDesign.md +++ b/Documentations/Internal/ABIEvolutionDesign.md @@ -212,7 +212,8 @@ swift-section evolution ... \ `--summary-only`(仅 Transitions 段 + 结论行)。 - `--fail-on-breaking`:任一转换 breaking 时以非零码退出。 - 加载 + 索引 + 冻结的逐输入流程与 diff 共享 `ABISnapshotInputLoader` - (swift-section Utilities),避免两个命令漂移。 + (swift-section Utilities),避免两个命令漂移。提案 `swift-section-kit` 之后它是 + `SwiftSectionKit` 的 `ABISnapshotLoading`,`evolution` 本身是 `ABIEvolutionRequest`。 ## 测试计划(`Tests/SwiftDiffingTests/`) diff --git a/Documentations/Internal/AccessorThunkResolutionExplained.md b/Documentations/Internal/AccessorThunkResolutionExplained.md index c85be04e1..8280690b0 100644 --- a/Documentations/Internal/AccessorThunkResolutionExplained.md +++ b/Documentations/Internal/AccessorThunkResolutionExplained.md @@ -200,7 +200,7 @@ thunk 之外还有一种「引用」不是指针:独立文件里的 witness ## 代码地图 ``` -Sources/SwiftThunkAnalysis/ +Sources/Analysis/SwiftThunkAnalysis/ ├── SwiftThunkAnalysis.swift # 模块说明 ├── Instructions/ │ ├── ThunkInstruction.swift # 我们自己的指令词汇表(寄存器、操作、条件码) @@ -220,11 +220,11 @@ Sources/SwiftThunkAnalysis/ ├── ThunkTypeNodeBuilder.swift # 第四步:表达式 → 类型名节点 └── AccessorThunkOwnerLayout.swift # thunk 主人的泛型参数布局(argument(k) 对应哪个参数) -Sources/MachODependencies/ +Sources/MachO/MachODependencies/ ├── DependencySearchPath.swift # 搜索路径的四种(含 system root)、从文件位置推断、按形状归类 └── FileDependencyLocator.swift # 按 load name 找依赖文件:显式文件 → system root → cache -Sources/SwiftDeclarationRendering/ +Sources/Output/SwiftDeclarationRendering/ ├── AccessorThunkResolution.swift # 渲染层用的 resolver(默认就是反汇编读取器,可带搜索路径)与宿主 / 测试注入点 ├── ConditionalWitnessComment.swift # `typealias` 上方那几行分支注释 ├── InProcessAccessorFunctionResolution.swift # 进程内那条路 diff --git a/Documentations/Internal/CLITransformerTemplateInterface.md b/Documentations/Internal/CLITransformerTemplateInterface.md index d2a9328f2..4e387a3d8 100644 --- a/Documentations/Internal/CLITransformerTemplateInterface.md +++ b/Documentations/Internal/CLITransformerTemplateInterface.md @@ -12,8 +12,10 @@ 新增: -- `Sources/swift-section/Models/TransformerOptionGroup.swift` —— `dump` 与 `interface` 共享的参数组 -- `Sources/swift-section/Commands/TransformerCommand.swift` —— `swift-section transformer` 发现性子命令(`tokens` / `templates` / `config`) +- `Sources/Executables/swift-section/Models/TransformerOptionGroup.swift` —— `dump` 与 `interface` 共享的参数组 +- `Sources/Executables/swift-section/Commands/TransformerCommand.swift` —— `swift-section transformer` 发现性子命令(`tokens` / `templates` / `config`) + +> 提案 `swift-section-kit` 之后:三个子命令的输出搬进 `SwiftSectionKit` 的 `TransformerTokensRequest` / `TransformerTemplatesRequest` / `TransformerConfigurationRequest`(模块清单 `TransformerModule` 也在那里),「启用的模块打开对应注释开关」的 `applyTransformersEnablingCommentKinds` 也随 `dump` / `interface` 的逻辑进了库;参数组与模板名解析仍在 CLI。 修改: diff --git a/Documentations/Internal/DiffableInterfacePlan.md b/Documentations/Internal/DiffableInterfacePlan.md index b784559da..3f94f08ce 100644 --- a/Documentations/Internal/DiffableInterfacePlan.md +++ b/Documentations/Internal/DiffableInterfacePlan.md @@ -98,11 +98,11 @@ as metadata, but nothing is dropped now. - `Compatibility` — `breaking`/`additive`, `ABIDiff.hasBreakingChange` / `.isBackwardCompatible`. - 33 unit tests pass (`Tests/SwiftDiffingTests/`). -- **`SwiftDiffableInterfaceBuilder`** (in `Sources/SwiftInterface/`): +- **`SwiftDiffableInterfaceBuilder`** (in `Sources/Output/SwiftInterface/`): per-binary — `prepare()` indexes AND fully `index(in:)`-es every definition (members are lazy otherwise); `abiModule()` (1:1 passthrough of the indexer's 10 buckets); `snapshot()`. -- **`swift-section diff` CLI** (`Sources/swift-section/Commands/DiffCommand.swift`): +- **`swift-section diff` CLI** (`Sources/Executables/swift-section/Commands/DiffCommand.swift`): two file paths (thin/fat, arm64 slice) OR `--dyld-shared-cache -n SwiftUICore` two caches. Outputs `ABIDiffReporter` text + breaking verdict. - Validated end-to-end on SwiftUICore: iOS 18.6 vs 26.5 (standalone, 88s) and diff --git a/Documentations/Internal/ExportedOnlyInterfaceFiltering.md b/Documentations/Internal/ExportedOnlyInterfaceFiltering.md index 47e1fab12..51393fa38 100644 --- a/Documentations/Internal/ExportedOnlyInterfaceFiltering.md +++ b/Documentations/Internal/ExportedOnlyInterfaceFiltering.md @@ -69,14 +69,14 @@ conformance 扩展全部漏下来。所以 `SwiftInterfaceBuilder.printRoot()` ## 模块结构 ``` -Sources/SwiftPrinting/ +Sources/Output/SwiftPrinting/ ├── SwiftDeclarationPrintConfiguration.swift # printExportedDeclarationsOnly ├── SwiftDeclarationPrinter+ExportFilter.swift # ExportFilterScope、installExportFilterScope、类型 / 协议 verdict 的转发、全部 isExcludedByExportFilter 判定 ├── SwiftDeclarationPrinter.swift # 三个入口的过滤壳 + printIncluded… 体;成员循环 where 过滤;exportFilterScope 存储 └── SwiftDeclarationPrinter+Headers.swift # renderModelFields 的字段预筛 -Sources/SwiftDeclaration/Components/ExportStatus.swift # 四态枚举、两腿裁决、descriptorSymbolName 重整(提案 exported-declaration-flag) -Sources/SwiftInterface/SwiftInterfaceBuilder.swift # printRoot 装 scope;全局块 where 过滤 -Sources/swift-section/Commands/InterfaceCommand.swift # --exported-only +Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift # 四态枚举、两腿裁决、descriptorSymbolName 重整(提案 exported-declaration-flag) +Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift # printRoot 装 scope;全局块 where 过滤 +Sources/Executables/swift-section/Commands/InterfaceCommand.swift # --exported-only ``` ## 核心算法与数据流 diff --git a/Documentations/Internal/ExtensionContainerUnification.md b/Documentations/Internal/ExtensionContainerUnification.md index 654c7f093..4301397aa 100644 --- a/Documentations/Internal/ExtensionContainerUnification.md +++ b/Documentations/Internal/ExtensionContainerUnification.md @@ -26,18 +26,18 @@ ## 模块结构 ``` -Sources/SwiftDeclaration/Components/Definitions/ +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/SwiftIndexing/SwiftDeclarationIndexer.swift +Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift # index() 入口四桶重置;unifyExtensionContainers()(桶内同身份合并 + 协议附着); # 变量签名分桶的空 requirement 折叠;updateConfiguration 复位 isPrepared -Sources/SwiftInterface/SwiftInterfaceBuilder.swift +Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift # allExtensionDefinitions 过滤已附着项;嵌套协议扩展块循环修复 -Sources/SwiftPrinting/SwiftDeclarationPrinter.swift # renderMember 的默认实现标注 -Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift # dump 侧标注 +Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift # renderMember 的默认实现标注 +Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift # dump 侧标注 ``` ## 与提案的差异 diff --git a/Documentations/Internal/FieldMetadataRenderingMigration.md b/Documentations/Internal/FieldMetadataRenderingMigration.md index f4f18ea5b..ffa315b6e 100644 --- a/Documentations/Internal/FieldMetadataRenderingMigration.md +++ b/Documentations/Internal/FieldMetadataRenderingMigration.md @@ -12,7 +12,7 @@ **委托给 SwiftDump 的 dumper** 的: ```swift -// 重构前 main: Sources/SwiftInterface/SwiftInterfacePrinter.swift +// 重构前 main: Sources/Output/SwiftInterface/SwiftInterfacePrinter.swift let dumper = typeDefinition.type.dumper(using: .init(... printFieldOffset: ..., printTypeLayout: ...), metadata: typeDefinition.metadata, in: machO) ... @@ -111,7 +111,7 @@ layout / spare-bit / per-case type layout 全部集中到这里。`SwiftDump` 现象:model 驱动的接口(`SwiftDeclarationPrinter`)里,**重载下标与(合并的)`@objc func` 成员顺序每次运行都变**(同一批成员、同样 metadata,仅顺序不同)。dump 路径不受影响(它直接按 `symbolIndexStore.memberSymbols` 的有序结果渲染)。 -根因:`Sources/SwiftDeclaration/Components/Building/DefinitionBuilder.swift` 有 **3 处普通 `Dictionary` 迭代**,Swift 字典迭代顺序随进程哈希随机化: +根因:`Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift` 有 **3 处普通 `Dictionary` 迭代**,Swift 字典迭代顺序随进程哈希随机化: - `subscripts(...)`:`accessorsByNode: [Node: [Accessor]]`(重载下标都叫 "subscript",无法像 `variables` 那样按名排序); - `functions(...)` / `allocators(...)`:`pendingMergedBy*Node: [Node: ...]`(合并 thunk 尾部追加)。 diff --git a/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md b/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md index aec258a83..a003f56ed 100644 --- a/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md +++ b/Documentations/Internal/FinalKeywordAndLazyAccessorTypeRecovery.md @@ -26,7 +26,7 @@ class 成员是否 `final` 决定调用方走 dispatch thunk 还是直接符号 ## 模块结构 ``` -Sources/SwiftDeclaration/Components/ +Sources/Declaration/SwiftDeclaration/Components/ ├── Definitions/FieldDefinition.swift # + accessors / accessorTypeNode / isFinal / hasVTableAccessor ├── Definitions/VariableDefinition.swift # + isFinal(Function/Subscript 同形) ├── Definitions/TypeDefinition+Indexing.swift # 主干:折回 accessor 组 @@ -34,12 +34,12 @@ Sources/SwiftDeclaration/Components/ ├── Definitions/TypeDefinition+FinalRecovery.swift # final 标记块与它的四道门 ├── Building/DefinitionBuilder.swift # variables → variablesProduct(交还被抑制的 accessor 组) └── Building/OverrideSymbolMatcher.swift # + memberJoinKey(Tu 标记剥离) -Sources/SwiftPrinting/ +Sources/Output/SwiftPrinting/ ├── SwiftDeclarationPrinter+Members.swift # printThrowingField:final 关键字 + fieldTypeNode 取型 ├── SwiftDeclarationPrinter+Headers.swift # renderModelFields:stored var 的 vtable 注释 ├── SwiftDeclarationPrinter.swift # isFinal 传入三个 node printer └── NodePrintables/MemberDeclarationNodePrintable.swift # 三个成员 printer 共用的 printRoot 写 "final "(提案 node-printer-declaration-layer-and-context-roles 之前是 NodePrinter/{Variable,Function,Subscript}NodePrinter.swift 各写一份) -Sources/SwiftDump/ +Sources/Output/SwiftDump/ ├── Protocols/TypedDumper.swift # fieldDeclarationKeywords + isFinal 参数 └── Dumper/ClassDumper.swift # 名字级 join(vtableAccessorFieldNames / storedAccessorFieldNames) ``` diff --git a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md index 74d7817b6..abe763f30 100644 --- a/Documentations/Internal/FixtureTestingAndContinuousIntegration.md +++ b/Documentations/Internal/FixtureTestingAndContinuousIntegration.md @@ -30,7 +30,7 @@ CI 上可复现性是唯一判据: `MachOFileName.SymbolTestsCore` 存的是相对路径 `../../Tests/Projects/SymbolTests/DerivedData/...`,**不是**对 CWD 解析,而是对 -`Sources/MachOTestingSupport/Extensions.swift` 的 `#filePath` 解析——`../../` 爬回仓库根再下行。 +`Sources/TestSupport/MachOTestingSupport/Extensions.swift` 的 `#filePath` 解析——`../../` 爬回仓库根再下行。 而构建端 `xcodebuild -derivedDataPath Tests/Projects/SymbolTests/DerivedData` 是对 `xcodebuild` 自己的 CWD 解析。两者对齐**当且仅当**构建从仓库根发起——任何从子目录跑 `xcodebuild` 的 CI 步骤都会悄悄打破对齐。CI 还遇到过第三种形态:runner 上 `xcodebuild` diff --git a/Documentations/Internal/GenericArgumentSubstitution.md b/Documentations/Internal/GenericArgumentSubstitution.md index a86587966..26768e508 100644 --- a/Documentations/Internal/GenericArgumentSubstitution.md +++ b/Documentations/Internal/GenericArgumentSubstitution.md @@ -238,12 +238,12 @@ expanded offsets**(一个独立的 metadata 回归);修掉那个回归后 ## 10. 涉及的文件 / commit -- 实现:`Sources/SwiftDeclarationRendering/FieldLayoutRenderer.swift` +- 实现:`Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift` (`substitutingGenericParameters` / `staticallyBoundMetatype` / `boundGenericArgumentType` / `substitutedValueNode` / `substitutedPackNode` / `genericArgumentWord` / `topLevelGenericLayout`)。 -- 模型:`Sources/MachOSwiftSection/Models/Generic/`(`GenericParamDescriptor` / `GenericParamKind` / +- 模型:`Sources/ABI/MachOSwiftSection/Models/Generic/`(`GenericParamDescriptor` / `GenericParamKind` / `GenericPackShapeDescriptor` / `GenericPackShapeHeader` / `GenericValueDescriptor` / `GenericContext`)。 -- 运行期入口:`Sources/MachOSwiftSection/Runtime/RuntimeFunctions.swift` +- 运行期入口:`Sources/ABI/MachOSwiftSection/Runtime/RuntimeFunctions.swift` (`getTypeByMangledNameInContext(specializedFrom:)`——即 §2 那条“会 trap”的路径)。 - 关键 commit:`0107c8a`(引入静态替换止 trap)、value-generic 止崩与 `kind` 硬化、value/pack 渲染支持。 - 权威 ABI 出处:`swift/include/swift/ABI/{GenericContext.h, Metadata.h, MetadataValues.h}`、 diff --git a/Documentations/Internal/LeafMigrationRegressionAudit.md b/Documentations/Internal/LeafMigrationRegressionAudit.md index dec7c31b6..d6bceaf37 100644 --- a/Documentations/Internal/LeafMigrationRegressionAudit.md +++ b/Documentations/Internal/LeafMigrationRegressionAudit.md @@ -28,12 +28,12 @@ leaf",首发 0.12.0-beta.6)及其直接配套提交(`ebb04d3` 等)的全 ### 1. 多 payload 枚举 Enum Layout 注释:错误容忍丢失 + 每枚举线性重扫 -- 旧:`MultiPayloadEnumDescriptorCache`(`ebb04d3^:Sources/SwiftDump/Dumper/EnumDumper.swift:249-286`) +- 旧:`MultiPayloadEnumDescriptorCache`(`ebb04d3^:Sources/Output/SwiftDump/Dumper/EnumDumper.swift:249-286`) 每 image 构建一次 `[Node: MultiPayloadEnumDescriptor]`,构建循环整体 `do/catch { print(error) }` 并发布**部分** map——单个 descriptor demangle 失败只让 那一个枚举查不到、降级到 `calculateTaggedMultiPayload` 仍出注释。 - 新:`RuntimeFieldLayoutBackend.multiPayloadEnumDescriptor(for:in:)` - (`Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift:681-691`) + (`Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift:681-691`) 内联线性扫描且 `throws`,错误经 `computeEnumLayout` 传播到 `try? await` (`:539`)→ `enumLayout == nil`:**section 中任一坏 descriptor 都会抑制该枚举的 Enum Layout 策略行与全部 per-case 块**。同时每枚举重扫 + 重 demangle 全部 @@ -44,7 +44,7 @@ leaf",首发 0.12.0-beta.6)及其直接配套提交(`ebb04d3` 等)的全 ### 2. 嵌套 field-offset 展开:深度截断诊断丢失,测试钉在死常量上 - 旧:`walkNestedExpandedFieldOffsets` 触达深度上限时经 `@Loggable` 发 - `#log(.info, …)`(`ebb04d3^:Sources/SwiftDump/Protocols/TypedDumper.swift:522-551`)。 + `#log(.info, …)`(`ebb04d3^:Sources/Output/SwiftDump/Protocols/TypedDumper.swift:522-551`)。 - 新:`RuntimeFieldLayoutBackend.swift:200-201` 直接返回空 `SemanticString()`——截断 完全静默。 - 复合问题:`nestedFieldOffsetExpansionDepthLimit` 现有两份——活值在 @@ -59,9 +59,9 @@ leaf",首发 0.12.0-beta.6)及其直接配套提交(`ebb04d3` 等)的全 ### 3. Void payload 的枚举 case 丢括号,dump / interface 两路不一致 - 旧(dump 路径至今仍是):按 `!mangledTypeName.isEmpty` gating → `case a()` - (`Sources/SwiftDump/Dumper/EnumDumper.swift:105-115`)。 + (`Sources/Output/SwiftDump/Dumper/EnumDumper.swift:105-115`)。 - 新(interface 路径):按渲染文本 gating——`payloadText != "()"` - (`Sources/SwiftPrinting/SwiftDeclarationPrinter+Members.swift`,`printEnumCase`) + (`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Members.swift`,`printEnumCase`) → `case a`。同一枚举两路输出不同;无 baseline 覆盖,实际触发罕见。 - 建议:二选一统一(倾向 interface 形式更接近源码,可改 dump 路径对齐并记录)。 @@ -79,7 +79,7 @@ leaf",首发 0.12.0-beta.6)及其直接配套提交(`ebb04d3` 等)的全 - 旧:`dumpProtocolName` 对 nil protocol 节点塌缩为空 `SemanticString`(非 nil), 输出悬空的 `extension Foo: `(外加 `@retroactive` / global-actor 标记)。 -- 新:`Sources/SwiftPrinting/SwiftDeclarationPrinter.swift:234-235` 的 +- 新:`Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift:234-235` 的 `try?` + optional-chain 使 nil 节点 → 整个子句(含 `@retroactive` / actor 标记) 被丢弃,输出 `extension Foo`。 - 新输出更干净,但丢了 retroactive/actor 信号且无文档。建议:接受现状并记录,或 @@ -88,7 +88,7 @@ leaf",首发 0.12.0-beta.6)及其直接配套提交(`ebb04d3` 等)的全 ### 6. SwiftDump 中的死代码副本(漂移风险) - `AssociatedTypeDumper.mergedRecords` + `collectUniqueRecords` - (`Sources/SwiftDump/Dumper/AssociatedTypeDumper.swift:84`、`:117`)——interface + (`Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift:84`、`:117`)——interface 路径在 `SwiftDeclarationPrinter+Headers.swift` 持有等价复制品后,SwiftDump 原件 已无任何调用者。 - `nestedFieldOffsetExpansionDepthLimit` 死副本(见问题 2)。 @@ -108,9 +108,9 @@ leaf",首发 0.12.0-beta.6)及其直接配套提交(`ebb04d3` 等)的全 - diff 路径的 extension 头用 `conformingProtocolName.node.printSemantic(using: .default)` 而非 `.interfaceTypeBuilderOnly`,且缺 `@retroactive` / global-actor 标记——与 `printExtensionHeader` 对同一 extension 的拼写不一致 - (`Sources/SwiftInterface/SwiftDiffableInterfaceRenderer.swift:265-276`)。 + (`Sources/Output/SwiftInterface/SwiftDiffableInterfaceRenderer.swift:265-276`)。 - diff/snapshot 的 associated-type witness 投影按 **name 单键**去重且不做 - `resolveOpaqueType`(`Sources/SwiftIndexing/SwiftDeclarationIndexer.swift:615-627`): + `resolveOpaqueType`(`Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:615-627`): 同名不同 witness 的第二条被静默丢弃;opaque witness 以 `some P` 形态参与 diff 而 interface 打印的是解析后的 underlying type。 diff --git a/Documentations/Internal/MetadataReaderCacheRetirement.md b/Documentations/Internal/MetadataReaderCacheRetirement.md index 422e4f3ab..cd7a6d4ee 100644 --- a/Documentations/Internal/MetadataReaderCacheRetirement.md +++ b/Documentations/Internal/MetadataReaderCacheRetirement.md @@ -16,8 +16,8 @@ RuntimeViewer 索引五个系统镜像(Foundation + libswiftCore + AppKit + SwiftUI + SwiftUICore)后抓 memory graph,归因过程由两条独立线索相互印证:本仓库 `DeclarationModelMemoryFootprint.md` 第五节第 3 条的分析,和对面会话(swift-demangling 侧)的独立全量持有点扫描。归因结果分三条: -- **持有主体是 `MetadataReaderCache.Storage`**(`Sources/SwiftInspection/MetadataReader.swift:649-660`)的三张字典,value 都是整棵 class `Node` 树:`nodeForMangledNameBox`(mangled name → 树)、`nodeForContextOffset`(descriptor offset → 树)、`nodeForSymbolName`(symbol 名 → 树,或一个表示「demangler 拒绝过这个名字」的 `nil` 裁决)。 -- **只进不出**。这个类是 `private` 单例。按镜像清除的能力其实存在——`SharedCache.remove(for:)` 就在那里(`Sources/MachOCaches/SharedCache.swift:121`)——但没有任何公开 seam 能调到它。`SwiftDeclarationIndexer.deinit` 按镜像清理了 symbol store 和 `InternedNodeReferenceCache`(`SwiftDeclarationIndexer.swift:156-160`),偏偏清不到这里。唯一的出口是内存压力触发的全局 `removeAll`。 +- **持有主体是 `MetadataReaderCache.Storage`**(`Sources/Analysis/SwiftInspection/MetadataReader.swift:649-660`)的三张字典,value 都是整棵 class `Node` 树:`nodeForMangledNameBox`(mangled name → 树)、`nodeForContextOffset`(descriptor offset → 树)、`nodeForSymbolName`(symbol 名 → 树,或一个表示「demangler 拒绝过这个名字」的 `nil` 裁决)。 +- **只进不出**。这个类是 `private` 单例。按镜像清除的能力其实存在——`SharedCache.remove(for:)` 就在那里(`Sources/MachO/MachOCaches/SharedCache.swift:121`)——但没有任何公开 seam 能调到它。`SwiftDeclarationIndexer.deinit` 按镜像清理了 symbol store 和 `InternedNodeReferenceCache`(`SwiftDeclarationIndexer.swift:156-160`),偏偏清不到这里。唯一的出口是内存压力触发的全局 `removeAll`。 - **零跨树共享**。早前的 Stage 5c 把树的**构造**改成了 transient(不再向全局 `NodeCache` 灌节点),但没有改**持有**形态:每棵被缓存的树都自带私有的 `.module("Swift")`、`.identifier("Int")` 这类叶子副本。几万棵树里大量重复的子树,hash-consing 去重率为零。 用户裁决(2026-08-08,经 swift-demangling 会话转达):这套旧式简单缓存机制去掉,方案与审批按本仓库规矩走。 @@ -26,16 +26,16 @@ RuntimeViewer 索引五个系统镜像(Foundation + libswiftCore + AppKit + Sw | 位置 | 改什么 | |---|---| -| `Sources/SwiftInspection/MetadataReader.swift:649-660`(`MetadataReaderCache.Storage`) | 三张字典的 value 从 `Node` / `Node?` 换成 `NodeReference` / `NodeReference?`。键不动(`MangledNameBox` / `Int` offset / `String` symbol 名)。为什么键不用动:键做的是对「demangle 这件工作」的去重,store 做的是对「树这份数据」的去重,两层各管各的——与 `lateDemangledNode` 已落地的模式完全同构。 | +| `Sources/Analysis/SwiftInspection/MetadataReader.swift:649-660`(`MetadataReaderCache.Storage`) | 三张字典的 value 从 `Node` / `Node?` 换成 `NodeReference` / `NodeReference?`。键不动(`MangledNameBox` / `Int` offset / `String` symbol 名)。为什么键不用动:键做的是对「demangle 这件工作」的去重,store 做的是对「树这份数据」的去重,两层各管各的——与 `lateDemangledNode` 已落地的模式完全同构。 | | 同文件的六个缓存方法(`demangleType` ×2、`demangleContext` ×2、`buildContextManglingForSymbol` ×2) | miss 路径:现有的 `_demangle…` 构造瞬时树(不变)→ 经 `InternedNodeReferenceCache.shared.reference(interning:in:)`(镜像作用域)或 `reference(interning:)`(进程作用域)intern 进 store → 字典存引用 → 把刚 demangle 出的树直接返回给调用方。hit 路径:`reference.materialize()` 重建一棵独立树返回;`nil` 拒绝裁决直接返回 `nil`。`@_spi(Internals) import MachOSymbols` 本来就在(`MetadataReader.swift:8`),无新依赖。 | -| `Sources/SwiftInspection/MetadataReader.swift`(新增) | 补上缺失的清理 seam:`MetadataReader.removeCache(for:)`(`@_spi(Internals) public`),实现就是一句 `MetadataReaderCache.shared.remove(for: machO)`。 | -| `Sources/SwiftIndexing/SwiftDeclarationIndexer.swift:156-160`(`deinit`) | 在既有的两个按镜像 remove 旁边追加 `MetadataReader.removeCache(for: machO)`,让这份缓存与 symbol store / interned-name 桶按同一节奏回收。 | +| `Sources/Analysis/SwiftInspection/MetadataReader.swift`(新增) | 补上缺失的清理 seam:`MetadataReader.removeCache(for:)`(`@_spi(Internals) public`),实现就是一句 `MetadataReaderCache.shared.remove(for: machO)`。 | +| `Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:156-160`(`deinit`) | 在既有的两个按镜像 remove 旁边追加 `MetadataReader.removeCache(for: machO)`,让这份缓存与 symbol store / interned-name 桶按同一节奏回收。 | | AGENTS.md「Symbol indexing」段 | 同步措辞:`MetadataReader` 的 demangle memo 载荷已是 `NodeReference`(汇入 `InternedNodeReferenceCache` 作用域 store),且随 indexer 的按镜像清理一起释放。 | ## 明确不动的部分 - **公开 API 与 103 处调用点**。`MetadataReader.demangleType` / `demangleContext` 仍返回 `Node`。Sources 内 36 个文件共 103 处调用点一行不改(对面会话报 112 处,差值是测试代码的口径差)。 -- **`MultiPayloadEnumDescriptorCache` 的 `[Node: MultiPayloadEnumDescriptor]` 键**(`Sources/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift:32`)。对面会话判断「主缓存动了,它必须同批改键」,核实后**不成立**:class `Node` 的 `==` / `hash` 是**结构语义**(上游 `Node+Hashable.swift`——全子树结构摘要加 DAG 记忆化,实例身份只是快路径),所以换了缓存后端之后,build 时的键和查询时的键即使是不同实例也照常命中。这个缓存人口极小——每镜像的 multi-payload enum 数量级是百,树是短名字树——保留原样;它残留的少量 class `Node` 在预期残余 ≲2.3 万之内。 +- **`MultiPayloadEnumDescriptorCache` 的 `[Node: MultiPayloadEnumDescriptor]` 键**(`Sources/Output/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift:32`)。对面会话判断「主缓存动了,它必须同批改键」,核实后**不成立**:class `Node` 的 `==` / `hash` 是**结构语义**(上游 `Node+Hashable.swift`——全子树结构摘要加 DAG 记忆化,实例身份只是快路径),所以换了缓存后端之后,build 时的键和查询时的键即使是不同实例也照常命中。这个缓存人口极小——每镜像的 multi-payload enum 数量级是百,树是短名字树——保留原样;它残留的少量 class `Node` 在预期残余 ≲2.3 万之内。 - **`isCacheEnabled` 开关与 `demangleTypeUncached`**。语义不变。后者存在的理由——在 `SharedCache` 的 build 闭包内再进 `storage()` 会 trap,所以要有一条免重入路径——在新形态下依旧成立。 - **`GenericArgumentEnvironment.swift:250` 往 `NodeCache.shared` 叶子表灌节点**。对面会话留档的次要项,属于剩余约 11% 的一部分,不在本次范围。 diff --git a/Documentations/Internal/MetadataReaderRefactoring.md b/Documentations/Internal/MetadataReaderRefactoring.md index b3e107f7b..d9496ca55 100644 --- a/Documentations/Internal/MetadataReaderRefactoring.md +++ b/Documentations/Internal/MetadataReaderRefactoring.md @@ -216,7 +216,7 @@ The cache key can use the mangledName's elements, which are context-independent. ## Files to Modify -1. `Sources/MachOReading/Reading/ReadingContext.swift` - Add `addressFromOffset` -2. `Sources/MachOReading/Reading/MachOContext.swift` - Implement `addressFromOffset` -3. `Sources/MachOReading/Reading/InProcessContext.swift` - Implement `addressFromOffset` -4. `Sources/SwiftInspection/MetadataReader.swift` - Refactor to use generic context +1. `Sources/MachO/MachOReading/Reading/ReadingContext.swift` - Add `addressFromOffset` +2. `Sources/MachO/MachOReading/Reading/MachOContext.swift` - Implement `addressFromOffset` +3. `Sources/MachO/MachOReading/Reading/InProcessContext.swift` - Implement `addressFromOffset` +4. `Sources/Analysis/SwiftInspection/MetadataReader.swift` - Refactor to use generic context diff --git a/Documentations/Internal/Modules/MachOCaches.md b/Documentations/Internal/Modules/MachOCaches.md index 401179b18..7a9e41506 100644 --- a/Documentations/Internal/Modules/MachOCaches.md +++ b/Documentations/Internal/Modules/MachOCaches.md @@ -10,7 +10,7 @@ 它回答一个问题:**一个镜像的某种一次性建好的索引放在哪、谁建、谁清。** 符号表(`SymbolIndexStore`)、interned 名字池(`InternedNodeReferenceCache`)、ObjC 方法表(`ObjCClassMethodIndex`)、`_symbolic` 符号索引(`SymbolicManglingIndex`)……每一种都是「按镜像算一次、之后人人共享」的东西,它们的持有者各在自己的模块里,共用的机制在这里: - `SharedCache`:按镜像的 get-or-build。同一镜像的并发首次访问只建一次,构建在锁外跑。 -- `SharedCacheKey`:镜像的键,只哈希 UUID 或基址。 +- `SharedCacheKey`:镜像的键,只哈希 UUID(从 dyld cache 读出的镜像再加上所在 cache 的 UUID)或基址。 - `SharedCacheRegistry` + `SharedCacheEvictionGroup`:谁认领了哪个镜像的哪些缓存、最后一个持有者走了清什么、宿主想在内存压力下清什么。 - `SharedCacheBuildPromise`:在途构建的会合点,等待者在 `NSCondition` 上睡。 @@ -62,12 +62,14 @@ package final class ObjCClassMethodIndex: @unchecked Sendable { ## 2. 键(`SharedCacheKey`) -`MachORepresentableWithCache` 的两个 conformer(`MachOFile`、`MachOImage`)的 identifier 都是 `MachOTargetIdentifier`:文件按 `LC_UUID` 加路径(`.uuidFile`),没有 UUID 的文件按 `LC_BUILD_VERSION` 或裸路径,进程内镜像按基址(`.image`)。以前键是 `AnyHashable(machO.identifier)`:`.uuidFile` 的载荷超过 existential 的 24 字节内联缓冲,每次查找一次堆分配,再把整条路径喂给 SipHash——而查找发生在按符号、按 mangled name 的循环里。 +`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(链接器按构建唯一分配,单独就能区分镜像),`.image` 只哈希指针,`.file` / `.versionedFile` 才哈希路径;**等值比较仍比完整值**,路径不同的两个键相等测试不通过,只是哈希相同。identifier 不是 `MachOTargetIdentifier` 的读者(今天没有)走 `.opaque(AnyHashable)` 兜底。`SharedCacheKey(opaque:)` 同时是测试造键的入口。 +`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 的声明取并集。今天的对照: diff --git a/Documentations/Internal/Modules/MachODependencies.md b/Documentations/Internal/Modules/MachODependencies.md index c6ead23f8..650b35968 100644 --- a/Documentations/Internal/Modules/MachODependencies.md +++ b/Documentations/Internal/Modules/MachODependencies.md @@ -28,6 +28,8 @@ MachODependencies 回答一个问题:**一个二进制链接了哪些镜像, 打不开的搜索路径**不抛错**,记进 `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` 钉住了共用。 + ## 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` 锁定)。 @@ -47,6 +49,8 @@ bare name 同时是所有依赖集合的**去重键**:同一个库会被不同 **平台守卫**(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`) @@ -84,6 +88,8 @@ providerDependencies.unresolvedLoadNames // 精确报告解析不到的依赖 - `Tests/MachODependenciesTests/DependencyLoadNameTests.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` — 端到端:闭包驱动的跨模块字段偏移(未改动)。 diff --git a/Documentations/Internal/Modules/MachOSymbols.md b/Documentations/Internal/Modules/MachOSymbols.md index 1662c163d..40df4b7eb 100644 --- a/Documentations/Internal/Modules/MachOSymbols.md +++ b/Documentations/Internal/Modules/MachOSymbols.md @@ -27,6 +27,10 @@ MachOSymbols 是**符号索引**层:把一个镜像的符号表和 export trie 存储形态是每个唯一符号名一行 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:)`)。只带名字的那几个重载会故意把所有子桶摊平,只用于「所有打印成这个名字的类型」这种聚合查询。 diff --git a/Documentations/Internal/Modules/README.md b/Documentations/Internal/Modules/README.md index c153716f9..207fcb661 100644 --- a/Documentations/Internal/Modules/README.md +++ b/Documentations/Internal/Modules/README.md @@ -14,7 +14,8 @@ | 模块 | 文档 | 说明 | |---|---|---| | SwiftInterface | [SwiftInterface.md](SwiftInterface.md) | ✅ 已写 | -| swift-section (CLI) | — | 待写 | +| SwiftSectionKit | [SwiftSectionKit.md](SwiftSectionKit.md) | ✅ 已写(调用方指南:[SwiftSectionKit.md](../../SwiftSectionKit.md)) | +| swift-section (CLI) | [SwiftSectionKit.md](SwiftSectionKit.md) | ✅ 已写(与 SwiftSectionKit 同篇:包装层只剩 flag 映射、错误翻译、流路由与退出码) | | SwiftIndexing | — | 待写 | | SwiftPrinting | — | 待写 | | SwiftSpecialization | — | 待写 | diff --git a/Documentations/Internal/Modules/SwiftInterface.md b/Documentations/Internal/Modules/SwiftInterface.md index 12724c7af..cef2f03a5 100644 --- a/Documentations/Internal/Modules/SwiftInterface.md +++ b/Documentations/Internal/Modules/SwiftInterface.md @@ -84,7 +84,8 @@ N ≥ 2 版本渲染成**一份**并集接口,声明尾注生命周期注解 - **渲染文本来自活模型**:每个声明由最后携带它的版本的 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 锚定,是真不同语义。 -- **结构化流**:`@_spi(Support) annotatedBlocks()` → `[[EvolutionLine]]`(`EvolutionAnnotation` 是纯数据——presence bitmap + `LineageEvent`s),宿主可自行着色/折叠。 +- **真 `@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` 属性行),宿主可自行着色/折叠。 限制:输入必须全是 binary(snapshot 没有可渲染接口);协议的 `pwtslot:` 记录不渲染(没有对应声明,与 `diff --interface` 一致,变化仍见于 lineage 报告与 JSON)。 @@ -94,7 +95,7 @@ N ≥ 2 版本渲染成**一份**并集接口,声明尾注生命周期注解 |---|---| | `swift-section interface` | `SwiftInterfaceBuilder`(+ `--resolve-c-module-names` 挂 TypeIndexing provider,opaque provider 只在 `--parse-opaque-return-type` 下挂,默认关) | | `swift-section diff --interface` | `SwiftDiffableInterfaceBuilder` ×2 + `SwiftDiffableInterfaceRenderer` | -| `swift-section evolution --interface` | `AnySwiftEvolutionInterfaceBuilder`(与 `--json`/`--summary-only` 互斥) | +| `swift-section evolution --interface` | `AnySwiftEvolutionInterfaceBuilder`,经 SwiftSectionKit 的 `ABIEvolutionRequest`(与 `--json`/`--summary-only` 互斥;`--emit-available` 打开 `@available` 属性,即 `Report.annotatedInterface(availabilityAttributes:)`:平台名从每个输入的 `LC_BUILD_VERSION` 推断,模拟器变体按对应的设备平台算,`--platform` 可以覆盖;推断不出或输入之间互相冲突时抛 `AvailabilityPlatformInferenceError`,命令行译成 usage 错误,不会悄悄地不发属性) | | `swift-section diff` / `snapshot` / `evolution`(数据路径) | `SwiftDiffableInterfaceBuilder.abiModule()/snapshot()` → SwiftDiffing | | RuntimeViewer 等宿主 | `@_spi(Support)`:indexer/printer 直达、`annotatedDiffBlocks()`、`annotatedBlocks()`;`InterfaceHeaderBlock` 是独立组件(per-type 导出不走 `printRoot`) | diff --git a/Documentations/Internal/Modules/SwiftSectionKit.md b/Documentations/Internal/Modules/SwiftSectionKit.md new file mode 100644 index 000000000..a2d1f8eba --- /dev/null +++ b/Documentations/Internal/Modules/SwiftSectionKit.md @@ -0,0 +1,82 @@ +# SwiftSectionKit 模块(及 swift-section 可执行文件) + +> 模块参考文档(module reference),随代码维护。读者:维护者。 +> 提案:[0058-swift-section-kit](../../Evolutions/0058-swift-section-kit.md)、[0059-dump-declaration-identity](../../Evolutions/0059-dump-declaration-identity.md)、[0060-evolution-interface-available-annotations](../../Evolutions/0060-evolution-interface-available-annotations.md)(只涉及 `ABIEvolutionRequest`)。调用方指南:[SwiftSectionKit.md](../../SwiftSectionKit.md)。 + +## 模块定位 + +SwiftSectionKit 是 `swift-section` 每个子命令的库版本:一个子命令对应一个请求类型,`run(output:…)` 执行,产物和诊断交给调用方注入的 `SwiftSectionOutput`。它位于依赖图的最顶层,在 `SwiftInterface`、`SwiftDump`、`SwiftDiffing`、`TypeIndexing` 和 MachOObjCSection 的 ObjC 产品之上;对外是一个 product。 + +`swift-section` 可执行文件是它的包装层,只做五件事:声明 flag(`--help` 文本就是 flag 声明本身)、`validate()` 里的 flag 组合校验、把 flag 映射成请求(`makeRequest()`)、把库的错误翻译回命令行的历史文案、决定诊断写哪个流以及退出码。**命令的新逻辑一律写进 SwiftSectionKit**,可执行文件里只放「命令行怎么拼写」的东西。 + +这样分的直接收益是可测:请求是 `Equatable` 的值,输出端可以换成内存记录器,时间与生成器名可以注入,所以每个子命令都能在测试进程里端到端跑完再断言。拆分之前,79 个 CLI 测试没有一个调用过 `run()`。 + +## 文件 → 子系统对照 + +| 子系统 | 文件 | +|---|---| +| 1. 输出端 | `Output/SwiftSectionOutput`、`SwiftSectionProduct`(含 `InterfaceAnnotationStyle` / `AnnotatedLineKind`)、`DumpedDeclaration`、`SwiftSectionDiagnostic`、`ProductDestination` | +| 2. 环境 | `Environment/SwiftSectionEnvironment`(含 `GeneratorIdentity`) | +| 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`) | +| CLI 包装层 | `Sources/Executables/swift-section/`:各命令的 `makeRequest()` + `run()`、`Models/CommandLineSupport`(flag → `MachOSource`、错误翻译、`ExpressibleByArgument`)、`Output/StandardStreamOutput` | + +## 1. 输出端 + +三路分开:`write(_:)` 收产物,`report(_:)` 收诊断,`indexEventHandlers(forInputLabeled:)` 给索引事件的 handler(默认空数组,即落到 `Dispatcher` 的 os_log 地板)。分开是为了宿主永远不用从一串进度行里挑产物。 + +**换行语义是盘点出来的契约**:现有的每一处 stdout 写入都等于「内容 + 换行」——`print(x)` 如此;annotated interface 按行着色后逐行补换行,拼起来恰好也是「全文 + 换行」;`snapshot` 的 `fwrite` 加 `fputs("\n")` 同样如此。所以 `SwiftSectionProduct` 每一块打印时都跟一个换行,`StandardStreamOutput` 照此写,`RecordingOutput.printedProduct` 照此拼。 + +**写文件不经过输出端**:`ProductDestination.file(path:)` 时由请求自己写文件,因为各命令写文件的老规矩不一样——`interface` / `diff` / `objc interface` / `transformer config` 写入的文本末尾不补换行,`evolution` 补,`dump` / `objc dump` 每块补。目的地携带路径字符串而不是 `URL`:「Report written to …」这类诊断要逐字复述调用方的拼写,而 `URL(fileURLWithPath:)` 会把 `dir/` 规整成 `dir`、把 `~/x` 展开(实测)。 + +**诊断 = 级别 + 原文**。原文就是命令行打出来的那句话,有些带 flag 名("warning: --resolve-c-module-names …")——这是「输出逐字节保持」的代价。级别决定命令行把它写到哪个流,这张路由表只存在于包装层:`interface` 的 `.progress` 和 `dump` 的 `.error` 写 stdout(历史怪癖,插件 skill 第 3 节专门警告过不要重定向 `interface` 的 stdout),其余写 stderr。以后修这两个怪癖只改两个命令的 `standardOutputSeverities`,库不用动。 + +**并发**:`diff` / `evolution` 并行索引多个输入,会从多个任务同时调用输出端,所以协议要求 `Sendable` 且实现必须线程安全。`StandardStreamOutput` 的每次写入是一次 `fwrite`(stdio 自带流锁);测试的 `RecordingOutput` 用锁。 + +**每块声明是什么**(提案 [0059-dump-declaration-identity](../../Evolutions/0059-dump-declaration-identity.md)):`dump` 与 `objc dump` 交出顶层声明时走 `write(_:declaring:)`,附一个 `DumpedDeclaration`——Swift 侧是来自哪个 `DumpSection` 加名字,ObjC 侧是 `ObjCDeclarationKind` 加名字。它是协议要求,扩展里的默认实现转给 `write(_:)`,所以 `StandardStreamOutput` 和 `RecordingOutput` 都不实现它,输出与以前逐字节相同;宿主要按声明拆文件时才实现。几条从签名看不出来的事: + +- **名字只在 `.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("")` 空行也是。 +- 代价是每个 Swift 声明多解析一次名字,命令行用不上也要付;落地前用 release 版对大镜像实测了耗时,见提案的决策日志。 + +## 2. 环境 + +`SwiftSectionEnvironment` 只装「请求会盖进产物、但不该由它自己去读进程状态」的两样东西:生成器名与版本(interface header、snapshot provenance),以及当前时间(provenance 的 `createdAt`)。CLI 传 `swift-section` 和 `BundledVersion.value`——版本号文件仍在 `Sources/Executables/swift-section/Version.swift`,`version-check.yml` / `release.yml` 写死的路径不用改;测试传固定值,两次运行的字节完全相同。`transformer` 的三个请求不盖任何东西,`run(output:)` 不收环境。 + +## 3. 输入 + +`MachOSource` 是全部请求共用的唯一加载器(原 CLI 的 `MachOFile.load`):文件(胖二进制按 `architecture` 挑切片,瘦二进制忽略它)、指定 cache 文件里的镜像、宿主 cache 里的镜像。cache 一律经 `FullDyldCache` 读(会映射子 cache;只读主 cache 文件的 `DyldCache` 会把落在子 cache 里的镜像读出界,见提案 0036 的动机)。 + +原 CLI 的 `SwiftSectionCommandError` 里有三种 flag 组合在 `MachOSource` 上写不出来(缺文件路径、`-n` 与 `-p` 同时给、`--dyld-shared-cache` 缺镜像名),它们留在包装层,由 `makeMachOSource(…)` 抛出、文案不变。`failedFetchFromSystemDyldSharedCache` 从来没被抛过,已删除。 + +`SnapshotSource.path` 是 `snapshot` / `diff` / `evolution` 的输入:snapshot 文档(JSON)或二进制,按文件第一个非空白字节区分(`{` 即文档)。annotated interface 只能吃二进制,`SnapshotSource.requireBinaries` 在加载任何输入之前就逐个检查,出错抛 `SnapshotSourceError.binaryRequired(path:)`。`BinaryLoadingOptions` 只作用于二进制输入:`dyldSharedCacheImage` 一旦给出,每个二进制输入都按 cache 文件处理、从中取同名镜像。 + +## 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()`,原文不动。 +- **请求是 `Equatable` 的值**,`run` 的依赖(输出端、环境)是参数而不是字段。包装层的测试靠这一点:解析 flag → `makeRequest()` → 与期望请求比较(`CommandRequestMappingTests`)。 +- **库只报告,不退出**:`ABIDiffOutcome.hasBreakingChange` 等结论由包装层对照 `--fail-on-breaking` 决定是否 `throw ExitCode.failure`。`diff --interface` 只在 `includesBreakingChangeVerdict` 时才额外算一遍 change-list diff,和原来「只有 CI 闸门需要它」的取舍一致。 +- **命令行拼写留在包装层**:模板名还是字面模板(`TransformerTemplateResolver`)、`--transformer-config` 的 JSON 文件、逗号分隔的 `--labels` / `--sections`、`--c-type-replacement` 的 `a=b`、demangle 的二十多个覆盖开关,都由包装层解释成库的值类型(`Transformer.SwiftConfiguration`、`[ObjCPrimitiveTypePattern: String]`、`DemangleOptions`…)再交给请求。代价见下一节的偏差 2。 + +## 5. 与拆分前的行为差异(只有两类) + +stdout、stderr、退出码、每个子命令的 `--help` 都与拆分前逐字节一致,只有下面两类例外,均有意为之: + +1. **写流统一走 `fwrite`**。`objc` 子命令以前经 `FileHandle.standardOutput/standardError.write(_:)` 写,stderr 被关闭时写一行提示就让进程 abort——实测旧二进制 `objc dump --sections unions 2>&-` 退出码 134,新的是 0。Swift 侧的 `snapshot` 早就因为同一原因改成了 `fwrite`。`CommandLineStreamWriteScanTests` 用源码扫描把整类写法挡在包装层之外。 +2. **参数层面的错误先于打开二进制报出**。命令行拼写在调用库之前解释,所以只写错一处时文案与退出码不变、只是不用等加载;同时写错二进制路径和这类参数时先报后者。同一原因带来的三个边角:`objc --verbose` 下 C type 替换串的错误前不再有进度行;`interface` 的「--supplementary-apinotes has no effect」警告在加载前就发出(加载失败时也会出现);`snapshot` 给 snapshot JSON 输入同时乱写 `--dyld-shared-cache` 现在会报错(以前因为没走到加载而被忽略)。另有一处随之消失的怪癖:`snapshot` 对普通文件给 `-n` / `-p`(帮助里写着会被忽略)时,provenance 的 `binaryPath` 不再带上那个没用到的镜像名。 + +## 6. 测试锚点 + +- `Tests/SwiftSectionKitTests/`:每个请求对 SymbolTestsCore fixture 端到端跑(`ABIRequestTests`、`DumpAndInterfaceRequestTests`、`ObjCRequestTests`、`TransformerRequestTests`),加纯逻辑(`MachOSourceTests` 里的胖二进制是测试现场拼的单切片胖文件,不依赖宿主;`InterfaceAnnotationStyleTests`;从 CLI 搬来的 `ObjCDumpDiagnosticsTests`)。`ABIRequestTests` 整个套件共用一份 fixture 的 snapshot 文档(静态 `Task`),只索引一次。它测 `@available` 平台推断失败时,平台不同的输入是现场改写了 `LC_BUILD_VERSION` 的 fixture 副本(`FixtureFiles.makeCopy(of:buildPlatform:in:)`);副本的 UUID 与原件相同,每个按镜像的缓存都会把它当成原件,所以只能交给在索引之前就结束的用例。`RecordingOutput` 只实现 `write(_:)`,所以用它的用例同时在测 `write(_:declaring:)` 的默认实现;要看每块声明是什么,用 `DeclarationRecordingOutput`(两个方法都实现,按顺序记下每块产物和它带的声明)。 +- `Tests/SwiftSectionCommandTests/`:原有的解析测试;`CommandRequestMappingTests`(flag → 请求)、`CommandLineErrorTranslationTests`(库错误 → 历史文案与退出码)、`StandardStreamOutputTests`(内存流读回字节;`Rainbow.enabled` 与 `outputTarget` 是进程全局量,套件 `.serialized` 并在测试内钉住、用完还原)、`CommandLineStreamWriteScanTests`。 +- `PrintFailureEventTests.libraryModulesWriteToNoProcessStream` 的豁免名单只有 `swift-section` 和 `MachOTestingSupport`,`SwiftSectionKit` 自动被扫描:库里出现任何 `print` / `fputs` / `FileHandle.standard*` 都会变红。 + +## 7. 加一个 flag / 子命令 + +1. 在请求类型上加字段(带默认值,保持源码兼容),在 `run` 里实现。互斥的就并进已有的 enum。 +2. 在命令里加 `@Option` / `@Flag`,在 `makeRequest()` 里映射;需要拒绝的组合写进 `validate()`。 +3. 库的新错误用中性措辞;命令行要另一种说法或要 `ValidationError` 的退出码 64,就在 `CommandLineErrorTranslation` 里加一条。 +4. 测试两头各一条:库侧对 fixture 断言行为,包装层断言 flag 到字段的映射。 +5. 同批改插件 skill(`AgentPlugins/swift-section/skills/swift-section-cli/`)与 README 的 CLI 章节。 diff --git a/Documentations/Internal/NestedFieldOffsetCycleGuard.md b/Documentations/Internal/NestedFieldOffsetCycleGuard.md index 91d6a9a65..a58a96215 100644 --- a/Documentations/Internal/NestedFieldOffsetCycleGuard.md +++ b/Documentations/Internal/NestedFieldOffsetCycleGuard.md @@ -49,8 +49,8 @@ struct 持有 `Optional>`,而这个 en | 文件 | 引擎 | |---|---| -| `Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` | 运行时(`MachOImage`,进程内 metadata) | -| `Sources/SwiftLayout/NestedFieldOffsetTree.swift` | 静态(`MachOFile`,离线描述符) | +| `Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` | 运行时(`MachOImage`,进程内 metadata) | +| `Sources/Analysis/SwiftLayout/NestedFieldOffsetTree.swift` | 静态(`MachOFile`,离线描述符) | 两者不共享代码,因此各自需要自己的守卫与回归测试。 diff --git a/Documentations/Internal/NodeStoreMigrationOpenIssues.md b/Documentations/Internal/NodeStoreMigrationOpenIssues.md index 05ca4a708..0cd080b38 100644 --- a/Documentations/Internal/NodeStoreMigrationOpenIssues.md +++ b/Documentations/Internal/NodeStoreMigrationOpenIssues.md @@ -92,7 +92,7 @@ - `allOpaqueTypeDescriptorSymbols(in:)` 在 `Sources/` 与 `Tests/` 中**零调用点**。 - RuntimeViewer 的 `main` 与 `feature/node-store-adoption` 两条分支均未调用这两个 API。 -当时给将来重开留的修法:vend `StructuralNodeReferenceKey`(或 `Node`)作键,或不暴露裸字典而改提供查询方法;修复位置在本仓库 `Sources/MachOSymbols/SymbolIndexStore.swift`。 +当时给将来重开留的修法:vend `StructuralNodeReferenceKey`(或 `Node`)作键,或不暴露裸字典而改提供查询方法;修复位置在本仓库 `Sources/MachO/MachOSymbols/SymbolIndexStore.swift`。 > **2026-08-14 更新——「不修」裁决已被推翻,两处均已按上述修法改为 `StructuralNodeReferenceKey` 键。** 上面记录的事实(类型级 SPI、包内调用点只遍历、RuntimeViewer 零调用)复核后仍然成立;推翻的理由是:同一类 bug 已经真实造成过一次回归——NodeStore 迁移 Stage 5a(声明层换持 `NodeReference` 的那一阶段)曾因裸键丢掉 `override` 关键字与 vtable offset 注释,单条查询版正是为此改成结构化键,这两个批量版是那次修复漏下的——且修复成本是每处一行。完整裁决见 [`ReviewAdjudications.md`](ReviewAdjudications.md) 的 A9(该文件是 code review 裁决的汇总台账,A 编号是其中的裁决序号)——**A9 是这一裁决的权威记录,本条不再单独维护**。 @@ -129,7 +129,7 @@ **可选优化**:在 `Storage.init` 里一次性建一份 `[StructuralNodeReferenceKey: NodeStore.NodeIndex]` 旁路索引——opaque 类型查找那一侧最终就是这么修的(2026-08-13 起为 `opaqueTypeDescriptorSymbolRowByMemberNode: [StructuralNodeReferenceKey: UInt32]`,单次哈希命中)。注意本条早先点名效仿的 `opaqueTypeDescriptorEntriesByMemberIdentifier`(按 `DemanglingNode.identifier` 分桶)是已被裁定不充分并移除的过渡手法——identifier 是成员名,SwiftUI 的 `some View` 实现几乎全叫 `body`,单桶数百项、桶内扫描仍是二次方;照抄它会复现已修掉的问题。收益上限受限于上面引用块里的实测,排期时不应优先于真正的回归项。 -**修复位置**:本仓库 `Sources/MachOSymbols/SymbolIndexStore.swift`。 +**修复位置**:本仓库 `Sources/MachO/MachOSymbols/SymbolIndexStore.swift`。 ### 6. ~~build sweep 由并行改为串行,且每个符号都无条件跨线程往返~~ —— 跨线程往返已修 ✅(2026-08-02,本仓库侧) @@ -149,7 +149,7 @@ 成因:`ABIKey.make(for:)` / `makeUnwrappingType(for:)` 泛型化到 `DemanglingNode` 之后,走的是 `mangleAsString` 的 `DemanglingNode` 重载,其实现是 `mangleAsString(node.materializedNode)`。而 `TypeName.node` / `ProtocolName.node` / `FieldDefinition.typeNode` / `FunctionDefinition.node` 现在全是 `NodeReference`,于是构建 `ABISnapshot` 时每个类型、协议、扩展容器、成员、字段的 key 都会重建一整棵 class 树再丢掉。 -当初认定的修法:`mangleAsString` 增加一条 store 原生路径(上游),或 `ABIKey` 改成每个声明 materialize 一次而非每个 key 一次(本仓库 `Sources/SwiftDiffing/ABIKey.swift`),取决于选哪条路。 +当初认定的修法:`mangleAsString` 增加一条 store 原生路径(上游),或 `ABIKey` 改成每个声明 materialize 一次而非每个 key 一次(本仓库 `Sources/Output/SwiftDiffing/ABIKey.swift`),取决于选哪条路。 **上游 `0.5.0` 状态(2026-08-03 核对):仍然打开。** `mangleAsString(_ node: some DemanglingNode)` 的实现依旧是 `mangleAsString(node.materializedNode)`(`RemangleInterface.swift:49`);根治需要 `Remangler` 泛型化到 `DemanglingNode`。本仓库侧每个 key 本来只 materialize 一次,无重复可省。 diff --git a/Documentations/Internal/ObjCImplementationClassRecognition.md b/Documentations/Internal/ObjCImplementationClassRecognition.md index 2272342ba..dc2670d0b 100644 --- a/Documentations/Internal/ObjCImplementationClassRecognition.md +++ b/Documentations/Internal/ObjCImplementationClassRecognition.md @@ -32,8 +32,8 @@ SE-0436 的 `@objc @implementation extension` 让 ObjC 头文件里声明的类 ## 两个 join 是怎么做的 -- **ivar ↔ `Wvd` 符号**:按**偏移值**。ivar_t 的 `offset` 字段指向的就是 `Wvd` 符号命名的那个全局变量,索引读出该全局变量的值(一个 word)与 `ivar.offset(in:)` 相等即配对。之所以不按名字:即时编译的 fixture 里头文件声明的 `title` 属性其 ivar name 字段是空指针;名字只作兜底。`Wvi`(间接字段偏移)不参与,`@implementation` 类没有 field offset vector,编译器也不会给它发 `Wvi`。 -- **存储属性 ↔ 成员定义**:按 Swift 属性名。`attachObjCImplementation(_:)` 把 `VariableDefinition.objcImplementationStorage` 填上,打印器据此改打存储形态;没对上的 ivar 由 `unrepresentedObjCImplementationInstanceVariables` 单独渲染,有 `Wvd` 的打 `var name: Type`,没有的打一行诚实注释。 +- **ivar ↔ `Wvd` 符号**:按**偏移值**。ivar_t 的 `offset` 字段指向的就是 `Wvd` 符号命名的那个全局变量,索引读出该全局变量的值(一个 word)与 `ivar.offset(in:)` 相等即配对。之所以不按名字:即时编译的 fixture 里头文件声明的 `title` 属性其 ivar name 字段是空指针;名字只作兜底。`Wvi`(间接字段偏移)不参与,`@implementation` 类没有 field offset vector,编译器也不会给它发 `Wvi`。符号里 `variable` 节点的名字有两种形状:普通属性是 `identifier`;`private` / `fileprivate` 属性和**每个 `lazy var` 的合成存储**(编译器总把它设为 private,不管属性本身写的什么访问级别)是 `privateDeclName`(鉴别符 + 名字)。第一版只认前者,这两类 ivar 在符号齐全的二进制里也拿不到类型,打出「Swift type not recoverable」注释,对应的成员还被打成 `{ get set }` 的计算属性(2026-09-29 修复)。 +- **存储属性 ↔ 成员定义**:按 Swift 属性名。`attachObjCImplementation(_:)` 用 `ObjCImplementationClassFacts.storageInstanceVariable(forPropertyNamed:)` 把 `VariableDefinition.objcImplementationStorage` 填上,打印器据此改打存储形态;没对上的 ivar 由 `unrepresentedObjCImplementationInstanceVariables` 单独渲染,有 `Wvd` 的打 `var name: Type`,没有的打一行诚实注释。`lazy var x` 的存储名是 `$__lazy_storage_$_x`,永远对不上属性自己的名字,所以查询先按原名找、找不到再找 `lazyPropertyName == x` 的 ivar。`lazyPropertyName` 读 Swift 名,`Wvd` 被剥掉后读 ObjC ivar 名,两者拼法相同(macOS 27.0 AppKit 的 `_NSTextFormattingViewController.campoTextSuggestionsViewController` 就是后一种:访问器导出,存储的 `Wvd` 是 local 符号、被剥掉了);只靠 ObjC 名连上的存储没有 Swift 名,所以「已有成员代表」的判断除按 Swift 名外还按对象身份。渲染规则照抄 Swift 类型自己的 lazy 字段:interface 打 `lazy var x: `,没有 getter 可连时打存储类型 `Optional<…>`;dump 与 `ClassDumper` 一样打 `lazy var x: <存储类型>`。 ## 边界与已知限制 @@ -43,6 +43,11 @@ SE-0436 的 `@objc @implementation extension` 让 ObjC 头文件里声明的类 - **IMP 偏移语义随 reader 变**:MachOFile 上 ObjC reader 给的是相对 header(cache 镜像为相对主 cache)的偏移,MachOImage 上是地址;索引按 reader 各自换算,dump 用 `addressString(forOffset:)` 打印。 - **在非主模块实现的 `@implementation`**(头文件在别的框架里)只得到 non-unique accessor,不进导出表;那种类靠 `Wvd` 或 inferred 档。 - **`-exported_symbols_list` 为空再 `strip -x` 的 app 二进制**只剩 inferred 档;一个存储属性类型全部 ObjC 可表示的类(没有 `?` / 空 encoding)在这种镜像里识别不到,输出维持今天的形态。 +- **Swift 侧的名字和类型只在符号里**:编译器不给 `@implementation` 类发 field descriptor(`GenReflection.cpp` 在 `getObjCImplementationDecl()` 时置 `needsFieldDescriptor = false`),也没有 vtable 和 method descriptor。符号的链接属性跟 Swift 访问级别走,SE-0436 又不要求这些成员写 `public`,所以系统 cache 里剥掉 local 符号的 AppKit 只剩 `public` 成员和编译器合成的 `override init()`(它取被实现类的访问级别,而导入的 ObjC 类是 public)。实测 macOS 26.7 AppKit 的 38 个类,Swift 侧成员与 export trie 逐类一致:NSScreen 有 138 个 ObjC 方法,Swift 侧只有 6 个。ObjC 方法表永远完整,dump 的 ObjC 段照常全列。 +- **ivar 编码**:`""` 表示这个存储属性不是 `@objc`(`final` / `@nonobjc` 的 Swift 独有成员、`lazy var` 的存储);`"?"` 表示是 `@objc`,但存储类型不能直接用 ObjC 表示(桥接的 `String` 与集合、`weak`、`AnyObject.Type`、闭包、可选的 typed enum)。ObjCSection 把这两种都打成 `Unknown`。 +- **`weak` / `unowned` 不打**:`Wvd` 的 mangled 类型不带引用的所有权修饰,这个信息普通 Swift 类放在 field descriptor 里,这类类没有;`weak var delegate` 因此打成普通 `var`。 +- **编译期限制**:`@implementation` 的实例属性不能用 property wrapper;存储属性不能用 library evolution 下大小可变的类型(`Date`、`URL`),所以 `ivar_t` 的大小永远准确;非 `final` 成员即使是 `private` 也隐式 `@objc`。 +- 还解不出的部分和已经验证过的推断路线(只用元数据的推断、SDK 头文件、运行时采样、反汇编)记在 [Roadmaps/2026-09-29-objc-implementation-unresolved-members.md](../../Roadmaps/2026-09-29-objc-implementation-unresolved-members.md)。 ## 副作用:extension 成员的 `@objc` @@ -50,8 +55,9 @@ SE-0436 的 `@objc @implementation extension` 让 ObjC 头文件里声明的类 ## 验证 -- `ObjCImplementationClassRecognitionTests`(SwiftInterfaceTests):即时编译的 fixture 三个变体各测一档,clang 类与普通 Swift 类作反例,事件派发。 +- `ObjCImplementationClassRecognitionTests`(SwiftInterfaceTests):即时编译的 fixture 三个变体各测一档,clang 类与普通 Swift 类作反例,事件派发。fixture 的 `Widget` 另有 `private final var hiddenTally` 与 `final lazy var summary`:`.full` 变体上两者都得到类型并按存储形态渲染(`var hiddenTally: Swift.Int`、`lazy var summary: Swift.String`),`strippedLocals` 上照旧是诚实注释。这几条在 2026-09-29 修复前的代码上逐条失败。 +- `ObjCMemberRecoveryTests.privateMembersHaveShapes`:`private` 成员的符号也能建出 `ObjCMemberShape`(名字在 `privateDeclName` 里)。 - `AppKitObjCImplementationClassTests`:系统 cache 的 AppKit,NSGlassEffectView 为 definitive 且 ≥ 9 个字段偏移符号,NSScreen / NSGradient / NSScene 命中,NSView / NSWindow 不命中,命中总数 ≥ 30;macOS 26 以下跳过。 -- `ObjCImplementationClassDumpTests`(SwiftDumpTests):dump 段的三段渲染与开关。 +- `ObjCImplementationClassDumpTests`(SwiftDumpTests):dump 段的三段渲染与开关,含 `private` 属性与 lazy 存储的 ivar 行。 - `DumpSectionsOptionTests`(SwiftSectionCommandTests):`--sections objcImplementationClasses`。 - 渲染 A/B:预期 dump 侧六个框架无差异(`So…CMa` 普查为零),interface 侧差异仅为 extension 成员新增的 `@objc` 等 attribute;见任务报告。 diff --git a/Documentations/Internal/ObjCMemberRecovery.md b/Documentations/Internal/ObjCMemberRecovery.md index 856966456..4a7ea47f4 100644 --- a/Documentations/Internal/ObjCMemberRecovery.md +++ b/Documentations/Internal/ObjCMemberRecovery.md @@ -15,7 +15,7 @@ | SwiftInspection | `ObjCAncestorResolver.swift` | 提案 `objc-ancestor-dependency-closure`:`ObjCAncestorResolver`(惰性求值的依赖镜像列表——根的传递闭包;`classObject(named:)` 先问每个镜像的 export trie 有没有 `_OBJC_CLASS_$_`,有才建那个镜像的名字表;命中 / 未命中都按名字 memo;`.empty` 是「没有镜像」)与按镜像的注册表 `ObjCAncestorResolverStore`(indexer 与 `dump` 注册,无人注册的文件首次查询时得到系统 cache 上的默认解析器;`MachOImage` 永远为 nil)。 | | SwiftInspection | `ObjCImplementationClassIndex.swift` | 读取器协议 `ObjCImplementationClassReading`(MachOFile / MachOImage 两份实现):`superclassLocation(of:)`(`.root` / `.resolved(reader, class)` / `.unresolvable(name)`;旧 bind 格式的槽位经 MachOKitExtensions 的 `resolveBind(fileOffset:)` 取名,Swift 类永不当根)、category 的目标类名(`targetClassName(of:)`,旧 bind 格式同样走 `resolveBind`)/ 目标类 / 实例与类方法表 / 协议表、类与 category 的协议 selector(`RawObjCProtocolSelectors`,沿协议继承链递归;跟不到的 bind、以及读成**空字符串**的 selector——归档 cache 里另一镜像的协议方法表,名字串读不到——都标 `isComplete = false`)。 | | SwiftInspection | `ObjCMember.swift` | `ObjCMember`(所属类名、selector、实例/类、`overriddenAncestorClassName?`、`evidence` 三档、`hasExplicitSelector`;`isInferredFromSelectorName` = 第三档,`isJoinedOverride` = 覆写且非第三档——消费者按证据强度过滤就靠这两个)与 `ObjCMemberTable`(按符号名索引的成员事实 + 联结不上的 `unattributedMethods` + 覆写投影 `overrides` / `unattributedOverriddenMethods` + 第三档的 `inferredOverrides(forMemberShapes:)`)。 | -| SwiftInspection | `ObjCMemberShape.swift` | 一个 Swift 成员对 selector 而言的形状(基名、标签、参数个数 / 属性名 / subscript accessor / 是否类型级 / 所属类型 / `throws` / `async`),从 demangle 树建(`To` thunk 符号的 `objCAttribute` 子节点跳过)。两套规则:`isConsistent(withSelector:isClassMethod:)` 是 importer 命名规则的**正向**检查(有损,做守卫);`defaultSelector()` / `isDefaultSelector(_:)` 是编译器 `getObjCSelector` 的移植(无损,判显式 selector),含 30 个介词的 `prepositions` 与驼峰分词 `CamelCaseWords`。 | +| SwiftInspection | `ObjCMemberShape.swift` | 一个 Swift 成员对 selector 而言的形状(基名、标签、参数个数 / 属性名 / subscript accessor / 是否类型级 / 所属类型 / `throws` / `async`),从 demangle 树建(`To` thunk 符号的 `objCAttribute` 子节点跳过;`private` / `fileprivate` 成员的名字在 `privateDeclName` 里,2026-09-29 起一并识别,此前这类成员建不出形状)。两套规则:`isConsistent(withSelector:isClassMethod:)` 是 importer 命名规则的**正向**检查(有损,做守卫);`defaultSelector()` / `isDefaultSelector(_:)` 是编译器 `getObjCSelector` 的移植(无损,判显式 selector),含 30 个介词的 `prepositions` 与驼峰分词 `CamelCaseWords`。 | | SwiftInspection | `NodeTypeNaming.swift` | 从 SwiftLayout 下沉(`package`),`nominalQualifiedName(ofDemangledRoot:)` 与 `swiftClassQualifiedName(fromRuntimeName:)`,ObjC 侧与 Swift 侧的类名 key 用同一个函数算。 | | SwiftThunkAnalysis | `ObjCMembers/ObjCMembers.swift` | 门面与成员表构建器:`table(forObjCClassNamed:in:)` / `table(forSwiftClassQualifiedName:in:)`,先问注册的 provider 再走库读取器。放这里而不是 SwiftInspection,因为第二档要用本模块的 Capstone 解码器。 | | SwiftThunkAnalysis | `ObjCMembers/ObjCMethodThunkReferences.swift` | 把一个 IMP 的代码反汇编,收 `bl` / 尾调 `b` 的目标与 `adrp`+`add` / `adr` 物化出的地址,换成本镜像的 Swift 符号名。MachOFile 与 MachOImage 两条腿;仅 ARM64。 | @@ -59,8 +59,8 @@ - **泛型 ObjC 派生类**(SwiftUI 26 个)无静态 class object,不标。它们的 `class_ro_t` 在泛型 metadata pattern 的 extra-data 块里,留待后续。 - **父类在另一个 resilience domain 的类**同样不在 classlist 里,改过名的也一样(它的名字从 `ResilientClassMetadataPattern` 读得到,方法表读不到),不标。 -- **iOS 18.5 及之后的模拟器运行时文件**:UIKitCore / Foundation 的 `__objc_classlist` 有约六分之一读不出(探针实测 UIKitCore 5017 项里 791 个 `class_ro_t` 读不到、624 个被误读为元类),`UIView` / `UIResponder` 这类根类恰在其中,解析器查不到它们的 class object,链在那里断并标 `(bound; chain not resolvable offline)`;iOS 15.5(旧 rebase 格式)大部分读得出。是 MachOKit / MachOObjCSection 对这批 chained-fixup 文件的读取问题,不在成员表这一层。 -- **磁盘上的独立二进制**:父类在别的镜像时是 bind,`superclassLocation` 返回 `.unresolvable(name)`;2026-09-21 起这个名字交给镜像的祖先解析器在依赖闭包里找(见下一节),找不到——依赖镜像不在宿主上、iOS 二进制在 macOS 宿主上没给 `--dependency-search-path`、`.unresolvable(nil)`(Swift 类的槽位为零又没有 bind 名)——链才在那里断;祖先的 category 若在闭包够不到的镜像里(闭包报为未解析的依赖),那个 category 的方法看不见,覆写它的成员会被判成显式 selector(fixture 的 `categoryInAnUnreachableImageIsInvisible` 钉住这条边界);断了的话同镜像祖先照常判,显式 selector 一律不判。旧的 `LC_DYLD_INFO` bind 格式(部署目标低于 macOS 12 / iOS 16——iOS 15.5 模拟器运行时的全部框架)把 bind 槽位留成 0,MachOObjCSection 把它读成「没有父类」;读取器补了一道 MachOKitExtensions 的 `resolveBind(fileOffset:)`(两种格式都认)取 bind 符号名,再兜一道「Swift 类不可能是 ObjC 根类」,否则链会被误判为走完、每个 UIKit 覆写都成了显式 selector(第一轮 A/B 的模拟器腿就是这样);这个名字现在也是解析器的输入。fixture 的 `.legacyBinds` 变体固定两种结果:空解析器下断在 `NSObject`,默认解析器下经宿主 cache 走完。 +- **模拟器运行时文件里读不全的类(2026-10-08 已修复)**:UIKitCore / Foundation 的 `__objc_classlist` 曾有约三分之一读不出(UIKitCore 5017 项里 791 个 `class_ro_t` 读不到、624 个被误读为元类),`UIView` / `UIResponder` / `UIDocument` 都在其中,链在那里断并标 `(bound; chain not resolvable offline)`,静态布局也排不出它们的 Swift 子类的字段。原因是这些框架用 `-interposable` 链接,导出的类在 classlist、`isa`、`superclass` 里都以「绑定到自己」的 bind 引用(UIKitCore 有 1,586 个这样的 classlist 条目,iOS 16.4 到 26.5 的模拟器都有),而 MachOObjCSection 只解 rebase。修复在 MachOObjCSection 与 MachOKitExtensions(`resolveSelfBind(fileOffset:)`),本库的 `SimulatorRuntimeObjCAncestorLayoutTests` 钉住 iOS 18.5 SwiftUI 的 `PlatformDocument` 排在 `UIDocument` 之后的 `0xc8`。 +- **磁盘上的独立二进制**:父类在别的镜像时是 bind,`superclassLocation` 返回 `.unresolvable(name)`;2026-09-21 起这个名字交给镜像的祖先解析器在依赖闭包里找(见下一节),找不到——依赖镜像不在宿主上、iOS 二进制在 macOS 宿主上没给 `--dependency-search-path`、`.unresolvable(nil)`(Swift 类的槽位为零又没有 bind 名)——链才在那里断;祖先的 category 若在闭包够不到的镜像里(闭包报为未解析的依赖),那个 category 的方法看不见,覆写它的成员会被判成显式 selector(fixture 的 `categoryInAnUnreachableImageIsInvisible` 钉住这条边界)。根本没被链接、只在运行时加载的框架也属此列:iOS 模拟器 runtime 的 SwiftUI 不链接私有框架 UIAccessibility,它给 `NSObject` 加的 `UIAccessibilityElementTraversal` 等 category 离线看不见,SwiftUI 里 6 个 `_accessibility…` 成员(如 `_accessibilityIsFirstSibling(for:)` ↔ `_accessibilityIsFirstSiblingForType:`)因此被判成 `@objc(…)`;离线分不出源码是显式写了 selector 还是覆写了头文件里的声明(2026-10-08 祖先链在模拟器腿上走通后才露出来);断了的话同镜像祖先照常判,显式 selector 一律不判。旧的 `LC_DYLD_INFO` bind 格式(部署目标低于 macOS 12 / iOS 16——iOS 15.5 模拟器运行时的全部框架)把 bind 槽位留成 0,MachOObjCSection 曾把它读成「没有父类」,链会被误判为走完、每个 UIKit 覆写都成了显式 selector(第一轮 A/B 的模拟器腿就是这样);本库当时在读取器里补了一道 MachOKitExtensions 的 `resolveBind(fileOffset:)` 取 bind 符号名。2026-10-08 起 MachOObjCSection 自己就按两种格式给名,那道补丁随之删掉;「Swift 类不可能是 ObjC 根类」这道兜底仍在。同一天起,父类在**同一个文件**里、却以 bind 引用自己导出的类时(`-interposable` 链接的文件,iOS 26 及更早模拟器 runtime 的框架都是),MachOObjCSection 直接跟到那个类,返回 `.resolved`;之前它见 bind 就放弃,链在这里退成按名字查([MachOObjCSection 的说明](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/main/Documentations/Internal/SelfBindPointerSlots.md))。fixture 的 `.legacyBinds` 变体固定两种结果:空解析器下断在 `NSObject`,默认解析器下经宿主 cache 走完。 - **strip 后的显式 selector**:只有第一档能给;第二档的 importer 拼法守卫天然拒绝它(见上),第三档只管覆写。 - **仅 ARM64**:第二档的解码器与模块其余部分一样只认 ARM64,x86_64 镜像只有第一、三档。 - **`required` 不还原**:`init?(coder:)` 打成 `override init?(coder:)`,库本来就不还原 `required`。 @@ -73,7 +73,7 @@ cache 镜像与进程内镜像顺着父类指针就能跨镜像走到根;磁盘上的独立文件(app 二进制、抽出来的框架、iOS 26 及更早模拟器运行时的框架文件)父类是 bind,在这之前链在第一跳就断——UIKit / AppKit 的覆写一个都标不出,显式 selector 一律不判(fail closed),渲染 A/B 的四条模拟器腿没有一行 `override`。现在的走法: -1. **名字从哪来**:`superclassLocation(of:)` 的 `.unresolvable(name)`(chained fixups 由 MachOObjCSection 直接给名,旧 `LC_DYLD_INFO` 格式由 `resolveBind(fileOffset:)` 给),category 的目标类用 `targetClassName(of:)`。bind 符号 `_OBJC_CLASS_$_UIView` 去前缀就是 `class_ro_t.name`;Swift 父类的 `_OBJC_CLASS_$__TtC7SwiftUI9Something` 去前缀得 `_TtC…`,不需要二次转换。 +1. **名字从哪来**:`superclassLocation(of:)` 的 `.unresolvable(name)`(chained fixups 与旧 `LC_DYLD_INFO` 格式都由 MachOObjCSection 直接给名),category 的目标类用 `targetClassName(of:)`。bind 符号 `_OBJC_CLASS_$_UIView` 去前缀就是 `class_ro_t.name`;Swift 父类的 `_OBJC_CLASS_$__TtC7SwiftUI9Something` 去前缀得 `_TtC…`,不需要二次转换。 2. **去哪找**:`ObjCAncestorResolver` 持有根的传递依赖闭包(`DependencyClosure(root:searchPaths:traversal: .transitive)`,BFS 顺序,惰性求值),对每个镜像先查 export trie 有没有 `_OBJC_CLASS_$_`(bind 只能落到导出符号,这一步是精确预检,省掉绝大多数镜像的 classlist 扫描;umbrella 的 re-export 条目会通过预检但 classlist 落空,跟在闭包后面的真正定义者接住),有才取 `ObjCClassMethodIndex.shared.storage(in:)` 的名字表;第一个命中即返回,命中 / 未命中都按名字 memo。一个解析器服务整条链的每一跳:显式文件里找到的父类自己的父类又是 bind,根的传递闭包里也有那个镜像。 **祖先的 category 来自别的文件**:cache 里的类,dyld 把同一 cache 内其它镜像的 category 预挂进它的 list-of-lists(cache 腿上 NSObject 的方法表里有 Foundation 的 KVO 方法);文件世界里 category 只在加载时挂,离线读不到——模拟器腿上 `observeValue(forKeyPath:of:change:context:)` 曾因此被判成 `@objc(observeValueForKeyPath:ofObject:change:context:)`。祖先链的每一跳都把根镜像自己与闭包里每个独立文件(`!isLoadedFromDyldCache`)对该祖先的 category 并进它的 selector 集合与协议集合(`ObjCAncestorResolver.fileCategorySelectors(onClassNamed:)`,按名字 memo,首次给闭包里每个文件建名字表;根的 category 由 `ObjCClassMethodIndex.AncestorCategoryFolding` 读)。cache 镜像的 category 不折。进程内同理:`dlopen` 进来的非 cache 镜像的 category 被运行时挂进 `class_rw_ext_t`,两个读取器只读 `class_ro_t`,所以 `MachOImage` 根也有一个只做折入的解析器(`ObjCAncestorResolver(inProcessRoot:)`,走 `DependencyClosure(root: MachOImage)`,只看 `!header.isInDyldCache` 的镜像)。 3. **谁装的**:`ObjCAncestorResolverStore` 按镜像登记。`SwiftDeclarationIndexer.index()` 用配置的 `dependencySearchPaths` 注册(与 property-wrapper catalog 共用一个 `SharedDependencyClosure`,闭包只求值一次;打不开的搜索路径派发 `renderingDegraded(.dependencyLoad)`),`swift-section dump` 自己按 `--dependency-search-path` 注册,无人注册的文件在首次查询时得到一个系统 cache 上的默认解析器——与 catalog 的契约相同,所以只走 dump 路径的宿主不用改;`MachOImage` 永远没有解析器。闭包的搜索路径与 catalog 一直以来的完全相同(落地时试过让 cache 内的根先查自己的 cache,A/B 抓到 catalog 因此在 `cache-15.5` 腿丢掉 `@IdentityLink`,撤回——见提案决策日志)。indexer 的 `deinit` 按独立的 claim 随最后一个活着的 indexer 驱逐,`ObjCClassHierarchies.removeCache(for:)` 也清它。 diff --git a/Documentations/Internal/OpaquePrimaryAssociatedTypeAttribution.md b/Documentations/Internal/OpaquePrimaryAssociatedTypeAttribution.md index dfcdc47b1..f7ec28afd 100644 --- a/Documentations/Internal/OpaquePrimaryAssociatedTypeAttribution.md +++ b/Documentations/Internal/OpaquePrimaryAssociatedTypeAttribution.md @@ -9,7 +9,7 @@ `SwiftInterfaceBuilderOpaqueTypeProvider` 曾把 opaque 参数上的 same-type 约束(primary associated type 的尖括号参数)无差别分发给该参数组合里的每一个协议,产出 `some Swift.Equatable<[A]>` 这类非法 Swift。修复后按 anchor 协议逐条裁决归属。 -## 实现结构(`Sources/SwiftInterface/`) +## 实现结构(`Sources/Output/SwiftInterface/`) | 文件 | 职责 | |---|---| diff --git a/Documentations/Internal/ProjectEvolutionLog.md b/Documentations/Internal/ProjectEvolutionLog.md index ffc8849e6..96df104fe 100644 --- a/Documentations/Internal/ProjectEvolutionLog.md +++ b/Documentations/Internal/ProjectEvolutionLog.md @@ -1426,6 +1426,7 @@ 也证实 0023 没有丢类型:SwiftUICore 顶层对象 3202 → 3138,少的 64 个全是嵌套在 enum 命名空间下的 struct/class 的重复 conformance 顶层条目(旧版 kind 推错才没并进类型),其余是 `__C` 改名。见 [TaskReports/2026-09-10-c-imported-extension-kind-from-descriptor.md](TaskReports/2026-09-10-c-imported-extension-kind-from-descriptor.md)。 +- **后续清理(2026-10-03)**:在 macOS 27 的五个框架上对比 0023 前后两版 CLI,共 244 组 C 导入类型改名。旧名只是 Swift 名的最后一截,20 个短名各指多个类型,曾让 `interface` 吞掉同名声明、把别的类型的 witness 挂进 conformance、让 `--resolve-c-module-names` 认错模块。用户定先保持 ABI name,从二进制推断 Swift 名留到以后,并要求改掉依赖旧短名的测试。MachOSwiftSection 与 RuntimeViewer 的测试断言都不依赖旧短名;唯一相关的 `SupplementaryAPINotesTests` 把描述符直出的 `__C.Graph` 当作一种 mangling 形态,说明已改。它测的 `TypeDatabase` 把 SwiftName spelling 登进归属表那一步,试删后 AppKit 的 `--resolve-c-module-names` 输出把 `ObjectiveC.NSObject` 变成 `Foundation.NSObject`:Foundation 与 AppKit 的 APINotes 也列了 `NSObject`,靠 ObjectiveC 条目里 `NSObject` 改名为自身才归位。于是保留,改注释并补 `renamingEntryKeepsItsModuleAgainstLaterListings` 钉住;公开指引、术语表、TypeIndexing 管线说明、A15 裁决、`StaticLayoutEngine.md` 与一处源码注释里的旧名同步更新。见 [TaskReports/2026-10-03-c-imported-names-after-type-import-info.md](TaskReports/2026-10-03-c-imported-names-after-type-import-info.md)。 ## 2026-09-10 property descriptor 的 ABI 模型(提案 0025 key-path-component-and-property-descriptor) @@ -2053,6 +2054,259 @@ - **关联文档**:[FixtureTestingAndContinuousIntegration.md](FixtureTestingAndContinuousIntegration.md)「runner 只有 3 核」一节。 - **对应版本**:0.21.0(发版 PR 合入 main 之前补上;只动测试与 CI,发布产物不变)。 +## 68. 特化测试时好时坏的根因:测试按 `currentName` 挑候选,挑到了库里的函数局部类型 + +- **时间段**:2026-09-29(单日,0.21.0 发布之后)。 +- **动机**:第 67 节补记里暂时用 `withKnownIssue` 包住的 `argumentCandidatePathSpecializesNonGenericCandidate`,用户要求发版后接着查根因。 +- **关键决策**:**① 先把反馈回路做快**:这个测试单跑一次要 4 分钟(索引测试程序本身、Foundation、libswiftCore),且只在部分进程里失败。临时探测测试(不提交)在准备好索引器后,于同一进程里把两条路径循环比较 40 次,并打出每次的候选名单和 metadata、witness table 地址。第一次运行就看到了根因:候选里有两个 `currentName == "Int"`,另一个是 `ObjCMemberApplication.inferFromSelectorNames(...) -> Int` 函数体里的 `enum MemberKey`。它的打印名以函数签名结尾,`currentName` 按 `.` 切出来就是 `Int`。之前推测的「witness table 不同」是错的。**② 库不动,改测试**:用户界定 `currentName` 是 dump/interface 的类型、协议声明用的,不是给测试查找定义用的,测试应该自己写方法。挑标准库候选的 14 处改为按全名比较;其余 13 处改用新加的 `DefinitionName.declaredNameForTesting`(`MachOTestingSupport`),它从节点读声明名,局部类型得到 `MemberKey`。**③ 规则写进 `AGENTS.md`**,防止以后的测试再用 `currentName` 查找定义。**④ 不在本批**:`currentName` 对局部类型的显示问题、上游 `Node.identifier` 不认 `.localDeclName`、该候选镜像路径为空,三件记在 A52 的「遗留」里。 +- **落地模块**:`Sources/MachOTestingSupport/DefinitionName+DeclaredNameForTesting.swift`(新)、`Package.swift`(`MachOTestingSupport` 声明 `Demangling` 依赖,`MachOTestingSupportTests` 声明 `SwiftDeclaration` 与 `Demangling`)、`Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift`(新)、6 个测试文件的 27 处调用点、`AGENTS.md`、[ReviewAdjudications.md](ReviewAdjudications.md) A52。 +- **验证**:受影响的 8 个套件(`GenericSpecializationTests`、`STCoreTests`、`DiffRendererHeaderFailureTests`、`PrintFailureEventTests`、两个 `GenericTypeNameSubstitution…`、`SubclassMapMaterializationFailureTests`、`DeclaredNameForTestingTests`)共 146 个测试 / 17 个套件,原始退出码 0;`MachOTestingSupportTests` 26 个测试通过。去掉 `withKnownIssue` 之后 `argumentCandidatePathSpecializesNonGenericCandidate` 单独跑 5 次全部通过,修复前同样条件下每次约一半到三分之二失败。 +- **关联文档**:[ReviewAdjudications.md](ReviewAdjudications.md) A52。 +- **对应版本**:0.21.0 之后(只动测试,发布产物不变)。 + +## 69. `Sources/` 按层分组 + +- **时间段**:2026-09-29(单日)。 +- **动机**:`Sources/` 下平铺 31 个 target,用户嫌太杂,要求分目录归类。 +- **关键决策**:**① 按层分 8 组**:`Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/`,对应 AGENTS.md 的依赖层级。用户在「按层 8 组」与「粗分 4 组」之间选了前者,因为粗分方案里 `Swift/` 下仍有 16 个 target。**② target / product / 模块名一律不变**,`Package.swift` 逐个写字面量 `path:`,下游无感。**③ 修掉依赖目录深度的代码**:fixture 路径的 rawValue 从 `../../Tests/…` 改成 `../../../Tests/…`(三处 `#filePath` 解析器的约定不变);`PrintFailureEventTests` 取 `Sources` 下两层作模块名;覆盖率不变式测试的 `Models/` 路径加 `ABI/`。**④ 文档只改活的**:AGENTS.md、Glossary、`SwiftEnumLayout` 两份、`Internal/` 主题笔记里的路径改成新路径;TaskReports、Reviews、Roadmaps、已落地提案、本账本保留当时的路径。AGENTS.md 加一段说明分组,以及新 target 必须声明 `path:`。**⑤ 顺带**:`next` 工作树里那份未提交的 `Package.swift` 改动(tools-version 6.3、swift-syntax `602..<605`、删掉没人用的 `MachOKitVersion`)按用户要求先单独提交,再从它切出分组分支。 +- **落地模块**:`Sources/` 全部 31 个 target 的目录、`Package.swift`、`Sources/TestSupport/MachOFixtureSupport/{MachOFileName,MachOImageName}.swift` 与两处解析器的注释、`Tests/SwiftInterfaceTests/PrintFailureEventTests.swift`、`Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift`、`.github/workflows/{release,version-check}.yml`、26 份活文档。 +- **验证**:`swift test --skip IntegrationTests` 原始退出码 0,19 批、2145 个测试、405 个套件全部通过;三个扫描源码树的套件(`PrintFailureEventTests`、`NodeStoreMigrationInvariantTests`、`MachOSwiftSectionCoverageInvariantTests`)均为绿。纯搬迁,未跑渲染 A/B 验证。 +- **关联文档**:[0055-group-sources-by-layer](../Evolutions/0055-group-sources-by-layer.md)。 +- **对应版本**:0.21.0 之后(发布产物不变)。 + +## 70. 抛错版 `init(bitPattern:)` 从 MachOKitExtensions 收回本仓库 + +- **时间段**:2026-09-29(单日)。 +- **动机**:MachOKitExtensions 接手了 MachOKit fork 里的缓存改动(它的提案 0001),MachOObjCSection 的核心 target 因此要依赖它。它原先公开的 `UnsafeRawPointer` / `UnsafePointer` 抛错版 `init(bitPattern:)` 借着 Swift「导入模块的扩展成员在整个模块可见」的规则,遮住了标准库的可失败版本,核心 target 里 27 处 `UnsafeRawPointer(bitPattern:)!` 因此编译不过。 +- **关键决策**:**① 移进本仓库的 `Utilities`,访问级别 `package`**:只有本仓库调用它们(用户确认),`package` 让它们不再漏给下游。**② 名字和语义不变**,调用点零改动;只有 `InProcessContext.swift` 补了一行 `import Utilities`,因为 `MachOReading` 里原本没有文件 import 它。**③ MachOKitExtensions 的要求提到 `from: "1.0.0"`**:1.0.0 起它不再导出这两个初始化方法,更早的版本仍然导出,与这里的声明同名会产生歧义。 +- **落地模块**:`Sources/Support/Utilities/ThrowingBitPatternInitializers.swift`(新增)、`Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift`、`Package.swift`。 +- **验证**:`USING_LOCAL_DEPENDENCIES=1 swift test --skip IntegrationTests` 原始退出码 0,各批全部通过(一个既有的 known issue)。另把本分支、MachOObjCSection 的新核心 target、新 MachOKitExtensions 与恢复成上游原样的 MachOKit 放在一起 `swift build --build-tests`,退出码 0。纯搬迁,未跑渲染 A/B 验证。 +- **关联文档**:MachOKitExtensions 仓库的提案 `Documentations/Evolutions/0001-cached-view.md`。 +- **对应版本**:0.22.0(要求 MachOKitExtensions 1.0.0)。 + +## 71. 标记模式:一次打印全量 interface,标出每段内容受哪个选项控制 + +- **时间段**:2026-09-29 — 2026-09-30。 +- **动机**:RuntimeViewer 的 Find 给每个类型存一份打印好的 interface 供全文搜索。用户报告能搜到内容区不显示的内容(被 strip 的 ivar、合成 getter / setter),并要求「语料要为所有可能出现的内容进行索引,但是只输出匹配当前options的内容」,切换选项不重新打印(SwiftUI 打一遍约两分钟);「每个选项各打一遍再 diff」被否:「目前打印2次的方法可能会有性能问题」,且偏移 / 地址注释的文字会被 transformer 改写,diff 出来也认不出归属。 +- **关键决策**:**① 归属由打印器在输出时给出**:`marksOptionalContent` 为真时,受选项控制的内容全部打出,包进 swift-semantic-string 的 `VisibilityRegion`(条件记在原子的 `identifier` 上,文字逐字节不变);这些注释要用的数据在标记模式下总是计算。**② opaque 类型约束事后补标**:`printOpaqueReturnType` 照常写入,写完用 `markAtoms(from:visibleUnder:)` 补条件,原子个数与类型引用的 identifier 都不变。**③ `infersObjCOverridesFromSelectorNames` 是替换不是增删**:两种判定结果不同时整条声明按两种各打一遍,分别包进开、关两个区域。**④ 容器不归打印器管**:swift-semantic-string 的容器把成员的条件带到自己打的换行、分隔符与前后缀上。**⑤ 不覆盖** `printExportStatus` 等 RuntimeViewer 不用的选项,也不覆盖 `memberSortOrder`(重排,区域表达不了)。 +- **落地模块**:`Sources/Output/SwiftPrinting/`(`SwiftDeclarationPrintConfiguration`、`SwiftDeclarationPrinter` 与 `+Headers` / `+ObjCImplementation`、新增的 `+VisibilityRegions`、`NodePrintables/{NodePrintableDelegate,TypeNodePrintable}`)、`Sources/Output/SwiftDeclarationRendering/`(`DeclarationRenderConfiguration`、两个布局后端、新增的 `SwiftVisibilityOption`)、`Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift`。 +- **验证**:`VisibilityRegionProjectionTests` 对 SymbolTestsCore 的每个顶层类型、协议与扩展断言「标记打印按某配置投影」与「按该配置直接打印」完全相等(文本、span、identifier):进程内 22 组配置、从文件 10 组。rebase 到 `next` 后,本地依赖下 `USING_LOCAL_DEPENDENCIES=1 swift test --skip IntegrationTests` 原始退出码 0,19 批、2146 个测试、406 个套件全部通过(一个既有的 known issue);快照测试全过,普通打印的输出不变。 +- **关联文档**:[0056-visibility-regions](../Evolutions/0056-visibility-regions.md);swift-semantic-string 的 `docs/VisibilityRegions.md`;MachOObjCSection 提案 0011;RuntimeViewer 提案 `draft-find-navigator`。 +- **对应版本**:0.22.0(要求 swift-semantic-string 0.4.0:它带 `VisibilityRegion`,2026-09-30 发布,同日抬了 `from:`)。 + +## 72. `@objc @implementation` 的 `private` 属性与 lazy 存储:符号在却没读出类型 + +- **时间段**:2026-09-29(单日)。 +- **动机**:用户问为什么很多 `@objc @implementation` 类在 Swift 侧看不到方法、ObjCSection 把一些 ivar 打成 `Unknown`。调研结论是二进制里本来就没有:编译器不给这类类发 field descriptor,Swift 名字和类型只在符号里,而系统 cache 里的 AppKit 只留下导出的 `public` 符号。调研中写了一组探针 fixture,查出一处真正的漏读:`private` 属性和 `lazy var` 存储的 field offset global 里,变量名字是 `privateDeclName`,索引只认 `identifier`。于是符号齐全时这两类 ivar 也拿不到类型,打成「Swift type not recoverable」注释,对应的成员还被打成 `{ get set }` 的计算属性。 +- **关键决策**:**① 只修漏读,推断全部记下来**:用户裁定「先把能解补了,然后剩下的记下来」,只用元数据的推断、SDK 头文件、运行时采样、反汇编四条路线连同验证过的证据写进路线图,不写代码。**② lazy 存储折叠到它的属性上**:渲染照抄 Swift 类型自己的 lazy 字段(interface 打 getter 的类型,没有 getter 时打存储类型;dump 打存储类型),不打 `$__lazy_storage_$_x` 这种不合法的名字。连接先按 Swift 名,`Wvd` 被剥掉时按 ObjC ivar 名,两者拼法相同。**③ 「已有成员代表」的判断只加不减**:在原来按 Swift 名的基础上加按对象身份,旧逻辑认定的结果一个不少,只多认出只靠 ObjC 名连上的 lazy 存储。**④ 横向排查同一写法**:`ObjCMemberShape` 取成员名同样只认 `identifier`,`private` 成员建不出形状。它眼下没有实际影响(`private` 成员的实现符号和 `To` thunk 都是 local 符号,同时在或同时被剥掉;`private` 成员也不可能是 override),按「修一类,不是修一个」一并修好并补单元测试。`RuntimeMetadataTypeBuilder.qualifiedDeclarationName` 只查标准库泛型的公开名字,不是同类。**⑤ `weak` / `unowned` 不打不算漏读**:`Wvd` 的 mangled 类型本来就不带引用的所有权修饰,记入路线图。**⑥ 顺带修掉一个从没被走到的兜底**:打印器自带的 `declaredTypeNode(ofVariableNode:)` 默认拿到的是 `variable` 节点,而 `VariableDefinition.node` 是符号的根节点,它因此永远返回 nil。以前它只在「存储没有类型」时兜底,而那种情况根本不会发生连接,所以一直没暴露;lazy 存储要取 getter 的类型时第一次用到它,测试里打出了 `lazy var summary: Swift.String?`。改用 SwiftDeclaration 里现成的 `WrappedPropertyRecovery.declaredTypeNode(of:)`,删掉这个辅助函数。 +- **落地模块**:SwiftInspection(`ObjCImplementationClassIndex` 的 `Wvd` 名字解析、`ObjCImplementationClassFacts.InstanceVariable.lazyPropertyName` 与 `storageInstanceVariable(forPropertyNamed:)`、`ObjCMemberShape.declaredName`)、SwiftDeclaration(`ExtensionDefinition.attachObjCImplementation` / `unrepresentedObjCImplementationInstanceVariables`)、SwiftPrinting(`@implementation` 存储属性的两处渲染,声明类型改由 `WrappedPropertyRecovery.declaredTypeNode(of:)` 给出)、SwiftDump(`ObjCImplementationClassDumper` 的 ivar 行)。测试 fixture `ObjCImplementationFixture` 的 `Widget` 加了 `private final var hiddenTally` 与 `final lazy var summary`,受影响的计数断言随之更新(ivar 数、`instanceSize`、field offset global 数、inferred 档的 ivar 数)。 +- **验证**:先只改 fixture 和测试跑一轮:interface、dump、facts 的新断言共 12 条失败(修复前 `Widget` 的 `hiddenTally` 和 `summary` 被打成 `{ get set }`,存储另列成两行注释),只随 fixture 变化的计数断言通过。修复后临时撤回 `ObjCMemberShape` 的改动再跑,`privateMembersHaveShapes` 失败,其余转绿;恢复后,所有碰这个 fixture 或 `@implementation` 的 6 个套件共 48 个测试通过(`swift test` 退出码 0)。修复前后的 CLI 对比:macOS 26.7 系统 AppKit 的 `dump --sections objcImplementationClasses` 与 `interface` 逐字节一致(AppKit 没有 local 的 field offset symbol,这次修的情况在系统框架里不出现);27.0 AppKit 的 dump 一致,interface 只有一处差异:`_NSTextFormattingViewController.campoTextSuggestionsViewController` 的访问器是导出的、存储符号被剥掉,以前打成 `{ get set }` 加一行存储注释,现在经 ObjC ivar 名连上,打成 `lazy var campoTextSuggestionsViewController: __C.NSCampoTextSuggestionsViewController`。全量 `swift test --skip IntegrationTests` 共 2142 个测试 / 404 个套件,原始退出码 1:两条是已登记的 known issue(`SymbolicManglingIndexTests` 的局部类型、特化 candidate 路径的间歇失败),真正失败的只有 `MultiPayloadEnumDescriptorCacheTests` 的两条(kind-9 非可复制 payload 的 enum 布局为 nil)。把改动恢复成 `next` 原样、用同一 scratch 与 fixture 重跑,这两条在同一位置同样失败,是本机既有问题,与本批无关。 +- **关联文档**:[ObjCImplementationClassRecognition.md](ObjCImplementationClassRecognition.md)「两个 join」「边界与已知限制」、[ObjCMemberRecovery.md](ObjCMemberRecovery.md)、[Roadmaps/2026-09-29-objc-implementation-unresolved-members.md](../../Roadmaps/2026-09-29-objc-implementation-unresolved-members.md)(还解不出的部分与推断路线)。 +- **对应版本**:0.22.0。 + +## 73. 读取接口统一到 `ReadingContext`:每个读取接口只剩一份实现,传 `machO` 与指针的旧形式废弃 + +- **时间段**:2026-09-30 — 2026-10-01。 +- **动机**:ABI 层的读取接口大多有三份实现(传 `machO`、直接用指针、收 `ReadingContext`),三份已经漂移,而且错的多是 `ReadingContext` 那一份:`Pointer` 不查 rebase、`TypeMetadataRecord` 不跳过被 bind 的记录、`SymbolOrElementPointer` 判空前不剥 tag。「新接口三套都写」的惯例让重复继续翻倍,上层模块又把三份复制了一遍。用户要求「把传递machO和直接用指针解析的接口全部迁移至ReadingContext,旧接口全部弃用」,并追加「弃用旧接口后旧接口的实现直接调用ReadingContext接口,确保实现只有1份」。 +- **关键决策**:**① 先修 `ReadingContext` 版,再切转发**:以传 `machO` 版的行为为准补齐五处分歧(上面三处,加上 `MangledName` 的偏移基准与 metadata 地址为 0 时抛错),前三处各带修复前确认红过的回归测试。**② 旧形式原地保留成一行转发并标废弃**:集中到协议扩展会让 `Pointer.resolve(from:in:).descriptor()` 这类链式调用在 `-> Self` 与 `-> Self?` 之间二义;`PointerProtocol` 与 `RelativeIndirectType` 保留已废弃的旧 requirement(`Pointer` 同时遵循两者),其余协议移除。**③ 约束扩展里的空指针 guard 放进私有 helper**:在 `where Pointee: OptionalProtocol` 的扩展里按名字调用同名 requirement,绑定的是无约束的 witness,一行转发会跳过 guard。**④ `ReadingContext` 声明缓存范围**(`cacheScope`:按镜像 / 全进程 / 不缓存),只暴露缓存身份、不暴露 Mach-O;`.image` 直接带 `MachOTargetIdentifier`,不装箱成 `AnyHashable`,否则每次 memo 查找一次堆分配。**⑤ 上层 61 个只读接口一起迁**:`public` 的加 context 版、旧版废弃转发,`package` 的直接改签名;`NamedDumpable` / `ConformedDumpable` 的取名逻辑从各 Dumper 抽成被 dump 类型上的一份。**⑥ 天生离不开 Mach-O 或本进程的接口不废弃**:section 枚举、运行时调用、坐标换算、地址格式化、底层读原语。**⑦ 0.22.0 废弃、0.23.0 删除**,删除前给 RuntimeViewer、MachOKitUI、swift-decompiler 提迁移 PR。**⑧ 性能**:`InProcessContext` 的 tag 掩码只算一次,`MachOContext` 去掉多余的预剥并改为不抛错。 +- **落地模块**:`MachOReading`(`ReadingContext.cacheScope`、`ReadingContextCacheScope`、两个 context 的实现)、`MachOResolving` / `MachOPointers`(requirement 收成 context 形式)、`Sources/ABI/MachOSwiftSection/Models/` 全部、`MachOSymbols`(`InternedNodeReferenceCache` 按范围选层)、`SwiftInspection`(`SymbolicDemangler`)、`SwiftDeclaration` / `SwiftDump` / `SwiftDeclarationRendering` 的只读接口,以及 `SwiftIndexing`、`SwiftSpecialization`、`SwiftPrinting`、`SwiftInterface`、`SwiftLayout`、`SwiftThunkAnalysis` 的调用点;测试与 baseline 生成器全部改走 context,新增 `DeprecatedReadingFormsTests`(转发套件,0.23.0 删除)、`ReadingContextRelocationTests`、`ReadingContextCacheScopeTests`。 +- **验证**(2026-09-30。先在公司的 10 核 Mac Studio 上对 `next` @ `32feff36` 做完正确性验收;分支没有推送,换到 JHs-Mac-Studio-Ultra 后按会话记录重建(各 commit 的文件清单与行数统计与原 commit 一致),在 Ultra 上对 `next` @ `f7c189b8` 重跑正确性验收并完成性能验收):**① 全量测试**:`swift test --skip IntegrationTests` 共 2157 个测试 / 410 个套件,原始退出码 1。失败只有 `MultiPayloadEnumDescriptorCacheTests` 的两条(kind-9 非可复制 payload 的 enum 布局为 nil),基线在同一 fixture 上同样失败,是本机既有问题;另有 1 个已登记的 known issue。`FunctionTypeMetadataTests` 在其中一轮失败三条、另两轮通过:`extendedFlags(in:)` 按 `Optional` 的内存形状多读一个字节,结果取决于那个字节的内容;源码与测试本批都没动,属既有问题。新增的三个套件通过,前三处分歧修复的回归测试在修复前确认失败。**② 警告**:零废弃警告,非废弃警告与基线完整构建的清单一致。**③ baseline**:`regen-baselines` 之后 `__Baseline__/` 只有 `ResilientWitness` 的登记名多了 `implementationAddressString`。**④ 渲染 A/B**:两侧 35 个依赖的版本与 revision 完全一致,候选 release 从零构建。共 90 对逐字节一致:归档 cache 26.6.2 与 15.5 各 12 对,iOS 15.5 模拟器 6 对,18.5 / 18.6 / 26.5 各 12 对,MachOImage 腿 24 对。iOS 27.x 的模拟器 runtime 里框架不以单独文件存在,脚本按设计跳过。Ultra 上重跑(Swift 6.4):全量测试 2157 个 / 410 个套件全部通过、原始退出码 0(fixture 须用 Xcode 26.6 编,用 Xcode 27 编会有约 195 个 offset 与 baseline 不符,属编译器漂移);渲染 A/B 96 对逐字节一致(15.5 归档 cache 12 对,iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器共 48 对,MachOImage 腿 24 对;Ultra 上没有脚本写死的 26.6.2 归档目录,脚本因此静默少了这条腿,于是按脚本的同样参数对 26.6 归档手动补跑 6 个框架,12 对一致)。**⑤ 性能**:在 Ultra 上完成(release,每组按「基线、候选、候选、基线」运行,SwiftUI),三条路径都没有变慢。dyld cache 里的 `MachOFile`(26.6)按退休指令数 `dump` 580.42G → 577.63G(−0.48%)、`interface` 740.22G → 738.64G(−0.21%);磁盘上的 `MachOFile`(iOS 26.5 模拟器)内核时间占一半、指令数随之波动,按 user 时间 `dump` 30.51 → 30.57 秒(+0.2%)、`interface` 各跑 4 次 38.75 → 38.97 秒(+0.57%,两侧区间 38.57–38.93 与 38.62–39.45 重叠);`MachOImage` 与本进程(`RenderingVerificationTests`)user 时间 504.2 → 498.2 秒(−1.2%)。公司那台机器内存不足、CPU 被其他会话占满,在那里测出的 MachOImage 腿「多 2.5%」判为噪声(那台机器上基线两次之间就差 3%);那时的采样对比里,读取层的函数(`MachOContext`、`cacheScope`、conformance 查找)也只占个位数到几百个样本。 +- **后续(2026-10-01)**:渲染 A/B 脚本加 `--skip-build`。验收时发现脚本自己跑两侧的 release 构建、不经 `queued-build`,在限流的 10 核 Mac Studio 上即使先经队列预构建,最后仍是两侧在队列之外并行全量重编。带这个开关时脚本什么都不构建,直接用预先构建好的产物;某一侧缺 CLI 时在渲染前停下,报出路径和这一侧该补的那一条预构建命令。脚本单元测试新增 6 条,共 15 条通过。分支 `chore/rendering-harness-skip-build` 合入 `next`(`01b57f74`),用法见 [SystemFrameworkRenderingVerification.md](SystemFrameworkRenderingVerification.md)「关键调用细节」。 +- **关联文档**:[0057-reading-context-migration](../Evolutions/0057-reading-context-migration.md)、[ReadingContextAbstraction.md](ReadingContextAbstraction.md)「单一实现与废弃」一节、[Glossary.md](../Glossary.md)「cache scope」「context form / Mach-O form / pointer form」。 +- **对应版本**:0.22.0。 + +## 74. Optional 读取多读一个 tag byte、ABI 层的 `print`:读取接口迁移时查出的两类既有问题 + +- **时间段**:2026-10-01(单日)。 +- **动机**:上一节的迁移验收时查出两类既有问题,用户决定另开分支修。**一是 Optional 读取**:`FunctionTypeMetadata.extendedFlags(in:)` 与 `EnumMetadataProtocol.payloadSize(descriptor:in:)` 在返回 Optional 的函数里直接 `return try context.readElement(at:)`,泛型 `readElement` 于是被推断成 `Optional`,按 Optional 的内存形状去读:字段后面多读一个 tag byte,那个字节不为 0 时结果就是 nil。`extendedFlags` 后面是 thrown error type 之前的对齐 padding,运行时不写它,内容取决于分配器给的内存——这就是 `FunctionTypeMetadataTests` 的 `extendedFlags` / `thrownErrorType` / `thrownErrorTypeOffset` 三条单独跑能过、全量时好时坏的原因,此前一直被当成并行抖动记录。提案 0026 写这个文件时在 `globalActorType` 上踩过同一个坑,只修了那一处;`payloadSize` 在 [ReadingContextAbstraction.md](ReadingContextAbstraction.md) 里一直记为「尚未验证」。**二是 `print`**:`ContextDescriptorWrapper`、`TypeContextDescriptorWrapper`、`ValueTypeDescriptorWrapper` 的 `-> Self?` 形式 resolve 失败时用 `print` 写 stdout,违反日志规则,也会弄脏 CLI 的产品输出。 +- **关键决策**:**① 按写法排查,不按字面排查**:用 Swift 6.4 的 `-dump-ast` 看泛型实际被推断成什么。会推断成 Optional 的写法:在返回 Optional 的函数里直接 `return`、`try?` 配带类型标注的 `guard let` 或 `let x: T?`、给 Optional 变量赋值、在 `flatMap` 闭包里返回;安全的写法:先读进标注了非 Optional 类型的局部变量、`as T`、`map` 闭包。按此把全仓 31 处 `readElement` 调用和全部 `readElements`、FileIO `read` 调用逐一归类,多找到一处:`SwiftClassObjectIndex` 读类对象 flag 字的 `guard let classFlags: UInt32 = try? machO.readElement(…)`。它后面是 `instanceAddressPoint` 的低字节,编译器永远写 0,所以真实二进制上不会触发。**② 三处都先读成非 Optional 再包起来**:前两处用标注类型的局部变量(与同文件的 `globalActorType` 一致),第三处用 `as UInt32`(与 `ObjCImplementationClassIndex` 一致)。**③ 复现测试不依赖内存里恰好是什么**:`OptionalAccessorReadTests` 手工拼 function type metadata 与 enum metadata 的记录,字段后面紧跟 `0x01`(Optional 表示「无值」的 tag),经 `InProcessContext` 读。第三处在 `SwiftClassObjectIndexTests` 里复制 `RenamedObjCClassFixture` 编出的库,把每个 Swift 类对象 flag 字后面的字节改成 `0x01`。副本必须连 `LC_UUID` 一起改:`MachOFile` 的缓存身份是 install name 加 UUID,与原库相同时,各个 per-image cache 会直接拿原库建好的索引作答,第一版测试就因此在修复前是绿的;测试里现在有一条「副本与原库身份不同」的前置断言。**④ `print` 换成 `@Loggable` + `#log`**:ABI 层经 `Utilities` 就能用 `FoundationToolbox`,`MachOSymbols` 是先例。subsystem 是 `com.machoswiftsection.macho-swift-section`,category 用各自的类型名;`ValueTypeDescriptorWrapper` 的报错文字原先误写成 `ContextDescriptorWrapper`,一并改正。以后排查这类被吞掉的解析错误,看统一日志里的这个 subsystem,不再 grep stdout。**⑤ 顺带清掉同类欠账 `SubstitutionMap`**(`Utilities`,泛型,所以用协议形式的 `@Loggable`);`SpareBitAnalyzer.printAnalysis` 留在扫描测试的欠账名单上:它是专门往 stdout 打表格的公开调试接口,只有 IntegrationTests 在用,要清就得改公开 API,不属于这次的修复。 +- **落地模块**:`MachOSwiftSection`(`FunctionTypeMetadata+TrailingObjects`、`EnumMetadataProtocol`、三个 descriptor wrapper)、`SwiftInspection`(`SwiftClassObjectIndex`)、`Utilities`(`SubstitutionMap`)。测试新增 `OptionalAccessorReadTests`,`SwiftClassObjectIndexTests` 加一条,`PrintFailureEventTests` 的欠账名单去掉三个文件。 +- **验证**:三条新测试在修复前确认失败(extended flags 与 payload size 读成 nil,补丁副本里的 `RenamedWidget` 认不出改名),修复后通过;扫描测试在名单去掉三个文件后列出 5 行 `print`,改完后通过。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,fixture 用 Xcode 26.6 编)共 2160 个测试 / 411 个套件全部通过,原始退出码 0;比迁移分支的基线多出的正好是新加的 3 个测试和 1 个套件,另有 1 个早已登记的 known issue(`SymbolicManglingIndexTests`),与基线相同。没有跑渲染 A/B:修过的两个接口只有 baseline 生成器在调,渲染路径不用;`SwiftClassObjectIndex` 那处在编译器产出的二进制上结果不变;输出上唯一的变化是 descriptor 解析失败时不再往 stdout 写「Error resolving …」。 +- **关联文档**:[AGENTS.md](../../AGENTS.md) 里 descriptor wrapper 那一节的 Optional 读取陷阱(扩写成任何类型、包括 `try?` 写法)、[ReadingContextAbstraction.md](ReadingContextAbstraction.md)「这次没动的已知缺口」、[EventBasedDegradationReporting.md](EventBasedDegradationReporting.md)(日志规则)、[0057-reading-context-migration](../Evolutions/0057-reading-context-migration.md)「不在本 PR、另开分支处理」、[PR #130](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/pull/130)(迁移的 PR #129 合入后直接对 `next`)。 +- **对应版本**:0.22.0。 + +## 75. 主可执行文件的符号偏移、STABS 调试条目:独立文件的符号值从没换算过 + +- **时间段**:2026-10-01 至 2026-10-02。 +- **动机**:用 swift-section 0.21.0 给 Mica.app(Apple 内部的 Core Animation 编辑器)生成接口,拿 IDA 核对时查出三个症状。**一是主可执行文件的成员地址翻倍**:`Mica` 的 `FontPickerControl.setup()` 打印成 `0x2001338E8`,实际在 `0x1001338E8`。**二是同一个文件的 vtable 对不上名字**:dump 里 192 个有实现的槽打印成 `sub_100133670`,`nm` 却显示那里就是 `fontName.getter`;interface 因此一条 vtable 偏移注释都没有,成员也不按槽位顺序排。**三是 `MicaKit`(dylib)的 30 个静态存储属性打印成 `Address: 0x0`**,而 `nm` 显示每个都有存储符号。前两个同源:`MachOKit` 给 `MachOFile` 符号的 `offset` 是原始 `n_value`(虚拟地址,它的文档注释写的是 file offset),`SymbolIndexStore` 只对 cache 内镜像做了换算(减 `sharedRegionStart`),独立文件直接拿虚拟地址当文件偏移。dylib 的 `__TEXT` 在 0,两者恰好相等;主可执行文件的 `__TEXT` 在 0x100000000,于是每个符号都被归到高出 0x100000000 的位置,打印时又按文件偏移加一次 `__TEXT` 基址。第三个是另一回事:`MicaKit` 保留了 4 万多条 STABS 调试条目,`N_GSYM` 和它描述的符号同名、值为 0;索引不过滤调试条目,同名行又是「后写覆盖」,排在调试映射前面的本地符号偏移就被改成了 0。翻历史:独立文件的换算从最早的 `symbolsByOffset` 版本起就没有过,不是回归;STABS 在 2026-09-10 写 `BaselineFixturePicker` 时撞见过(「Release 构建带着同名、`n_value` 为 0 的 stab 条目」),当时只在测试辅助函数里跳过,库本身没修。 +- **关键决策**:**① 换算集中到一处**:新增 `SymbolValueOffsetConverter`(`MachOSymbols`),`MachOImage` 不变、cache 内减 `sharedRegionStart`(原逻辑搬进来)、独立文件按段表把地址换成文件偏移;段表只读一次,因为 `segments` 每次访问都遍历 load commands。`SymbolIndexStore` 的 `MachOFile` 采集腿(Swift 符号与 `_symbolic` 符号两张表)和公开的 `swiftSymbols` 都改走它。export trie 那条腿本来就对(通用二进制、strip 前后打印的地址逐一相同),没动。**② 同类排查找到第二处**:`MachOThunkEnvironment` 找镜像自带的 `__swift_instantiateConcreteTypeFromMangledNameV2` 时,把符号值当文件偏移经段表转成地址,主可执行文件里于是找不到,kind-9 thunk 里的具体类型字段打印成 `accessor function at …`。`MachOKit` 给的值本来就是未滑动地址,cache 内也一样,所以改成 `ThunkAddressSpace.address(forSymbolValue:)`:落在本镜像某个段里就原样当地址,原来的 `address(forFileOffset:)` 只有这一个调用方,一并删掉。**③ STABS 条目只能占位建行,不能决定偏移**:第一版直接丢掉调试条目,偏移都对了,但 SymbolTestsCore 的 42 个快照全部变成「同样的行、不同的顺序」。原因是调试映射按编译顺序排列,行在它那里先建好,行序就是源码顺序,打印器又按行序列成员;丢掉以后改按符号表顺序(导出符号按名字排序)。没有调试映射的发版二进制本来就是后一种顺序,但 RuntimeViewer 在进程里看自己的 Debug 构建时会因此换掉成员顺序。所以改成 `SymbolTableBuilder.reserveRow`:名字还没有行时建一行占位,此后不改、也不登记到任何偏移,偏移由真符号决定,不管真符号排在前面还是后面。`strip -x` 会把本地符号和调试条目一起删掉,所以「只有调试条目、没有真符号」的名字实际上不会出现。快照全部回到原样,一个都没改。 +- **落地模块**:`MachOSymbols`(新增 `SymbolValueOffsetConverter`、`SymbolTableBuilder.reserveRow`、`NlistProtocol.isDebuggingEntry`,`SymbolIndexStore` 两条采集腿、`swiftSymbols`)、`SwiftThunkAnalysis`(`ThunkAddressSpace.address(forSymbolValue:)`、`MachOThunkEnvironment`)。测试新增 `ExecutableImageSymbolOffsetTests`(现场编一个主可执行文件和一个 dylib 做对照,都带 `-g`),`StandaloneFileThunkResolutionTests` 加一条可执行文件的用例。另有 `Scripts/run-rendering-ab-verification.py` 的归档 cache 目录候选(见「验证」)。 +- **验证**:新测试在修复前确认失败。`ExecutableImageSymbolOffsetTests` 的可执行文件用例全红;dylib 用例里 STABS 两条红,`hiddenNames`(`internal static let`)打印成 `Address: 0x0`,`_symbolic` 表的偏移是 0;`swiftSymbols` 那条是把这一个文件单独换回旧代码后确认变红的;thunk 用例的两个字段打印成 `accessor function at …`。修复后全部通过。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,`USING_LOCAL_DEPENDENCIES=1`)共 2168 个测试 / 412 个套件通过,原始退出码 0,比上一节多出的正好是新加的 8 个测试和 1 个套件,另有那条早已登记的 known issue(`SymbolicManglingIndexTests`)。渲染 A/B(基线是同一提交 `514bb4bd` 的分离检出,两侧预构建后 `--skip-build`):92 对全部逐字节一致,覆盖 26.6 与 15.5 归档 cache、当前系统 27.0(进程内与 cache 文件)、iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器 runtime;iOS 15.5 的 SwiftUI / WidgetKit 两侧同码失败,记为 SKIPPED,是既有现象。第一轮缺了 26.x 归档 cache 这条腿:脚本写死 `26.6.2`,而这台机器的归档卷上是 `26.6`。两台工作机一台是 `26.6.2`、一台是 `26.6`,常量此前已来回改过两次,所以同批把它改成每个槽位一组候选、哪个有用哪个(见 [SystemFrameworkRenderingVerification.md](SystemFrameworkRenderingVerification.md)),harness 自己的单元测试重跑通过,再单独补跑 `cache-26.6` 的 12 对。Mica 实测:主可执行文件 434 个、`MicaKit` 844 个不同地址全部等于 `nm -U` 的已定义符号地址,vtable 偏移注释从 0 条变为 188 条,原先指向 `__DATA_CONST` 指针槽的 120 个一致性成员现在指向各自的见证函数,IDA 抽查 15 处吻合。 +- **关联文档**:[Modules/MachOSymbols.md](Modules/MachOSymbols.md)「规范化偏移的口径」与 STABS 两段、[AGENTS.md](../../AGENTS.md) 符号索引那一节新增的一条、[SystemFrameworkRenderingVerification.md](SystemFrameworkRenderingVerification.md)「跑之前先确认归档目录真的存在」。 +- **对应版本**:0.22.0。 + +## 76. MachOObjCSection 下限抬到 0.8.108:`objc` 在 macOS 14.4–15.3.2 的 cache 上 SIGTRAP + +- **时间段**:2026-10-03。 +- **动机**:另一个会话报告 `swift-section objc interface` 在 macOS 14.4–15.3.2 的归档 cache 上没有任何输出就退出(rc=133,即 SIGTRAP),换哪个镜像都一样。根因在 MachOObjCSection:这些 cache 用指针格式的方法列表存协议方法,列表里的槽位存的是 slide info 编码而不是地址,读取时却直接拿原值当地址。14.4 起是 slide info v5,原值是「相对 cache 起点的偏移」,每页 fixup 链最后一个槽位减 `sharedRegionStart` 时下溢陷阱;更早的 v3 不崩,但协议方法全部丢名。修复、测试与逐版本数据都在 MachOObjCSection 0.8.108 及其实现说明里。 +- **对本库的影响**:本库代码不动,只把 `Package.swift` 里 MachOObjCSection 的远程下限从 `0.8.106` 抬到 `0.8.108`。可见的变化有三处。一是 `objc` 子命令在旧 cache 上不再崩,协议方法也有了名字。二是 `--strip-protocol-conformance` 能剔掉 CoreFoundation 的 `NSCopying` 这类协议声明的成员:15.4 之后仍有少数协议是指针格式,以前读出来是空名。三是 15.8.1 及更早 cache 上的 `dump` / `interface` 多出 explicit selector 判定:`RawObjCProtocolSelectors` 把空 selector 记为「没读全」,这个判定此前一直被压住;修复后 15.0 上 AppKit 的 NSGradient 与 26.0 的输出一致。0.8.108 同时带出了 0.8.107 之后攒下的两项:标记渲染,以及 `stripProtocolConformance` 改为剔掉整条协议链的成员。 +- **验证**:同一个 `next` 分别链接修复前、后的 MachOObjCSection 做对照。53 个归档 macOS 版本(11.0.1–27.0)上 `objc interface NSCoding` 全部正确;26.0 / 27.0 cache 上四个镜像和五个独立文件的 `objc dump` 修复前后逐字节一致;带修复的兄弟依赖下,`swift test --filter ObjC --skip IntegrationTests` 的 152 个测试全部通过。抬下限后,用 `git archive` 导出的干净副本、只用远程依赖构建,依赖解析到 MachOObjCSection 0.8.108,14.3.1 / 15.0 / 15.3.2 上的复现命令都正确返回 0。 +- **关联文档**:MachOObjCSection 的实现说明 [DyldCachePointerSlotDecoding.md](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/0.8.108/Documentations/Internal/DyldCachePointerSlotDecoding.md) 与 [0.8.108 changelog](https://github.com/MxIris-Reverse-Engineering/MachOObjCSection/blob/0.8.108/Changelogs/0.8.108.md)。 +- **对应版本**:0.22.0。 + +## 77. SwiftSectionKit:swift-section 的功能抽成对外 product,CLI 只剩一层包装 + +- **时间段**:2026-10-03(单日)。 +- **动机**:用户要「把 swift-section CLI 的功能抽出来,方便进行测试,CLI 层只是一层包装」。拆分前 `Tests/SwiftSectionCommandTests` 的 79 个测试没有一个调用过任何命令的 `run()`:逻辑直接写 stdout / stderr 和文件,中途抛 ArgumentParser 的 `ValidationError` / `ExitCode`,还把 `Date()` 与 `BundledVersion` 盖进输出,测不了。两套命令也已经各写各的:Swift 侧的 `snapshot` 早把 `FileHandle.standardOutput.write` 换成了 `fwrite`,0036 搬进来的 `objc` 子命令还在用它。 +- **关键决策**(完整档提案,三轮澄清提问后定稿):**① 对外发布的 product**(推荐的是仅包内可见、用 `package` 访问级别,用户选了对外),模块名 `SwiftSectionKit`,放新分组 `Sources/Commands/`。**② 范围是全部子命令**,含 `objc` 五个。**③ 输出逐字节保持**,只有两处有意偏差:写流统一走 `fwrite`;命令行拼写(模板名、JSON 配置文件、逗号列表、C type 替换串)在调用库之前解释,所以「参数错误先于打开二进制报出」。**④ 输出走注入的输出端** `SwiftSectionOutput`,产物、诊断、索引事件 handler 三路分开;`dump` 照旧边算边输出。**⑤ 公开 API 按用途建模**:互斥选项是 enum(`ABIDiffRequest.Report` 只能是 change list / summary / JSON / annotated interface 之一),flag 组合校验与原报错留在 CLI 的 `validate()`。**⑥ 诊断 = 级别 + 命令行原文**;哪一级写哪个流由 CLI 决定,`interface` 进度行与 `dump` 错误行写 stdout 这两个历史怪癖只留在包装层,修起来只改一处。**⑦ 库的错误不提 flag 名**,CLI 翻译回历史文案与退出码;退出码由 CLI 按库返回的结论决定;生成器名、版本与时间经 `SwiftSectionEnvironment` 注入,`Version.swift` 留在可执行文件里,CI 写死的路径不变。**⑧ MCP server 不在本次范围**,列为后续。实现中的细化:目的地携带路径字符串而不是 `URL`(诊断要逐字复述调用方的拼写,`URL` 会规整 `dir/`、展开 `~`);偏差 2 实际多出三个边角,都是误用或两处写错的情形,记在提案里。 +- **落地模块**:新增 `SwiftSectionKit`(`Output/`、`Environment/`、`Inputs/`、`Swift/`、`ObjC/`),`swift-section` 改为包装层(各命令只剩 flag、`validate()`、`makeRequest()` 与三五行 `run()`,新增 `Models/CommandLineSupport`、`Output/StandardStreamOutput`;删掉 `Utilities/` 下的加载器、配色与 `IgnoreCoding`,以及 `objc` 的 session、加载器与 `writeStandardErrorLine`)。新增测试目标 `SwiftSectionKitTests`,`SwiftSectionCommandTests` 加四个套件,全部进 CI 白名单。 +- **验证**:新增与改动的测试 151 个通过;全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,`USING_LOCAL_DEPENDENCIES=1`)2240 个测试 / 422 个套件全部通过,原始退出码 0。渲染 A/B(两侧都是源码编出的 release 二进制,`--skip-build --skip-image-part`):归档 cache 15.5 / 26.6 与 iOS 15.5 / 16.4 / 17.5 / 18.5 / 26.5 模拟器共 68 对逐字节一致,iOS 15.5 的 SwiftUI / WidgetKit 两侧同样以信号 5 退出,是既有现象。新旧二进制逐字节对比 93 条命令行:83 条一致,7 条只差并发索引带来的 stderr 行序(旧二进制自己连跑也不同,`--jobs 1` 后一致),3 条属偏差 2。偏差 1 实测:旧二进制 `objc dump --sections unions 2>&-` 退出码 134,新的是 0。`SwiftSectionKit` 能为 iOS / tvOS / watchOS / visionOS 编译;顺带发现 Xcode 27 的 Swift Build 不接受包声明的 iOS 13.0 下限,是整个包的问题,未在此处理。 +- **关联文档**:[0058-swift-section-kit](../Evolutions/0058-swift-section-kit.md)、[Modules/SwiftSectionKit.md](Modules/SwiftSectionKit.md)、调用方指南 [SwiftSectionKit.md](../SwiftSectionKit.md) / [SwiftSectionKit_zh.md](../SwiftSectionKit_zh.md)、[AGENTS.md](../../AGENTS.md) 里改 CLI 那一节新增的「可执行文件是包装层」。 +- **对应版本**:0.22.0。发版说明要写新 product `SwiftSectionKit` 与两处行为偏差。 + +## 78. SwiftSectionKit:dump 与 objc dump 交出每个声明时附上种类与名字 + +- **时间段**:2026-10-04(单日)。 +- **动机**:ReverseEngineeringToolbox 的 dump 服务改用 SwiftSectionKit,用户要求「不要自己重写 dump 逻辑」。它默认每个类型写一个文件(`NSView.h`、`NSView+Animation.h`,Swift 类型连同它的 conformance),可 `DumpRequest` / `ObjCDumpRequest` 交出的每个声明只是一块不带名字的 `.declarations`,宿主要按声明拆文件只能自己再建一遍索引。 +- **关键决策**(轻量档提案,问过一轮):**① 新增协议要求 `SwiftSectionOutput.write(_:declaring:)`**,扩展里的默认实现转给 `write(_:)`;不给 `SwiftSectionProduct` 加 case,那会让每个穷举 `switch` 它的宿主编不过。**② `DumpedDeclaration`**:`.swift(DumpSection, name: String?)` 或 `.objc(ObjCDeclarationKind, name: String)`,复用已有的两个 enum。**③ 名字只在 `.output` 目的地、声明 dump 成功之后才算**,算不出来置 `nil`、不报诊断,命令行一个字节都不多。**④ conformance 的名字取 `extension` 行的完整拼法**(`dumpedTypeName(isFull: true, …)`),不用公开的 `dumpTypeName`:后者按 interface-type 选项打印,会去掉文件级 private 类型的判别符,fixture 的 `AlphaProtocolWitness` 就会和它的 conformance 名字对不上(单点变异实测)。**⑤ 名字一律算、不加开关**:release 版 dump macOS 27 的 SwiftUICore 中位数慢 2.8%,不值得多一个必须与新方法配对打开的开关。 +- **落地模块**:`SwiftSectionKit`(新增 `Output/DumpedDeclaration.swift`;`SwiftSectionOutput`、`DumpRequest`、`ObjCDumpRequest`);`SwiftSectionKitTests` 新增 `DeclarationRecordingOutput` 与 8 个用例。 +- **验证**:`SwiftSectionKitTests` 60 个、`SwiftSectionCommandTests` 99 个及三个源码扫描套件通过,原始退出码 0;新用例先红后绿。`git archive` 导出的 `next` 与本分支各编一个 release 版对照:`dump` libswiftObservation、SwiftUICore(8.5 MB,交替各三次),`objc dump` AppKit(5.9 MB),stdout 与 stderr 逐字节一致。没有跑全量 `swift test`。 +- **关联文档**:[0059-dump-declaration-identity](../Evolutions/0059-dump-declaration-identity.md)、[Modules/SwiftSectionKit.md](Modules/SwiftSectionKit.md)「1. 输出端」、调用方指南 [SwiftSectionKit.md](../SwiftSectionKit.md) / [SwiftSectionKit_zh.md](../SwiftSectionKit_zh.md)。 +- **对应版本**:0.22.0。发版说明要写:`dump` / `objc dump` 交出每个声明时附上种类与名字。 + +## 79. evolution 联合接口的 `@available` 生命周期标注:真属性作补充,位图注释保留 + +- **时间段**:2026-08-31 写成;2026-10-01 rebase 到 `next`;2026-10-05 落地。 +- **动机**:用户希望在既有 ABI 演进事实的基础上,让 `evolution --interface` 直接产出编译器语法的 `@available` 标注,而不只有位图注释。 +- **关键决策**:真属性作**补充**不作替换(前案否决的是「伪 @available 替代注解载体」,本案只在生命周期完整可表达时发语法合法真属性,位图注释继续承载 modified 与不可表达形状——两条否决理由均不复现);不可表达即整条不发、注释兜底(宁缺勿假);平台名从各输入 `LC_BUILD_VERSION` 推断,可以直接指定,推断失败响亮报错;默认配置输出逐字节不变。**落地时的实施偏差**:分支写在 SwiftSectionKit 之前,命令行那一半(平台推断与报错)原本写在 `EvolutionCommand` 里;落地时按 0058 的约定搬进库,`ABIEvolutionRequest.Report.annotatedInterface` 带上关联值 `availabilityAttributes`(`.none` / `.inferredPlatform` / `.platform(_:)`),推断失败抛 `AvailabilityPlatformInferenceError`,CLI 的 `--emit-available` / `--platform` 只做映射与错误译文。 +- **落地模块**:`SwiftInterface`(`EvolutionMarking` 属性生成纯函数 + 图例第三行、`SwiftEvolutionInterfaceRenderer` 前插属性行、两个 builder 的 `availabilityAnnotationPlatform` 配置)、`SwiftSectionKit`(`ABIEvolutionRequest` 的 `AvailabilityAttributes`、平台推断、`AvailabilityPlatformInferenceError`)、`swift-section`(`EvolutionCommand` 的两个 flag 与组合校验,`CommandLineErrorTranslation` 的两条译文)。测试:`EvolutionMarkingTests`、`SwiftEvolutionInterfaceBuilderTests`、`ABIRequestTests`(不同平台的输入是现场改写了 `LC_BUILD_VERSION` 的 fixture 副本,测试辅助 `FixtureFiles.makeCopy(of:buildPlatform:in:)`)、`InterfaceAnnotationStyleTests`、`EvolutionCommandValidationTests`、`CommandRequestMappingTests`、`CommandLineErrorTranslationTests`。 +- **验证**:定向套件全部通过(`SwiftSectionKitTests` 64 个、`SwiftSectionCommandTests` 103 个、evolution 渲染相关 49 个,原始退出码 0);新用例经变异检验,三处故意改坏正好让对应的 3 个用例变红。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,远端依赖)2268 个测试 / 422 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。CLI 冒烟:现编三版 dylib,推断出 macOS、`introduced:` / `obsoleted:` 各落在对的声明上、`--platform` 覆盖生效、默认输出没有 `@available`;平台冲突与推不出平台都以退出码 64 报错。没有跑渲染 A/B:改动全在开关后面,默认输出由现有快照测试兜底。 +- **关联文档**:[0060-evolution-interface-available-annotations](../Evolutions/0060-evolution-interface-available-annotations.md)(轻量档提案)、[TaskReports/2026-08-31-evolution-interface-available-annotations.md](TaskReports/2026-08-31-evolution-interface-available-annotations.md)、[Modules/SwiftInterface.md](Modules/SwiftInterface.md)「子系统 5」、[Modules/SwiftSectionKit.md](Modules/SwiftSectionKit.md)、使用指南 [SwiftSectionKit.md](../SwiftSectionKit.md) / [SwiftSectionKit_zh.md](../SwiftSectionKit_zh.md) 的「Errors / 错误」、插件 skill 第 7 节、README 的 evolution 一节。 +- **对应版本**:0.22.0。发版说明要写:`evolution --interface --emit-available [--platform <名字>]`。 + +## 80. 测试用的 dyld shared cache 路径按版本取 + +- **时间段**:2026-10-05,后续于 2026-10-06。 +- **动机**:用户要「DyldSharedCachePath改成String Type Enum结构体,支持传递版本返回路径」,并「再加一个SwiftInterfaceBuilderTests加上Diff和Evolution版本」。原来每用一个归档 cache 都得给 enum 加一个 case、手写完整路径,evolution 的 IntegrationTests 还要另写一份与路径一一对应的版本标签数组。 +- **关键决策**(轻量档提案,问过一轮):**① 以 `String` 为原始值的结构体**,写法同 `SymbolicManglingReference.Kind`;原有 8 个 case 变成同名 `static let`,调用点不改。**② 版本函数只有 `macOS(_:)` / `iOS(_:)`**,按 `/Volumes/DyldSharedCaches/<平台>/<版本>/dyld_shared_cache_arm64e` 拼,不检查文件在不在;模拟器 runtime 的 cache 路径带 build 号,版本推不出,继续写死。**③ 三个 IntegrationTests 套件各加一个 `ArchivedDyldCacheTests`**,只填版本号;evolution 那个拿版本号当轴标签,并打开 `@available(macOS, …)` 输出。**④ 顺带发现的两处不改**(用户选「都先不动」):`macOS_26_5_1` 指向的目录是空的,diff 套件里两处一跑就失败;`iOS_18_5` / `iOS_26_1` 指向没挂载的 `/Volumes/Generic`,全仓没有调用。 +- **落地模块**:`MachOFixtureSupport`(`DyldSharedCachePath`);`MachOTestingSupportTests` 新增 `DyldSharedCachePathTests`;`IntegrationTests` 的三个 `ArchivedDyldCacheTests` 与 `SwiftEvolutionInterfaceDumpTests` 两个辅助函数的 `availabilityAnnotationPlatform` 参数。 +- **验证**:全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,Swift 6.4,远端依赖)2270 个测试 / 423 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。IntegrationTests 只编译、不运行:新类编译通过、没有新警告,三个默认版本在卷上都有 cache 文件。 +- **后续(同日):`versionLabel`**:用户要 evolution 那边不再另写标签。`DyldSharedCachePath` 加 `versionLabel`,和路径一起在构造时给出:`macOS(_:)` / `iOS(_:)` 拿传入的版本当标签,其余常量直接写明(`current` 标为 `current`,标签不一定是系统版本,这是用户定的);因此不再遵循 `RawRepresentable`。`MultiVersionDyldCacheImageTests` 删掉 `cacheLabels`,轴标签取 `versionLabel`,默认三个 cache 的标签与原来手写的相同。没有从 cache 文件解析版本:cache 头的 `osVersion` 不带补丁号(26.5.2 读出 26.5.0),macOS 11 的 cache 里是 0.0.0。验证:按用户要求只编译,全部测试目标(含 IntegrationTests)编译通过、没有新警告,没有运行测试。 +- **后续(2026-10-06):evolution 的归档套件铺满 macOS 11–27,没有 Swift 的版本跳过**:`SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests` 改列 `cacheVersions`(卷上 macOS 11.0.1 → 27.0 每个次版本一个 cache,共 51 个;11.0、12.0 只有 `11.0.1`、`12.0.1`),`cachePaths` 由它生成,镜像换成 SwiftUI(这两处是用户改的)。`MultiVersionDyldCacheImageTests` 跳过 cache 里没有该镜像、或镜像没有 `__swift5_*` 节的版本,不再报错:AppKit 在 macOS 14 之前把 Swift API 放在 `libswiftAppKit.dylib`,本体在 11.0.1–13.7 没有 Swift 节,不跳过时每个这样的版本都会以 error 级别写进四条提取失败。规模参考(`next` 的 debug 版 CLI 走同一条 `--interface` 路径,AppKit 51 个版本、28 路并行):178 s,峰值内存 0.78 GB;同时打开的文件峰值 2749 个,其中 2214 个是本机 cache——MachOKit 的 `FullDyldCache.host` 每访问一次就重新打开、映射一遍本机 cache,而库里默认的依赖搜索路径每个版本都会访问它(未处理)。SwiftUI 51 个版本目前跑不完:测试第 140 秒在 13.5 上崩溃(崩溃前峰值 2.2 GB),读 Swift 类的 ObjC RO 数据时,MachOKit `DyldChainedFixupPointer._rebaseTargetRuntimeOffset` 里的 `UInt64` 减法下溢;CLI 路径同样会崩,崩在另一个旧版本上。根因是同一个 SwiftUI 构建出现在 13.5 和 13.6 两个 cache 里、按镜像的缓存撞 key,修复见第 81 节。只跑 14.4 → 27.0 的 23 个版本能跑完:CLI 用时 26 分钟,峰值 4.64 GB,出现在成员索引阶段,渲染阶段约 2.6–2.9 GB;照此推算 51 个版本的峰值在 6–8 GB。(成员索引阶段的峰值其实主要是读子 cache 时堆积的 autorelease 池,修掉之后 51 个版本以 4.86 GB 的峰值跑完,见第 82 节。)验证:只编译,全部测试目标(含 IntegrationTests)编译通过、没有新警告;按用户要求运行过一次 `evolutionInterfaceFile`(如上,崩溃),其余测试没有运行。 +- **关联文档**:[0061-dyld-shared-cache-path-versions](../Evolutions/0061-dyld-shared-cache-path-versions.md)(轻量档提案)。 +- **对应版本**:不进发布产物,只改测试支撑代码与测试。 + +## 81. 同一次构建出现在两个 dyld cache 里:按镜像的缓存不再串用 + +- **时间段**:2026-10-06(单日)。 +- **动机**:用户把 `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests` 换成 SwiftUI、铺满卷上 macOS 11.0.1 → 27.0 的 51 个归档 cache,测内存时测试进程第 140 秒 SIGTRAP,CLI 的 `evolution --interface` 同样会崩。崩溃点在 MachOKit `DyldChainedFixupPointer._rebaseTargetRuntimeOffset` 的 `unpacked -= preferedLoadAddress`,调用链是给成员补 ObjC 信息时读 Swift 类的 ObjC RO 数据(`ObjCMembers.table` → `ObjCClassMethodIndex.hierarchy` → MachOObjCSection `ObjCClass64.classROData` → `DyldCache.resolveOptionalRebase`)。 +- **根因**:macOS 13.5 和 13.6 的 cache 里是同一个 SwiftUI 构建,`LC_UUID` 都是 `3694A102-…`,而 cache 里镜像的标识是 `uuidFile(install name, LC_UUID)`,两份成了同一个 `SharedCacheKey`,共用一切按镜像的缓存。先建好的那份类对象偏移(13.6 的 `JoinedViews` 在 `0x5bbea7e0`,13.5 的在 `0x5bbe27e0`)被拿到另一个 cache 里读,读到的位置(13.5 主 cache 文件 `0x59BEA800`)存的是整数 `0xa9`,slide info 按指针解出一个低于 shared region 起点的目标,无检查的减法下溢。复现回路:先对 13.6、再对 13.5 调 `ObjCClassMethodIndex.hierarchy`,0.25 秒、退出码 133,栈与原始崩溃逐帧相同。 +- **以前修过吗**:这类撞键 2026-06-20 修过两次——`c4bc9c4a` 把裸路径改成路径加 `LC_BUILD_VERSION`(两个 cache 里的 SwiftUI 撞了),`32733775` 改为优先 `LC_UUID`(相邻系统版本 platform 与 SDK 相同)。两次都假设不同系统版本的二进制一定不同;这次是同一个二进制原样进了两个 cache。cache 镜像真正的身份是「哪个 cache 里的哪个镜像」。 +- **关键决策**(问过一轮):**① 修在身份的源头**:MachOKitExtensions 给 `MachOTargetIdentifier` 加 `.dyldCacheImage(path:uuid:cacheUUID:)`,`MachOFile.identifier` 对 cache 里的镜像带上主 cache 头部的 UUID——用主 cache 的,同一镜像无论只开主文件还是连子 cache 一起开都是同一个身份(13.5、27.0 实测)。`SharedCacheKey`、`ReadingContext` 的缓存范围、demangler 的记忆、node 驻留缓存都直接用这个身份,一处改全覆盖,本库除了 `SharedCacheKey` 给新 case 补一条只哈希两个 UUID 的快路径,不用动。公开枚举加 case 严格说会让穷举 `switch` 编不过,已知下游(MachOKitUI 只用 typealias、RuntimeViewer 没用到)都不受影响,用户定为发 1.1.0,MachOObjCSection 的 `from: "1.0.0"` 能接住,不用跟着发。**② MachOKit 不再 trap**:解 rebase 时对文件读出的值做的无检查运算一律改成算不出来就返回 nil——`_rebaseTargetRuntimeOffset` 的 arm64e、`._64`、`._32`、`._32_firmware` 四处减法,`arm64e_segmented` 的段下标与偏移算术,以及 `_resolveRebase` 里 v1 的减法与最后的加法。本库远程依赖固定在 MachOKit 0.52 线,所以从 0.52.103 拉分支发 0.52.104,再合进 fork 的 `next`。光改 MachOKit 不够:MachOObjCSection 拿到 nil 会退回槽里的原始值,原始值可能恰好高于 region 起点,变成一个错的偏移——所以根因必须在身份上修。 +- **横向排查**:本库所有按镜像的缓存都经 `identifier`(`SharedCacheKey`、`MachOContext` 的范围、`DependencyClosure` 的去重);唯一按路径做键的 `CacheImageResolver.entryPointAddressesByImagePath` 是每个 cache 一个实例,不会跨 cache。MachOObjCSection 没有全局的按镜像缓存。MachOKit 里同类的无检查运算只在这两个函数里(`DyldCacheLoaded` 那处读的是进程自己的 cache 头)。 +- **落地模块**:MachOKitExtensions(`MachOTargetIdentifier.dyldCacheImage`、`DyldCacheImageIdentifierTests`);MachOKit fork(`DyldChainedFixupPointer`、`_DyldCacheFileRepresentable`、`DyldChainedFixupPointerRebaseTargetTests`);本库 `MachOCaches`(`SharedCacheKey` 快路径与 `SharedCacheKeyTests` 两条)、`SwiftInspectionTests/DyldCacheTwinImageTests`(归档 cache 不在时跳过)。 +- **验证**:三个仓库都先红后绿——MachOKitExtensions 的身份测试在 1.0.0 上断言失败;MachOKit 的 6 条合成数据测试中 5 条在 0.52.103 上 SIGTRAP 或数组越界(另一条是对照);本库两条在发版依赖(MachOKitExtensions 1.0.0、MachOKit 0.52.103)上一条记录偏移不对后崩溃、一条 SIGTRAP,用 `swift package edit` 换成两个修复分支后全绿。原始场景:修复后的 CLI 跑 SwiftUI 11.0.1 → 14.3 的 28 个版本,459 秒跑完、峰值 2.43 GB、日志 0 条 error(修复前同一批版本第 123 秒崩溃)。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,远端依赖加两个 `package edit`)2275 个测试 / 424 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue;MachOKitExtensions 全套 11 个测试通过。 +- **对应版本**:0.22.0。依赖下限已抬到 MachOKitExtensions 1.1.0 与 MachOKit 0.52.104(两者 2026-10-06 已发:1.1.0 快进推到 MachOKitExtensions 的 `main`;0.52.104 打在从 0.52.103 拉出的修复分支上,修复同时合进 fork 的 `next`,`main` 没动)。发版说明要写:同一次构建出现在两个 dyld cache 里时,按镜像的缓存不再串用(不再崩溃)。 + +## 82. 读 dyld cache 时子 cache 只建一次:evolution 的内存峰值与一半耗时 + +- **时间段**:2026-10-06(单日)。 +- **动机**:第 81 节修掉崩溃后,SwiftUI 51 个版本的 `evolution --interface` 仍推算要 6–8 GB,超过用户定的 5 GB 上限(macOS 超内存不杀进程,只会吃满内存再走 swap)。用户要求先查怎么解决爆内存。 +- **根因**:拆账用 SwiftUI 26.7 + 27.0 两个版本,在索引中途和渲染开始时各用 `heap` 抓一次。 + - 峰值 3.2 GB,索引中途堆里 1.18 GB 是 `@autoreleasepool content`。索引完 footprint 回落到 0.47 GB,其中 malloc 217 MB,即每个版本约 108 MB 常驻。 + - autorelease 来自读取。本库 `MachOFile+Readable.swift` 的每次读取都经过 MachOKitExtensions 的 `cacheAndFileOffset(for:)`。地址既不在镜像自己的文件、也不在主文件时(比如 `SymbolicDemangler` 读别的镜像的上下文描述符),它逐个子 cache 条目调用 MachOKit 的 `DyldSubCacheEntry.subcache(for:)`: + - 经 `FullDyldCache` 打开的,这个调用每次都通过计算属性 `FullDyldCache.subCaches` 把全部子 cache 新建一遍,再挑出一个; + - 只开了主文件的,每次都重新打开那个子文件。 + - 每个新 `DyldCache` 初始化时查一次 `FileHandleIdentityStore`(`NSMapTable` 弱表,`objectForKey:` 会 autorelease 一次)。本库按实例缓存的 `fileIO` 也因为实例是新的,每次都要 open 加 mmap。 + - 大栈执行器每个 job 外面包一个 autoreleasepool,而一个版本的整个索引是一个不挂起的 job,所以池要攒到索引结束才清。 + - 代价与子文件数的平方成正比。归档里 13.5 有 1 个子文件、15.5 有 2 个、26.7 有 12 个、27.0 约 80 个,所以几乎是 macOS 27 才有的问题。27.0 单版本索引中途就到 3.4 GB;成员索引阶段抽样 15 秒,63% 的 CPU 在 `cacheAndFileOffset` 里。 +- **以前修过吗**:没有。逐条目的循环是本库 2025 年写的,2026-08 随抽包移进 MachOKitExtensions。上游 MachOKit 2025-11 让 `subcache(for:)` 改走 `FullDyldCache.subCaches`,省掉了重开文件,代价是每次重建全部子 cache;2026-07-25(21463c0)起每个 `DyldCache` 初始化都要做一次弱表查询。macOS 27 的 cache 拆成约 80 个文件后,问题才大到能看见。 +- **关键决策**: + - **① 修在 MachOKitExtensions,按它的提案 0001 做成 cached 视图**,性能改动不进 fork 的上游文件。`MachOFile` 的 cached 存储里放一张各子 cache 映射区间的表:查找是一次二分,落到的子 cache 每次都返回同一个实例。也考虑过直接调用 `FullDyldCache.cacheAndFileOffset(for:)`(MachOObjCSection 的读取就是这么做的),但它每次返回新实例,本库按实例缓存的文件映射照样每次重开。用户选了原方案。 + - **② 两种打开方式分开处理**: + - 经 `FullDyldCache` 打开的,用 `_cachedFullCache` SPI 一次拿齐全部子 cache,共享 FullDyldCache 已经打开的文件。MachOKitExtensions 依赖的 MachOKit 下限因此抬到 0.52.0。 + - 只开主文件的,为读映射表把每个子文件打开一次再关掉,只留下查找真正落到的那些。否则 macOS 27 的 cache 每读一个镜像就要常驻 80 个文件。 + - **③ 表挂在 `MachOFile` 上,不挂在 cache 上**:子 cache 实例强引用它的 `FullDyldCache`,只开主文件时还强引用主 cache,挂在 cache 上会形成循环引用。 + - **④ 同类**: + - 按名字找镜像(MachOKitExtensions 的 `DyldCache.machOFile(by:)`)是同一种逐条目循环,改为一次拿齐。 + - MachOObjCSection 的读取有自己的查找。经 FullDyldCache 打开时不受影响;只开主文件时是同一类问题,当时漏判了,见本节「后续」。 + - `FullDyldCache.host` 每访问一次重开 82 个文件(第 80 节):51 个版本时同时开着 4,182 个本机 cache 文件。「后续」里改为进程内只开一次。 +- **落地模块**:MachOKitExtensions(`DyldCacheSubCacheTable`、`MachOCached.subCacheTable`、`DyldCache.subCacheFiles`、`DyldCacheSubCacheLookupTests`)。本库只抬依赖下限。 +- **验证**: + - **新测试先红后绿**:MachOKitExtensions 加了两条测试,各在两种打开方式下跑。「同一地址查两次拿到同一个实例」在 1.1.0 上两种方式都失败,修复后通过;「查到的文件与偏移等于 `FullDyldCache` 自己的映射结果」是对照,修复前后都通过。全套 13 个测试通过。 + - **两个版本**:同一个 debug 版 CLI(`next` 同源,MachOKit 0.52.104),SwiftUI 26.7 + 27.0。 + - 耗时 376 s → 198 s,峰值 3.2 GB → 427 MB。 + - 渲染时 malloc 217 MB → 219 MB,常驻不变;autorelease 池 1.18 GB → 20 KB。 + - 输出 118,970 行,逐字节相同。 + - 同一阶段打开的文件:27.0 从 198 个到 212 个,26.7 从 33 个到 35 个。 + - **51 个版本**(11.0.1 → 27.0,`--interface --emit-available`,默认 28 路并行):39 分钟跑完,峰值 4.86 GB,日志 0 条 error,输出 29.9 万行。 + - 成员索引结束时约 4.32 GB,平均每个版本约 84 MB 常驻。 + - 峰值出现在之后的快照加 lineage 矩阵阶段,51 份快照与 51 个索引同时在内存里,约多出 0.55 GB。 + - 渲染阶段回落到 4.31–4.41 GB。 + - **全量测试**:`swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,远端依赖,MachOKitExtensions 用 `swift package edit` 指向修复分支):20 个测试产物共 2,274 个测试、424 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。测试名单与第 81 节那次逐条相同。第 81 节写的 2,275 是当时数法不同。 +- **还剩什么**:51 个版本离 5 GB 只剩约 250 MB。结构性的上限是 evolution 的渲染要求所有版本的索引一直留到最后,这部分随版本数线性增长。要真正留出余量,需要把渲染改成从新到旧逐版本合并、渲染完就释放,属于架构改动,要走提案,待用户决定。 +- **后续(同日):集成测试本身仍超 5 GB,再修四处** + - **现象**:用户要求跑 `SwiftEvolutionInterfaceBuilderTestSuite.ArchivedDyldCacheTests.evolutionInterfaceFile`(51 个 SwiftUI 版本,当时用只开主文件的 `DyldCache(path:)` 打开)。第 8 分钟 5,138 MB,被看门狗杀掉,比同样 51 个版本的 CLI 高。 + - **诊断**:4.0 GB 那一刻的构成: + - malloc 3.5 GB; + - 页表 445 MB,4.5 GB 时已到 847 MB; + - 映射文件 4,453 段:本机 cache 2,706 段(33 份 × 82 个文件),14.4 的 `.01` 一个文件 250 段,14.5、14.6 各 247 段。 + - **原因**: + - MachOObjCSection 的读取有自己的一份 `cacheAndFileOffset`。只开主文件时,每次跨文件读都现开一次子 cache,再按新实例另映射一份文件。 + - 它的 `FileHandleHolder` 和 MachOKit 的 `FileHandleIdentityStore` 都是弱键强值的 `NSMapTable`,键释放后值要等表扩容才清,于是这些映射一直留着。 + - 原先以为是 autorelease 让文件开着,复现测试证明 MachOKit 自己的句柄会立即关闭,留下来的是标识对象和以它为键的映射。 + - **看门狗失效一次**:进程映射膨胀后,`footprint` 自己卡了 9 分钟,看门狗没能杀掉进程,是手动杀的。当时 RSS 显示 149 GB,大部分是重复映射重复计数,系统没有用到 swap。之后改用 `top` 读数。 + - **修复**(用户选了全部四项,都先红后绿): + 1. **MachOObjCSection 0.8.109**:删掉自己的三个查找函数,改用 MachOKitExtensions 1.1.1 的;`FileHandleHolder` 在有 ObjC 运行时的平台上改为关联对象。`DyldCacheSubCacheReadTests` 两条。 + 2. **MachOKit 0.52.105**:fork 从 0.52.104 拉修复分支,已合进 fork 的 `next`。标识对象改为挂在文件句柄上的关联对象。`FileHandleIdentityLifetimeTests` 一条红绿、一条对照。这处修复主要服务本库与 MachOObjCSection 的需求,只留在 fork 里,不提给上游。 + 3. **MachOKitExtensions 1.1.2**:加 `FullDyldCache.cachedHost`,进程内只打开一次。本库 `FileDependencyLocator` 与 `MachOSource` 改用它。`FileDependencyLocatorTests.locatorsShareOneOpeningOfTheSystemCache` 一条。 + 4. **测试支撑**:`MultiVersionDyldCacheImageTests` 改用 `FullDyldCache` 打开,和 CLI 一致。 + - **验证**: + - 集成测试 `evolutionInterfaceFile` 通过,用时 2,416 秒,峰值 4,456 MB,出现在快照加 lineage 矩阵阶段;渲染阶段 3.8–4.0 GB;打开的文件不超过 718 个。输出与上面 CLI 跑 51 个版本的结果逐字节相同,只多了测试自己追加的那行 `ABI-breaking` 结论。 + - 全量 `swift test --skip IntegrationTests`:2,275 个测试、424 个套件,只有一条失败:`Arm64eSignedVWTPointerTests` 的探针子进程报 `slotCarriesTagBits=0`。它单独重跑三次都通过,探针也不依赖这次改动的代码,判为偶发。另有早已登记的 `SymbolicManglingIndexTests` known issue。 +- **对应版本**:0.22.0。依赖下限:MachOKit 0.52.105、MachOKitExtensions 1.1.2、MachOObjCSection 0.8.109。 + +## 83. MachOKit 依赖统一为 `from: "0.54.101"` + +- **时间段**:2026-10-07(单日)。 +- **动机**:用户先要 MachOKit fork 合并上游 0.54.0 并发 0.54.100,随后要求「MachOKit依赖全部改成 from: "0.54.100"」。范围定为本库这条依赖链上的三个库:本库、MachOObjCSection、MachOKitExtensions。只推送、不单独发版;下游的 App 与工具(RuntimeViewer、MachOKitUI、swift-decompiler 等)仍按 0.22.0 发版后的迁移计划处理。本库原来写的是 `"0.52.105" ..< "0.53.0"`,上限是 `8e3a49aa` 为防 fork 在次版本里删公开 API 而设;按用户要求改成只有下限的 `from:` 之后,fork 的次版本升级不再被这里挡住,删 API 的风险由升级时的全量测试与渲染 A/B 兜住。 +- **fork 这边**:上游 0.54.0 合进 fork 的 `next`,没有冲突。上游这一版收下了 fork 之前提的三个修复(p-x9/MachOKit#330–#332),合并后 fork 相对上游只剩 swift-crypto / swift-asn1 的版本范围、0.52.104 与 0.52.105 两个修复,以及 Xcode scheme。0.52.105 那处(文件句柄的标识随句柄释放)主要服务本库与 MachOObjCSection,按用户决定只留在 fork,不提上游。 +- **A/B 查出的回归**:第一轮 A/B 的基线是 `next` @ `91b6c206`(MachOKit 0.52.105),候选只把 MachOKit 换成 0.54.100,两侧共用同一份 `Package.resolved`。96 对里 92 对一致,剩下 4 对是候选侧 SIGTRAP:iOS 15.5 模拟器的 SwiftUI、WidgetKit,dump 与 interface 各一对。 + - 崩在 MachOKit `MachOFile.ExportTrie.init` 对 `_readLinkEditData(...)` 结果的强制解包。调用方是 `ObjCAncestorResolver.classObject(named:)`:沿 ObjC 父类链找类时,它会读依赖闭包里每个镜像的导出表。 + - 根因是上游 0.53.0 的 `7adae68` 给 link-edit 读取加了一条检查:读取起点不能早于 `__LINKEDIT`。iOS 15.5 模拟器的 `UIKit` 是只转发 `UIKitCore` 的外壳,`LC_DYLD_INFO_ONLY` 的 `export_off` 与 `export_size` 都是 0;起点 0 过不了检查,读取返回 nil,强制解包就 trap。0.52.105 在这里返回的是一张空表。 + - 凡是用 `LC_DYLD_INFO` 又没有导出符号的镜像都会触发,与具体框架无关。本库读导出表的 4 处(`ObjCAncestorResolver`、`DependencyImageResolver`、`MachOThunkEnvironment`、`PropertyWrapperTypeCatalog`)都是 `exportTrie?.…` 的写法,MachOKit 改成返回 nil 后会自然退回别的查法。 + - 本库全量测试没有抓到它:fixture 与测试用的镜像都没有这种形状,只有 A/B 的旧模拟器 runtime 那条腿覆盖到了。 +- **修法**(用户选):上游已在 `17ff04e`(p-x9/MachOKit#337,2026-10-03 合入上游 `main`,尚未进上游正式版)把导出表、函数起始表与符号表这几处读取改成读不到就返回 nil。把它单独挑进 fork,配一条回归测试 `ExportTrieWithoutExportsTests`:照 `UIKit` 的形状合成一个镜像,没有这个修复时 trap。然后发 fork 0.54.101,三个库的下限都改成 `from: "0.54.101"`;MachOKitExtensions 与 MachOObjCSection 先按 0.54.100 推送过一次,随后各追加一个提交。横向排查:挑入后 fork 里不再有对 link-edit 读取结果的强制解包。 +- **0.53 起 fork 不再在 `MachOFile` 里缓存 chained fixups**(`7426642`,这部分缓存搬进了 MachOKitExtensions 的 cached view)。本库的 rebase / bind 查询都经 `context.bindRebaseResolver`,走的是 MachOKitExtensions 的缓存版本,所以不受影响,A/B 的耗时也印证了这一点(见下)。 +- **落地**:本库 `Package.swift`;MachOKitExtensions `main`(`795fd47` 改为 0.54.100,`156f54a` 改为 0.54.101);MachOObjCSection `next`(`81972ff`、`a35e763`,连同 `Package.resolved`);MachOKit fork 的 `next` 与 `main`(`a8723af` 合并上游 0.54.0,`ecae5d1` 挑入上游修复与回归测试),tag 0.54.100、0.54.101。 +- **验证**: + - fork:MachOKit 全部 192 个测试,失败的仍是合并前就有的 5 个环境问题(3 个 `ArchiveFileTests`、2 个 `testDylibsPreBuildLoaderSet`;`AotCachePrintTests` 在本机会崩,照旧跳过)。新测试先红(signal 5,与 A/B 的崩溃同一行)后绿。两次推送 `main` 的 CI 都通过。 + - MachOKitExtensions 15 个测试、MachOObjCSection 161 个测试(`--skip MachOObjCSectionTests`)在远端 0.54.101 上全部通过。 + - 本库:全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,远端依赖)在 0.54.100 与 0.54.101 上各跑一次,都是 2,275 个测试、424 个套件全部通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。第二轮 A/B(候选换成 0.54.101)96 对全部逐字节一致。耗时:第一轮两侧同时现跑,68 个两侧都成功的渲染合计基线 1,512 秒、候选 1,503 秒,没有变慢。 +- **对应版本**:0.22.0。发版说明要写:MachOKit 依赖从 `"0.52.105" ..< "0.53.0"` 改为 `from: "0.54.101"`,随之带上上游 0.53.0 与 0.54.0 的全部改动。 + +## 84. 从 dyld cache 读出的镜像在自己的 cache 里找依赖 + +- **时间段**:2026-10-07 至 10-08。 +- **动机**:用户对比新旧两版 SwiftUICore 的 dump,看到 `LinkDestination.Configuration.url` 的大小从 16 变成 24,以为 24 不对(REPL 里 `MemoryLayout.size` 是 16)。查下来 24 才是对的:iOS 18.5 / macOS 15.5 的 Foundation 里 `URL` 有 `_url: NSURL`、`_parseInfo`、`_baseParseInfo` 三个字段,共 24 字节;REPL 量的是本机 macOS 27 的 Foundation,`URL` 从 macOS 26 起改成了一个 `any _URLProtocol & AnyObject`,16 字节。旧 dump 是 0.19.0 或更早的版本生成的,那时 `dump` 做布局时不理会 `--dependency-search-path`,一律用宿主 cache。但顺带查出一个真问题:用 `--dyld-shared-cache` 读归档的 macOS 15.5 cache 里的 SwiftUICore、又不给搜索路径时,依赖仍然去宿主 cache 找,`URL` 被算成 16(0.21.0 与 `next` 都如此)。 +- **修法**:`DependencyClosure(root: MachOFile, …)` 是全库唯一构建 `FileDependencyLocator` 的地方(静态布局、ObjC 祖先、thunk 读取器、property wrapper 目录、interface 依赖、索引器都经过它),在这里让 root 所在的 cache 排在所有搜索路径前面,与 dyld 的行为一致。root 经 `FullDyldCache` 打开时直接交出那个实例(`FileDependencyLocator(rootDyldCache:)`),不重新打开;搜索路径里再点名同一个 cache 文件、或 root 本就来自 `FullDyldCache.cachedHost` 时不重复加入。root 只经单个 cache 文件打开时,把主 cache 文件当第一条 `.dyldSharedCache` 路径。不用 `root.fullCache`:它第一次被读时才打开并写回 `MachOFile`,无锁,而同一个 root 的闭包会在多个线程上构建。判为 bug 修复而非新功能:`DependencySearchPathUsage` 的注释早已写明意图是「按点名的 cache 的系统布局,而不是宿主的」,没给路径时违背了它。 +- **落地**:`Sources/MachO/MachODependencies/`(`DependencyClosure.swift`、`FileDependencyLocator.swift`);CLI `--dependency-search-path` 的帮助文字、`AgentPlugins` 的 skill、AGENTS.md 同步说明 cache 里的镜像不需要搜索路径;[Modules/MachODependencies.md](Modules/MachODependencies.md) §3 记规则与线程安全的理由,[StaticLayoutDependencyClosure.md](StaticLayoutDependencyClosure.md) 加指针。 +- **验证**:`CacheRootDependencyClosureTests`(按 `LC_UUID` 认出闭包找到的是 15.5 的 Foundation,两种打开方式各一例;点名同一个 cache 时用的是 root 来自的实例)与 `CacheRootDependencyLayoutTests`(`Foundation.URL` 是 24 字节),修复前 3 例全红、修复后全绿,没有归档 15.5 cache 时跳过。全量 `swift test --skip IntegrationTests`(JHs-Mac-Studio-Ultra,远端依赖)2,279 个测试通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。CLI 端到端:15.5 cache 的 SwiftUICore 不带搜索路径,`url` 为 24、`isSensitive` 在 `0x18`。渲染 A/B(基线 `next` @ `433f1421`,候选为本节的修复加上同期的「模拟器框架里绑定到自己的 ObjC 类」修复(第 85 节),两侧共用一份 `Package.resolved`):cache 两条腿 24 对里只有两对 interface 不同,都是 property wrapper 的识别——候选按镜像自己 cache 里的 SwiftUICore 判断。15.5 腿上基线把 `IdentityLink` 当成 wrapper(宿主 macOS 27 的同名类型才是,15.5 的 `IdentityLink` 在 SwiftUI 里,只有一个 `_value` 字段),又没认出 15.5 SwiftUICore 里确为 `@propertyWrapper` 的 `AtomicBox`;26.6 腿上候选多认出 4 处 `AtomicBox`。都是候选对。dump 不带布局注释,所以 `URL` 的变化不在 A/B 里,由上面的测试与 CLI 端到端覆盖。 +- **对应版本**:0.22.0。发版说明要写:从 dyld cache 读出的镜像改为先在自己的 cache 里找依赖,归档 cache 的布局注释会随之改变(按那个系统自己的框架计算)。 + +## 85. 模拟器框架里绑定到自己的 ObjC 类 + +- **时间段**:2026-10-07 至 10-08。 +- **动机**:用户对比新旧两版 iOS 18.5 模拟器 SwiftUI 的 dump,`PlatformDocument: UIDocument` 的字段偏移从 `0xc8` 变成了 `unknown (Objective-C ancestor UIDocument unresolved)`,整份 dump 有 392 处。旧 dump 是 0.19.0 或更早的版本生成的:那时布局不理会 `--dependency-search-path`,从宿主 cache 的 Mac Catalyst 版 UIKitCore 读到了 `UIDocument`;0.20.0 起改读模拟器 runtime 里的 UIKitCore 文件,就读不到了(0.21.0 与 `next` 都如此)。 +- **根因**:模拟器 runtime 的框架用 `-interposable` 链接,导出的 ObjC 类在 `__objc_classlist`、`isa`、`superclass`、category 的 `cls` 与 ivar offset 指针里都以 bind 指向本镜像自己的导出符号(`dyld_info -fixups` 里的 `bind /_OBJC_CLASS_$_UIDocument`)。UIKitCore 的 classlist 5,017 项里 1,586 项是这种 self-bind,iOS 16.4 到 26.5 的模拟器都有;libobjc 的 `NSObject`、ActivityKit 与 WidgetKit 自己的类也是。MachOObjCSection 只解 rebase,这些类要么丢、要么读错。`UIDocument` 的 `class_ro_t.instanceSize` 实为 `0xc4`,按 8 对齐即 `0xc8`,旧值是对的。之前记录的「模拟器文件约六分之一的类读不出」就是它。 +- **修法**(用户要求修):读取在 MachOObjCSection,按两种 fixup 格式解 self-bind 的查询放在 MachOKitExtensions(新增 `resolveSelfBind(fileOffset:)`,旧格式的 bind 索引补记 library ordinal 与 addend)。MachOObjCSection 的指针解码遇到 self-bind 解到导出符号、遇到指向别的镜像的 bind 返回 nil、空槽返回 nil;读类、metaclass、父类、category 的类与 ivar offset 时不再先判 `isBind` 或槽位原值。同一类问题顺带修掉:旧 `LC_DYLD_INFO` 文件的 bind 槽原值是 0,曾被当成文件偏移 0 去读 Mach-O header;MachOObjCSection 的 bind 名字查询只认 chained fixups。后者修好后,本库 `ObjCImplementationClassIndex` 里补这道名字的两段代码(`superclassLocation(of:)`、`targetClassName(of:)`)就多余了,删掉,由原有的 `LegacyDyldInfoBindTests` 与 `ObjCMemberRecoveryTests` 的旧格式用例验证。横向排查:本库自己的 Swift 指针与 thunk 读取路径在这三个模拟器框架里没有遇到 self-bind(SwiftUI 30 个、SwiftUICore 34 个、UIKitCore 的全部 self-bind 都是 `_OBJC_CLASS_$_` / `_OBJC_METACLASS_$_`),只经 MachOObjCSection 受影响。实现说明在 MachOObjCSection 的 `Documentations/Internal/SelfBindPointerSlots.md`,本库 [ObjCMemberRecovery.md](ObjCMemberRecovery.md) 同步。 +- **落地**:MachOKitExtensions 1.2.0(`resolveSelfBind(fileOffset:)`、`cached.exportTrie`,`main` 39bdf74)与 MachOObjCSection 0.8.110(`next` / `main` ea14b1d)已发版;本库把 MachOObjCSection 的下限抬到 0.8.110(它要求 MachOKitExtensions 1.2.0),删 `ObjCImplementationClassIndex` 的两段补丁。 +- **验证**: + - MachOObjCSection:`SelfBindPointerSlotTests` 测试时用 `-interposable` 编一个小 dylib,chained fixups 与旧格式各一份,7 个测试 14 例修复前全红、修复后全绿;另有 iOS 18.5 模拟器 UIKitCore 的 `UIDocument` instance size 为 `0xc4`。全量(`--skip MachOObjCSectionTests`)通过。MachOKitExtensions:`SelfBindResolutionTests` 4 个测试两种格式,全量 19 个通过。 + - 本库:`SimulatorRuntimeObjCAncestorLayoutTests` 钉住 iOS 18.5 SwiftUI 的 `PlatformDocument` 第一个字段在 `0xc8`,用已发布的 MachOObjCSection 0.8.109 为红、用修复后为绿(没有该模拟器 runtime 时跳过)。全量 `swift test --skip IntegrationTests` 2,277 个测试通过,原始退出码 0,只有早已登记的 `SymbolicManglingIndexTests` known issue。CLI 端到端:用户原命令下 SwiftUI 的 `unresolved` 从 392 处降到 0。 + - 渲染 A/B(基线 `next` @ `433f1421`,候选为本节加上第 84 节,两侧共用一份 `Package.resolved`,候选的 MachOObjCSection 与 MachOKitExtensions 用 `swift package edit` 指向修复分支):96 对里 70 对逐字节一致,进程内 24 对、iOS 15.5 模拟器 6 对全部一致;cache 两对的差异见第 84 节。其余 24 对在 iOS 16.4 / 17.5 / 18.5 / 26.5 模拟器腿上,逐行归类都是类读得到以后的结果:481 行新的 `// ObjC ancestor chain:`、321 条 `// overrides -[…]`、235 行带 `override` 的声明(`init()` → `override init()`,`PlatformDocument` 的 `init(fileURL:)` 由 `@objc` 改判为覆写 `UIDocument`),空 body 的 UIKit 子类多出祖先链注释,3 个改了 ObjC 运行时名的类认出了 `@objc(CHKWidgetEnvironment)` 这类类名,`final var debugDescription` 这类覆写 `NSObject` 的成员去掉了 `final`。新增 7 个显式 selector 判定:`_nsAttributedSubstringFromRange:` 只出现在 SwiftUI 自己的二进制里,判得对;另外 6 个 `_accessibility…`(如 `_accessibilityIsFirstSiblingForType:`)由私有框架 UIAccessibility 的 `NSObject (UIAccessibilityElementTraversal)` 等 category 声明,SwiftUI 不链接它(运行时由辅助功能 bundle 加载),落在已登记的「闭包够不到的镜像里的 category 不可见」边界上——以前这些链在 libobjc 的 `NSObject` 就断了、按 fail closed 不判,现在链走得通才露出来。离线分不出 SwiftUI 源码是写了显式 `@objc(…)` 还是覆写了头文件里的声明。抽两对候选输出原样重跑,逐字节一致。 +- **对应版本**:0.22.0。依赖下限:MachOObjCSection 0.8.110(随之 MachOKitExtensions 1.2.0)。发版说明要写:iOS 26 及更早模拟器 runtime 的框架里,导出的 ObjC 类(含 UIKit 的 `UIView` / `UIDocument`、libobjc 的 `NSObject`)现在都读得到,Swift 子类的字段偏移、`override`、ObjC 祖先链与自定义 ObjC 类名随之出现。 + +## 86. 0.22.0 发版 + +- **时间段**:2026-10-08(单日)。 +- **动机**:用户指示「把 next 当前提交合并到 main 发一个新版本」。自 0.21.0 以来 `next` 多了 82 个提交:第 68–85 节的工作,其中第 70–79、81–85 节进入发布产物。 +- **关键决策**:**① 不做发版审查**:各批工作合入时都跑过全量测试,涉及渲染的批次跑过渲染 A/B;这次只在只含远端依赖的干净副本上重新验证一遍。**② 提案不用再取号**:0055–0061 合入时已取号并标为 Implemented;未开工的 `draft-static-layout-through-accessor-thunks` 继续留作草稿。**③ Changelog 改用一句话一条的写法**(按 `write-release-notes` skill,只写用户看得到的变化,不写原因、实现、提案编号与链接)。用户同批把 0.20.0 与 0.21.0 的 Changelog 也改写成同样写法,单独提交。0.22.0 共 2,349 字符,超出普通版本 1,500 的预算:这一版带新 product `SwiftSectionKit`、0057 的一批废弃与三处行为变化、五个依赖下限变化。**④ 废弃写进 Breaking**:传 `machO` 与指针的读取接口在 0.22.0 只是废弃(照常编译、多一条警告),0.23.0 删除;调用方迟早要改,所以与三处行为变化、`NamedDumpable` / `ConformedDumpable` 的 requirement 变化、`ResilientWitness` 的改名一起放在最前。**⑤ 构建脚本同批发出**:用户的 `build-executable-product.sh` 改动(Swift 6.4 的 Swift Build 一次编出 universal、6.3 及更早的原生引擎分架构编再 `lipo`)单独提交。`release.yml` 不调用这个脚本,发版产物不受它影响;本批没有运行它。**⑥ 版本号**:`Version.swift`、两个 `plugin.json` 改为 0.22.0,README 的安装示例同步;`--emit-available` / `--platform` 在 0060 合入时已写进插件 skill,skill 这次不用改。 +- **落地模块**:`Sources/Executables/swift-section/Version.swift`、`AgentPlugins/swift-section/`(两个 `plugin.json`)、`Changelogs/0.20.0.md`、`Changelogs/0.21.0.md`、`Changelogs/0.22.0.md`、`build-executable-product.sh`、`README.md`、本账本(第 69–85 节的「对应版本」改为 0.22.0,新增本节)。 +- **验证**:`next` @ `5c8a551f` 经 `git archive` 导出到外置卷上的干净副本,新鲜 scratch,依赖全部从远端解析(MachOKit 0.54.101、MachOKitExtensions 1.2.0、MachOObjCSection 0.8.110、swift-demangling 0.7.1、swift-semantic-string 0.4.0、swift-capstone 6.0.1),工具链为 Xcode 26.6,fixture 链主 checkout 的那份(SDK 26.5 编出)。全量 `swift test --skip IntegrationTests` 共 2279 个测试 / 427 个套件,原始退出码 0;唯一的 known issue 是 `SymbolicManglingIndexTests` 里局部类型的那一条 `withKnownIssue`。release 构建(`swift-section`)Xcode 26.6 的 x86_64 与 arm64 都是 0 warning,两个二进制都能运行。Claude Code 的 `claude plugin validate`(marketplace 加 `--strict`)通过;本机 Codex 的 `plugin-creator` skill 已不带 `validate_plugin.py`,只确认了 Codex 清单能解析、自 0.21.0 起只改了版本号。 +- **关联文档**:[Changelogs/0.22.0.md](../../Changelogs/0.22.0.md)。 +- **对应版本**:0.22.0。 + ## 维护约定 1. **每个非平凡批次结束时必须在本文追加/更新一节**(新工作弧新增一节;延续既有弧则在该节 diff --git a/Documentations/Internal/ReadingContextAbstraction.md b/Documentations/Internal/ReadingContextAbstraction.md index e5176372f..c9c903e07 100644 --- a/Documentations/Internal/ReadingContextAbstraction.md +++ b/Documentations/Internal/ReadingContextAbstraction.md @@ -159,36 +159,19 @@ extension RelativeDirectPointerProtocol { ## Usage Examples -### Existing API (Unchanged) +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.23.0. ```swift -// MachO file reading - continues to work +// A Mach-O file or image: pass its context. let machO: MachOFile = ... -let name = try descriptor.layout.name.resolve( - from: descriptor.offset(of: \.name), - in: machO +let name = try descriptor.name(in: machO.context) +let pointee = try descriptor.layout.name.resolve( + at: descriptor.offset(of: \.name), + in: machO.context ) -// Direct pointer reading - continues to work -let ptr: UnsafeRawPointer = ... -let name = try descriptor.layout.name.resolve(from: ptr) -``` - -### New Unified API - -```swift -// Using MachO context -let machO: MachOFile = ... -let context = machO.context // MachOContext -let name = try descriptor.layout.name.resolve( - from: descriptor.offset(of: \.name), - in: context -) - -// Using InProcess context -let ptr: UnsafeRawPointer = ... -let context = InProcessContext.shared -let name = try descriptor.layout.name.resolve(from: ptr, in: context) +// Process memory: pass the in-process context. +let inProcessName = try pointerDescriptor.name(in: .inProcess) ``` ### Generic Functions @@ -278,7 +261,7 @@ Sources/ | **1. Add Infrastructure** | Add `ReadingContext`, `MachOContext`, `InProcessContext` | Non-breaking | | **2. Add Extensions** | Add `resolve(at:in:)` to `Resolvable` and pointer protocols | Non-breaking | | **3. Gradual Migration** | New code uses `ReadingContext` API | Progressive | -| **4. Deprecation** | Mark old APIs as `@available(*, deprecated)` | Future | +| **4. Deprecation** | The `ReadingContext` form becomes the only implementation; the Mach-O and pointer forms are deprecated forwarders (0.22.0) and removed (0.23.0) | Done 2026-09-30, see below | ## Benefits @@ -291,7 +274,7 @@ Sources/ ## Model Coverage Completion Pass (2026-05) When the abstraction landed, only ~15 of the ~60 files under -`Sources/MachOSwiftSection/Models/` that expose a MachO-based API also exposed a +`Sources/ABI/MachOSwiftSection/Models/` that expose a MachO-based API also exposed a `ReadingContext` overload — any caller adopting the abstraction had to drop back to the MachO/InProcess APIs for the rest. A dedicated completion pass (original spec: `docs/superpowers/specs/2026-05-02-reading-context-api-design.md`, now in @@ -322,13 +305,62 @@ Two deliberate decisions worth keeping in mind: - `runtimePointer(at:)` is an **extension method with a default, not a protocol requirement** — keeping it out of the requirement set makes the addition non-breaking for external conformers. A future conformer that needs it must - override the extension, not implement a witness. + override the extension, not implement a witness. **Superseded:** it became a + requirement with a default shortly after (commit `35162f69`), so a call + through `any ReadingContext` reaches the concrete context's implementation; + the default still keeps new conformers non-breaking. - The `machO as? MachOImage` runtime cast inside `MachOContext`'s override is unavoidable: the generic parameter is unconstrained at the conformance site, so a `where MachO == MachOImage` specialization would not produce a witness. For `MachOContext` the method returns `nil`, matching the pre-existing MachO overload's behavior. +## 单一实现与废弃(2026-09-30,第 4 阶段) + +提案:[0057-reading-context-migration](../Evolutions/0057-reading-context-migration.md)。 + +每个读取接口原先最多有三份手写实现:按偏移读 Mach-O 的、用裸指针读本进程的、经 `ReadingContext` 读的。现在只剩 `ReadingContext` 那一份;另外两份是一行转发(`machO.context` / `InProcessContext.shared`),标 `@available(*, deprecated)`,0.23.0 删除。下面是代码里看不出来、下次维护会踩的几点。 + +### 转发必须原地保留 + +旧声明留在原来的类型上、原来约束的扩展里,只换函数体。把它们统一挪到协议扩展里看起来更整洁,但会改变重载解析:`Pointer` 原来在具体类型上有 `resolve(from:in:) -> Self`,挪走之后协议扩展里的 `-> Self` 与 `-> Self?` 两个形式同级,`resolve(from:in:).descriptor()` 这种链式调用直接二义(迁移时实际撞上)。也不能用 `@_disfavoredOverload` 硬压:`ContextDescriptorWrapper` 等类型的 `-> Self?` 形式遇到非法 kind 返回 nil 而不是抛错,一律压成 `-> Self` 会悄悄改变旧调用方拿到的结果。 + +### 旧 requirement 的去留 + +旧形式大多从协议 requirement 里移除,只作为扩展上的废弃转发保留。转发调用的是 `ReadingContext` 那条 requirement,分派结果不变:`TypeContextDescriptorProtocol` 覆盖 `genericContext` 的那条链路照样走到 16 字节的 type generic context header。例外是 `PointerProtocol` 与 `RelativeIndirectType`:`Pointer` 同时遵循两者,两个互不相关的协议扩展各给一份转发,会让对 `Pointer` 的每次调用都二义,所以这两个协议把旧形式留作 requirement,requirement 与默认实现一起标废弃。Swift 6.3 实测:只废弃默认实现、不废弃 requirement,每个依赖该默认实现的遵循类型都报 “deprecated default implementation is used to satisfy …”;两者一起标,只在调用处报。 + +### 约束扩展里的空指针 guard + +在 `where Pointee: OptionalProtocol` 这类约束扩展里,按名字调用一个同时是协议 requirement 的方法,绑定的是 requirement,也就是无约束的 witness,而不是旁边那个约束重载。所以转发如果写成 `try resolve(at: offset, in: machO.context)`,就会跳过空指针 guard,去读空指针自己所在位置的字节。guard 因此放在一个私有 helper 里,由 `ReadingContext` 入口和各个转发共同调用(`RelativeDirectPointerProtocol` 等四个协议,以及 `PointerProtocol`、`SymbolOrElementPointer`)。 + +### 收成一份时修掉的分歧 + +`ReadingContext` 那份实现以前有几处漏掉了传 `machO` 那份做的事,现在补齐。回归测试在 `Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift`,三条在修复前都确认红过: + +- `Pointer.resolve(at:in:)` 先查 rebase 表:文件里 rebase 槽存的是 chained fixup 编码,不是地址。 +- `TypeMetadataRecord.contextDescriptor(in:)` 对槽位是 bind 的间接记录返回 nil(iOS 26.5 模拟器 `libswiftSynchronization` 里那条指向 `Swift.Optional` 的记录)。 +- `SymbolOrElementPointer` 的可选元素先剥 tag 再判空。 + +另外两处没有专门的回归测试:`MangledName` 的所有偏移都以起始地址为基准,带 tag 的起点不再算错长度;metadata 地址为 0 时,本进程读取与原来的指针版一样抛错。bind / rebase 判定一律走 `context.bindRebaseResolver`,不再用 `as? MachOFile`,所以实现了 `MachOBindRebaseResolving` 的包装类型(MachOKitUI 的 `MachOFileSource`)也能拿到。旧指针版因此多了两处行为变化:遇到空指针或只带 tag 的指针会抛错而不是崩溃,遇到符号引用会返回 `.symbol` 而不是 `fatalError()`。 + +### 性能 + +`InProcessContext` 的 tag 掩码在进程里只算一次;`UnsafeRawPointer.stripPointerTags()` 每次调用都要找当前镜像、遍历一遍 load command。`advanceAddress` 也会剥 tag,与旧指针版的 `resolveDirectOffset(from:)` 一致。`MachOContext.addressFromVirtualAddress` 不再在 `resolveOffset(at:)` 之前多剥一次,因为 `MachOFile.fileOffset(of:)` 与 `MachOImage.resolveOffset(at:)` 自己会剥;它与 `addressFromOffset`、`offsetFromAddress` 一起声明成不抛错。 + +### 缓存范围:上层只读接口也收成一份 + +上层有一批接口只读数据,却因为要按镜像缓存而离不开 `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` 转型。 + +### 这次没动的已知缺口 + +- `ValueMetadataProtocol.descriptor(in:)` 等经绝对指针读取的字段,对 dyld shared cache 里的镜像,偏移口径不对:`fileOffset(of:)` 给的是 cache 文件内的偏移,读取却按 `unslidVirtualAddress - sharedRegionStart` 来理解。三种形式本来就一样,这次既没修好也没弄坏。 +- `EnumMetadataProtocol.payloadSize` 的返回类型是 `StoredSize?`,泛型读取按 9 字节的 `Optional` 去读,和 AGENTS.md 里的 Optional 读取陷阱同类。迁移之后已单独修复并验证,同时修了 `FunctionTypeMetadata.extendedFlags` 与 `SwiftClassObjectIndex` 读 class flags 的两处同类写法,见 [ProjectEvolutionLog.md](ProjectEvolutionLog.md)「Optional 读取多读一个 tag byte」一节。 + ## Future Considerations 1. **Async Support**: Add `AsyncReadingContext` for async reading operations diff --git a/Documentations/Internal/ReviewAdjudications.md b/Documentations/Internal/ReviewAdjudications.md index 8ad2a0892..517d6aecb 100644 --- a/Documentations/Internal/ReviewAdjudications.md +++ b/Documentations/Internal/ReviewAdjudications.md @@ -19,7 +19,7 @@ 2. 根治在上游:把约 6200 行的 Remangler 泛型化到 `DemanglingNode`(需引入 overlay 节点表示"新脊柱挂旧子树"的两簇合成点,并把替换表的身份 hash / 深比较异构化)。上游已把它列为既定方向——`materializedNode` 的文档注释原话是 *"remangling until the `Remangler` is genericized"*——且所需基础设施(跨表示 `structurallyEquals` / 一致的 `structuralHash`、`printCacheIdentity` 身份抽象、printer 泛型化先例)在 `feature/node-store` 分支均已就绪。 3. 下游任何 workaround(如自写泛型 remangler、绕过 `ABIKey` 的 remangle 身份)都比等上游代价大。 - **既往修复**:无。上游有意设计,非回归。 -- **代码锚点**:`Sources/SwiftDiffing/ABIKey.swift` `make(for:)` 调用点注释("Adjudicated — not worth fixing")。 +- **代码锚点**:`Sources/Output/SwiftDiffing/ABIKey.swift` `make(for:)` 调用点注释("Adjudicated — not worth fixing")。 - **复审条件**:① 上游发布泛型化的 Remangler 后,删调用点注释即可直接受益,本条目关闭;② profiling 显示批量建 key 时 materialize 占总耗时比例可观(当前仅为推断成本,无测量数据)——届时正确动作是推动上游泛型化,而非下游绕路。 - **关联上游事项**(非本表裁决,仅备查):`structuralHash` 分配一条见 A2。~~同轮核对的 `NodeReference` 缺 async `print(using:)` 一条属上游补齐范畴~~——**已闭环(2026-08-03)**:上游 `f913742` 把 print 便利方法整体迁到 `DemanglingNode` 协议扩展并补 async 变体,发布为 **0.5.1**,对 `NodeReference` 直接可用;本仓库依赖已升 `from: "0.5.1"`,`indexExtensions` 的 `await` 已恢复。 @@ -194,6 +194,7 @@ - **复现 / 是否误报**:机制上可构造,但无真实实例——SDK 全部 80 个 apinotes 的 6145 个条目中**零个**以 `Ref` 结尾(review 会话实证),swift-api-digester dump 的 CoreFoundation 同样没有。 - **这是不是刻意设计**:是。commit `97d9f39a` 记录了 CG/CV/CM 实测:同一类型两种 mangling 形态并存(签名 `__C.CGContextRef`、字段元数据 `__C.CGContext`),「剥后名存在于索引」正是有意选的判据。反向风险真实:interface 提取会收进 obsoleted 的 typealias stub(`CFStringRef` 在 Swift 里是编译器认识的重命名 stub),加守卫可能把 CF 剥除整体关掉。 - **复审条件**:出现「以 `Ref` 结尾、且剥后名恰好是另一个真实类型」的实例。 +- **2026-10-03 补记**:提案 0023 之后字段元数据也按 import info 里的 ABI name 拼成 `__C.CGContextRef`,上面说的「剥后名」形态不再出现,CF class 只剩 `…Ref` 一种拼写,全靠剥除规则还原。不加守卫的理由(反向风险)不变,裁决维持。 --- @@ -241,7 +242,7 @@ - **与 main 基线对比**:行为变化确由本 PR 引入,但项目已把旧行为定性为 bug,故不是回归。 - **既往修复**:无。这是首次把发射对齐 first-wins 的 deliberate 改动。 - **残余关切(不构成缺陷)**:`--interface` 模式直接从 live model 渲染、不经 `ABIDiff`,所以 `keyCollisions()` 诊断在该视图无处输出。**main 同样如此**,属可选增强而非本 PR 缺陷。 -- **代码锚点**:`Sources/SwiftInterface/InterfaceUnionWalker.swift` `matchAcrossVersions` 的 first-wins 注释。 +- **代码锚点**:`Sources/Output/SwiftInterface/InterfaceUnionWalker.swift` `matchAcrossVersions` 的 first-wins 注释。 - **复审条件**:把碰撞诊断带进 interface 视图(事件或注释形式)被单独提案时,本条目关闭。 --- @@ -276,7 +277,7 @@ ## A23 — `MachOSwiftSection` 对 `FoundationToolbox` / `SwiftStdlibToolbox` / `MachOReading` 的 import 未在 manifest 声明(PR #121 review 发现 I,部分) - **裁决**:本 PR 只补新丢的 `.target(.Utilities)`;其余三个模块的未声明 import **延后**到独立清理批次(2026-09-04)。 -- **发现**:`Sources/MachOSwiftSection` 里 `import FoundationToolbox` ×5、`import SwiftStdlibToolbox` ×6、`import MachOReading` ×5,target 依赖列表里都没有;今天能编是因为 `MachOBase` 再导出 `MachOReading`,而 FrameworkToolbox 的两个模块经 `MachOKitExtensions` 等传递可见。 +- **发现**:`Sources/ABI/MachOSwiftSection` 里 `import FoundationToolbox` ×5、`import SwiftStdlibToolbox` ×6、`import MachOReading` ×5,target 依赖列表里都没有;今天能编是因为 `MachOBase` 再导出 `MachOReading`,而 FrameworkToolbox 的两个模块经 `MachOKitExtensions` 等传递可见。 - **复现 / 是否误报**:属实。`git diff f3782248 -- Package.swift` 证明 `Utilities` 是本 PR 从依赖列表里删掉的(`MachOFoundation` → `MachOBase` 替换时一并丢失),其余三个在 `next` 上就没声明。 - **与 main 基线对比**:`Utilities` 一条为本 PR 引入(已补);其余为既有状态,非回归。 - **为什么延后**:整仓同类问题不止这一个 target(PR #121 自己就补了 16 个 target 的 `MachOFoundation` 声明),应当一次性用「每个 import 都有直接声明」的脚本扫全仓并统一修,而不是每个 PR 顺手补几条。零行为影响,无用户可见后果。 @@ -298,7 +299,7 @@ ## A25 — 「六个 `import MachOFoundation` 冗余」(PR #122 review 发现 F11,**误报**) - **裁决**:误报(2026-09-04)。 -- **发现**:审查者依据「`Sources/MachOSwiftSection/Exported.swift` 是 `@_exported import MachOFoundation`」判定 `SwiftDump/Dumpable/*+Dumpable.swift` 六处新增的 `import MachOFoundation` 多余。 +- **发现**:审查者依据「`Sources/ABI/MachOSwiftSection/Exported.swift` 是 `@_exported import MachOFoundation`」判定 `SwiftDump/Dumpable/*+Dumpable.swift` 六处新增的 `import MachOFoundation` 多余。 - **为什么是误报**:提案 0018 把 ABI 层的再导出收窄到 `MachOBase`(注释原文 "the ABI layer deliberately stops here"),`LargeStackTaskExecution` 住在 `MachOSymbols`,只有 `MachOFoundation` 再导出它;去掉那六行编译不过。审查者读的是 0018 之前的状态。 - **附带子主张**:① `MachOSymbols` target 未声明 `FoundationToolbox` product 而 `LargeStackTaskExecution.swift` import 它——属实但基线既有(`SymbolIndexStore.swift` / `Symbol.swift` 同样如此),归 A23 同类清理批次;② `AnySwiftEvolutionInterfaceBuilder.swift` 新加的 `import Utilities` 冗余(`MachOSwiftSection → MachOBase → Utilities`)——属实,已删。 - **复审条件**:无。 @@ -317,7 +318,7 @@ ## A27 — 新 `Collection.concurrentMap(maximumConcurrency:)` 与既有 `Array.concurrentMap(_:)` 同名而语义不同(PR #122 review 发现 F10) - **裁决**:不修(2026-09-04)。 -- **发现**:`Sources/Utilities/ConcurrentMap.swift` 的 `concurrentMap(_:)` 是 `DispatchQueue.concurrentPerform` 的同步阻塞版;新函数是 async、窗口化、可抛错。参数标签不同、无重载歧义,纯可读性。 +- **发现**:`Sources/Support/Utilities/ConcurrentMap.swift` 的 `concurrentMap(_:)` 是 `DispatchQueue.concurrentPerform` 的同步阻塞版;新函数是 async、窗口化、可抛错。参数标签不同、无重载歧义,纯可读性。 - **为什么不修**:两者的调用形态(`await` + `try` + `maximumConcurrency:` 标签)已把区别写在调用点上;改名或合并文件是纯搬动。既有同步版零调用方(2026-09-03 调研已记录),更合适的动作是下次清理批次删掉它。 - **复审条件**:同步版被删或被重新启用时一并统一命名。 @@ -371,7 +372,7 @@ ## A33 — `TypeIndexing.TypeDatabase.index` 的 task group 用 `addTask`,取消后仍提交剩余模块(PR #122 review 发现 1 的横向同类) - **裁决**:延后(2026-09-04)。 -- **发现**:`Sources/TypeIndexing/TypeDatabase.swift:76` 与 `concurrentMap` 修复前同形;基线既有,非本 PR 引入。 +- **发现**:`Sources/Declaration/TypeIndexing/TypeDatabase.swift:76` 与 `concurrentMap` 修复前同形;基线既有,非本 PR 引入。 - **为什么延后**:正确修法是 `addTaskUnlessCancelled` + 注册前 `Task.checkCancellation()`(否则取消会把残缺索引静默登记进去),而 `index(dependencies:moduleFilter:)` 直接构造 `SDKIndexer` / `ModuleInterfaceIndexer`(需要 SourceKit 与 SDK),没有注入缝可以写单元级复现测试;按「修复必带能变红的测试」规则,先补注入缝再修。 - **复审条件**:`TypeDatabase` 获得 indexer 注入缝时一并修,或 GUI 宿主报告取消 `--resolve-c-module-names` 后 CPU 仍被占用。 @@ -576,12 +577,28 @@ --- -## A52 — `argumentCandidatePathSpecializesNonGenericCandidate` 时好时坏:`.candidate(Int)` 与 `.metatype(Int.self)` 特化出两份 metadata(0.21.0 发版 CI 发现,**基线既有,暂缓**) - -- **裁决**:暂缓修(2026-09-29),断言先用 `withKnownIssue(isIntermittent: true)` 包住,发版之后单独查根因。用户在「再重跑一次 / 先标成已知问题 / 现在就查」三个选项里选了第二个。 -- **发现**:`GenericSpecializationTests.swift` 里这条断言要求两条路径拿到同一个 `TestSingleProtocolStruct` metadata 指针,时常拿到两份,地址相差 3872 字节。0.21.0 发版当天 debug 下 1 过 3 挂:本地两次、PR #127 两次失败,PR #128 的验证 run 通过;release 在 CI 上一直通过。它连续两次卡住了发版 PR 的 CI。 -- **复现 / 是否误报**:属实。2026-09-23 实测单独跑 4 次挂 2 次;2026-09-29 加上 `withKnownIssue` 后单独跑 6 次,4 次记为已知问题、2 次干净通过,退出码都是 0。fixture 里没有第二个叫 `Int` 的类型,所以不是测试挑错了候选。未验证的方向:两条路径给 `Hashable` 用了不同的 witness table,于是运行时泛型 metadata 缓存的键不同;候选列表来自 `ConformanceProvider.swift` 里的 `Set`,顺序每个进程都不一样,和「时好时坏」对得上。 -- **与 main 基线对比**:基线既有。2026-09-23 在 `b3e93a80`(已在 main 上)上就同样失败;main 的 CI 此前几次通过是碰巧。 -- **为什么暂缓**:和发版内容无关,查根因要单独花时间;一直红会让 CI 失去意义,而断言本身是对的,所以不删、不放宽,只标成间歇性已知问题。`withKnownIssue` 在它通过时也不会报错,失败时记为已知问题,不影响退出码。 -- **既往修复**:`325a0b10`(2026-05-02)把候选从「第一个非泛型候选」固定为 `Int`,修的是「挑错候选」那一层,没有碰到「同一类型两份 metadata」。测试由 `dea51656` 引入。 -- **复审条件**:查到根因并修掉后,去掉 `withKnownIssue`,让它在 debug 下连续多次通过(例如单独跑 20 次)再关闭本条。 +## A52 — `argumentCandidatePathSpecializesNonGenericCandidate` 时好时坏:`.candidate(Int)` 与 `.metatype(Int.self)` 特化出两份 metadata(0.21.0 发版 CI 发现,**基线既有,2026-09-29 已修**) + +- **裁决**:**已修**(2026-09-29)。根因是测试按 `currentName == "Int"` 挑候选,会挑到库里一个函数局部类型;测试改为按全名挑,库不动。当天早些时候的原裁决是「暂缓修,断言先用 `withKnownIssue(isIntermittent: true)` 包住」(用户在「再重跑一次 / 先标成已知问题 / 现在就查」里选了第二个),发版之后接着查到了根因,包装已去掉。 +- **发现**:`GenericSpecializationTests.swift` 里这条断言要求两条路径拿到同一个 `TestSingleProtocolStruct` metadata 指针,时常拿到两份。0.21.0 发版当天 debug 下 1 过 3 挂:本地两次、PR #127 两次失败,PR #128 的验证 run 通过。它连续两次卡住了发版 PR 的 CI。 +- **根因**: + - 这组测试的索引器会索引测试程序本身(`MachOImage.current()`),库代码是静态链接进去的,所以库里的类型也会成为特化候选。 + - 2026-09-20 的 `4c8643c0` 在 `ObjCMemberApplication.inferFromSelectorNames(...) -> Int` 的函数体里声明了 `enum MemberKey: Hashable`。它打印出来是 `MemberKey #1 in static SwiftDeclaration.ObjCMemberApplication.inferFromSelectorNames(...) -> Swift.Int`。 + - `currentName` 取的是打印名按 `.` 切开后的最后一段,所以这个局部类型的 `currentName` 是 `Int`。 + - `A: Hashable` 的候选里于是有两个 `currentName == "Int"`:`Swift.Int` 和 `MemberKey`。候选列表的顺序来自 `ConformanceProvider` 里的 `Set`,每个进程都不一样。排到 `MemberKey` 时测试特化出的是 `TestSingleProtocolStruct`,和 `.metatype(Int.self)` 那份自然不同。 +- **更正原条目**:原条目说「fixture 里没有第二个叫 `Int` 的类型,所以不是测试挑错了候选」,推测是「两条路径给 `Hashable` 用了不同的 witness table」。两句都错了:挑错的正是候选,只是那个类型不在 fixture 里,而在测试程序自己链接的库代码里;witness table 不同只是因为类型本身就不同。 +- **复现 / 是否误报**:属实。临时探测测试准备好索引器后,在同一进程里循环 40 次比较两条路径:每次候选里都有这两个 `Int`,其中 1 次挑中了 `MemberKey`(它的 metadata 是 `0x1161600f8`,`Swift.Int` 是 `0x1f77118d8`)。此前的记录是 2026-09-23 单独跑 4 次挂 2 次;加上 `withKnownIssue` 后单独跑 6 次,4 次记为已知问题。 +- **与 main 基线对比**:基线既有。触发它的局部类型 `4c8643c0` 在 main 上;`currentName` 的写法从 2025 年就是这样。main 的 CI 此前几次通过是碰巧。 +- **修复**: + - 按用户的界定,`currentName` 是给 dump/interface 的类型、协议声明用的,不是给测试查找定义用的,所以库不改,改测试。 + - `GenericSpecializationTests.swift` 里挑 `Int` / `Array` / `Dictionary` 候选的 14 处改为按全名(`Swift.Int` 等)比较。 + - 按短名查定义、比较名字集合的其余 13 处(6 个文件共 27 处),改用新加的测试专用方法 `DefinitionName.declaredNameForTesting`(`Sources/TestSupport/MachOTestingSupport/`)。它从节点读声明本身的名字,依次处理 `.identifier`、`.localDeclName`、`.privateDeclName`,不认识的形状退回完整打印名,让短名比较失败而不是误配。 + - `AGENTS.md` 写测试一节加了一条规则。 +- **回归测试**: + - `DeclaredNameForTestingTests` 用 `$s4Main3fooSiyF9MemberKeyL_OD`(打印为 `MemberKey #1 in Main.foo() -> Swift.Int`,与出事的候选同形)断言新方法取到 `MemberKey`,同时断言 `currentName` 在同一个节点上是 `Int`,把这个差别钉住。 + - 原测试去掉 `withKnownIssue`,恢复成普通断言;按全名挑候选之后,结果不再取决于候选顺序。 +- **既往修复**:`325a0b10`(2026-05-02)把候选从「第一个非泛型候选」固定为按 `currentName` 匹配 `Int`,当时库里还没有叫 `Int` 的局部类型,这种写法是安全的;直到 `4c8643c0` 加了那个局部 enum,它才开始误配。测试由 `dea51656` 引入。 +- **遗留**: + - dump/interface 打印的声明里如果出现函数局部类型,`currentName` 会把它显示成外层函数签名的尾巴。库代码里目前没有调用它,影响待查。 + - 上游 swift-demangling 的 `Node.identifier` 同样不认 `.localDeclName`。 + - `MemberKey` 这个候选的镜像路径是空字符串,原因没查。 diff --git a/Documentations/Internal/SharedNodeStoreMigration.md b/Documentations/Internal/SharedNodeStoreMigration.md index bac2588c8..c2e4e6f29 100644 --- a/Documentations/Internal/SharedNodeStoreMigration.md +++ b/Documentations/Internal/SharedNodeStoreMigration.md @@ -16,9 +16,9 @@ | 位置 | 改什么 | |---|---| -| `Sources/MachOSymbols/InternedNodeReferenceCache.swift` | `Storage` 里的结构哈希桶 `[Int: [NodeReference]]` 整层退役,换成持有一个 `SharedNodeStore`;`reference(interning:)` 的实现缩成一句 `store.intern(node)`。**类本身保留**,因为它做的事 `SharedNodeStore` 不会做:`SharedNodeStore` 不认识 Mach-O 镜像,per-image / per-process 两个作用域的键控、以及和 `SharedCache` 内存压力驱逐的接线,是这个类继续存在的理由。31 个调用点(分布在 7 个文件)的公开 API 不变,零波及。 | -| `Sources/SwiftDeclaration/Components/Definitions/TypeDefinition.swift:164–195` | 删除 `fieldNodeStoreBuilder` + `freeze()` 的「每类型一个批量 store」两阶段流程。字段类型树改走 `InternedNodeReferenceCache.shared.reference(interning:in:)`,直接汇入镜像 store。顺带拿到一项旧形态给不了的收益:跨类型的结构去重——每类型各一个 store 时,两个类型共用的子树只能各存一份。 | -| `Sources/MachOSymbols/SymbolIndexStore.swift:256–275` | 删除 `lateDemangledNode(forName:)` 的「每个名字铸一个 builder」形态。`Storage` 自持一个 late-names 专用的 `SharedNodeStore`,demangle 改为 `lateStore.demangle(name)`。名字 → 裁决字典**保留**——拒绝名的 `nil` 裁决和成功结果的 memo 都还需要,`SharedNodeStore` 不按名字缓存拒绝。insert-if-absent 的写入流程保留,但竞态的后果从「有害」变「良性」:两个线程同时 miss 时,双方各自 demangle、各自 intern 进同一个 store,结构去重保证它们拿到同一个引用,于是原来处理「输家丢弃自己那个 store」的一整段代码直接删除。 | +| `Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift` | `Storage` 里的结构哈希桶 `[Int: [NodeReference]]` 整层退役,换成持有一个 `SharedNodeStore`;`reference(interning:)` 的实现缩成一句 `store.intern(node)`。**类本身保留**,因为它做的事 `SharedNodeStore` 不会做:`SharedNodeStore` 不认识 Mach-O 镜像,per-image / per-process 两个作用域的键控、以及和 `SharedCache` 内存压力驱逐的接线,是这个类继续存在的理由。31 个调用点(分布在 7 个文件)的公开 API 不变,零波及。 | +| `Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift:164–195` | 删除 `fieldNodeStoreBuilder` + `freeze()` 的「每类型一个批量 store」两阶段流程。字段类型树改走 `InternedNodeReferenceCache.shared.reference(interning:in:)`,直接汇入镜像 store。顺带拿到一项旧形态给不了的收益:跨类型的结构去重——每类型各一个 store 时,两个类型共用的子树只能各存一份。 | +| `Sources/MachO/MachOSymbols/SymbolIndexStore.swift:256–275` | 删除 `lateDemangledNode(forName:)` 的「每个名字铸一个 builder」形态。`Storage` 自持一个 late-names 专用的 `SharedNodeStore`,demangle 改为 `lateStore.demangle(name)`。名字 → 裁决字典**保留**——拒绝名的 `nil` 裁决和成功结果的 memo 都还需要,`SharedNodeStore` 不按名字缓存拒绝。insert-if-absent 的写入流程保留,但竞态的后果从「有害」变「良性」:两个线程同时 miss 时,双方各自 demangle、各自 intern 进同一个 store,结构去重保证它们拿到同一个引用,于是原来处理「输家丢弃自己那个 store」的一整段代码直接删除。 | ## 明确不动的部分 diff --git a/Documentations/Internal/StaticFieldOffsetComputation.md b/Documentations/Internal/StaticFieldOffsetComputation.md index 2bea8fea9..a460b490a 100644 --- a/Documentations/Internal/StaticFieldOffsetComputation.md +++ b/Documentations/Internal/StaticFieldOffsetComputation.md @@ -40,13 +40,13 @@ ### 静态分流信号:`MetadataInitialization` kind -不需要重做编译器判定——类型描述符里有现成的静态信号。`TypeContextDescriptorFlags`(`Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorFlags.swift`,2 位宽字段)区分: +不需要重做编译器判定——类型描述符里有现成的静态信号。`TypeContextDescriptorFlags`(`Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorFlags.swift`,2 位宽字段)区分: - `none` → metadata 完整、编译期静态化 → **vector 是真值,直接读**; - `singleton` → 需运行时 `swift_initStructMetadata` / `initClassFieldOffsetVector` 完成 → **vector 是占位,要算**; - `foreign` → C/ObjC 互操作,另算。 -本项目已暴露 `SingletonMetadataInitialization` / `ForeignMetadataInitialization` 模型(`Sources/MachOSwiftSection/Models/Metadata/MetadataInitialization/`)及 `Struct.singletonMetadataInitialization` / `.foreignMetadataInitialization`。 +本项目已暴露 `SingletonMetadataInitialization` / `ForeignMetadataInitialization` 模型(`Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataInitialization/`)及 `Struct.singletonMetadataInitialization` / `.foreignMetadataInitialization`。 > **第 0 步必须实测验证**:`MetadataInitialization == none` 的 fixed 类型,在 MachOFile(非 InProcess)上下文下读出来的 vector 是否 == 运行期值。两份子调研在此有分歧(一份认为 fixed struct vector 编译期写死、可静态读;另一份认为静态镜像里是 0 或 relocation)。本项目 `StructMetadata.fieldOffsets(for:in:)` 已有 MachOFile overload,用现有 fixture 二进制 + `otool` 即可确认。**这条结论是整个方案 (A) 类捷径的地基。** @@ -83,11 +83,11 @@ stride = max(1, roundUpToAlignMask(size, alignMask)) // 尾部 padding 只进 s 离线要把「mangled name → (size, alignment, stride, extraInhabitants)」做成递归求解器,数据源分层: 1. **硬编码固定布局表(主力)**:`Int/UInt/Int64/Double/裸指针/任意 class 引用 = 8B@8`;`Int32/Float = 4B`;`Bool/Int8 = 1B`;`Int128 = 16B`;`String = 16B`。这些 ABI 永久冻结,照抄 runtime 的 known-layout 表。 -2. **`__swift5_builtin` 的 `BuiltinTypeDescriptor`**:已确认静态内嵌 `size` / `alignmentAndFlags` / `stride` / `numExtraInhabitants`(`Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift:6-12`,`alignment = alignmentAndFlags & 0xFFFF`,`isBitwiseTakable = (alignmentAndFlags >> 16) & 0x1`)。仅覆盖编译器实际发射的 builtin 原语,不能当唯一来源。 +2. **`__swift5_builtin` 的 `BuiltinTypeDescriptor`**:已确认静态内嵌 `size` / `alignmentAndFlags` / `stride` / `numExtraInhabitants`(`Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift:6-12`,`alignment = alignmentAndFlags & 0xFFFF`,`isBitwiseTakable = (alignmentAndFlags >> 16) & 0x1`)。仅覆盖编译器实际发射的 builtin 原语,不能当唯一来源。 3. **嵌套 struct / enum** → 递归到目标 descriptor 重新跑 §2 算法。enum 复用 `EnumLayoutCalculator`,但要把它的 payload-size / XI 输入从「InProcess VWT」改接到本求解器。 4. **resilient / 跨模块字段** → 见 §4(遍历依赖闭包递归到定义镜像)。 -> 现有唯一的「mangled name → 具体类型 size」路径是 `RuntimeFunctions.getTypeByMangledNameInContext`(`Sources/MachOSwiftSection/Runtime/RuntimeFunctions.swift`),是 **InProcess-only** runtime 函数。`PrimitiveTypeMapping` 只给类型名映射、**不给数值**。所以静态侧的数值化求解器是从零新建。 +> 现有唯一的「mangled name → 具体类型 size」路径是 `RuntimeFunctions.getTypeByMangledNameInContext`(`Sources/ABI/MachOSwiftSection/Runtime/RuntimeFunctions.swift`),是 **InProcess-only** runtime 函数。`PrimitiveTypeMapping` 只给类型名映射、**不给数值**。所以静态侧的数值化求解器是从零新建。 --- @@ -104,7 +104,7 @@ resilient 的本质是「编译当前二进制时不知道字段布局,但运 ### 已有基础设施 - **按依赖名解析镜像**:上游包 `MachOKitExtensions` 的 `DyldCache+.swift` 的 `machOFile(by mode:)` —— 按 install name / image name 从 dyld shared cache 捞 `MachOFile`。系统 Swift 库、Foundation、SwiftUI 等都在 cache 里,这条路已通。 -- **符号索引**:`Sources/MachOSymbols/SymbolIndexStore.swift` —— 按 name/offset 建索引。 +- **符号索引**:`Sources/MachO/MachOSymbols/SymbolIndexStore.swift` —— 按 name/offset 建索引。 - **ReadingContext 抽象**:`MachOContext` 已把「从哪个镜像读」参数化,扩展成多镜像顺理成章。 ### 需新建三块 @@ -138,8 +138,8 @@ resilient 的本质是「编译当前二进制时不知道字段布局,但运 **可直接复用:** - 字段记录读取:`FieldDescriptor` / `FieldRecord`(三 overload 全静态可读,给字段类型名 + 顺序 + flags)。 -- 数据模型:`ValueWitnessTable` / `TypeLayout` / `ValueWitnessFlags`(`Sources/MachOSwiftSection/Models/ValueWitnessTable/`)、`BuiltinTypeDescriptor`(带数值)。 -- enum 算法骨架:`EnumLayoutCalculator` + `BitMask` + `SpareBitAnalyzer`(`Sources/SwiftInspection/`)。 +- 数据模型:`ValueWitnessTable` / `TypeLayout` / `ValueWitnessFlags`(`Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/`)、`BuiltinTypeDescriptor`(带数值)。 +- enum 算法骨架:`EnumLayoutCalculator` + `BitMask` + `SpareBitAnalyzer`(`Sources/Analysis/SwiftInspection/`)。 - 名字解析:`MetadataReader` + `ReadingContext` 抽象(静态/运行期通吃)。 - 静态分流信号:`MetadataInitialization` kind、`singleton/foreignMetadataInitialization` 模型。 - 现成 vector 读取:`StructMetadata.fieldOffsets(...)` / `FinalClassMetadata.fieldOffsets(...)`(含 MachOFile overload)。 @@ -231,14 +231,14 @@ fixed-layout 非泛型(单镜像) 直接读 vector,几乎零成本 | 主题 | 位置 | |---|---| -| 字段记录静态读取 | `Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift`、`Models/FieldRecord/FieldRecord.swift` | +| 字段记录静态读取 | `Sources/ABI/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift`、`Models/FieldRecord/FieldRecord.swift` | | field-offset vector 读取(含 MachOFile overload) | `Models/Type/Struct/StructMetadataProtocol.swift:16-29`、`Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift` | | value witness / type layout 模型 | `Models/ValueWitnessTable/{ValueWitnessTable,TypeLayout,ValueWitnessFlags}.swift` | | builtin 静态数值 | `Models/BuiltinType/BuiltinTypeDescriptor.swift:6-12` | | MetadataInitialization 分流信号 | `Models/Type/TypeContextDescriptorFlags.swift`、`Models/Metadata/MetadataInitialization/` | -| enum 静态布局算法 | `Sources/SwiftInspection/EnumLayoutCalculator.swift`、`SpareBitAnalyzer.swift`、`BitMask.swift` | -| 现有 field rendering(runtime 依赖点) | `Sources/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/MachOSymbols/SymbolIndexStore.swift` | -| InProcess-only runtime 桥 | `Sources/MachOSwiftSection/Runtime/RuntimeFunctions.swift` | -| 泛型 specialization(runtime 编排,可作 ground truth/fallback) | `Sources/SwiftSpecialization/GenericSpecializer.swift`、`ConformanceProvider.swift`(已静态、可复用) | -| ObjC ivar / class_ro_t | MachOObjCSection `ObjCIvarListProtocol`、`ClassROData`;本项目用例 `Sources/SwiftInspection/ClassHierarchyDumper.swift`、`Sources/TypeIndexing/ObjCInterfaceIndexer.swift` | +| 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` | +| 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` | diff --git a/Documentations/Internal/StaticLayoutDependencyClosure.md b/Documentations/Internal/StaticLayoutDependencyClosure.md index 3471c5be1..b370544c2 100644 --- a/Documentations/Internal/StaticLayoutDependencyClosure.md +++ b/Documentations/Internal/StaticLayoutDependencyClosure.md @@ -50,7 +50,7 @@ `ImageReference` / `ImageUniverse` 是单态的:所有镜像须同一具体 `MachO` 类型(`ImageReference.swift:12`)。直觉上闭包要混 `MachOFile`(磁盘依赖)与 dyld cache 镜像(不同具体类型),似乎要类型擦除。 **结论:不需要类型擦除——按 root 类型保持同构即可。** -- `MachOFile` root → 依赖也解析为 `MachOFile`:`FullDyldCache.host?.machOFile(by:)` 返回 `MachOFile`(`DyldCache+.swift:19`),磁盘依赖经 `File.loadFromFile`。 +- `MachOFile` root → 依赖也解析为 `MachOFile`:`FullDyldCache.cachedHost?.machOFile(by:)` 返回 `MachOFile`(`DyldCache+.swift:19`),磁盘依赖经 `File.loadFromFile`。 - `MachOImage`(在进程)root → 依赖经 `MachOImage(name:)` 返回 `MachOImage`。 两条路各自同构,`ImageReference` / `ImageUniverse` 泛型签名不变。这复用了 `SwiftInterfaceBuilderDependencies`(`SwiftInterfaceBuilderDependencies.swift:19/60` 两条平行路径)的现成模式。 @@ -67,7 +67,7 @@ extension ImageUniverse { ``` 加两个**便利工厂**承担实际定位(解析策略与索引构建解耦): -- `MachOFile` 版:`dependencyClosure(root: MachOFile, searchPaths: [DependencyPath])` —— 复用 `FullDyldCache.host` + 显式路径(`DependencyPath` 枚举,`DependencyPath.swift`),递归遍历 `machO.dependencies.map(\.dylib.name)`。 +- `MachOFile` 版:`dependencyClosure(root: MachOFile, searchPaths: [DependencyPath])` —— 复用 `FullDyldCache.cachedHost`(进程内只打开一次)+ 显式路径(`DependencyPath` 枚举,`DependencyPath.swift`),递归遍历 `machO.dependencies.map(\.dylib.name)`。 - `MachOImage` 版:`dependencyClosure(root: MachOImage)` —— 经 `MachOImage(name:)` 用活动 dyld 解析(系统框架天然走 dyld cache)。 ### 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.host` + 显式路径。 +4. **`MachOFile` 便利工厂**:`dependencyClosure(root: MachOFile, searchPaths:)` 经 `FullDyldCache.cachedHost` + 显式路径。2026-10-08 起,从 dyld cache 里读出来的 root 先在自己所在的 cache 里找依赖,再查这些路径([Modules/MachODependencies.md](Modules/MachODependencies.md) §3)。 5. **resilient 验证扩展**(见下)。 6. **文档**:更新 `StaticLayoutEngine.md`(移除阶段 3 残留项)、本文「实测」回填、`Documentations/README.md`。 @@ -128,9 +128,9 @@ ObjC 祖先(`ObjCMembersTest` / `ObjCBridge`):接 MachOObjCSection 读 `cl ## 关键文件 -- 复用:`Sources/SwiftInterface/SwiftInterfaceBuilderDependencies.swift`(依赖解析两条路径)、`Sources/SwiftInterface/DependencyPath.swift` +- 复用:`Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift`(依赖解析两条路径)、`Sources/Output/SwiftInterface/DependencyPath.swift` - 复用:上游包 `MachOKitExtensions` 的 `DyldCache+.swift`(`machOFile(by:)`、bare-name 匹配)、`MachORepresentableWithCache.swift`(`imagePath` / `cache`) -- 改动:`Sources/SwiftLayout/ImageUniverse.swift`、`Sources/SwiftLayout/ImageReference.swift`(**仅这两个** + 新增便利工厂文件) +- 改动:`Sources/Analysis/SwiftLayout/ImageUniverse.swift`、`Sources/Analysis/SwiftLayout/ImageReference.swift`(**仅这两个** + 新增便利工厂文件) - 不动:`StaticTypeLayoutResolver.swift`、`BasicLayout.swift`、`ExistentialLayoutBridge.swift`、`EnumLayoutBridge.swift` - runtime 参照:`/Volumes/SwiftProjects/swift-project/swift/stdlib/public/runtime/Metadata.cpp:3767-3830`(class 字段布局 + Swift/ObjC 父类分派) diff --git a/Documentations/Internal/StaticLayoutEngine.md b/Documentations/Internal/StaticLayoutEngine.md index 34c0d4315..e20b75e24 100644 --- a/Documentations/Internal/StaticLayoutEngine.md +++ b/Documentations/Internal/StaticLayoutEngine.md @@ -21,7 +21,7 @@ ## 模块结构 ``` -Sources/SwiftLayout/ +Sources/Analysis/SwiftLayout/ ├── StaticTypeLayout.swift # 输出值类型 (size/stride/alignmentMask/XI/isBitwiseTakable) ├── BasicLayout.swift # runBasicLayout 内核(performBasicLayout 离线移植) ├── KnownLayoutTable.swift # 硬编码 stdlib 固定布局表 @@ -48,7 +48,7 @@ Tests/SwiftLayoutTests/ ├── ExistentialLayoutTests.swift # existential / actor 字面值锁定(精确 field-offset 向量) ├── DependencyClosureLayoutTests.swift # 跨依赖闭包:DistributedActorTest 对 runtime vector 自动校验 + resilient 字面值锁定 + 单镜像 partial 回归守卫 + MachOFile 离线路径 ├── ObjCAncestorLayoutTests.swift # 阶段 4:ObjCMembersTest/ObjCBridge 闭包重算对 runtime vector 自动校验(均 [8])+ 无字段 ObjCBridgeWithProto + 单镜像 partial 回归守卫 -├── BuiltinTypeLayoutTests.swift # builtin 整体布局回退:multi-payload enum + __C.Decimal 索引对 runtime VWT 自动对拍 + resolver 端到端 +├── BuiltinTypeLayoutTests.swift # builtin 整体布局回退:multi-payload enum + __C.NSDecimal 索引对 runtime VWT 自动对拍 + resolver 端到端 ├── EdgeTypeKindLayoutTests.swift # 边角函数 kind:cFunctionPointer / objCBlock / escapingObjCBlock = 单指针,对比 thick functionType ├── ObjCProtocolExistentialTests.swift # ObjC 协议 existential:objCProtocolBareName 单元 + 纯/多/混合(any NSCopying[& Swift]) class-bound 布局 ├── MultiPayloadEnumStructuralTests.swift # multi-payload enum 结构化兜底:multiPayloadEnumLayout 直接算对 runtime VWT(spare-bits + indirect)+ XI 逐枚举相等 + `Optional` 包装 size/stride 对 runtime `MemoryLayout` 端到端相等(XI 错则多/少 1 个 tag 字节,必被抓住);泛型描述符跳过(无参 accessor 调不得——真值经非泛型 holder 走 GenericSpareBitsEnumLayoutTests) @@ -60,7 +60,7 @@ Tests/SwiftLayoutTests/ ├── ClassBoundParameterLayoutTests.swift # 阶段 9:class-bound 泛型参数**不特化**即对具体类实例化 runtime offset 逐字段相等(AnyObject/ObjC 协议/superclass 约束经 accessor 传 metatype 取真值,Swift class-bound 协议靠同字段形状传递性锁定;双 reader)+ 双层嵌套双深度绑定 + ObjC 祖先泛型子类 + 非 class-bound 参数仍降级守卫 + placeholder 替换单测 ├── MetatypeAndGenericEnumProjectionLayoutTests.swift # metatype 字段 thin/thick 两种 lowering 世界对 runtime 逐字段相等(非泛型具体 metatype thin、class thick、`Int64.Type?` 1 字节;泛型 `Element.Type` thick 且不特化即算、`Int64.Type` 仍 thin、参数 metatype 与实参无关)+ class-bound 泛型 enum 经 `enumCaseLayoutResult` 不特化投影(双 reader) ├── SameTypePinnedParameterLayoutTests.swift # 具体 sameType 钉住:约束扩展里嵌套类型的参数 `Value == Int64`(单镜像)/ `== Range`(依赖闭包)不特化即对 runtime offset 逐字段相等(钉住参数被丢出 accessor key 实参,无参 runtime 向量即真值)+ **value 参数同值钉住** `count == 5`(`InlineArray` 字段 10 字节不特化解析,双 reader)+ 无 sameType 的自由参数仍降级守卫 -├── ForeignStructTopLevelLayoutTests.swift # foreign(C-imported)struct 的**顶层** fieldLayout:`__C.Decimal` 整型取 builtin(20/20/4)、逐字段降级(bitfield 不可见,`_mantissa@0` 是错值)——守顶层入口的 builtin 交叉校验 +├── ForeignStructTopLevelLayoutTests.swift # foreign(C-imported)struct 的**顶层** fieldLayout:`__C.NSDecimal` 整型取 builtin(20/20/4)、逐字段降级(bitfield 不可见,`_mantissa@0` 是错值)——守顶层入口的 builtin 交叉校验 ├── ObjCAncestorSlideLayoutTests.swift # ObjC ivar 滑动:fixture 自身 instanceStart 索引(ObjCMembersTest = 8,无漂移零滑动)+ 真实漂移端到端(dyld cache SwiftUI 的 AppKitTableHeaderCell / SplitViewChildController 离线计算 == realize 后 ivar_getOffset) ├── Support/StaticLayoutTestSupport.swift # 闭包/ObjC/builtin 套件共用的 helper(fieldLayout / runtimeFieldOffsets / runtimeValueWitnessLayout / assertFullyComputed,单一真源) ├── StaticLayoutVsRuntimeTests.swift# 核心:遍历 fixture 真实类型 static == runtime 逐字段(单镜像,**仅 struct/class**,枚举无字段偏移向量故跳过) @@ -72,7 +72,7 @@ Tests/SwiftLayoutTests/ - **`BasicLayout.compute`**:照搬 `Metadata.cpp:2321-2360`。逐字段 `offset = roundUpToAlignMask(accumulator, fieldAlignMask)`,累加用 **size 不是 stride**,尾部 padding 只进 stride。struct 起点 0;class 起点 = 父类 instance size(= 父类 `size`,根类 16 = `HeapObject`),递归父类;tuple 起点 0。**同时求整体 XI = 字段中最大者**(`swift_initStructMetadata`:“use the field with the most”,与 tuple 同规则),随 `AggregateLayout` 带出;`asStaticTypeLayout()` 直接采用。**曾漏此步致 struct XI 恒 0**:`asStaticTypeLayout(extraInhabitantCount:)` 默认 0、`computeStructLayout` 从不传播,于是**任何 struct 的整体 XI 都记成 0**。后果是「payload 为带 XI 的 struct(如包类引用的 `SwiftUI.Font`)」的**单 payload 枚举**误加一个 tag 字节(`Text.Style.TextStyleFont` 本应 8 字节算成 9/stride 16),并把外层聚合的后续字段偏移整体推移。修复即把 tuple 早已做对的 max-over-fields 下放进 `compute`,struct/tuple/class 共用(class 聚合的该值不作为 class *值* 的 XI,无人读取,无害)。class 值作字段时仍取 `.pointerSized`(引用 XI),不受影响。 - **`StaticTypeLayoutResolver`**:按 `Node.Kind` 分派。`builtinTypeName` → KnownLayoutTable / `builtinPrimitiveLayout`(含 `Builtin.DefaultActorStorage` 特判,见下);`class`/`boundGenericClass` → 一个指针(**不递归字段,天然破环**);`structure` → **BuiltinTypeLayoutIndex 回退**(C-imported 值类型,见下)或 known 表 / 递归 descriptor;`enum` → EnumLayoutBridge;`protocolList`·`protocolListWithAnyObject`·`protocolListWithClass`·`existentialMetatype`·`symbolicExtendedExistentialType`(受约束 existential) → ExistentialLayoutBridge;`dependentMemberType`(关联类型) → DependentMemberTypeBridge;`builtinFixedArray`(含 `InlineArray` 特判) → fixed-array 公式;`tuple`/`functionType`(thick=2 words)/`cFunctionPointer`·`objCBlock`·`escapingObjCBlock`(单指针=1 word)/`weak`·`unowned`·`unmanaged`(**引用存储:宽度由 referent 决定**,普通类引用 1 word,class-bound existential 则保留见证表字,见「引用存储不坍缩 existential」)/`metatype`(thin=0/thick=8) 各自处理;其余抛 `unknown` 降级。memoize 按限定名,`inProgressKeys` 防环兜底。 - **`EnumLayoutBridge`**:no-payload(最小 tag 字节)+ single-payload(含 `Optional`,用 payload 的 extra inhabitants 编码空 case,溢出才加 tag 字节)。`getEnumTagCounts` 公式从 runtime `EnumImpl` 移植。**multi-payload enum** 两条路解析:①首选 `BuiltinTypeLayoutIndex` 整体布局(编译器 emit 的精确值,见下);②无 builtin descriptor 时**结构化兜底**——`multiPayloadEnumLayout` 复用 `SwiftInspection.EnumLayoutCalculator`(`GenEnum.cpp`/`TypeLowering.cpp` 的离线移植):payload 区 = 最大 payload case 的尺寸,tag 编码在公共 spare bits(取自该 enum 的 `MultiPayloadEnumDescriptor`,`__swift5_mpenum` 段)或退而附加 extra tag bytes(`calculateTaggedMultiPayload`)。indirect case 的 payload 按单指针计。**泛型 MPE 按「记录存在性」分流(2026-08-05 修正,此前模型错误)**:编译器只为**静态 fixed**(布局与实参无关)的 MPE 发射 builtin + mpenum 记录(`GenReflection.cpp` `emitFieldDescriptor` 的门槛 `payload>1 && !needsPayloadSizeInMetadata()`),这类泛型 enum 的完整 VWT 烘焙在 metadata pattern 里、运行时从不重算(`Swift.Dictionary.Iterator._Variant` 40/40/XI 126 即典型,未绑定形态与所有实例化共享同一布局),故 builtin/spare-bits 两条路对泛型节点(实例化或未特化)照常放行——记录命中即编译器原话;而**依赖实参**的泛型 MPE(某 payload 布局需要实参,如 `Environment.Content` 的裸 `Value`)一条记录都没有,走 runtime `swift_initEnumMetadataMultiPayload` 的 tagged 公式:附加 tag 字节,**未用 tag 值即 extra inhabitants**(`(1 << (numTagBytes×8)) − numTags`,4 字节 tag 饱和,capped `MaxNumExtraInhabitants`)——`Optional.Content>` 形态因此精确(阶段 8)。`!AllowFixedLayoutOptimizations` 时(GenEnum.cpp:7192)编译器自己也清空 spare bits 退回与 runtime 一致的 tagged 布局且不发记录,故「记录存在 ⇔ spare-bits/fixed」在构造上精确、零启发式。跨镜像场景在 `compute()` 里补查**定义镜像**的 builtin 索引(enum 记录由声明模块发射,与 imported C 的逐引用方发射不同),顺带闭合 mask>16k 不发 mpenum 记录的边角。 -- **`BuiltinTypeLayoutIndex`(整体布局回退)**:`__swift5_builtin` 段的 `BuiltinTypeDescriptor` 记录了「reflection 无法结构化推导布局」类型的**整体布局**(size/stride/align/XI/bitwiseTakable)——即**imported C 值类型**(`__C.CGRect`/`__C.Decimal`/…)与 **multi-payload enum**。编译器在**每个反射性引用该类型的镜像**(如把它当存储字段的类型所在镜像)里都 emit 一份,故「使用方镜像」必带。求解器在 `structureLayout`/`enumLayout` 里对 `structure`/`enum` 节点(enum 侧含泛型实例化与未特化泛型——见上条「记录存在性」分流)先查 `originImage.builtinLayoutIndex`:命中(C 类型、multi-payload enum)即返回该整体布局;未命中(普通 struct/enum 不 emit builtin descriptor)落回结构化路径。enum 记录由**声明模块**发射(imported C 记录才是逐引用方发射),跨镜像 enum 在 `compute()` 里补查定义镜像的索引。索引侧跳过 typeref 为**具体 bound-generic 实例化**(`Foo`)的记录——按剥参数 key 收录会误配到其它实例化(5 个 OS 镜像实测为零例,纯防御);泛型声明记录 demangle 出来就是无参数的普通 nominal 引用,key 天然与查找侧一致。对「作为字段」的场景只需整体 size/align/stride,故无需 C struct 内部偏移、也无需 multi-payload 的 spare-bit 分析。descriptor 的 `typeName` 是**符号引用**(裸串为空),故按 demangle 还原的限定名建 key(与求解器查找侧同一格式)。语义同 resilient:「针对这组具体二进制」。 +- **`BuiltinTypeLayoutIndex`(整体布局回退)**:`__swift5_builtin` 段的 `BuiltinTypeDescriptor` 记录了「reflection 无法结构化推导布局」类型的**整体布局**(size/stride/align/XI/bitwiseTakable)——即**imported C 值类型**(`__C.CGRect`/`__C.NSDecimal`/…)与 **multi-payload enum**。编译器在**每个反射性引用该类型的镜像**(如把它当存储字段的类型所在镜像)里都 emit 一份,故「使用方镜像」必带。求解器在 `structureLayout`/`enumLayout` 里对 `structure`/`enum` 节点(enum 侧含泛型实例化与未特化泛型——见上条「记录存在性」分流)先查 `originImage.builtinLayoutIndex`:命中(C 类型、multi-payload enum)即返回该整体布局;未命中(普通 struct/enum 不 emit builtin descriptor)落回结构化路径。enum 记录由**声明模块**发射(imported C 记录才是逐引用方发射),跨镜像 enum 在 `compute()` 里补查定义镜像的索引。索引侧跳过 typeref 为**具体 bound-generic 实例化**(`Foo`)的记录——按剥参数 key 收录会误配到其它实例化(5 个 OS 镜像实测为零例,纯防御);泛型声明记录 demangle 出来就是无参数的普通 nominal 引用,key 天然与查找侧一致。对「作为字段」的场景只需整体 size/align/stride,故无需 C struct 内部偏移、也无需 multi-payload 的 spare-bit 分析。descriptor 的 `typeName` 是**符号引用**(裸串为空),故按 demangle 还原的限定名建 key(与求解器查找侧同一格式)。语义同 resilient:「针对这组具体二进制」。 - **`GenericArgumentEnvironment`(具体 bound-generic 实例化作字段,阶段 5)**:`MyBox` 作字段时,基础 generic descriptor 的字段记录存的是依赖参数(`A` = `dependentGenericParamType(depth,index)`)。做**纯语法 Node 替换**、不调任何 metadata accessor / PWT:从 `boundGeneric*` 节点自带的 `typeList` 按**位置**取具体实参(depth-0 下 index i ↔ typeList[i]),建 `(depth,index)→Node` 映射;解析字段/payload/超类类型前,先 demangle 再用一个 `Node.Rewriter`(Demangling)把节点里的 `dependentGenericParamType` 深度替换为具体实参节点,然后照常 `layout(forTypeNode:)`。深度替换意味着 `(A,B)`、`Pair` 等也一并替换,递归再自然重建子环境;`structureLayout`/`enumLayout` 命中 `boundGeneric*` 时按节点建环境、并以**实例化 key**(remangle)memoize,使 `Foo`/`Foo` 区分缓存与防环(`memoizedInstantiationLayout` 跳过 KnownLayoutTable 探测)。**仅限 depth-0 参数**;实参可为纯类型、**value(`.integer`/`.negativeInteger`,SE-0452)**或**扁平 pack(SE-0393)**——仅当 pack 实参自身仍含未展开 expansion(未解析的转发形态)时环境才整体降级为空(避免位置错配),depth>0 的参数保持降级。`class Sub: Base` 经 `superclassStartLayout` 先把超类节点按子类环境替换、再据替换后的 `Base` 建超类环境递归。**纯语法的副带修复**:单 payload 泛型枚举 `enum E{case a(Second)}` 现按 payload 字段记录 + 环境替换取**正确参数**(旧逻辑无条件取 `typeList.first` 会取错第 0 个实参)。 - **Pack expansion 展开(阶段 6)**:替换递归改为**自定义 top-down**(弃用 bottom-up 的 `Node.Rewriter`)——展开是**上下文相关**的:expansion 实例 i 里的 pack 参数引用要解析成 pack 的第 i 个元素而非整包;bottom-up 会先把 pattern 里的引用替换成整个 `.pack` 节点,与 `(repeat Pair)` 这类 pattern 中的**字面 pack** 无法区分。`.tuple` 节点:packExpansion 元素按 count(替换后须为具体 `.pack`)逐元素实例化 pattern(经 `packElementEnvironment(atIndex:)` 把 pack 绑定缩窄为第 i 元素)后拼接;空 pack → 空 tuple;展开后**恰好 1 个无标签元素 → 坍缩为该元素本身**(一元素无标签 tuple 不存在,runtime 对其直接返回元素 metadata)。`.pack` 字面量:含 expansion 的子节点(`Foo` 转发形态的 `Pack{PackExpansion(…)}`)展开拼接成扁平 pack。count 未具体绑定的 expansion 原样保留,交给求解器按 `genericParameterUnsubstituted` 降级。类型侧的简化前提(编译器强制):**一个泛型类型最多声明一个 type pack、enum 不能声明 type pack**。 - **Fixed array / value generics(阶段 6)**:求解器新增 `builtinFixedArray` 分派(`Builtin.FixedArray`):`count ≤ 0` → empty;否则 **size = stride = element.stride × count**(count = 1 也不回收尾部 padding)、align/bitwiseTakable 随元素、**XI 取首元素**——从 runtime `swift_getFixedArrayTypeMetadata`/`FixedArrayCacheEntry::tryInitialize` 移植,与 IRGen `convertBuiltinFixedArrayType`、RemoteInspection `ArrayTypeInfo` 三方一致。`Swift.InlineArray` 与其唯一 stored field `Builtin.FixedArray` 布局恒等,在 `structureLayout` 里特判直接走同一公式(descriptor 在 stdlib,与 `Optional` 特判同理,单镜像可算;依赖闭包可达 stdlib 时结构化路径 + 环境替换算得同一结果)。tuple 的 XI 同步修正为**取元素中最多者**(runtime `swift_getTupleTypeMetadata` 语义,旧实现恒 0)——`Optional<(Int16, Bool)>` 不再多算 1 个 tag 字节。 @@ -105,7 +105,7 @@ Tests/SwiftLayoutTests/ `BuiltinTypeLayoutTests` 验证 builtin 整体布局回退(multi-payload enum + imported C 值类型): - **multi-payload enum**(`MultiPayloadEnumTests`/`MultiPayloadEnumTests2`/`FunctionReferenceCaseTest`/`AssociatedValueErrorTest`/`CodableEnumTest`):`BuiltinTypeLayoutIndex` 按限定名解析出的 size/stride 与 **runtime value-witness table 自动相等**。 -- **`__C.Decimal`**(imported C 值类型,无 Swift descriptor):经 builtin 索引解析出 `size/stride=20、align=4`。 +- **`__C.NSDecimal`**(imported C 值类型,无 Swift descriptor):经 builtin 索引解析出 `size/stride=20、align=4`。 - **resolver 端到端**:之前降级为 unknown 的 `MultiPayloadEnumTests`,现经 resolver 走 builtin 回退算出整体布局,与 runtime VWT 一致。 > 单镜像 `StaticLayoutVsRuntimeTests` 基线仍只遍历 `SymbolTests*` 模块自己定义的**非泛型 struct/class**(且只比对有 field-offset vector 的类型);C-imported 值类型与 multi-payload enum 作为**字段**时已能解析(见 `BuiltinTypeLayoutTests`)。foreign struct 被**顶层**枚举(`fieldLayout(of:)` 直接喂 `__C` 描述符)的路径由 `ForeignStructTopLevelLayoutTests` 单独覆盖——整型取 builtin、逐字段诚实降级。 @@ -131,11 +131,11 @@ Value-generic / pack(阶段 6)由 `ValueGenericAndPackLayoutTests` 验证: - **ObjC 起点取 `instanceSize` 而非 `instanceStart`,且 realized 类不可读 `classROData`(阶段 4 的关键坑)**:调研单点 finding 主推「读 `class_ro_t.instanceStart`」,实测**否决**——(1) `instanceStart` 是 ObjC 类自身首 ivar 起点(= 其父类大小),dyld cache 上常写 0;Swift 子类字段起点应是父类 **`instanceSize`**(`NSObject` = 8)。(2) **in-process 的 `NSObject` 是 realized 类**,`classROData(in: MachOImage)` 返回 `nil`(`data` 指向 `class_rw_t`),须经 `classRWData → classROData`(或 `ext.classROData`)回退取 instance ro;offline 的 cache `MachOFile` 则 `classROData` 直接可读。唯一在 in-process 与 cache 两条 reader 上都正确且一致的值是 instance `class_ro_t.instanceSize`(= `ObjCClass.info(in:).instanceSize`,但 `ObjCClassIndex` 直接读 ro、不解析 methods/ivars/metaclass,故更轻)。 - **ObjC 索引随 Swift 索引同步惰性折入,无额外扫描**:`resolveObjCClassInstanceSize` 复用 `resolveType` 的 `indexNextDependency` 折入机制(ObjC 索引在 `ImageReference.init` 里一并构建、`mergeIndexes` 一并合并)。又因 ObjC 父类在 `superclassStartLayout` 里**先于** Swift `resolveType` 判断,ObjC 名不会触发「Swift 全 miss → 折满 551 镜像」;折到 libobjc 命中 `NSObject` 即停,比旧路径(ObjC 名走 `resolveType` 折满全闭包再抛错)更快。 - **`objc.classes64` / `info(in:)` 是 `MachOFile`/`MachOImage` 具体重载(非协议泛型)**:故 `ObjCClassIndex` 与 `ImageReference` 的 ObjC 索引构建须按 `as? MachOImage` / `as? MachOFile` 向下转型分派,复刻 `ImageUniverse+DependencyClosure` 的 `where MachO == …` 拆分写法。 -- **`BuiltinTypeDescriptor.typeName` 是符号引用,裸串为空——必须 demangle 才有 key**:`__swift5_builtin` 段实测**不含** `Builtin.*` 条目,全是 imported C 值类型(`__C.Decimal`/`__C.CGRect`/…)与 multi-payload enum;其 `typeName` 指向 context descriptor(相对指针),`typeString` 为空字符串。旧 `BuiltinTypeLayoutIndex` 按 `typeString` 建 key,把全部条目塞进 key `""`(互相覆盖)→ 索引等于失效、且只在 `builtinTypeName` 分支被查(而该段无 `Builtin.*`),实为死代码。修复:用 `MetadataReader.demangleType` 还原成限定名(`__C.Decimal` / `SymbolTestsCore.Enums.MultiPayloadEnumTests`)建 key。 -- **builtin descriptor 由「使用方」镜像 emit,故查 `originImage`**:编译器在每个**反射性引用**该类型的镜像里都 emit 一份 builtin descriptor(实测 fixture 自己就带 `__C.Decimal`、Foundation 也带一份)。所以解析某字段类型时查**字段所属镜像**(`originImage`,求解器已线程化)的 builtin 索引正中靶心,无需跨镜像合并。 +- **`BuiltinTypeDescriptor.typeName` 是符号引用,裸串为空——必须 demangle 才有 key**:`__swift5_builtin` 段实测**不含** `Builtin.*` 条目,全是 imported C 值类型(`__C.NSDecimal`/`__C.CGRect`/…)与 multi-payload enum;其 `typeName` 指向 context descriptor(相对指针),`typeString` 为空字符串。旧 `BuiltinTypeLayoutIndex` 按 `typeString` 建 key,把全部条目塞进 key `""`(互相覆盖)→ 索引等于失效、且只在 `builtinTypeName` 分支被查(而该段无 `Builtin.*`),实为死代码。修复:用 `MetadataReader.demangleType` 还原成限定名(`__C.NSDecimal` / `SymbolTestsCore.Enums.MultiPayloadEnumTests`)建 key。 +- **builtin descriptor 由「使用方」镜像 emit,故查 `originImage`**:编译器在每个**反射性引用**该类型的镜像里都 emit 一份 builtin descriptor(实测 fixture 自己就带 `__C.NSDecimal`、Foundation 也带一份)。所以解析某字段类型时查**字段所属镜像**(`originImage`,求解器已线程化)的 builtin 索引正中靶心,无需跨镜像合并。 - **builtin 回退限非实例化节点**:builtin key 是 generic-argument-free 的限定名(`nominalQualifiedName` 会剥泛型实参),查表前须确认节点未被实例化,避免 `Foo` 与 `Foo` 撞到同一 key;`Optional` 等泛型枚举继续走结构化/payload 路径。判据在阶段 8 从 `node.kind`(非 `boundGeneric*`)改为**环境为空**——`Enum(BoundGeneric…, Content)` 形态的 kind 是裸 `.enum`,但实参在父链上、层层可见于环境。 - **ObjC 祖先的类字段起点不是「祖先 instanceSize」,而是「本类 ro.instanceStart + moveIvars 滑动」**:静态发射的非泛型 Swift 类把 ivar 从**自己** `class_ro_t.instanceStart`(编译期对父类尺寸的假设;resilient ObjC 父类模式下仅为 base 8 一类的最小值)起排;realize 时若实际父类尺寸超过它,ObjC runtime(objc4 `moveIvars`)把全部 ivar **整体滑动**,滑动量按**本类 ivar 最大对齐**向上取整——所以字段块起点保持与编译期同余,而不是落在实际父类尺寸上(`NSTableHeaderCell` 实际 241,`AppKitTableHeaderCell` 的 Bool 字段在 248 不在 241)。dyld cache 镜像更进一步:cache builder 已预 realize,盘上 `instanceStart` 就是滑动后的最终值(实测 248/120)。Swift runtime 侧(`Metadata.cpp` `initClassFieldOffsetVector:3778-3785`)对 ObjC 父类同样从 `rodata->InstanceStart` 起排再交给 ObjC 滑动;对 Swift 父类则取精确 `super->getInstanceSize()` 不取整——该路径只有泛型/singleton 初始化(resilient 父类)的类走,而这类类**不在** `__objc_classlist`。故引擎的判据即 classlist 成员资格:查到本类 `instanceStart` → `start = instanceStart + (superEnd > instanceStart ? roundUp(superEnd − instanceStart, maxOwnFieldAlign) : 0)`;查不到(泛型 / singleton)→ 维持原「实际父类尺寸起排」。源码改过运行时名的类(`@objc(Name)`,app 二进制里很常见)classlist 名不是 mangling、demangle 不出 key,以前也落进这一支;现在查不到时再按描述符向 `SwiftClassObjectIndex` 取它自己的 `instanceStart`(提案 `0052-objc-custom-class-name`,见 [CustomObjCClassNames.md](CustomObjCClassNames.md)),两种算法只在父类尺寸不是本类最宽字段对齐的整数倍时分叉。普查里 3 个类各错 4–8 字节(`AppKitTableHeaderCell` 一族、`SplitViewChildController`)由此清零。注意 classlist 名是 legacy `_TtC…` mangling,demangle 后取 `.class` 节点建 `nominalQualifiedName` key(`demangleAsNode` 外层是 `.global` 包裹,直接建名会全表落空)。见 `ObjCAncestorSlideLayoutTests`。 -- **顶层入口对 foreign(C-imported)struct 须用 builtin 记录交叉校验,不能裸信字段记录**:builtin 查表原本只在**字段类型解析路径**(`structureLayout(forNode:)`)上;顶层入口 `fieldLayout(of:)` / `typeLayout(ofStruct:)` 拿到描述符直接结构化累加。`__C` foreign 描述符出现在**每个引用它的镜像**的 `__swift5_types` 里,被顶层枚举(如全量 dump / 对拍普查)就会走进这条无防护路径:Swift 字段记录看不见 C bitfield 与 padding,`__C.Decimal` 的 `_mantissa` 被排到 0(真值 4)、整型 16/align 2(真值 20/align 4);无字段记录的 `__C.PathData`/`Size3D` 等直接算成 size 0。修复(SwiftUI/SwiftUICore/SwiftData 6246 类型对拍普查发现):顶层 struct 路径检测 `hasForeignMetadataInitialization`,有 builtin 记录时——结构化累加与 builtin 的 size/stride/align **一致**则保留逐字段结果(字段记录完整的 C struct,如 `__C.RBColor`,结构化累加本就正确;XI 仍取 builtin 权威值),**不一致**则逐字段降级为 `.unknown(.foreignTypeFieldOffsetsUnavailable)`、整型取 builtin;无 builtin 记录维持现状(无从校验)。见 `ForeignStructTopLevelLayoutTests`。 +- **顶层入口对 foreign(C-imported)struct 须用 builtin 记录交叉校验,不能裸信字段记录**:builtin 查表原本只在**字段类型解析路径**(`structureLayout(forNode:)`)上;顶层入口 `fieldLayout(of:)` / `typeLayout(ofStruct:)` 拿到描述符直接结构化累加。`__C` foreign 描述符出现在**每个引用它的镜像**的 `__swift5_types` 里,被顶层枚举(如全量 dump / 对拍普查)就会走进这条无防护路径:Swift 字段记录看不见 C bitfield 与 padding,`__C.NSDecimal` 的 `_mantissa` 被排到 0(真值 4)、整型 16/align 2(真值 20/align 4);无字段记录的 `__C.PathData`/`Size3D` 等直接算成 size 0。修复(SwiftUI/SwiftUICore/SwiftData 6246 类型对拍普查发现):顶层 struct 路径检测 `hasForeignMetadataInitialization`,有 builtin 记录时——结构化累加与 builtin 的 size/stride/align **一致**则保留逐字段结果(字段记录完整的 C struct,如 `__C.RBColor`,结构化累加本就正确;XI 仍取 builtin 权威值),**不一致**则逐字段降级为 `.unknown(.foreignTypeFieldOffsetsUnavailable)`、整型取 builtin;无 builtin 记录维持现状(无从校验)。见 `ForeignStructTopLevelLayoutTests`。 - **紧密排列可证明时不降级(issue #116 收窄)**:「任一不等即全降级」误伤了 `#pragma pack` 但字段本就自然对齐的 C struct——`__C.CMTime`(pack(4))的四个偏移 0/8/12/16 完全正确,只有聚合 alignment(4 vs 结构化自然值 8)不一致,0.16.0 却把全部字段降成 unknown。收窄条件(`fieldOffsetsProvenByTightPacking`):每个字段都成功解析、且偏移恰等于**前序字段 size 的累计和**(结构化累加零内部 padding)、且累计和恰等于 builtin 整型 size(C 侧也零 padding、零隐藏存储/bitfield)——两边都被迫是同一种紧密顺序排列(C 不重排字段),逐字段偏移不可能不同,故保留偏移、整型事实(size/stride/**alignment**/XI)仍取 builtin。注意这个证明**不依赖** size/stride 逐项相等——它同时覆盖「pack 后整型 size 因尾部 padding 缩小」的变体。`Decimal`(可见字段和 16 ≠ builtin 20)与无记录的 `PathData` 通不过证明,照旧降级。比 issue 里建议的「只差 alignment 就放行」更严:那个宽条件在 bitfield/隐藏字段与 pack 叠加的构造性极端情形下无法证明偏移正确。 - **泛型替换:`MetadataReader.demangleType` 返回的是 `.type`-包裹节点,但求解器分派会先解包**:求解器 `layout(forTypeNode:)` 先 `unwrappedType` 再分派,故 `structureLayout` 收到的是裸 `boundGenericStructure`;而 `superclassStartLayout` 拿到的超类节点是**刚 demangle 的 `.type`-包裹**节点。`GenericArgumentEnvironment.make` 若不容忍 `.type` 包裹,对超类节点会 `kind == .type` → 误判非泛型 → 返回空环境 → 超类字段 `A` 不替换而降级(具体泛型超类子类用例实测踩到)。修复:`make` 先解一层 `.type` 再判 `boundGeneric*`,使「已解包」与「刚 demangle」两侧建出同一环境。 - **泛型实例化的 memoize/防环 key 必须含实参,且要绕开冻结表**:原 `memoizedNominalLayout` 按裸限定名做 key 且首步查 `KnownLayoutTable`——对 `Foo`/`Foo` 会撞同 key(裸名相同)。故 `boundGeneric*` 改用 `memoizedInstantiationLayout`(key = remangle 后的实例化名,**跳过**冻结表探测)。同时 `structureLayout`/`enumLayout` 仍在建环境前**先按裸名查冻结表**:`Array`/`UnsafePointer` 等 stdlib 泛型布局与实参无关、靠裸名命中冻结表(指针大小);若直接走实例化 key 会漏表并尝试结构化展开 stdlib 内部存储而失败(单镜像下其 descriptor 也不可达)。`Range` 不在冻结表,单镜像下降级、依赖闭包下方可结构化解析。 diff --git a/Documentations/Internal/SwiftModularizationMigration.md b/Documentations/Internal/SwiftModularizationMigration.md index 0c3ecff9b..12cfe99fa 100644 --- a/Documentations/Internal/SwiftModularizationMigration.md +++ b/Documentations/Internal/SwiftModularizationMigration.md @@ -15,7 +15,7 @@ ## 1. SwiftInterface 单体 → 分层模块(`47b5961`) -重构前 `Sources/SwiftInterface/` 是一个大单体(模型 + 索引 + 打印 + 节点打印器 + 属性推断 + 泛型特化 + 编排)。拆成了 6 个分层模块,`SwiftInterface` 只留下薄薄的编排器。 +重构前 `Sources/Output/SwiftInterface/` 是一个大单体(模型 + 索引 + 打印 + 节点打印器 + 属性推断 + 泛型特化 + 编排)。拆成了 6 个分层模块,`SwiftInterface` 只留下薄薄的编排器。 ### 1.1 → `SwiftDeclaration`(共享声明模型) diff --git a/Documentations/Internal/SystemFrameworkRenderingVerification.md b/Documentations/Internal/SystemFrameworkRenderingVerification.md index bf8d24791..58e6b29c7 100644 --- a/Documentations/Internal/SystemFrameworkRenderingVerification.md +++ b/Documentations/Internal/SystemFrameworkRenderingVerification.md @@ -6,11 +6,12 @@ ```bash Scripts/run-rendering-ab-verification.py <基线检出> <重构检出> \ - [--output-root 目录] [--frameworks A,B,...] \ - [--baseline-scratch 目录] [--candidate-scratch 目录] [--skip-image-part] + [--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] ``` -脚本自动构建两侧 release CLI、跑完三部分、输出逐对 IDENTICAL/DIFFERS 表格;有任何差异以非零码退出。 +脚本默认自己构建两侧的 release CLI(带 `--skip-build` 时什么都不构建,只用预先构建好的产物,见「关键调用细节」),跑完三部分、输出逐对 IDENTICAL/DIFFERS 表格;有任何差异以非零码退出。 ## 框架清单 @@ -20,13 +21,13 @@ SwiftUI、SwiftUICore、SwiftData、Combine、ActivityKit、WidgetKit——**输 | 部分 | 首选输入 | 目标不存在时的回退 | | --- | --- | --- | -| **DyldCache**(cache 内 MachOFile) | 归档 cache:`/Volumes/DyldSharedCaches/macOS/26.6.2` 与 `15.5` 的 `dyld_shared_cache_arm64e` | **当前系统的 dyld shared cache**(`--uses-system-dyld-shared-cache -p <镜像路径>`,不传文件参数) | +| **DyldCache**(cache 内 MachOFile) | 归档 cache:`/Volumes/DyldSharedCaches/macOS/26.6.2`(没有就用 `26.6`)与 `15.5` 的 `dyld_shared_cache_arm64e` | **当前系统的 dyld shared cache**(`--uses-system-dyld-shared-cache -p <镜像路径>`,不传文件参数) | | **MachOFile**(磁盘上的普通 Mach-O) | iOS 15.5 / 18.5 / 26.5 模拟器 runtime 的框架二进制 | **当前环境已安装的全部 iOS 模拟器 runtime**(脚本自动发现 `/Library/Developer/CoreSimulator/Profiles/Runtimes` 与 `/Library/Developer/CoreSimulator/Volumes/*/…/Runtimes` 下的 `*.simruntime`) | | **MachOImage**(进程内) | 当前系统(dlopen + `MachOImage(name:)`),经 `RenderingVerificationTests` harness | 无回退(永远是当前系统) | ## 关键调用细节(踩过的坑) -- **跑之前先确认归档目录真的存在**:`ARCHIVED_CACHE_DIRECTORIES` 是写死的两条路径,对不上时脚本**不报错**,只打印一行 `No archived cache found - falling back to the current system's dyld shared cache.` 就降级成只跑当前系统 cache——跨版本语料整段消失,而最终报告照样是「全部一致」。2026-09-17 撞上一次:归档卷把带 build 号的 `26.5.2_25F84` / `15.5_24F74` 改成了纯版本号,且 `26.5.2` 目录下已不再放 cache(换成 `26.6.2`)。常量随之改为 `26.6.2` 与 `15.5`。2026-09-18 再撞一次:`26.6.2` 目录已改名为 `26.6`(旁边新增 `27.0`),常量改为 `26.6`。2026-09-28 第三次:目录又改回 `26.6.2`(旁边有 `26.7`),常量随之改回 `26.6.2`。跑之前 `ls /Volumes/DyldSharedCaches/macOS/` 对一眼,比事后从报告里发现少了一条腿便宜。 +- **跑之前先确认归档目录真的存在**:`ARCHIVED_CACHE_DIRECTORY_CANDIDATES` 是写死的路径,每个槽位一组候选,取第一个有 `dyld_shared_cache_arm64e` 的;一组都没有时打印一行 `[skip] no archived cache in any of: …`,这条腿就不跑了,而最终报告照样是「全部一致」。所有槽位都落空时,还会再打印 `No archived cache found - falling back to the current system's dyld shared cache.`,降级成只跑当前系统 cache。2026-09-17 撞上一次:归档卷把带 build 号的 `26.5.2_25F84` / `15.5_24F74` 改成了纯版本号,且 `26.5.2` 目录下已不再放 cache(换成 `26.6.2`)。之后常量在 `26.6.2` 与 `26.6` 之间来回改了两次(2026-09-18 改成 `26.6`,09-28 改回 `26.6.2`),10-02 又撞上一次——原因是两台工作机的归档卷一台是 `26.6.2`、一台是 `26.6`,按一台改完,另一台就少一条腿。2026-10-02 起 26.x 槽位同时列出这两个目录,哪个有就用哪个,场景名随之是 `cache-26.6.2` 或 `cache-26.6`。跑之前 `ls /Volumes/DyldSharedCaches/macOS/` 对一眼,比事后从报告里发现少了一条腿便宜。 - **`--frameworks` 只认 `Versions/A` 的框架**:cache 腿按 `/System/Library/Frameworks/<名字>.framework/Versions/A/<名字>` 找镜像,AppKit、Foundation 在 `Versions/C` 下,传进去只会得到一行 `[skip] … not in cache`,这一对就不存在了(2026-09-28 撞上)。需要它们时用两侧构建好的 release CLI 手动渲染,`-p` 传 `Versions/C` 路径,输出按 `<场景>/<侧>/<框架>.<子命令>.txt` 放,照样能逐对比较。 - **cache 镜像用 `-p` 全路径而非 `-n` 名字**:SwiftUI / WidgetKit / ActivityKit 在 macOS cache 里有 `/System/iOSSupport/` 下的 Catalyst 副本,按名字查有歧义。 - **模拟器二进制要显式 `-a arm64`**:iOS 15.5 / 18.5 的模拟器框架是 fat(x86_64 + arm64),CLI 遇 fat 文件不指定架构会直接报错退出;26.5 起是 thin arm64,加该参数也无害,所以脚本一律加。 @@ -35,6 +36,11 @@ SwiftUI、SwiftUICore、SwiftData、Combine、ActivityKit、WidgetKit——**输 - **`RV_OPTS` 不含 `expandedFieldOffsets`**:harness 注释记录了它在 SwiftUI 级深嵌套泛型的 MachOImage 路径上会触发既有的栈溢出。 - **MachOImage 两侧必须在同一次开机会话内运行**:`memberAddress` 注释里的地址来自 dyld shared cache 的 per-boot slide,跨重启比对必然全线假差异。 - **两个检出绝不共用 SwiftPM scratch**(AGENTS.md 环境漂移检查的血泪教训:混入另一分支的陈旧目标文件会制造链接错误或假输出);agent 会话另按全局规约使用独立 scratch 路径。 +- **要让构建走机器的构建队列,就先预构建、再带 `--skip-build` 跑**(2026-10-01 起):脚本默认自己跑两侧的 `swift build -c release`(两侧并行),MachOImage 部分再跑 `swift test -c release`,都不经 `queued-build`。在限流的 10 核 Mac Studio(`JHs-Mac-Studio`)上,`queued-build` 会给构建加 `--jobs 8`,release build 里它传给 swiftc 变成 `-num-threads 8`;脚本自己的命令不带 `--jobs`,命令行对不上,已经编好的东西一样都复用不了。2026-09-30 就因此出现过两侧并行、绕过队列的两次全量 release build。带 `--skip-build` 时脚本什么都不构建:CLI 直接用每侧的 `/release/swift-section`,哪侧缺了就在任何渲染开始之前退出,并列出该侧要跑的预构建命令;MachOImage 部分的 `swift test` 追加 `--skip-build`,直接跑现成的 release test bundle。 + - 每侧只需预构建**一条**命令。要跑 MachOImage 部分就用 `queued-build swift test -c release --filter NoSuchTestForPrebuild --package-path <检出> --scratch-path `:`swift test` 会构建全部产物,CLI 也在其中,这个 `--filter` 又匹配不到任何测试,所以只构建、不运行。不跑 MachOImage 部分(带 `--skip-image-part`,或 `--scenarios` 里没有 `machoimage-current`)就用 `queued-build swift build -c release --product swift-section --package-path <检出> --scratch-path `。缺产物时脚本列出的也是按这条规则选出的命令。 + - 两条命令**不要在同一个 scratch path 上先后跑**:`swift test` 默认给整个构建打开 testability(release 也开,见 SwiftPM 的 `Sources/Commands/Utilities/TestingSupport.swift`),`swift build -c release` 不开。编译参数不同,后跑的那条会把整个包重编一遍,还会覆盖前一条编出的 CLI。不带 `--skip-build` 的默认跑法也因为这个原因,每侧实际要整包编两遍。 + - 脚本**不检查**现成产物是否对应检出当前的代码:预构建之后又改了代码,比的就是旧产物,这由调用方负责。`Using prebuilt` 那行打印的构建时间是唯一的线索。 + - 缺 test bundle 时 `swift test --skip-build` 以非零码退出(报 `.xctest doesn't exist in file system`),按 HARD-FAILURE 判整轮失败,但要等 CLI 渲染全部跑完才会报出来。 - **兄弟依赖对齐**:跑之前确认两个检出各自解析到预期的 sibling 内容(例如基线 main pin 了 `exact: "0.4.5"`,则 `/Volumes/Code/Personal/swift-demangling` 需在 0.4.5 tag 上:`git -C ../swift-demangling tag --points-at HEAD`)。sibling 内容错位会把 A/B 变成「比较两个不同的依赖版本」。 - **脚本的进度行经 Python 的 stdout,重定向进文件时会被整块缓冲**:跑完之前日志里只有子进程(`swift build`)的输出,看不到任何一对的进度,盯日志会误以为卡住。后台跑要 `python3 -u`,或者直接看 `--output-root` 下 `<场景>/<侧>/*.txt` 的落盘情况(每一对两侧都落盘后就可以先 `cmp`,不必等收尾)。2026-09-18 撞上一次。 - **interface 输出一律走 `-o` 落盘**:进度日志(带墙钟时间戳)走 stdout,不会混进被比对的文件。 diff --git a/Documentations/Internal/TaskReports/2026-08-31-evolution-interface-available-annotations.md b/Documentations/Internal/TaskReports/2026-08-31-evolution-interface-available-annotations.md new file mode 100644 index 000000000..da4b8e96e --- /dev/null +++ b/Documentations/Internal/TaskReports/2026-08-31-evolution-interface-available-annotations.md @@ -0,0 +1,48 @@ +# 2026-08-31 · evolution 联合接口的 @available 生命周期标注 + +## 问题 + +用户诉求:「目前已经有了 ABI 演进的功能了,能从这个开始实现 @available 标注吗」。`swift-section evolution --interface` 的联合接口用位图注释(`// [○●●] added in 18.0`)承载生命周期,但不产出真正的 `@available` 属性——想要接口里直接出现 `@available(iOS, introduced: 18.0)` 这种编译器语法的标注。 + +## 调研结论 + +- 事实层零缺口:`ABIEvolution` 的 lineage 已带逐版本 presence 位图 + added/removed 事件,`introduced:`/`obsoleted:` 需要的事实全部现成;格式层(`EvolutionMarking`)与事实层分离,属性渲染是纯格式层扩展。 +- 历史决策核对:前案 [0013(SwiftEvolutionInterfaceBuilder)](../../Evolutions/0013-swift-evolution-interface-builder.md) 否决过「伪 `@available` 属性形态」(似 Swift 而语义不符、modified 塞不进)。本案只发语法合法真属性、只在事实完整可表达时发、注释继续承载全部真相——两条否决理由均不复现,不构成翻案。 +- 平台名可从二进制 `LC_BUILD_VERSION` 推断,仓内已有先例(TypeIndexing 按它选 SDK,`Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift`)。 + +## 定案(一轮澄清提问,轻量档) + +1. 形态:真属性 + 保留位图注释(否:替换注释、只改注释措辞)。 +2. 不可表达时(`●○●`、非版本号标签、首版已存在无 introduced 事实、modified-only):不发属性,注释兜底(否:尽力发部分事实)。 +3. 范围:仅 `evolution --interface`(否:同时扩展 `diff --interface`——其 `-`/`+` 标记已表达增删)。 +4. 未提问自定:平台自动推断 + `--platform` 覆盖、推断失败响亮报错;长形态 `@available(iOS, introduced: 18.0, obsoleted: 26.0)`;removal 映射 `obsoleted:`。 + +提案:[0060-evolution-interface-available-annotations](../../Evolutions/0060-evolution-interface-available-annotations.md)(写成时是 draft,落地时取号)。 + +## 实际执行 + +- `EvolutionMarking`(格式层纯函数):`availabilityAttributeText(for:versions:platform:)`(单区间判据 `○ᵃ●ᵇ○ᶜ`、只解析涉事标签、任何一步不满足即整体 `nil`)、`availabilityVersion(fromLabel:)`(1–3 段 ASCII 数字)、`prependingAvailabilityAttribute(_:to:indentLevel:)`(空单元不发、属性行自身不带注解);`legendLines`/`renderInterface` 加可选平台参数,启用时图例第三行声明轴分辨率语义。 +- `SwiftEvolutionInterfaceRenderer`:持 `versionDescriptors` + `availabilityAnnotationPlatform`,成员单元在声明行上方、容器单元在 header 首行上方(缩进 `level - 1`,与 assembler 的 header 层级一致)前插属性行。 +- `AnySwiftEvolutionInterfaceBuilder` / pack façade:新增 `availabilityAnnotationPlatform: String? = nil` init 参数(默认关,输出逐字节不变),façade 透传并转发只读属性。 +- `EvolutionCommand`:`--emit-available` flag(要求 `--interface`)+ `--platform` 覆盖(要求 `--emit-available`);`resolveAvailabilityAnnotationPlatform` 逐输入读 `LC_BUILD_VERSION` 映射 `@available` 拼写(模拟器归并到设备平台;driverKit/bridgeOS 等无拼写平台返回 `nil`),缺失或跨输入冲突时 `ValidationError` 指路 `--platform`,绝不静默降级。这一条落地时搬进了 SwiftSectionKit,见文末「落地(2026-10-05)」。 + +## 验证 + +- 新增单测:`EvolutionMarkingTests` 可表达性矩阵 9 个(introduced-only / obsoleted-only / 双端 / 全程在场 / `●○●` / 涉事标签解析 / 位图错位防御 / 版本字面量规则 / 前插规则)+ 图例条件行;`SwiftEvolutionInterfaceBuilderTests.availabilityAttributesRenderWhenConfigured` 端到端(属性落位与缩进、注释保留、modified-only 与未变声明裸行、默认配置零属性);`EvolutionCommandValidationTests` 4 个(两条 flag 依赖规则、并行解析、平台拼写映射)。 +- 定向套件 47 tests 绿;`SwiftInterfaceTests` + `SwiftSectionCommandTests` 全量 168 tests / 25 suites 绿(`--skip IntegrationTests`)。 +- CLI 冒烟:即时编译双版本 dylib,验证平台推断(`macOS`)、属性 + 位图注释共存、默认输出零 `@available`、`--platform iOS` 覆盖生效。 + +## 偏差与备忘 + +- 实施与提案零偏差。 +- 环境备忘一:`--filter SwiftEvolutionInterfaceBuilderTests` 会同时命中 `Tests/IntegrationTests/` 里的同名 suite(维护者手工目标,读本机不存在的框架路径而红)——按 AGENTS.md 规矩带上 `--skip IntegrationTests` 即可,非本次改动引入。 +- 环境备忘二:本地兄弟仓 `../MachOObjCSection` 停在 detached 旧 commit(缺 `ObjCIndexing` product),`USING_LOCAL_DEPENDENCIES=1` 构建必败;本次未动用户检出,改用远端解析 scratch(`/tmp/claude/SwiftPM/MachOSwiftSection-remote`)构建与测试。 + +## 落地(2026-10-05) + +分支写成后一个多月没合,期间 `next` 把每个子命令的逻辑抽进了 SwiftSectionKit(提案 0058),CLI 只剩包装层。用户说「合并一下」时,`EvolutionCommand.swift` 上的冲突已经没法照原样解,于是问了用户一句:搬进 SwiftSectionKit 再合,还是这次只合另一个分支。用户选前者。 + +- **rebase**:原提交只保留 SwiftInterface 部分(builder、`EvolutionMarking`、渲染器与它们的测试),`EvolutionCommand.swift` 取 `next` 的版本,CLI 测试的新增也先拿掉;这个提交单独编译通过。 +- **搬进 SwiftSectionKit**(第二个提交):`ABIEvolutionRequest.Report.annotatedInterface` 带上关联值 `availabilityAttributes`(`.none` / `.inferredPlatform` / `.platform(_:)`),照 diff 的 `annotatedInterface(format:includesBreakingChangeVerdict:)` 的样子;平台推断在加载之后、索引之前,失败抛 `AvailabilityPlatformInferenceError`(`.noPlatform(path:)` / `.conflictingPlatforms(_:)`),错误文案不提 flag。`LC_BUILD_VERSION` 改用 MachOKitExtensions 公开的 `buildVersionCommand`,原分支自己写的那个私有扩展不要了。CLI 只剩两个 flag、两条组合校验、`makeRequest()` 的映射,以及 `CommandLineErrorTranslation` 里把两种推断错误译回原分支的报错文案(`ValidationError`,退出码 64)。 +- **测试**:推断失败要一个平台不同的输入,测试里现场把 fixture 副本的 `LC_BUILD_VERSION` 平台字段改掉(`FixtureFiles.makeCopy(of:buildPlatform:in:)`,照 `makeSingleSliceFatFile` 手工拼字节的先例)。副本 UUID 不变,各个按镜像的缓存会把它当成原件,所以只用在索引之前就结束的用例里,并断言没有出现「Indexing」进度行。模拟器归设备平台这条规则不单测纯函数,而是让 iOS 模拟器副本与 macOS 的 fixture 冲突,看错误里列出的是 `iOS`。 +- **验证**:定向套件、变异检验、全量与 CLI 冒烟的结果见提案决策日志「2026-10-05 验证」一行与账本第 79 节。 diff --git a/Documentations/Internal/TaskReports/2026-09-30-c-imported-typedef-types-uncolored-in-runtimeviewer.md b/Documentations/Internal/TaskReports/2026-09-30-c-imported-typedef-types-uncolored-in-runtimeviewer.md new file mode 100644 index 000000000..87fd422e9 --- /dev/null +++ b/Documentations/Internal/TaskReports/2026-09-30-c-imported-typedef-types-uncolored-in-runtimeviewer.md @@ -0,0 +1,178 @@ +# 2026-09-30 - C-imported typedef types uncolored and unsearchable in RuntimeViewer + +- **日期**: 2026-09-30 +- **任务**: C-imported typedef types uncolored and unsearchable in RuntimeViewer +- **作者**: Mx-Iris +- **仓库**: https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection + +## 1. 问题 / 任务 + +用户在 RuntimeViewer 里看 AppKit 的 `NSSliderAquaduckVisualProvider`,发现 stored property `var state: __C.NSSliderDrawingState` 的类型名没有着色、点不了,在侧边栏也搜不到。用户还有一个疑问:如果它是 ObjC 类,Type Layout 为什么是 `size: 232`,而不是一个指针的大小。解释清楚之后,用户要求评估提案 0023 对 AppKit、UIKitCore、SwiftUI、SwiftUICore、Foundation、CoreFoundation 这六个库的影响。0023 就是 `type-import-info-identity`:读取 C 导入类型 descriptor 上的 import info,按运行时的规则定名字和种类。A/B 对比准备到一半时,用户叫停,要求先把调查结果写下来。 + +## 2. 探索与调研 + +### 调研内容 + +- **本仓库**(`next` @ `32feff36`): + - 代码:`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift`、`Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift`、`Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift`、`Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift`、`Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift`。 + - CLI 着色:`Sources/Executables/swift-section/Models/SemanticColorScheme.swift`、`Sources/Executables/swift-section/Utilities/Extensions.swift`。 + - 文档:提案 [0023](../../Evolutions/0023-type-import-info-identity.md),以及三份相关任务报告 [2026-09-09-type-import-info-identity](2026-09-09-type-import-info-identity.md)、[2026-09-10-remove-primitive-type-mapping](2026-09-10-remove-primitive-type-mapping.md)、[2026-09-10-c-imported-extension-kind-from-descriptor](2026-09-10-c-imported-extension-kind-from-descriptor.md)。 +- **RuntimeViewer**(`.worktrees/RuntimeViewer`,`next` @ `92bff04a`): + - `RuntimeViewerCore/Sources/RuntimeViewerCore/` 下的 `Common/RuntimeObjectKind.swift`、`Core/RuntimeObjCSection.swift`、`Core/RuntimeSwiftSection.swift`、`Indexing/RuntimeSwiftInterfaceIndexer.swift`。 + - `RuntimeViewerPackages/Sources/RuntimeViewerApplication/Theme/` 下的 `SemanticString+ThemeProfile.swift`、`ThemePreset+ThemeProfile.swift`。 +- **兄弟仓库**:MachOObjCSection 的 `Sources/ObjCIndexing/ObjCInterfaceIndexer.swift`,swift-semantic-string 的 `Sources/Semantic/SemanticType.swift`,swift-demangling 的 `Sources/Demangling/Node/Printer/NodePrintContext.swift`。 +- **Swift 编译器源码**(`/Volumes/SwiftProjects/swift-project/swift`,`swift-6.4-RELEASE`):`lib/AST/ASTMangler.cpp`、`stdlib/public/runtime/Demangle.cpp`、`include/swift/ABI/TypeIdentity.h`。 +- **本机逆向资料**: + - `/Volumes/DyldSharedCaches/macOS/26.5.2/AppKit/ObjCHeaders/` 下的 `NSSliderCell.h`、`NSSliderTrack.h`、`NSSliderDial.h`、`NSSliderKnob.h`、`NSSliderVisualProvider-Protocol.h`。 + - `26.5.2/AppKit/SwiftInterfaces/AppKit.NSSliderAquaduckVisualProvider.swiftinterface` 和 `26.6.2/AppKit/SwiftInterfaces/AppKit-types-layout-host-dependencies-unverified.txt`。 + - 内部 SDK `MacOSX15.5.Internal.sdk` 里没有这个 struct(它是 macOS 26 才有的)。 +- **本机 dyld shared cache**(macOS 26.7,`/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/`):做了字节级搜索。 +- **Rainbow**(CLI 用来上色的库;当前 scratch 解析到的是 4.2.2):`Sources/Rainbow.swift`、`Sources/OutputTarget.swift`。 + +### 关键发现 + +**一、232 字节是对的:`NSSliderDrawingState` 是 C struct,不是 ObjC 类** + +- **`__C` 不等于 ObjC 类。** `__C` 是 Swift 给所有从 C / ObjC 头文件导入的东西用的伪模块,ObjC class、C struct、C enum、typedef 都在里面。只有 ObjC class 是一个指针,比如同一个类里的 `weak var sliderCell: __C.NSSliderCell?` 就是 `size: 8`。 +- **整个 struct 直接存在对象里。** `state` 从 `0x20` 开始;最后一个字段 `hidesKnob` 在 `0x100`,按 8 字节对齐补到 `0x108`,正好是下一个属性 `_hostingView` 的偏移,`0x108 - 0x20 = 0xE8 = 232`。C 的 size 本来就包含 tail padding,所以 size 和 stride 都是 232。 +- **声明形状是推断出来的,头文件原文没见到。** 它在 AppKit 私有头文件里应该是 anonymous struct 加 typedef name。下面的字段取自 Swift 侧的 field record: + + ```c + typedef struct { + NSSliderType sliderType; + NSControlSize controlSize; + // … + } NSSliderDrawingState; + ``` + + 依据有两条: + - ObjC type encoding 里它是匿名的。导出的头文件只写成 `struct { NSUInteger x0; … }`,出现在 `NSSliderCell.h` 的 `-_currentDrawingState` 和 `+_visualProviderClassForDrawingState:`、`NSSliderTrack` / `NSSliderDial` / `NSSliderKnob` 的 `drawingState`,以及 `NSSliderVisualProvider-Protocol.h`。 + - Swift 侧的 descriptor 带着 C typedef 标记(见下一节第 2 步)。 + +**二、为什么不着色、点不了:从编译器到 RuntimeViewer 的一条链** + +1. **编译器按 typedef 拼 mangled name。** 对 anonymous tag,`ASTMangler::getClangDeclForMangling`(`lib/AST/ASTMangler.cpp:2915`)改用它的 typedef name;`tryAppendClangName` 碰到 `TypedefNameDecl` 就追加 `a`(`:3237`)。所以它的 mangled name 是 `So20NSSliderDrawingStatea`,结尾的 `a` 表示 typealias,而不是 struct 用的 `V`。 +2. **二进制里的 descriptor 带着 C typedef 标记。** 在本机 26.7 cache 的 `dyld_shared_cache_arm64e.01` 里能直接搜到 `NSSliderDrawingState\0St\0`:descriptor 名字后面跟着 import info 分量 `S`(symbol namespace),值是 `t`,也就是 C typedef(`include/swift/ABI/TypeIdentity.h:54`)。在 `.01`、`.05`、`.09` 三个 subcache 里都搜不到字面的 `So20NSSliderDrawingState`,说明 field record 是用 symbolic reference 指向这个 descriptor 的。这和 0023 任务报告对 IRGen `CanSymbolicReference` 的分析一致。 +3. **本库从 0023 起把它还原成 `typeAlias` node。** 0023(`1c8d8588`,2026-09-09)之后,`SymbolicDemangler.cImportedTypeIdentity`(`Sources/Analysis/SwiftInspection/SymbolicDemangler.swift:736-737`)对带 C typedef 标记的 descriptor 产出 `typeAlias` node,和运行时 `stdlib/public/runtime/Demangle.cpp:168-169` 一致。0023 之前这里用 descriptor 自己的种类,产出的是 `structure` node;提案 0023 对照表里 `Decimal` 那一行就是这个形态。 +4. **打印器给 `typeAlias` 名字打的是 `.standard`。** `TypeNodePrintable.swift:30-40` 把 `.typeAlias` 和 `.enum`、`.structure`、`.class`、`.protocol` 一起交给 `printType`,后者用 `parentKind: name.kind` 打印 identifier(`:202`)。`SemanticString` 的 `write(_:context:)`(`Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift:36-52`)按 `parentKind` 选 semantic type,但没有 `.typeAlias` 分支,于是落到 `default: .standard`。swift-semantic-string 的 `SemanticType.TypeKind` 本身也只有 `enum`、`struct`、`class`、`protocol`、`other` 这几种。 +5. **RuntimeViewer 只给 `.type` token 上色和加链接。** 颜色只看 semantic type:`.type(_, .name)` 用类型名颜色,其余用正文颜色(`ThemePreset+ThemeProfile.swift:103`)。跳转链接也只挂在含 `.type` token 的片段上(`SemanticString+ThemeProfile.swift:162-166` 的 `resolveTargetKind`);`resolveSwiftLinkTargets` 的注释写明,typealias 引用是有意不给链接的。 + +**结论:这是 0023 的副作用。** 提案和它的三份任务报告都只比了纯文本,没看 semantic type,所以当时没发现。 + +**波及面是按代码推断的,没有实测。** 受影响的是所有以 C typedef 为身份的类型: +- CF class,比如 `__C.CGColorRef`; +- `swift_wrapper` typedef,比如 `NSAttributedStringKey`、`NSNotificationName`; +- typedef anonymous struct,比如 `NSDecimal`、`CMTime`、`NSSliderDrawingState`。 + +这些类型出现在从符号 demangle 出来的位置时(名字里本来就是 `…a`),0023 之前就已经是 `typeAlias` node、不着色。0023 让 field type 这类从 descriptor 推出来的位置也和它们一致了,只不过是一致地不着色。 + +**三、为什么搜不到:两个独立原因,都在 RuntimeViewer** + +- **Swift 侧被过滤了。** 这个 descriptor 就在 AppKit 的 `__swift5_types` 里:26.6.2 的 dump 导出第 270 行是 `struct __C.NSSliderDrawingState {`,后面带着全部字段。但 RuntimeViewer 建 Swift 索引时把 `SwiftDeclarationIndexConfiguration(showCImportedTypes: false)` 写死在了 `RuntimeViewerCore/Sources/RuntimeViewerCore/Core/RuntimeSwiftSection.swift:1208` 和 `RuntimeViewerCore/Sources/RuntimeViewerCore/Indexing/RuntimeSwiftInterfaceIndexer.swift:153`。索引器按这个开关跳过所有 C 导入的 descriptor(本仓库 `Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift:495`)。按 `git log -S` 看,这个写法至少从 `9b48c942`(2026-01-05)起就在了。 +- **ObjC 侧根本没有这个名字。** 侧边栏的「C Struct」来自 `objcIndexer.structNames`(`RuntimeObjCSection.swift:105-106`),是从 ObjC type encoding 里收集的,而且只收有名字的 struct(MachOObjCSection `Sources/ObjCIndexing/ObjCInterfaceIndexer.swift:218-219` 的 `if let name`)。`NSSliderDrawingState` 在 encoding 里是 `{?=…}`,这个名字在 ObjC 元数据里根本不存在。 + +所以二进制里唯一同时带着这个名字和字段定义的,是 Swift 侧这个 C 导入类型的 descriptor,而它恰好被过滤掉了。 + +**四、顺带看到、没深究的两点** + +- **字段偏移的两处说法不一样。** 26.6.2 的 dump 里,`__C.NSSliderDrawingState` 自己的条目每个字段都写着 `Field offset: unknown (C-imported type; field offsets not derivable from reflection)`;可在 `NSSliderAquaduckVisualProvider` 的 expanded field tree 里,同一批字段都有具体偏移。 +- **旧导出的类型名和现在不同。** 本机旧导出(26.5.2 的 `AppKit.NSSliderAquaduckVisualProvider.swiftinterface`,以及 26.6.2 那份由 swift-section 0.19.0 生成的 dump)把同一批字段写作 `__C.SliderType` / `__C.ControlSize`;用户截图(当前 `next`)里是 `__C.NSSliderType` / `__C.NSControlSize`。这和 0023 的 ABI name 规则一致,同类例子是 `__C.Style` → `__C.NSTableViewStyle`。不过两份旧导出的生成版本是否早于 0023,没有核实。 + +**五、0023 影响评估:已有什么、还缺什么** + +- **已有:** + - [2026-09-09-type-import-info-identity](2026-09-09-type-import-info-identity.md) 做过 SwiftUI 和 Foundation 的纯文本前后对比。 + - [2026-09-10-c-imported-extension-kind-from-descriptor](2026-09-10-c-imported-extension-kind-from-descriptor.md) 用 `runtime-viewer-cli` 对比过 SwiftUICore 侧边栏的对象清单,并修掉了 `__C.AGSubgraphRef` 从 Class Extension 掉到 Struct Extension 的退化。 + - [2026-09-10-remove-primitive-type-mapping](2026-09-10-remove-primitive-type-mapping.md) 删的是死代码,不改输出。 +- **还缺:** 所有库的 semantic 维度(着色和链接)都没看过;AppKit、UIKitCore、CoreFoundation 三个库完全没比过。 +- **对比哪两个提交:** + - 0023 前的最后一个提交是 `7071ac46`,0023 本身是 `1c8d8588`,两者之间 `Package.swift` 没变。 + - `e4783365`(删 `PrimitiveTypeMapping`)和 `296f192c`(extension 的 kind 改按 descriptor 定;按报告,它不改 dump / interface 文本)是 0023 的延续。 + - 中间还夹着三批与 0023 无关的提交:0024(给类型和协议定义带上导出状态)、0025(property descriptor 建模)、0026(补五种缺失的 ABI 结构)。 + - 所以拿 `7071ac46` 对比 `1c8d8588`,量出来的就是 0023 对输出的直接影响。 + +**六、A/B 的技术准备(已查明,未执行)** + +- **着色可以直接用 CLI 量。** `interface` 和 `dump` 都有 `--color-scheme`。在当前 `next` 的 `withColorHex(for:colorScheme:)`(`Sources/Executables/swift-section/Utilities/Extensions.swift`)里,`.type(_, .name)` 统一用一种颜色(dark 下是 `#D0A8FF`),`.standard` 不上色,所以「掉色」能从 ANSI 输出里直接看出来。但 NS_ENUM 从 `enum` 改成 `structure` 这类变化只改链接目标的 kind、不改颜色,这样看不出来。`1c8d8588` 时两个命令都有 `--color-scheme`,颜色映射没有逐行核对。 +- **录彩色输出要套伪终端。** Rainbow 只在 stdout 是终端、且设了 `TERM` 时才输出颜色(`OutputTarget.current` 会检查 `isatty`)。`FORCE_COLOR` 只影响 `Rainbow.enabled`,对非终端目标,`generateString` 照样返回纯文本。所以要用 `script -q ` 之类的办法套伪终端,再用去掉 ANSI 的版本做文本 diff。 +- **`1c8d8588` 时的 CLI 选项:** + - `interface`:`--emit-offset-comments`、`--emit-expanded-field-offsets`、`--emit-type-layout`、`--emit-enum-layout`、`--show-c-imported-types`、`--resolve-c-module-names`。 + - `dump`:`--emit-field-offsets`、`--emit-type-layout`、`--emit-expanded-field-offsets`、`--emit-enum-layout`。 + - 读本机 cache:`--uses-system-dyld-shared-cache --cache-image-path `。 +- **依赖必须两侧对齐。** `Package.resolved` 被 gitignore 了,依赖又是按范围写的。`7071ac46` 时的范围是:MachOKit `0.52.101..<0.53.0`、MachOObjCSection `0.8.105..<0.9.0`、swift-demangling `0.6.3..<0.7.0`、MachOKitExtensions `from: "0.1.1"`、swift-semantic-string `from: "0.3.0"`。9 月 9 日之后,这些范围里又发了 MachOKit 0.52.103、MachOObjCSection 0.8.106 / 0.8.107、MachOKitExtensions 0.1.2 / 0.1.3、swift-semantic-string 0.4.0。两侧必须共用同一份 `Package.resolved`;旧代码能不能在这些今天的最新版本上编译通过,还没验证。 +- **构建要排队。** 这台是 `JHs-Mac-Studio`(10 核),`queued-build` 全机串行。当时队列被另一个会话的 release `swift test`(`RenderingVerificationTests`)占着。 + +### 候选方案 + +没有做取舍,只列出可以改的地方: + +| 方案 | 位置 | 优点 | 缺点 | +|------|------|------|------| +| A. 打印器按 descriptor 的真实种类,给 `__C` 下的 `typeAlias` 打 `.type(.struct / .class, .name)` | `Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift:36-52`,另外需要一条在打印时拿到 descriptor 种类的途径 | 恢复着色,不动 0023 的身份规则 | 打印时手里只有 node,`typeAlias` 树分不出 CF class 和 typedef struct(`296f192c` 修的就是同一个问题),要额外去查 descriptor | +| B. `typeAlias` 一律打 `.type(.other, .name)` | 同上 | 改动最小,能恢复着色 | RuntimeViewer 对 Swift 侧的 `.other` 不给链接;还要确认会不会波及原生 Swift typealias 引用(RuntimeViewer 的注释说它们是有意不给链接的) | +| C. RuntimeViewer 把 C 导入类型收进索引 | RuntimeViewer `RuntimeViewerCore/Sources/RuntimeViewerCore/Core/RuntimeSwiftSection.swift:1208`、`RuntimeViewerCore/Sources/RuntimeViewerCore/Indexing/RuntimeSwiftInterfaceIndexer.swift:153` | 能搜到,也能跳过去 | 直接放开会让侧边栏多出大量 `CGRect`、NS_ENUM 之类的条目;可以考虑只进搜索和跳转,不进默认列表 | + +A 或 B 最好和 C 一起做。只改着色的话,会出现有颜色但点不过去的链接。 + +## 3. 最终方案 + +还没有定方案。用户先要解释,再要 0023 的影响评估;评估在准备 A/B 时被用户叫停,改为先把这份报告写下来。修不修、按哪个方案修、A/B 要不要继续,都等用户决定。 + +## 4. 实际执行与改动 + +### 改动清单 + +| 文件 | 操作 | 说明 | +|------|------|------| +| `Documentations/Internal/TaskReports/2026-09-30-c-imported-typedef-types-uncolored-in-runtimeviewer.md` | 新建 | 本报告 | +| `/Volumes/DerivedData/Agents.noindex/claude/SourceExports/MachOSwiftSection-7071ac46` 和 `…/MachOSwiftSection-1c8d8588` | 新建(在仓库外) | A/B 用的 `git archive` 源码导出,各约 12 MB,还没构建;不用了可以删 | + +没有改动任何源代码。 + +### 关键命令 + +在本机 cache 里搜 descriptor 名字后面的 import info,以及字面的 mangled name: + +```bash +cd /System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/ +LC_ALL=C grep -a -o -b -E 'NSSliderDrawingState\x00[A-Za-z][A-Za-z0-9_]*\x00' dyld_shared_cache_arm64e.01 +LC_ALL=C grep -a -c 'So20NSSliderDrawingState' dyld_shared_cache_arm64e.01 +``` + +第二条命令对 `.05` 和 `.09` 也各跑了一次,三个 subcache 的结果都是 0。 + +A/B 用的源码导出: + +```bash +git archive 7071ac46 | tar -x -C /Volumes/DerivedData/Agents.noindex/claude/SourceExports/MachOSwiftSection-7071ac46 +git archive 1c8d8588 | tar -x -C /Volumes/DerivedData/Agents.noindex/claude/SourceExports/MachOSwiftSection-1c8d8588 +``` + +被用户拒绝、没有执行的一步:在 `7071ac46` 的导出上跑 `swift package resolve`,scratch path 是 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Pre0023`。 + +### 验证 + +只有只读的证据:没有构建、没有跑测试,也没有跑 RuntimeViewer。 +- **直接看到的:** import info 里的 `St` 是字节级搜出来的。 +- **读代码得出的:** 着色失效的那条链。 +- **推断、未实测的:** 「波及所有以 C typedef 为身份的类型」和「符号位置在 0023 之前就不着色」。 + +### 与原方案的差异 + +- **差异点**:计划中的 0023 A/B 没有执行。原计划是 `7071ac46` 对比 `1c8d8588`,六个库都跑 `interface` 和 `dump`,同时比纯文本和 ANSI 着色。 +- **原因**:解析依赖那一步被用户叫停,改为先写报告。 +- **影响**:六个库还没有量化数字。现有的数字只有旧报告里 SwiftUI、Foundation(文本)和 SwiftUICore(侧边栏)那几组。 + +### 恢复 A/B 时的步骤 + +1. 在 `7071ac46` 的导出上解析一次依赖,把得到的 `Package.resolved` 复制到 `1c8d8588` 的导出,两侧共用。 +2. 两侧各跑一次 `queued-build swift build -c release --product swift-section`,放后台。scratch path 分别用 `/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-Pre0023` 和 `…-Post0023`。 +3. 对六个库各跑 `interface`(带上布局注释选项)和 `dump`,都加 `--color-scheme dark`,用 `script -q` 套伪终端录下 ANSI 输出。两个待确认的点: + - macOS cache 里的 UIKitCore 是 Mac Catalyst 版,路径还没确认; + - CoreFoundation 先确认有没有 `__swift5_*` section。 +4. 去掉 ANSI 后做文本 diff,看改名和 conformance 块重排。再按 `__C.<名字>` 统计同一个名字在两侧着色和不着色的次数,得出掉色清单。 + +下一次会话可以用的 skill: +- `xcode-build-and-test`:排队构建和 scratch path; +- `swift-section:swift-section-cli`:CLI 选项; +- 决定修复时用 `evolution` 写轻量提案,用 `write-tests` 先写一条能变红的着色回归测试。 diff --git a/Documentations/Internal/TaskReports/2026-10-03-c-imported-names-after-type-import-info.md b/Documentations/Internal/TaskReports/2026-10-03-c-imported-names-after-type-import-info.md new file mode 100644 index 000000000..7b0fba82c --- /dev/null +++ b/Documentations/Internal/TaskReports/2026-10-03-c-imported-names-after-type-import-info.md @@ -0,0 +1,96 @@ +# 2026-10-03 读 TypeImportInfo 之后 C 导入类型名字的变化,与依赖旧短名的地方 + +对应提案:无([0023-type-import-info-identity](../../Evolutions/0023-type-import-info-identity.md) 的后续核查,豁免档)。前置:[2026-09-30-c-imported-typedef-types-uncolored-in-runtimeviewer](2026-09-30-c-imported-typedef-types-uncolored-in-runtimeviewer.md) 第五、六节准备好却没跑的那次对比。 + +## 问题 + +RuntimeViewer 的快照测试里 `__C.Decimal.FormatStyle` 变成了 `__C.NSDecimal.FormatStyle`。用户先要调查读 TypeImportInfo 之后 C 导入类型的名字到底怎么变了,再问二进制里有没有信息能还原真实的 Swift 名,最后定:先保持 ABI name(它是准确的),从二进制推断 Swift 名以后再做;检查有没有测试依赖之前被截短的 Swift 类型名,改掉;顺便查 RuntimeViewer 的测试。 + +## 调研 + +### 名字变了多少(2026-10-01) + +改动前最后一个提交 `7071ac46` 与改动 `1c8d8588` 各编一个 release CLI,两侧共用同一份 `Package.resolved`,在本机 macOS 27.0 的系统 dyld cache 上跑 `dump` 与 `interface --show-c-imported-types`,逐行比对。CoreFoundation 没有 Swift section,不在其中。 + +| 框架 | `dump` 变化行 | 其中改名行 | 不同的改名 | `interface` 顶层声明 | C 类型 extension 目标 | +|---|---|---|---|---|---| +| AppKit | 633 | 633 | 81 | 768 → 773 | 404 → 406 | +| UIKitCore(Mac Catalyst) | 546 | 546 | 77 | 997 → 1003 | 646 → 644 | +| SwiftUI | 565 | 507 | 66 | 4400 → 4406 | 112 → 112 | +| SwiftUICore | 566 | 518 | 47 | 3058 → 3058 | 127 → 118 | +| Foundation | 510 | 375 | 33 | 406 → 406 | 205 → 200 | + +`dump` 里不是改名的变化行都是 protocol witness:原来打成 `sub_…` 地址的拿到了真名(SwiftUI 35、SwiftUICore 48、Foundation 135),以及 SwiftUI 里 23 行原来挂着别的类型的 witness(见下)。 + +**旧名是什么**:描述符名字字段里的 user-facing name,也就是 Swift 名的最后一个成分。IRGen `computeIdentity`(`lib/IRGen/GenMeta.cpp`)取 `Type->getName()`,C 名作为 import info 的 `N` 分量跟在后面;`getAddrOfParentContextDescriptor`(`lib/IRGen/GenDecl.cpp`)把每个 Clang 导入类型的父级都设成 `__C` 模块,所以 `NSTableView.Style` 在二进制里只剩 `Style`,嵌套关系和所属模块都不记录。 + +**五个框架合计 244 组改名**: + +| 类别 | 组数 | 例子 | +|---|---|---| +| 加回外层类型名或前缀 | 166 | `Style` → `NSTableViewStyle`、`Name` → `NSNotificationName`、`Decimal` → `NSDecimal` | +| CF class 加回 `Ref` | 38 | `CGColor` → `CGColorRef`、`Subgraph` → `AGSubgraphRef` | +| 完全换了名字 | 26 | `Event` → `UIControlEvents`、`BounceOptions` → `RBSymbolAnimationBounceFlags` | +| `swift_private` 去掉 `__` | 13 | `__UIButtonConfigurationSize` → `UIButtonConfigurationSize` | +| importer 合成的错误类型 | 1 | `__C_Synthesized.UISSceneConnectionValueError` → `__C_Synthesized.related decl 'e' for UISSceneConnectionValueError` | + +**旧名造成的问题**(0023 之后都没有了): + +- 20 个短名各指多个类型:`Style` 8 个、`Identifier` 5 个、`Name` 4 个。 +- `interface --show-c-imported-types` 只留下同名 C 类型中的一个:AppKit 少 5 个声明,UIKitCore、SwiftUI 各少 6 个。 +- SwiftUI 里 `NSTouchBarItem.Identifier` 的 conformance 下面列的是 `NSToolbarItemIdentifier` 的 witness,`NSAppearance.Name`、`NSButton.BezelStyle` 同理,共 23 行。 +- 同一类型拆成两个名字:描述符给短名,符号给 C 名。SwiftUICore 里 `CGColor` 的 extension 分成 `__C.CGColor` 5 块与 `__C.CGColorRef` 1 块;Foundation 的 `interface` 里 `__C.Decimal` 106 行、`__C.NSDecimal` 67 行并存。 +- `--resolve-c-module-names` 按短名查模块会认错:AppKit 的 `controlSize` 字段被写成 `SwiftUICore.ControlSize`,`__C.Mode` 被写成 `QuartzCore.Mode`。用当前代码,同一字段写成 `AppKit.NSControl.ControlSize`。 + +**仍然存在、本批没动的**:默认输出没有 Swift spelling;`interface` 里 C 类型自己的声明头仍是描述符的短名(AppKit 的 `NSAppearanceName`、`NSFontCollectionName`、`NSNotificationName` 都打成 `struct Name {`,`dump` 的声明头却是全名),RuntimeViewer 自 `d300bafd` 起把 C 类型列进侧边栏后会看到这一点;开了 `--resolve-c-module-names` 时 extension 头仍是 `extension __C.NSControlSize`,只有引用处被改写。 + +### 二进制能还原多少 Swift 名 + +拿 SDK 当标准答案:所有 `.apinotes` 的顶层条目(4530 条,含 Mac Catalyst 的 UIKit)、头文件里的 `NS_SWIFT_NAME` 等标注(405 条)、importer 的固定规则(CF `Ref` 剥除、`swift_private` 的 `__`、合成错误类型)。244 组里 188 组有答案。 + +- 不嵌套的 64 组:二进制里的最后一截就是完整 Swift 名(`Decimal`、`CGColor`、`StringTransform`)。 +- 嵌套的 124 组:二进制只有最后一截。按「C 名去掉最后一截,剩下的前缀若是 ObjC class 就当外层类型」去猜,89 组的 C 名正好是外层类名加最后一截,用 AppKit、Foundation、UIKitCore、UIFoundation、CoreData 的 ObjC class 名单猜对 79 组;另外 35 组的 C 名对不上,必错(`NSControlSize` 实为 `NSControl.ControlSize`,`UIControlEvents` 实为 `UIControl.Event`,`NSRunLoopMode` 实为 `RunLoop.Mode`)。 +- 合计猜对 143 组,错的 45 组看起来和对的一样。 +- 56 组 SDK 里没有答案,几乎都是私有框架(AttributeGraph、RenderBox、UIKit 的 `_UI…`)。对它们来说二进制里的最后一截是唯一来源,而 0023 之后开不开 `--resolve-c-module-names` 都打印 C 名(SwiftUICore 的 `__C.AGSubgraphRef` 140 行,开了之后仍是 140 行)。 + +改名过的 ObjC class 与 protocol(`NSFileManager` → `FileManager`、`NSObject` protocol → `NSObjectProtocol`)没有 Swift 描述符,二进制里没有它们的 Swift 名。 + +### 依赖旧短名的地方 + +用只出现在旧侧的 212 个拼写搜索: + +- **MachOSwiftSection 的测试**:没有断言依赖旧短名,0023 当时已改过 `__C.Decimal` 的期望和两份快照。唯一相关的是 `SupplementaryAPINotesTests.userSuppliedMappingsResolveInAllManglingShapes`,它的说明把描述符直出的 `__C.Graph` 列为第三种 mangling 形态;0023 之后这种形态不再出现,SwiftUICore 的 `dump` 里 `__C.Graph` / `__C.Subgraph` 从 107 行变成 0。 +- **MachOSwiftSection 的注释与文档**:`StaticLayoutCalculator` 的注释与 `StaticLayoutEngine.md` 里的 `__C.Decimal`;`TypeIndexingPipeline.md`、公开指引 `SupplementaryTypeMappings.md` 与术语表对第三种形态的描述和「二进制零残留」的说法;A15 裁决对「剥后名」形态的引用;`TypeDatabase.registerAttribution` 的注释。任务报告、提案和账本的旧节是历史记录,不改。 +- **其它分支**:`next` 之外三个未合并分支的测试都没有旧短名。 +- **RuntimeViewer**:12 个 worktree 的测试与快照里,C 导入类型名都已是 ABI name。唯一依赖旧名的 `relationships-swift-baseline.txt` 已在 RuntimeViewer `next` 的 `81a79054` 更新;仍带旧基线的五个分支都已并入 `next`。RuntimeViewer 没有改动。 + +## 实际执行 + +**先删后撤**:一开始判断 `TypeDatabase.registerAttribution` 里把 APINotes 的 SwiftName spelling 登进归属表的那段循环只为第三种形态存在,删掉了它,并把测试里 `Graph` / `Subgraph` 的归属期望改成 `nil`。单元测试全过,但改动前后两版 release CLI 在系统框架上对比 `interface --resolve-c-module-names --show-c-imported-types` 时输出不同,差异全是 `NSObject` 的模块归属: + +| 框架 | 变化行 | `ObjectiveC.NSObject` → `Foundation.NSObject` | `ObjectiveC.NSObjectProtocol` → `Foundation.NSObjectProtocol` | +|---|---|---|---| +| AppKit | 129 | 108 | 22 | +| UIKitCore | 136 | 130 | 6 | +| SwiftUI | 260 | 263 | 4 | + +原因:Foundation 与 AppKit 的 APINotes 为了标注 category 方法也列了 `NSObject`,`APINotesIndex` 的 C 名登记是后加载的文件说了算;ObjectiveC 的条目把 `NSObject` 改名为它自己,那段循环在 C 名之后登记这个 SwiftName spelling,`NSObject` 才回到 ObjectiveC。也就是说它早就不服务第三种形态,却在替「多个模块列出同一个 C 名」的情况定归属。现有测试没有覆盖这一点,所以删掉后全绿。 + +于是撤回删除,改成: + +- `TypeDatabase.registerAttribution`:保留循环,注释改写成它现在实际起的作用。源码只有注释变化,行为不变。 +- 新增 `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings`:两个模块的 APINotes 都列出 `TSTBase`,改名条目所在的模块先加载、只做标注的后加载,断言归属仍是改名条目的模块。 +- `SupplementaryAPINotesTests`:断言不变,说明改为两种 mangling 形态,并指明 Swift spelling 为什么仍被登记。 +- 文档:`SupplementaryTypeMappings.md`(二进制只留最后一截、typedef 名也出现在字段元数据里、`__C.Graph` 不必登记)、术语表「supplementary APINotes」、`TypeIndexingPipeline.md`(第三种形态标为不再出现,记下那段登记为什么要留)、A15 加补记、`StaticLayoutEngine.md` 与 `StaticLayoutCalculator` 注释里的 `__C.Decimal` 改成 `__C.NSDecimal`。 + +## 验证 + +- `swift test --filter TypeIndexingTests`(退出码取自 `swift test` 本身):38 条 / 7 个 suite 全过。 +- 红/绿:把那段循环临时去掉再跑 `TypeDatabaseMergePriorityTests` 与 `SupplementaryAPINotesTests`,3 处失败(`TSTBase` 归到 `AnnotatingModule`,`Graph` / `Subgraph` 归属为 nil);恢复后全过。 +- 源码改动只有注释(`git diff -- Sources` 里除注释外没有增删行),所以没有再对系统框架做输出对比;上面那次对比就是删掉循环时做的。 + +## 环境备忘 + +- 对比产物与派生表:`/Volumes/DerivedData/Agents.noindex/claude/Logs/TypeImportInfoNames/`。`all-renames.tsv` 是 244 组改名,`all-renames-truth.tsv` 是 SDK 答案与分类,`sdk-apinotes-swift-names.tsv` / `sdk-header-swift-names.tsv` 是从 SDK 抽出的 C name → Swift name,`spelling-ab/` 是删循环那次的输出对比。 +- CLI:`/Volumes/DerivedData/Agents.noindex/claude/SwiftPM/MachOSwiftSection-{Pre0023,Post0023}/release/swift-section`(名字调查),`…/MachOSwiftSection-SwiftSpellingBaseline-Release` 与 `…/MachOSwiftSection-DropSwiftSpellingAttribution-Release`(删循环那次的对比,后者是删掉循环的版本)。 +- 本批构建时 GitHub 连不上(`SSL_ERROR_SYSCALL`)。依赖用 FindNavigator worktree 的 `Package.resolved` 加 `--skip-update --only-use-versions-from-resolved-file` 从本机缓存离线解析,两侧共用同一份。 diff --git a/Documentations/Internal/TypeIndexingPipeline.md b/Documentations/Internal/TypeIndexingPipeline.md index 4c6fdbfe1..abf3efb67 100644 --- a/Documentations/Internal/TypeIndexingPipeline.md +++ b/Documentations/Internal/TypeIndexingPipeline.md @@ -27,7 +27,7 @@ module 名替换之外,`__C` 类型的 **identifier 本身**也可能是 Swift - **查询必须带声明类别**(`CImportedTypeNameCategory`,由 mangling 的 `Node.Kind` 映射:class / protocol / 值类型 / other)。这是第一版合并改名表当场踩出的回归:ObjC 的 class `NSObject` 与 protocol `NSObject` 同名,APINotes 只把 **protocol** 改名为 `NSObjectProtocol`——类别盲查让所有 class 继承行都被错写成 `NSObjectProtocol`(而 protocol 继承行反而是被修对的)。`APINotesIndex` 的改名表按 Classes / Protocols / 值类型(Tags + Enumerators + Typedefs)三张隔离,`.other`(typealias 等 mangling 不定类别的引用)查值类型表再查 class 表、**永不查 protocol 表**。 - **CF `Ref` 剥除**是 APINotes miss 后的兜底规则:`Ref` 结尾且剥后名真实存在于归属表才重写(碰巧以 `Ref` 结尾的 ObjC 类不受影响),protocol 类别不适用(无 CF protocol 惯例)。 - 归属表(`moduleNamesByCName`)不拆类别——同名实体同模块,归属无歧义。 -- **`Ref` 规则对整个 `objc_bridge`(`CF_BRIDGED_TYPE` / `CV_BRIDGED_TYPE` 等各框架宏别名)家族通用**,不是 CoreFoundation 专属——判据只是「剥后名存在于索引」。CG / CV / CM 探针实测(链 CoreGraphics + CoreVideo + libswiftCoreMedia 的 dylib):同一类型**两种 mangling 形态并存**——符号签名用 C typedef 名(`__C.CGContextRef`),字段元数据用剥后名(`__C.CGContext`)——分别由剥除规则与归属表直查覆盖,全部解析为 `CoreGraphics.CGContext` / `CoreVideo.CVBuffer` / `CoreMedia.CMFormatDescription`(`CVPixelBuffer` 在 mangling 层已归一为 `CVBuffer`,输出如实反映 ABI)。CoreMedia 仅以 `libswiftCoreMedia` overlay 形式出现在依赖里,`libswift` 前缀剥除使过滤命中其 SDK 模块——overlay-only 依赖场景成立。 +- **`Ref` 规则对整个 `objc_bridge`(`CF_BRIDGED_TYPE` / `CV_BRIDGED_TYPE` 等各框架宏别名)家族通用**,不是 CoreFoundation 专属——判据只是「剥后名存在于索引」。CG / CV / CM 探针实测(链 CoreGraphics + CoreVideo + libswiftCoreMedia 的 dylib):同一类型**两种 mangling 形态并存**——符号签名用 C typedef 名(`__C.CGContextRef`),字段元数据用剥后名(`__C.CGContext`)——分别由剥除规则与归属表直查覆盖(提案 0023 之后字段元数据也按描述符 import info 里的 ABI name 拼成 `__C.CGContextRef`,两种形态合一,只靠剥除规则),全部解析为 `CoreGraphics.CGContext` / `CoreVideo.CVBuffer` / `CoreMedia.CMFormatDescription`(`CVPixelBuffer` 在 mangling 层已归一为 `CVBuffer`,输出如实反映 ABI)。CoreMedia 仅以 `libswiftCoreMedia` overlay 形式出现在依赖里,`libswift` 前缀剥除使过滤命中其 SDK 模块——overlay-only 依赖场景成立。 - **Swift interface 类型名**:对二进制依赖命中的每个 SDK 模块,经 sourcekitd `editor.open.interface`(带 `key.enablesubstructure`)生成含 ObjC 导入声明的 Swift 视角 interface,`InterfaceTypeNameExtractor` 从结构树提取 fully-qualified 类型名。**不用 SwiftSyntax**(体积裁定,见提案 A′ 节);`.swiftinterface` 文件也不可用——它只含 Swift 声明,而本功能主要目标恰是 ObjC 导入类型。 - **APINotes**:`.apinotes` 是编译器视角的权威归属记录,`APINotesIndex` 把**每个列出的实体**(含无 `SwiftName` 改名、含 `SwiftPrivate`)的 C 名注册到声明模块,后写覆盖 interface 名。双向改名表(`swiftName(forCName:)` / `cName(forSwiftName:)`)只收非 `SwiftPrivate` 的改名实体。 @@ -35,13 +35,13 @@ module 名替换之外,`__C` 类型的 **identifier 本身**也可能是 Swift ## 补充映射:私有框架的外部知识入口(提案 0010) -AttributeGraph 这类私有框架在 SDK 里没有任何模块(无头文件、无 swiftmodule、无 apinotes),三源全 miss;而 `AG_SWIFT_NAME(Graph)` 的改名只活在头文件 attribute 里、二进制零残留,原理上不可恢复。[提案 0010](../Evolutions/0010-community-type-mapping-bundles.md) 的补充映射就是这份外部知识的入口:映射用**标准 `.apinotes` 格式**表达(零新格式,直接进 `APINotesIndex` 既有管线,类别隔离天然携带),**全部由用户自备**——宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes`(可重复,文件或目录)传入;库自身不内置任何映射(首版曾内置 SPM resource bundle,review 后按用户裁定移除:`Bundle.module` accessor 在 bundle 缺失时 fatalError,而 `build-executable-product.sh` 只分发裸二进制,分发出去一用就崩——纯用户自备把整个 resource 分发问题结构性消掉)。覆盖顺序:SDK APINotes → 用户文件按传入序,`APINotesIndex.register(files:)` 的后写覆盖即优先级实现。面向用户的公开指引见 [SupplementaryTypeMappings.md](../SupplementaryTypeMappings.md)。 +AttributeGraph 这类私有框架在 SDK 里没有任何模块(无头文件、无 swiftmodule、无 apinotes),三源全 miss;而 `AG_SWIFT_NAME(Graph)` 的改名在二进制里只剩消费方类型记录名字字段里的最后一截 `Graph`,所属模块与嵌套关系都不记录,完整的 `AttributeGraph.Graph` 原理上无法从二进制恢复。[提案 0010](../Evolutions/0010-community-type-mapping-bundles.md) 的补充映射就是这份外部知识的入口:映射用**标准 `.apinotes` 格式**表达(零新格式,直接进 `APINotesIndex` 既有管线,类别隔离天然携带),**全部由用户自备**——宿主经 provider 的 `supplementaryAPINotesURLs:`、CLI 经 `--supplementary-apinotes`(可重复,文件或目录)传入;库自身不内置任何映射(首版曾内置 SPM resource bundle,review 后按用户裁定移除:`Bundle.module` accessor 在 bundle 缺失时 fatalError,而 `build-executable-product.sh` 只分发裸二进制,分发出去一用就崩——纯用户自备把整个 resource 分发问题结构性消掉)。覆盖顺序:SDK APINotes → 用户文件按传入序,`APINotesIndex.register(files:)` 的后写覆盖即优先级实现。面向用户的公开指引见 [SupplementaryTypeMappings.md](../SupplementaryTypeMappings.md)。 -**同一个 CF-bridged 类型有三种 mangling 形态**(AG probe 实测:手造 clang module 复刻 `objc_bridge` + `swift_name` 声明,5 处引用全解析为 `AttributeGraph.Graph` / `.Subgraph`),各自的覆盖机制不同: +**同一个 CF-bridged 类型有两种 mangling 形态**(AG probe 实测:手造 clang module 复刻 `objc_bridge` + `swift_name` 声明,5 处引用全解析为 `AttributeGraph.Graph` / `.Subgraph`;当时还有第三种,见第 3 条),各自的覆盖机制不同: 1. **typedef 名**(`__C.AGGraphRef`,符号签名,typealias node → `.other` 类别):`Typedefs` 条目的改名表命中。 2. **storage / tag 名**(`__C.AGGraphStorage`,字段元数据的 foreign **class** descriptor,`.objcClass` 类别):条目按 C 语义归 `Tags`(值类型表),所以 `.objcClass` 查询在 class 表 miss 后**回退值类型表**。安全性论证:C 的 tag namespace 与 ObjC class namespace 理论上可同名共存,但 class 表先查先赢,「改名只在 tag 侧、同名 ObjC class 又真被引用」无已知真实实例;protocol 表仍绝不回退(`NSObject` 隔离不动)。系统 dyld cache 的 SwiftUI 里实测存在孤立的 `AGGraphStorage` descriptor 名,即此形态。 -3. **导入名直出**(`__C.Graph`,probe 实测:消费方二进制 emit 的 foreign descriptor 记录的是 **swift_name 之后**的拼写):identifier 已是最终拼写、无需也无从改名,缺的只是归属——因此 `TypeDatabase` 的归属同步(`registerAttribution(fromAPINotesIndex:)`)把改名反查表(`cNamesBySwiftName`)的 **SwiftName 拼写也登进归属表**(带点的嵌套改名如 `ProcessInfo.ActivityOptions` 不会以单 identifier 出现,跳过)。此登记对 SDK APINotes 同样生效(`NSDecimal → Decimal` 的 `__C.Decimal` 引用同理受益)。 +3. **导入名直出**(`__C.Graph`,已不再出现):消费方二进制 emit 的 foreign descriptor,名字字段记录的是 **swift_name 之后**的拼写,而且只是最后一截。提案 0023 之前描述符就按这个名字打印,`TypeDatabase` 的归属同步(`registerAttribution(fromAPINotesIndex:)`)因此把改名反查表(`cNamesBySwiftName`)里不带点的 SwiftName spelling 也登进归属表。0023 起描述符按 import info 里的 ABI name 打印(`__C.AGGraphRef`、`__C.NSDecimal`),走第 1、2 条。2026-10-01 用 macOS 27 的 SwiftUICore 实测 `dump`:0023 之前 `__C.Graph` / `__C.Subgraph` 共 107 行,之后为 0。那段登记却不能删:它排在 C 名登记之后,还决定着几个模块的 APINotes 都列出的 C 名归谁。Foundation 与 AppKit 的 APINotes 为了标注 category 方法也列了 `NSObject`,C 名登记是后加载的文件说了算;ObjectiveC 的条目把 `NSObject` 改名为它自己,这个 SwiftName spelling 最后登记,`NSObject` 才回到 ObjectiveC。2026-10-03 试删后,AppKit 的 `--resolve-c-module-names` 输出里 `ObjectiveC.NSObject` 108 行、`ObjectiveC.NSObjectProtocol` 22 行全部变成 `Foundation.…`,于是撤回,并用 `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings` 钉住。 映射内容立场:**宁缺毋滥**——条目错了输出跟着错,公开指引要求每条改名都有头文件级一手证据(重建头文件声明或 OpenGraph 这类文档化项目)。 diff --git a/Documentations/ObjCCommandLine.md b/Documentations/ObjCCommandLine.md index 6bcaa7c6e..975d5be57 100644 --- a/Documentations/ObjCCommandLine.md +++ b/Documentations/ObjCCommandLine.md @@ -81,7 +81,7 @@ removed and nothing annotated. | Switch | Effect | |---|---| -| `--strip-protocol-conformance` | Drop the `` list, and the members those protocols already declare | +| `--strip-protocol-conformance` | Drop every property and method the adopted protocols declare — required and optional, along the whole protocol chain — as a hand-written header leaves them out; the `` list stays | | `--strip-overrides` | Drop members that merely override a superclass member (**strips less on files — see below**) | | `--strip-synthesized-ivars` | Drop ivars synthesized by `@property` | | `--strip-synthesized-methods` | Drop getters and setters synthesized by `@property` | diff --git a/Documentations/ObjCCommandLine_zh.md b/Documentations/ObjCCommandLine_zh.md index 9ba6b1e4b..b53d0b5ce 100644 --- a/Documentations/ObjCCommandLine_zh.md +++ b/Documentations/ObjCCommandLine_zh.md @@ -74,7 +74,7 @@ Objective-C 这边目前不读取别的镜像(见「必须知道的四件事 | 开关 | 作用 | |---|---| -| `--strip-protocol-conformance` | 去掉 `` 列表,以及这些协议已经声明过的成员 | +| `--strip-protocol-conformance` | 去掉所遵循协议声明的全部属性和方法(必需与可选,沿整条协议继承链),像手写头文件那样不重复声明;`` 列表保留 | | `--strip-overrides` | 去掉只是覆写父类的成员(**分析单个文件时剥得更少,见下文**) | | `--strip-synthesized-ivars` | 去掉 `@property` 合成的 ivar | | `--strip-synthesized-methods` | 去掉 `@property` 合成的 getter / setter | diff --git a/Documentations/README.md b/Documentations/README.md index 2f7103ea6..668d4d470 100644 --- a/Documentations/README.md +++ b/Documentations/README.md @@ -38,6 +38,8 @@ Public, reference-style documentation. Bilingual (English + 中文). records of pure-Swift classes, the baseline `formatVersion` contract, and `dump`'s stderr-only empty-result notes. - 中文版:**[Objective-C 命令行 —— `swift-section objc`](ObjCCommandLine_zh.md)** +- **[SwiftSectionKit — everything `swift-section` does, as a library](SwiftSectionKit.md)** — the guide for the `SwiftSectionKit` product (evolution proposal `swift-section-kit`): one request type per subcommand, and the output contract the protocol's signature does not show — concurrent calls, three separate channels, a newline after every product piece, file destinations bypassing the output, diagnostics worded as the command line prints them. + - 中文版:**[SwiftSectionKit —— `swift-section` 的全部功能,以库的形式提供](SwiftSectionKit_zh.md)** Everything under [`Internal/`](Internal/) is maintainer-facing. @@ -67,6 +69,7 @@ selects names using each access's offset and width. | Doc | What it covers | |---|---| | [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 的三步。 | | [Modules/SwiftInterface.md](Internal/Modules/SwiftInterface.md) | SwiftInterface 模块参考:编排层定位与三种输出产品(单版本 interface / 两侧 diff / N 路 evolution),五个子系统(核心 builder、opaque 解析、共享 union 走查、diff 渲染、evolution 渲染)的分工、契约与测试锚点,消费入口速查。 | @@ -105,7 +108,7 @@ 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, including the 2026-05 model-coverage completion pass (`runtimePointer(at:)` extension-not-requirement decision). | +| [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 的绑定陷阱、收成一份时修掉的分歧与性能处理。 | | [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`。 | @@ -153,7 +156,11 @@ selects names using each access's offset and width. | [Evolutions/0052-objc-custom-class-name.md](Evolutions/0052-objc-custom-class-name.md) | **提案 0052(Implemented)**:改过 ObjC 运行时名的 Swift 类——`@objc(Name)` 让类对象的 `class_ro_t` 名字不再是 `_TtC…` mangling(macOS 27 AppKit 的 `NSColorModel`、`NSScrollPocket`),今天接口看不出来;而且成员恢复与布局引擎都靠 demangle 运行时名配对,这些类一律配不上(`NSScrollPocket.layout()` 丢了 `override` / `@objc`)。改用类元数据自带的描述符指针配对(classlist 之外的 resilient 父类类走 `ResilientClassMetadataPattern`),interface 与 dump 打印 `@objc(Name)`,原生 Swift 类印 `@_objcRuntimeName(Name)`,并让两处既有配对覆盖改过名的类。 | | [Evolutions/0053-shared-cache-composition-and-eviction-registry.md](Evolutions/0053-shared-cache-composition-and-eviction-registry.md) | **提案 0053(Implemented)**:按镜像缓存整治——`SharedCache` 的并发核心不动,改它周围四件事:每实例的内存压力 `removeAll()` 绕过「最后一个 indexer 才驱逐」的认领规则且回收不到被活引用钉住的存储,整个去掉、改为注册表暴露显式 API;基类 `buildStorage(for: some MachORepresentableWithCache)` 把读者类型擦掉、6 个子类各自 `as?` 再分派,改为不可继承的组合式原语、构建闭包在调用点给;每次查找把 identifier 装箱成 `AnyHashable` 并哈希整条路径,改为只哈希 UUID / 指针的 `SharedCacheKey`;同线程同键重入静默死锁,改为带信息的 precondition。驱逐收口到下沉至 `MachOCaches` 的 `SharedCacheRegistry`(eviction group 加 dependents 表),两个手写 Store 并入。暂不改名,句柄 API 待测量后另议。 | | [Evolutions/0054-interface-descriptor-only-vtable-members.md](Evolutions/0054-interface-descriptor-only-vtable-members.md) | **提案 0054(Implemented)**:interface 按 vtable 槽位顺序打印类成员,并补上 descriptor-only member——剥掉 local 符号的镜像(系统 dyld cache 里的 AppKit)里,class 的 public 方法实现没有符号、只剩 `Tj` / `Tq`,interface 过去只从实现符号建成员,于是 AppKit 的 `NSTableViewDiffableDataSource` / `NSCollectionViewDiffableDataSource` 只剩 `init` 和 `deinit`(整个 AppKit 少 53 个成员)。改为从 vtable 槽出发、用 `Tq` 建成员,vtable 成员按槽位顺序打印,没有名字的槽跳过;顺带修掉闭包参数返回 Optional 时 `init` 被误打成 `init?`。ABI snapshot `formatVersion` 5 → 6。 | -| [Glossary.md](Glossary.md) | **项目术语表**:sweep、腿(reader-split leg)、名字来源、detach、物化、permutation 二分、store-identity vs 结构相等、wrapper vs descriptor、桶、trailing objects、SymbolicDemangler(旧名 MetadataReader)、`_symbolic` 符号与被引用者、TypeImportInfo 等本项目自造词与特定用法;跨项目通用术语在全局表(iCloud Global),不重复登记。提案与专题文档引入新术语时同批登记。 | +| [Evolutions/0055-group-sources-by-layer.md](Evolutions/0055-group-sources-by-layer.md) | **提案 0055(Implemented)**:`Sources/` 按层分组——31 个平铺的 target 分进 `Support/`、`MachO/`、`ABI/`、`Analysis/`、`Declaration/`、`Output/`、`Executables/`、`TestSupport/` 八个目录,`Package.swift` 逐个声明 `path:`;target / product / 模块名不变,下游无感。连带修正靠 `#filePath` 深度找 fixture 与扫描源码的几处代码,以及 CI 里写死的 `Version.swift` 路径。 | +| [Evolutions/0057-reading-context-migration.md](Evolutions/0057-reading-context-migration.md) | **提案 0057(Implemented)**:读取接口统一到 `ReadingContext`——ABI 层每个读取接口有传 `machO`、直接用指针、传 `ReadingContext` 三份各自手写的实现,已经漂移(`ReadingContext` 版在 `MachOFile` 上漏了 rebase / bind,指针版遇到坏指针直接崩)。收成一份:`ReadingContext` 版补齐正确行为后成为唯一实现,旧接口一行转发、0.22.0 废弃、0.23.0 删除;范围含上层 61 个纯读取接口,为此 `ReadingContext` 新增缓存范围声明。 | +| [Evolutions/0058-swift-section-kit.md](Evolutions/0058-swift-section-kit.md) | **提案 0058(Implemented)**:把 swift-section 的功能抽成对外 product `SwiftSectionKit`——每个子命令一个按用途建模的请求类型(`DumpRequest`、`ABIDiffRequest`……),输出交给调用方注入的输出端,测试换成内存记录器即可断言;CLI 只剩 flag 声明与校验、flag → 请求映射、库错误翻译回历史文案、诊断的流路由和退出码。输出逐字节保持,只有两处有意偏差(写流统一走 `fputs` / `fwrite`;参数层面的错误先于打开二进制报出)。 | +| [Evolutions/0059-dump-declaration-identity.md](Evolutions/0059-dump-declaration-identity.md) | **提案 0059(Implemented)**:`DumpRequest` / `ObjCDumpRequest` 交出每个顶层声明时附上种类与名字(`DumpedDeclaration`),`SwiftSectionOutput` 新增带默认实现的 `write(_:declaring:)` 接收;默认实现转给 `write(_:)`,CLI 输出逐字节不变。让宿主不必自己重建索引就能按声明拆文件(首个宿主:ReverseEngineeringToolbox 的「每个类型一个文件」)。 | +| [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 的数量与内存实测。 | | [DeclarationModelMemoryFootprint.md](Internal/DeclarationModelMemoryFootprint.md) | NodeStore 迁移后的声明模型内存足迹量测:`TypeDefinition` 1272 字节的逐属性构成(两份 `TypeContextWrapper` 占 74%)、`TypeContextWrapper` 按最大 case `Class` 定尺的原因、`parentContext` 是被当成永久字段的临时值、mini-store 增殖与 `MetadataReaderCache` 仍持 `Node` 树;含四项可回收估算(合计 ~8–10%)与「当前不建议实施、应先剖析其余 90%」的结论。 | diff --git a/Documentations/SupplementaryTypeMappings.md b/Documentations/SupplementaryTypeMappings.md index 0ed5ff72e..f8e6e899c 100644 --- a/Documentations/SupplementaryTypeMappings.md +++ b/Documentations/SupplementaryTypeMappings.md @@ -3,9 +3,11 @@ `swift-section interface --resolve-c-module-names` resolves `__C.NSString` to `Foundation.NSString` by indexing the SDK. Private frameworks such as **AttributeGraph** have no SDK module at all — no headers, no `.swiftmodule`, -no `.apinotes` — so nothing can be indexed, and their `swift_name` renames -(`AG_SWIFT_NAME(Graph)`) exist *only* in headers: no tool can recover -`AttributeGraph.Graph` from a binary. That knowledge has to come from outside. +no `.apinotes` — so nothing can be indexed. A binary keeps little of their +`swift_name` renames (`AG_SWIFT_NAME(Graph)`): a type descriptor records the +last component, `Graph`, but neither the module nor an enclosing type, so no +tool can recover `AttributeGraph.Graph` from a binary. That knowledge has to +come from outside. Supplementary type mappings are that outside channel: user-provided [APINotes](https://clang.llvm.org/docs/APINotes.html) files loaded on top of @@ -51,11 +53,13 @@ A CF-bridged type (`CF_BRIDGED_TYPE` / `objc_bridge` typedefs like | Spelling | Where it appears | Section | |---|---|---| -| Typedef name (`AGGraphRef`) | symbol signatures | `Typedefs` | +| Typedef name (`AGGraphRef`) | symbol signatures and field metadata | `Typedefs` | | Storage/tag name (`AGGraphStorage`) | field-metadata foreign descriptors | `Tags` | -(A third shape — the imported Swift name itself, `__C.Graph` — is derived -from `SwiftName` automatically; no extra entry is needed.) +The imported Swift name itself, `__C.Graph`, is not a shape to register: +since 0.20.0 swift-section spells a type descriptor by the C name its import +info records, the way the compiler mangles it, not by the Swift name it +also records. ### Choosing the section diff --git a/Documentations/SwiftEnumLayout.md b/Documentations/SwiftEnumLayout.md index e086396bf..dd9a4b854 100644 --- a/Documentations/SwiftEnumLayout.md +++ b/Documentations/SwiftEnumLayout.md @@ -876,14 +876,14 @@ This project implements the ABI twice, for two different trust models. Used when the enum's metadata is loaded in-process (`MachOImage`). Pipeline (in `RuntimeFieldLayoutBackend` + `SwiftInspection`): -1. **Formulas first.** `EnumLayoutCalculator` (in `Sources/SwiftInspection/EnumLayoutCalculator.swift`) is a line-audited port of the algorithms in Part 2 — `calculateSinglePayload`, `calculateMultiPayload` (spare bits, from the `__swift5_mpenum` mask), `calculateTaggedMultiPayload`. It produces per-case projections including per-byte **fixed-bit masks** (3.3) and per-strategy XI counts (2.6.6, 2.7.4). +1. **Formulas first.** `EnumLayoutCalculator` (in `Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift`) is a line-audited port of the algorithms in Part 2 — `calculateSinglePayload`, `calculateMultiPayload` (spare bits, from the `__swift5_mpenum` mask), `calculateTaggedMultiPayload`. It produces per-case projections including per-byte **fixed-bit masks** (3.3) and per-strategy XI counts (2.6.6, 2.7.4). 2. **Payload XI from the real VWT.** The payload's XI count is read from its live value witness table. An `indirect` payload is special-cased to the heap-object count `0x7FFF_FFFF` (2.5.2). If the payload type cannot be resolved, the count is *inverted* from the enum's own VWT: for a payload-sized layout, `payloadXI = enumXI + emptyCases` exactly reverses the runtime's subtraction (2.5.1) — and for an overflow layout it is not invertible, so the layout is dropped rather than guessed. -3. **Exact patterns from the witnesses.** `RuntimeEnumCaseProjector` (`Sources/SwiftInspection/RuntimeEnumCaseProjector.swift`) resolves XI patterns (3.4) by *running* the enum's own `destructiveInjectEnumTag` witness twice per case — once into an all-`0x00` buffer, once into all-`0xFF` — and keeping the bytes both runs agree on: those were deterministically written. Empty cases must round-trip through `getEnumTag`, or the projection is rejected. (The dual-baseline trick is valid precisely because single-payload injection *stores* patterns; a spare-bits injection ORs, so that strategy takes its patterns from the mask instead.) +3. **Exact patterns from the witnesses.** `RuntimeEnumCaseProjector` (`Sources/Analysis/SwiftInspection/RuntimeEnumCaseProjector.swift`) resolves XI patterns (3.4) by *running* the enum's own `destructiveInjectEnumTag` witness twice per case — once into an all-`0x00` buffer, once into all-`0xFF` — and keeping the bytes both runs agree on: those were deterministically written. Empty cases must round-trip through `getEnumTag`, or the projection is rejected. (The dual-baseline trick is valid precisely because single-payload injection *stores* patterns; a spare-bits injection ORs, so that strategy takes its patterns from the mask instead.) 4. **Cross-check against ground truth.** The assembled layout's implied total size must equal the enum VWT's size, or the layout is discarded — derived inputs (payload sizes, spare masks) can be subtly wrong, and a confident wrong answer is worse than none. #### The static path — offline, honest about limits -Used for `MachOFile` (no process). `EnumLayoutBridge` (`Sources/SwiftLayout/EnumLayoutBridge.swift`) resolves, in order: +Used for `MachOFile` (no process). `EnumLayoutBridge` (`Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift`) resolves, in order: 1. **The compiler's own answer when available:** the `__swift5_builtin` whole-type descriptor (size/stride/alignment/XI as IRGen computed them) — the same source RemoteInspection trusts. 2. **Structural computation otherwise:** payload types are resolved recursively (through the image's dependency closure), the `__swift5_mpenum` mask feeds `calculateMultiPayload`, and — going one step beyond the official offline implementation — **spare-bits XI counts are derived structurally** (`TypeLowering.cpp` never does this; it falls back to tagged XI without a builtin descriptor). @@ -925,10 +925,10 @@ In this repository: | File | Role | |---|---| -| `Sources/SwiftInspection/EnumLayoutCalculator.swift` | the formula port (all three strategies, per-case projections, fixed-bit masks) | -| `Sources/SwiftInspection/RuntimeEnumCaseProjector.swift` | witness-driven exact pattern projection | -| `Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` | runtime-path assembly: VWT reads, XI inversion, size cross-check | -| `Sources/SwiftLayout/EnumLayoutBridge.swift` | static-path assembly: builtin descriptors, `__swift5_mpenum`, structural fallback | +| `Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift` | the formula port (all three strategies, per-case projections, fixed-bit masks) | +| `Sources/Analysis/SwiftInspection/RuntimeEnumCaseProjector.swift` | witness-driven exact pattern projection | +| `Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` | runtime-path assembly: VWT reads, XI inversion, size cross-check | +| `Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift` | static-path assembly: builtin descriptors, `__swift5_mpenum`, structural fallback | | `Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift` | every formula in this document, verified against live memory | --- diff --git a/Documentations/SwiftEnumLayout_zh.md b/Documentations/SwiftEnumLayout_zh.md index 3026921d4..e82994af3 100644 --- a/Documentations/SwiftEnumLayout_zh.md +++ b/Documentations/SwiftEnumLayout_zh.md @@ -876,14 +876,14 @@ SizeFlags (高 16 位:内容大小,单位是 32 位字;最低 用在枚举 metadata 已经加载进本进程的场合(`MachOImage`)。流水线在 `RuntimeFieldLayoutBackend` + `SwiftInspection` 里: -1. **公式先行。** `EnumLayoutCalculator`(`Sources/SwiftInspection/EnumLayoutCalculator.swift`)是第二部分那些算法的逐行审计移植——`calculateSinglePayload`、`calculateMultiPayload`(spare bits,掩码来自 `__swift5_mpenum`)、`calculateTaggedMultiPayload`。它产出每个 case 的投影,包括按字节的**固定位掩码**(3.3)和按策略算出的 XI 数量(2.6.6、2.7.4)。 +1. **公式先行。** `EnumLayoutCalculator`(`Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift`)是第二部分那些算法的逐行审计移植——`calculateSinglePayload`、`calculateMultiPayload`(spare bits,掩码来自 `__swift5_mpenum`)、`calculateTaggedMultiPayload`。它产出每个 case 的投影,包括按字节的**固定位掩码**(3.3)和按策略算出的 XI 数量(2.6.6、2.7.4)。 2. **Payload 的 XI 取自真实 VWT。** payload 的 XI 数量从它活的 value witness table 里读。`indirect` payload 特判为堆对象的数量 `0x7FFF_FFFF`(2.5.2)。payload 类型解析不出来时,从枚举自己的 VWT *反推*:payload-sized 布局下,`payloadXI = enumXI + emptyCases` 就是运行时那步减法的精确逆运算(2.5.1);溢出布局反推不出来,那就宁可放弃这个布局也不去猜。 -3. **精确模式来自 witness 本体。** `RuntimeEnumCaseProjector`(`Sources/SwiftInspection/RuntimeEnumCaseProjector.swift`)靠*运行*枚举自己的 `destructiveInjectEnumTag` witness 来解析 XI 模式(3.4):每个 case 注入两次——一次注进全 `0x00` 的缓冲区、一次注进全 `0xFF` 的——两次结果一致的字节就是被确定性写入的字节。empty case 还必须经 `getEnumTag` 往返校验,否则整个投影被拒绝。(双基线这一招之所以成立,正是因为 single-payload 的注入是*覆盖写*;spare-bits 的注入是 OR,所以那个策略的模式改从掩码取得。) +3. **精确模式来自 witness 本体。** `RuntimeEnumCaseProjector`(`Sources/Analysis/SwiftInspection/RuntimeEnumCaseProjector.swift`)靠*运行*枚举自己的 `destructiveInjectEnumTag` witness 来解析 XI 模式(3.4):每个 case 注入两次——一次注进全 `0x00` 的缓冲区、一次注进全 `0xFF` 的——两次结果一致的字节就是被确定性写入的字节。empty case 还必须经 `getEnumTag` 往返校验,否则整个投影被拒绝。(双基线这一招之所以成立,正是因为 single-payload 的注入是*覆盖写*;spare-bits 的注入是 OR,所以那个策略的模式改从掩码取得。) 4. **对照 ground truth 交叉校验。** 组装出的布局,它推算出的总大小必须等于枚举 VWT 的 size,否则整个布局作废——派生输入(payload 大小、spare mask)可能出错,而一个自信的错误答案比没有答案更糟。 #### 静态路径——离线,对自己的极限诚实 -用在 `MachOFile`(没有进程)。`EnumLayoutBridge`(`Sources/SwiftLayout/EnumLayoutBridge.swift`)按下面的顺序解析: +用在 `MachOFile`(没有进程)。`EnumLayoutBridge`(`Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift`)按下面的顺序解析: 1. **优先拿编译器自己的答案**:`__swift5_builtin` 整型布局描述符(IRGen 算出的 size/stride/alignment/XI 原样照录)——和 RemoteInspection 信任的是同一来源。 2. **没有就结构化计算**:payload 类型经镜像依赖闭包递归解析,`__swift5_mpenum` 的掩码喂给 `calculateMultiPayload`,而且——比官方离线实现更进一步——**spare-bits 的 XI 数量也结构化推导**(`TypeLowering.cpp` 从来不这么做;没有 builtin 描述符时它直接退回 tagged 的 XI)。 @@ -925,10 +925,10 @@ SizeFlags (高 16 位:内容大小,单位是 32 位字;最低 | 文件 | 角色 | |---|---| -| `Sources/SwiftInspection/EnumLayoutCalculator.swift` | 公式移植(三大策略、逐 case 投影、固定位掩码) | -| `Sources/SwiftInspection/RuntimeEnumCaseProjector.swift` | witness 驱动的精确模式投影 | -| `Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` | 运行时路径组装:VWT 读取、XI 反推、大小交叉校验 | -| `Sources/SwiftLayout/EnumLayoutBridge.swift` | 静态路径组装:builtin 描述符、`__swift5_mpenum`、结构化回退 | +| `Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift` | 公式移植(三大策略、逐 case 投影、固定位掩码) | +| `Sources/Analysis/SwiftInspection/RuntimeEnumCaseProjector.swift` | witness 驱动的精确模式投影 | +| `Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift` | 运行时路径组装:VWT 读取、XI 反推、大小交叉校验 | +| `Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift` | 静态路径组装:builtin 描述符、`__swift5_mpenum`、结构化回退 | | `Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift` | 本文每一条公式对照活内存的验证 | --- diff --git a/Documentations/SwiftSectionKit.md b/Documentations/SwiftSectionKit.md new file mode 100644 index 000000000..329de42c4 --- /dev/null +++ b/Documentations/SwiftSectionKit.md @@ -0,0 +1,96 @@ +# SwiftSectionKit — everything `swift-section` does, as a library + +`SwiftSectionKit` is the library behind the `swift-section` command-line tool. Every subcommand is one request type; you build the request, run it, and receive the product and the diagnostics through an output you supply. The command-line tool is a thin wrapper around it, so a request run from your own code produces exactly what the matching command line prints. + +中文版:[SwiftSectionKit_zh.md](SwiftSectionKit_zh.md) + +## Adding it + +```swift +.product(name: "SwiftSectionKit", package: "MachOSwiftSection"), +``` + +Declare the products of every other module whose types you name as well — `SwiftOutputTransformer` for `Transformer.SwiftConfiguration`, `SwiftDiffing` for `ABIDiff` and `ABISnapshotDocument`, `SwiftDeclaration` for `SwiftIndexEvents.Handler`, and so on. + +## Quick start + +```swift +import SwiftSectionKit + +final class CollectingOutput: SwiftSectionOutput, @unchecked Sendable { + private let lock = NSLock() + private(set) var text = "" + + func write(_ product: SwiftSectionProduct) { + lock.withLock { + if case .text(let line) = product { + text += line + "\n" + } + } + } + + func report(_ diagnostic: SwiftSectionDiagnostic) {} +} + +let output = CollectingOutput() +let outcome = try await ABIDiffRequest( + old: .path("Old.framework/Old"), + new: .path("New.framework/New"), + report: .changeList +).run( + output: output, + environment: SwiftSectionEnvironment(generator: GeneratorIdentity(name: "MyTool", version: "1.0")) +) +if outcome.hasBreakingChange == true { + // fail the build +} +``` + +## The requests + +| Request | Command line | Returns | +|---|---|---| +| `DumpRequest` | `swift-section dump` | — | +| `InterfaceRequest` | `swift-section interface` | — | +| `ABISnapshotRequest` | `swift-section snapshot` | the `ABISnapshotDocument` | +| `ABIDiffRequest` | `swift-section diff` | `ABIDiffOutcome` (the diff, `hasBreakingChange`) | +| `ABIEvolutionRequest` | `swift-section evolution` | `ABIEvolutionOutcome` (the evolution, `hasBreakingChange`) | +| `TransformerTokensRequest`, `TransformerTemplatesRequest`, `TransformerConfigurationRequest` | `swift-section transformer tokens / templates / config` | — | +| `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 | + +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. + +## The output contract + +These are the rules an implementation of `SwiftSectionOutput` must honour. None of them is visible in the protocol's signature. + +- **It is called concurrently.** `diff` and `evolution` index their inputs side by side, and each in-flight input reports through the same output. Protect any state with a lock. +- **Three channels, kept apart.** `write(_:)` receives the product only. `report(_:)` receives progress lines, warnings, notes and per-declaration errors. `indexEventHandlers(forInputLabeled:)` returns the handlers that hear about indexing degradations; the default returns none, which leaves those to `os_log`. The label names the input when a request indexes several (`"old"`, `"new"`, a version label). +- **Every product piece is followed by a newline when printed.** To reproduce `swift-section`'s stdout byte for byte, print each `.declarations(_:)` (its `.string`, or colored by its semantic types), `.text(_:)`, `.annotatedInterface(_:style:)` and `.data(_:)` followed by `"\n"`. +- **A file destination bypasses the output.** With `destination: .file(path:)`, the request writes the file itself, the way the command line writes `-o`, and the output receives diagnostics only. One exception: the verdict line of a `.summary` diff report goes to the output even then, as it always has on the command line. +- **`.annotatedInterface` lines carry their own coloring rule.** `InterfaceAnnotationStyle.lineKinds(of:)` classifies each line as added, removed, modified, header or plain — the rule `swift-section` colors by. +- **`dump` and `objc dump` say what each declaration is.** Every top-level declaration they hand over arrives through `write(_:declaring:)` with a `DumpedDeclaration`: the Swift section or the Objective-C kind it comes from, and its name. A conformance and an associated type are named after the type they extend, spelled as that type's own name is, so the pieces of one type can be filed together; a Swift name that could not be rendered is `nil`. The default implementation forwards to `write(_:)`, so an output that only prints needs nothing more. Everything else — a header, the empty line after each Objective-C declaration, the single piece of an `interface` — comes through `write(_:)`. + +## Diagnostics + +A `SwiftSectionDiagnostic` is a severity and a message. The message is the line exactly as `swift-section` prints it, so some messages name command-line options (`warning: --supplementary-apinotes path does not exist: …`). Severities let a host filter: show warnings, drop progress. + +Where the command line prints a diagnostic is the command line's business: it writes `interface`'s progress lines and `dump`'s per-declaration errors to stdout and everything else to stderr. A host chooses for itself. + +## 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. + +`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. + +## The environment + +`SwiftSectionEnvironment` holds what a request stamps into its product without computing it: the generator's name and version (interface headers, snapshot provenance) and the current date (snapshot provenance's `createdAt`). Pass your own tool's identity; pass a fixed date in tests to get the same bytes on every run. + +## Source compatibility + +`SwiftSectionKit` is distributed as source, like the rest of the package. New request fields arrive with default values, so existing calls keep compiling. The enums a caller constructs — `ABIDiffRequest.Report`, `DumpSection`, `ObjCDeclarationKind` and the like — may gain cases in a later release; build them, but do not rely on switching over them exhaustively. So may `DumpedDeclaration`, which a host only receives. diff --git a/Documentations/SwiftSectionKit_zh.md b/Documentations/SwiftSectionKit_zh.md new file mode 100644 index 000000000..6a5905f1b --- /dev/null +++ b/Documentations/SwiftSectionKit_zh.md @@ -0,0 +1,96 @@ +# SwiftSectionKit —— `swift-section` 的全部功能,以库的形式提供 + +`SwiftSectionKit` 是 `swift-section` 命令行背后的库。每个子命令对应一个请求类型:构造请求、运行它,产物和诊断通过你提供的输出端交回来。命令行本身只是它的一层包装,所以在你自己的代码里运行一个请求,得到的就是对应命令行打印的内容。 + +English: [SwiftSectionKit.md](SwiftSectionKit.md) + +## 引入 + +```swift +.product(name: "SwiftSectionKit", package: "MachOSwiftSection"), +``` + +用到其他模块的类型时,把对应的 product 也声明上——`Transformer.SwiftConfiguration` 来自 `SwiftOutputTransformer`,`ABIDiff` 与 `ABISnapshotDocument` 来自 `SwiftDiffing`,`SwiftIndexEvents.Handler` 来自 `SwiftDeclaration`,依此类推。 + +## 快速上手 + +```swift +import SwiftSectionKit + +final class CollectingOutput: SwiftSectionOutput, @unchecked Sendable { + private let lock = NSLock() + private(set) var text = "" + + func write(_ product: SwiftSectionProduct) { + lock.withLock { + if case .text(let line) = product { + text += line + "\n" + } + } + } + + func report(_ diagnostic: SwiftSectionDiagnostic) {} +} + +let output = CollectingOutput() +let outcome = try await ABIDiffRequest( + old: .path("Old.framework/Old"), + new: .path("New.framework/New"), + report: .changeList +).run( + output: output, + environment: SwiftSectionEnvironment(generator: GeneratorIdentity(name: "MyTool", version: "1.0")) +) +if outcome.hasBreakingChange == true { + // 让构建失败 +} +``` + +## 请求一览 + +| 请求 | 对应命令行 | 返回 | +|---|---|---| +| `DumpRequest` | `swift-section dump` | — | +| `InterfaceRequest` | `swift-section interface` | — | +| `ABISnapshotRequest` | `swift-section snapshot` | `ABISnapshotDocument` | +| `ABIDiffRequest` | `swift-section diff` | `ABIDiffOutcome`(diff 本身与 `hasBreakingChange`) | +| `ABIEvolutionRequest` | `swift-section evolution` | `ABIEvolutionOutcome`(evolution 本身与 `hasBreakingChange`) | +| `TransformerTokensRequest`、`TransformerTemplatesRequest`、`TransformerConfigurationRequest` | `swift-section transformer tokens / templates / config` | — | +| `ObjCDumpRequest` | `swift-section objc dump` | `ObjCDumpRequest.Outcome`(找到了什么) | +| `ObjCInterfaceRequest` | `swift-section objc interface` | — | +| `ObjCAPISnapshotRequest`、`ObjCAPIDiffRequest`、`ObjCAPIEvolutionRequest` | `swift-section objc snapshot / diff / evolution` | 文档 / outcome | + +互斥的选项是一个 enum 而不是几个开关:`ABIDiffRequest.Report` 只能是 change list、summary、JSON、annotated interface 之一,不会同时是两个。命令行上一个 flag 隐含另一个的(`--emit-expanded-field-offsets` 隐含字段偏移),请求里是一个值同时表达两者(`FieldOffsetComments.expanded`)。 + +二进制用 `MachOSource` 指明:瘦或胖的文件、dyld shared cache 文件里的一个镜像、或运行系统 cache 里的一个镜像。`snapshot`、`diff`、`evolution` 收 `SnapshotSource.path`,它可以指向二进制,也可以指向 snapshot 文档;和命令行一样,按文件第一个非空白字节区分。 + +## 输出端契约 + +实现 `SwiftSectionOutput` 必须遵守下面几条,它们都不在协议签名里。 + +- **会被并发调用。** `diff` 和 `evolution` 并行索引多个输入,每个进行中的输入都通过同一个输出端汇报。内部状态要加锁。 +- **三路分开。** `write(_:)` 只收产物;`report(_:)` 收进度、警告、提示和单个声明的错误;`indexEventHandlers(forInputLabeled:)` 返回接收索引降级事件的 handler,默认一个都不返回,这些事件就落到 `os_log`。请求索引多个输入时,label 指明是哪一个(`"old"`、`"new"`、版本标签)。 +- **每块产物打印时后面跟一个换行。** 要逐字节复现 `swift-section` 的 stdout,就把每个 `.declarations(_:)`(取 `.string`,或按语义类型着色)、`.text(_:)`、`.annotatedInterface(_:style:)`、`.data(_:)` 后面各补一个 `"\n"` 打印出来。 +- **文件目的地不经过输出端。** `destination: .file(path:)` 时由请求自己写文件,写法和命令行的 `-o` 一样,输出端只收诊断。唯一例外:`.summary` 报告的结论行即使在这种情况下也写给输出端,命令行一直如此。 +- **`.annotatedInterface` 自带着色规则。** `InterfaceAnnotationStyle.lineKinds(of:)` 把每一行归为 added、removed、modified、header、plain 之一,`swift-section` 就按这个着色。 +- **`dump` 和 `objc dump` 会说明每个声明是什么。** 它们交出的每个顶层声明都经 `write(_:declaring:)` 到达,附一个 `DumpedDeclaration`:来自哪个 Swift section 或哪种 Objective-C 声明,以及名字。conformance 和 associated type 以它们所扩展的类型命名,拼法与那个类型自己的名字相同,所以同一个类型的几块可以归到一起;解析不出名字的 Swift 声明,名字为 `nil`。默认实现转给 `write(_:)`,只管打印的输出端什么都不用加。其余的产物——header、每个 Objective-C 声明后面的空行、`interface` 的那一整块——照旧经 `write(_:)` 到达。 + +## 诊断 + +`SwiftSectionDiagnostic` 是一个级别加一条消息。消息就是 `swift-section` 打印的那一行原文,所以有些消息里带命令行选项名(`warning: --supplementary-apinotes path does not exist: …`)。宿主可以按级别过滤:显示警告、丢掉进度。 + +诊断写到哪里由命令行自己决定:它把 `interface` 的进度行和 `dump` 的单个声明错误写到 stdout,其余写到 stderr。宿主自己决定自己的去处。 + +## 错误 + +抛出的错误不提命令行选项:`MachOSourceError`(胖二进制没给架构、没有那个切片、cache 里没有那个镜像)、`SnapshotSourceError.binaryRequired(path:)`(把 snapshot 文档交给了 annotated interface)、`AvailabilityPlatformInferenceError`(让 annotated evolution 从输入推断 `@available` 平台,可某个输入的平台在 `@available` 里没有名字,或者输入之间平台不一致)、`ObjCDeclarationLookupError`。来自下层的错误原样透传——文件不存在、snapshot 文档格式版本不支持、`ABIEvolutionError.labelCountMismatch`。 + +`swift-section` 把第一类错误翻译回它一直打印的文案,并把用法错误报成 validation error(退出码 64)。宿主想用自己的措辞,也照这样做。 + +## 环境 + +`SwiftSectionEnvironment` 装的是请求会盖进产物、但不由它自己计算的东西:生成器的名字和版本(interface header、snapshot provenance),以及当前时间(snapshot provenance 的 `createdAt`)。传你自己工具的身份;测试里传固定时间,每次运行就能得到相同的字节。 + +## 源码兼容性 + +`SwiftSectionKit` 和包里其他模块一样以源码分发。请求的新字段一律带默认值,已有的调用照常编译。调用方构造的 enum——`ABIDiffRequest.Report`、`DumpSection`、`ObjCDeclarationKind` 之类——以后的版本可能加 case;可以构造它们,但不要依赖对它们做穷举 `switch`。宿主只接收不构造的 `DumpedDeclaration` 也一样。 diff --git a/Package.swift b/Package.swift index 49512777b..a34029eb3 100644 --- a/Package.swift +++ b/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version: 6.2 +// swift-tools-version: 6.3 // The swift-tools-version declares the minimum version of Swift required to build this package. @preconcurrency import PackageDescription @@ -74,8 +74,6 @@ extension Package.Dependency { } } -let MachOKitVersion: Version = "0.46.1" - let isSilentTest = envEnable("MACHO_SWIFT_SECTION_SILENT_TEST", default: false) var testSettings: [SwiftSetting] = [] @@ -92,7 +90,7 @@ var dependencies: [Package.Dependency] = [ .Semantic, .Capstone, - .package(url: "https://github.com/swiftlang/swift-syntax.git", "509.1.0" ..< "604.0.0"), + .package(url: "https://github.com/swiftlang/swift-syntax.git", "602.0.0" ..< "605.0.0"), .package(url: "https://github.com/apple/swift-async-algorithms", from: "1.0.4"), .package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.1"), .package(url: "https://github.com/apple/swift-collections", from: "1.2.0"), @@ -125,9 +123,18 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/MachOKit.git", - // 0.52.103 stops reading chained-fixup starts for a segment that has - // none, which crashed on a dylib with no `__DATA` segment. - "0.52.103" ..< "0.53.0", + // 0.54.101 is the fork's release over upstream 0.54.0. It keeps the + // fixes the 0.52 line needed: no chained-fixup starts read for a + // segment that has none, which crashed on a dylib with no `__DATA` + // segment; no rebase target for a slot holding no pointer instead + // of a trap; and a file handle's identity released with the + // handle, which MachOObjCSection keys its mapping on. It also + // reads an image without an export trie as exporting nothing: + // 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", ), ) @@ -138,9 +145,16 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/MachOKitExtensions", - // 0.1.2 decides whether an in-process image is in the shared cache - // from its header flag, not from where it happens to be loaded. - from: "0.1.2", + // 1.0.0 no longer exports the throwing `init(bitPattern:)`, which + // Utilities now declares; an earlier release would make every + // call ambiguous. 1.1.0 keys an image read from a dyld cache by + // 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. + // 1.1.2 adds `FullDyldCache.cachedHost`, the system cache opened + // once per process rather than once per dependency locator. + from: "1.1.2", ), ) @@ -151,9 +165,15 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/MachOObjCSection.git", - // 0.8.106 is the first release with ObjCDiffing, which the `objc` - // subcommands (snapshot / diff / evolution) are built on. - "0.8.106" ..< "0.9.0", + // 0.8.108 decodes the pointer slots of a dyld cache's method lists: + // earlier releases trapped on every image of the macOS 14.4-15.3.2 + // caches and lost protocol method names on older ones. 0.8.109 + // stops remapping a sub-cache file on every read of a cache opened + // from its main file alone. 0.8.110 reads the classes a simulator + // runtime's frameworks bind to their own exports (`-interposable`), + // which the static layout engine and the ObjC ancestor chain need, + // and names a legacy LC_DYLD_INFO file's bound superclass itself. + "0.8.110" ..< "0.9.0", ), ) } @@ -179,7 +199,7 @@ extension Package.Dependency { ), remote: .package( url: "https://github.com/MxIris-Reverse-Engineering/swift-semantic-string", - from: "0.3.0", + from: "0.4.0", ), ) @@ -293,6 +313,7 @@ extension Target { .product(name: "Dependencies", package: "swift-dependencies"), .product(name: "AsyncAlgorithms", package: "swift-async-algorithms"), ], + path: "Sources/Support/Utilities", ) static let MachOCaches = Target.target( @@ -302,6 +323,7 @@ extension Target { .product(.MachOKitExtensions), .target(.Utilities), ], + path: "Sources/MachO/MachOCaches", ) /// Dependency resolution shared by every feature that needs a binary's @@ -316,6 +338,7 @@ extension Target { .product(.MachOKit), .product(.MachOKitExtensions), ], + path: "Sources/MachO/MachODependencies", ) static let MachOReading = Target.target( @@ -326,6 +349,7 @@ extension Target { .target(.Utilities), .product(name: "FileIO", package: "swift-fileio"), ], + path: "Sources/MachO/MachOReading", ) static let MachOResolving = Target.target( @@ -335,6 +359,7 @@ extension Target { .product(.MachOKitExtensions), .target(.MachOReading), ], + path: "Sources/MachO/MachOResolving", ) static let MachOSymbols = Target.target( @@ -347,6 +372,7 @@ extension Target { .target(.Utilities), .target(.MachOCaches), ], + path: "Sources/MachO/MachOSymbols", ) static let MachOPointers = Target.target( @@ -358,6 +384,7 @@ extension Target { .target(.MachOResolving), .target(.Utilities), ], + path: "Sources/MachO/MachOPointers", ) /// The reader / resolver / pointer layer as one import: everything the @@ -373,6 +400,7 @@ extension Target { .target(.MachOPointers), .target(.Utilities), ], + path: "Sources/MachO/MachOBase", ) static let MachOFoundation = Target.target( @@ -383,10 +411,12 @@ extension Target { .target(.MachOSymbols), .target(.MachODependencies), ], + path: "Sources/MachO/MachOFoundation", ) static let MachOSwiftSectionC = Target.target( name: "MachOSwiftSectionC", + path: "Sources/ABI/MachOSwiftSectionC", ) /// The ABI model. Depends on the reader / resolver / pointer layer only: @@ -400,6 +430,7 @@ extension Target { .target(.Utilities), .target(.MachOSwiftSectionC), ], + path: "Sources/ABI/MachOSwiftSection", ) /// Token-template transformers for rendered output — the `Transformer` @@ -419,6 +450,7 @@ extension Target { dependencies: [ .product(.OutputTransformer), ], + path: "Sources/Output/SwiftOutputTransformer", ) static let SwiftInspection = Target.target( @@ -436,6 +468,7 @@ extension Target { .target(.MachOSwiftSectionC), .target(.SwiftOutputTransformer), ], + path: "Sources/Analysis/SwiftInspection", ) /// Static aggregate-layout engine: computes Swift struct/class field @@ -456,6 +489,7 @@ extension Target { .target(.MachOSwiftSection), .target(.SwiftInspection), ], + path: "Sources/Analysis/SwiftLayout", ) /// Low-level Swift declaration rendering engine extracted from `SwiftDump`: @@ -482,6 +516,7 @@ extension Target { .target(.SwiftLayout), .target(.SwiftThunkAnalysis), ], + path: "Sources/Output/SwiftDeclarationRendering", ) /// Recovers what a **kind-9 accessor-function symbolic reference** points @@ -509,6 +544,7 @@ extension Target { .target(.MachOSwiftSection), .target(.SwiftInspection), ], + path: "Sources/Analysis/SwiftThunkAnalysis", ) static let SwiftDump = Target.target( @@ -525,6 +561,7 @@ extension Target { .target(.SwiftDeclarationRendering), .target(.SwiftThunkAnalysis), ], + path: "Sources/Output/SwiftDump", ) /// Shared declaration model: `TypeDefinition`, `ProtocolDefinition`, @@ -551,6 +588,7 @@ extension Target { .target(.SwiftDeclarationRendering), .target(.SwiftThunkAnalysis), ], + path: "Sources/Declaration/SwiftDeclaration", ) /// Builds the `SwiftDeclaration` model from a Mach-O image: @@ -576,6 +614,7 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftDeclarationRendering), ], + path: "Sources/Declaration/SwiftIndexing", ) /// Infers source-level Swift attributes (`@propertyWrapper`, @@ -594,6 +633,7 @@ extension Target { .target(.SwiftInspection), .target(.SwiftDeclaration), ], + path: "Sources/Declaration/SwiftAttributeInference", ) /// Diffs the Swift ABI of two indexed modules. Keys every declaration on @@ -606,6 +646,7 @@ extension Target { .product(.Demangling), .target(.SwiftDeclaration), ], + path: "Sources/Output/SwiftDiffing", ) /// Renders the `SwiftDeclaration` model as Swift source: @@ -628,6 +669,7 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftAttributeInference), ], + path: "Sources/Output/SwiftPrinting", ) /// Runtime generic-specialization engine (`GenericSpecializer`, @@ -649,6 +691,7 @@ extension Target { .target(.SwiftDeclaration), .target(.SwiftIndexing), ], + path: "Sources/Declaration/SwiftSpecialization", ) /// Orchestrator: `SwiftInterfaceBuilder` ties indexing and printing @@ -674,6 +717,7 @@ extension Target { .target(.SwiftSpecialization), .target(.SwiftDiffing), ], + path: "Sources/Output/SwiftInterface", ) /// Module-attribution index for `__C` types (evolution proposal 0009): @@ -692,23 +736,37 @@ extension Target { .product(name: "SourceKitD", package: "SourceKitD", condition: .when(platforms: [.macOS])), .product(name: "APINotes", package: "swift-apinotes", condition: .when(platforms: [.macOS])), ], + path: "Sources/Declaration/TypeIndexing", ) - static let swift_section = Target.executableTarget( - name: "swift-section", + // MARK: - Commands + + /// Everything `swift-section` does, as a library (evolution proposal + /// `swift-section-kit`): one request type per subcommand, its product and + /// diagnostics delivered to a host-supplied `SwiftSectionOutput`. The + /// executable is a wrapper around it — flag parsing, error wording, + /// stream routing and exit codes. + static let SwiftSectionKit = Target.target( + name: "SwiftSectionKit", dependencies: [ .target(.MachOFoundation), + .target(.MachOSwiftSection), .target(.SwiftDump), .target(.SwiftInspection), .target(.SwiftOutputTransformer), .target(.SwiftDeclaration), + .target(.SwiftDeclarationRendering), .target(.SwiftIndexing), .target(.SwiftPrinting), .target(.SwiftDiffing), .target(.SwiftInterface), .target(.TypeIndexing), - // The `objc` subcommand group (formerly the `objc-section` - // executable of MachOObjCSection). + .target(.Utilities), + .product(.MachOKit), + .product(.MachOKitExtensions), + .product(.Semantic), + .product(.Demangling), + .product(.OutputTransformer), .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), .product(name: "ObjCDiffing", package: "MachOObjCSection"), .product(name: "ObjCIndexing", package: "MachOObjCSection"), @@ -719,9 +777,31 @@ extension Target { // does not import. .product(name: "ObjCMetadataSource", package: "MachOObjCSection"), .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), + ], + path: "Sources/Commands/SwiftSectionKit", + ) + + static let swift_section = Target.executableTarget( + name: "swift-section", + dependencies: [ + .target(.SwiftSectionKit), + // What the wrapper names itself while mapping its flags onto the + // library's requests: `DependencySearchPath`, `DemangleOptions`, + // `Transformer.SwiftConfiguration`, `ConsoleEventHandler`, the + // ObjC generation options and C type presets. + .target(.MachOFoundation), + .target(.SwiftDump), + .target(.SwiftOutputTransformer), + .target(.SwiftDeclaration), + .target(.SwiftIndexing), + .product(.Semantic), + .product(.OutputTransformer), + .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), .product(name: "Rainbow", package: "Rainbow"), .product(name: "ArgumentParser", package: "swift-argument-parser"), ], + path: "Sources/Executables/swift-section", ) static let baseline_generator = Target.executableTarget( @@ -730,6 +810,7 @@ extension Target { .target(.MachOFixtureSupport), .product(name: "ArgumentParser", package: "swift-argument-parser"), ], + path: "Sources/Executables/baseline-generator", swiftSettings: testSettings, ) @@ -766,6 +847,7 @@ extension Target { .product(.SwiftCompilerPlugin), .product(.SwiftSyntaxBuilder), ], + path: "Sources/Support/MachOMacros", ) // MARK: - Testing @@ -792,6 +874,7 @@ extension Target { .product(.SwiftParser), .product(.SwiftSyntaxBuilder), ], + path: "Sources/TestSupport/MachOFixtureSupport", swiftSettings: testSettings, ) @@ -803,6 +886,7 @@ extension Target { name: "MachOTestingSupport", dependencies: [ .product(.MachOKit), + .product(.Demangling), .target(.MachOFoundation), .target(.MachOReading), .target(.MachOResolving), @@ -814,6 +898,7 @@ extension Target { .target(.SwiftSpecialization), .target(.SwiftInterface), ], + path: "Sources/TestSupport/MachOTestingSupport", swiftSettings: testSettings, ) @@ -821,6 +906,7 @@ extension Target { name: "MachOTestingSupportC", dependencies: [ ], + path: "Sources/TestSupport/MachOTestingSupportC", swiftSettings: testSettings, ) @@ -1023,6 +1109,8 @@ extension Target { name: "SwiftSectionCommandTests", dependencies: [ .target(.swift_section), + .target(.SwiftSectionKit), + .target(.MachOFoundation), .target(.SwiftOutputTransformer), .target(.SwiftDeclarationRendering), .target(.SwiftPrinting), @@ -1030,6 +1118,23 @@ extension Target { .product(name: "ObjCDeclarationRendering", package: "MachOObjCSection"), .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), .product(name: "ArgumentParser", package: "swift-argument-parser"), + .product(name: "Rainbow", package: "Rainbow"), + ], + swiftSettings: testSettings, + ) + + static let SwiftSectionKitTests = Target.testTarget( + name: "SwiftSectionKitTests", + dependencies: [ + .target(.SwiftSectionKit), + .target(.MachOFoundation), + .target(.SwiftDeclaration), + .target(.SwiftDiffing), + .target(.SwiftOutputTransformer), + .product(.Semantic), + .product(.OutputTransformer), + .product(name: "ObjCDiffing", package: "MachOObjCSection"), + .product(name: "ObjCOutputTransformer", package: "MachOObjCSection"), ], swiftSettings: testSettings, ) @@ -1068,6 +1173,8 @@ extension Target { dependencies: [ .target(.MachOTestingSupport), .target(.MachOFixtureSupport), + .target(.SwiftDeclaration), + .product(.Demangling), ], exclude: [ "Coverage/Fixtures/SampleSource.swift.txt", @@ -1133,6 +1240,7 @@ let package = Package( .library(.SwiftSpecialization), .library(.SwiftInterface), .library(.TypeIndexing), + .library(.SwiftSectionKit), .executable(.swift_section), ], dependencies: dependencies, @@ -1163,6 +1271,7 @@ let package = Package( .SwiftSpecialization, .SwiftInterface, .TypeIndexing, + .SwiftSectionKit, .MachOMacros, .MachOFixtureSupport, .MachOTestingSupport, @@ -1191,6 +1300,7 @@ let package = Package( .SwiftAttributeInferenceTests, .SwiftDiffingTests, .SwiftSectionCommandTests, + .SwiftSectionKitTests, .SwiftIndexingTests, .SwiftSpecializationTests, .SwiftInterfaceTests, diff --git a/README.md b/README.md index f7dcd5aad..f8dc0d408 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.21.0"), + .package(url: "https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection", from: "0.22.0"), ], targets: [ .target( @@ -85,6 +85,12 @@ Declare every product whose module you import. In particular, `MachOSwiftSection | `SwiftDeclarationRendering` | The comment rendering shared by dump and interface (field layouts, opaque types, specialized metadata). | | `SwiftOutputTransformer` | Token templates for the layout comments, shared with RuntimeViewer's settings UI. | +**The command-line tool as a library** + +| Product | Purpose | +| --- | --- | +| `SwiftSectionKit` | Everything `swift-section` does, one request type per subcommand (`DumpRequest`, `InterfaceRequest`, `ABIDiffRequest`, `ObjCDumpRequest`, …), with the product and diagnostics delivered to an output you supply. The `swift-section` executable is a thin wrapper around it. | + ### Usage #### Basic @@ -163,6 +169,36 @@ Generated interfaces reflect a wide range of Swift language features: - `ClassHierarchyDumper` — walk a class's inheritance chain across Swift/ObjC boundaries (requires `@_spi(Internals) import SwiftInspection`, `MachOImage` only). - `SymbolicDemangler` — demangle types, symbols, context descriptors, and build generic signatures against a Mach-O (requires `@_spi(Internals) import SwiftInspection`). Named `MetadataReader` before 0.20.0; the old name remains as a deprecated alias for one release. +#### 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. + +```swift +import SwiftSectionKit + +struct PrintingOutput: SwiftSectionOutput { + func write(_ product: SwiftSectionProduct) { + if case .text(let line) = product { + print(line) + } + } + + func report(_ diagnostic: SwiftSectionDiagnostic) {} +} + +let outcome = try await ABIDiffRequest( + old: .path("Old.framework/Old"), + new: .path("New.framework/New"), + report: .summary +).run( + output: PrintingOutput(), + environment: SwiftSectionEnvironment(generator: GeneratorIdentity(name: "MyTool", version: "1.0")) +) +// outcome.hasBreakingChange tells a CI gate whether the ABI broke. +``` + +The output contract — concurrent calls, three separate channels, a newline after every product piece, and the kind and name `dump` and `objc dump` attach to each declaration they hand over — is described in [SwiftSectionKit.md](Documentations/SwiftSectionKit.md). + ## swift-section CLI Tool ### Installation @@ -171,7 +207,7 @@ You can get the swift-section CLI tool in three ways: - **GitHub Releases**: Download from [GitHub releases](https://github.com/MxIris-Reverse-Engineering/MachOSwiftSection/releases) - **Homebrew**: Install via `brew install swift-section` -- **Build from Source**: Build with `./build-executable-product.sh` (requires Xcode 26.0 / Swift 6.2+ toolchain) +- **Build from Source**: Build with `./build-executable-product.sh` (requires Xcode 26.0 / Swift 6.2+ toolchain), or build and install in one step with `./install.sh [install-directory]` (defaults to `/usr/local/bin`, using `sudo` only when that directory is not writable) ### Usage @@ -506,6 +542,14 @@ swift-section evolution --interface v17/Foo.dylib v18/Foo.dylib v26/Foo.dylib -- swift-section evolution --interface --dyld-shared-cache -n SwiftUICore cache-17 cache-18 cache-26 --fail-on-breaking -o SwiftUICore-evolution.swift ``` +Add `--emit-available` to also spell a lifecycle as a genuine attribute: a declaration whose whole lifecycle one `@available` can express gets `@available(iOS, introduced: 18.0, obsoleted: 26.0)` on the line above it and keeps its comment. That takes one unbroken run of versions carrying the declaration, numeric version labels (`--labels 17.0,18.0,26.0`; file names do not count), and an addition or removal inside the axis; anything else, and every `modified` event, stays in the comment alone. `introduced:` names the first version on the axis that carries the declaration and `obsoleted:` the first one that no longer does — not necessarily the releases that really introduced or removed it, as a legend line says. The platform comes from every input's `LC_BUILD_VERSION`, a simulator counting as its device; an input whose platform `@available` has no name for (DriverKit), or inputs of different platforms, are an error. `--platform` names it instead. + +```bash +# @available attributes for the platform the inputs name, or the one given +swift-section evolution --interface --emit-available v17/Foo.dylib v18/Foo.dylib v26/Foo.dylib --labels 17.0,18.0,26.0 +swift-section evolution --interface --emit-available --platform macCatalyst v17/Foo v18/Foo v26/Foo --labels 17.0,18.0,26.0 +``` + #### transformer - Customize Comment Formats The memory-layout comments `dump` and `interface` emit are rendered from token diff --git a/Roadmaps/2026-09-29-objc-implementation-unresolved-members.md b/Roadmaps/2026-09-29-objc-implementation-unresolved-members.md new file mode 100644 index 000000000..fe03347c0 --- /dev/null +++ b/Roadmaps/2026-09-29-objc-implementation-unresolved-members.md @@ -0,0 +1,77 @@ +# `@objc @implementation` 类还解不出的成员与 ivar 类型(2026-09-29) + +用户问「为什么很多 `@objc @implementation` 类在 Swift 侧看不到方法、ObjCSection 把一些 ivar 打成 `Unknown`」,调研后查明了成因,也试了几条推断路线。 + +**当前状态:只落记录,推断部分的代码未改。** 用户裁定「先把能解补了,然后剩下的记下来」。符号明明在、库却漏读的那一处(`private` 属性与 `lazy var` 存储的 field offset global,名字节点是 `privateDeclName`)已在同一批次修复,见 [ProjectEvolutionLog](../Documentations/Internal/ProjectEvolutionLog.md) 第 72 节。本文只记还需要推断的部分。 + +## 现象 + +- macOS 26.7 的 AppKit 里有 38 个 `@implementation` 类,Swift 侧显示的成员与 AppKit 的 export trie 逐类一致,没有一个来自 local 符号。NSScreen 有 138 个 ObjC 方法,Swift 侧只有 6 个;NSCoordinateSpace 与 NSHostedViewScene 一个都没有;NSFontPanelColorWellVisualProvider 有 43 个 ObjC 方法,Swift 侧只有编译器合成的 `init()`。 +- 26.6.2 的 AppKit 里这些类共有 170 个 ivar,55 个拿到了 Swift 类型,全部来自导出的 field offset global(`…vpWvd`)。编码为空串的 61 个一个都没拿到。 +- ObjCSection 把编码为 `""` 和 `"?"` 的 ivar 打成 `Unknown`。 + +## 成因(都已核实) + +1. **编译器不给 `@implementation` 类发 field descriptor。** `lib/IRGen/GenReflection.cpp` 里,类有 `getObjCImplementationDecl()` 时 `needsFieldDescriptor = false`;这类类也没有 vtable 和 method descriptor。所以 Swift 名字和类型只存在于符号里:成员实现符号、field offset global(ivar 的 offset 槽位指向的就是它)、访问器。普通 Swift 类的字段类型记在 `__swift5_fieldmd` 里,是数据,strip 删不掉,这就是两者的差别。 +2. **符号是否留下,取决于源码写的访问级别。** `SILDeclRef::getDefinitionLinkage` 按访问级别定链接属性:`public` / `open` 导出;`internal` 是 hidden,链接后变成 local 符号;`private` 同样是 local 符号;`To` thunk 永远是 private。AppKit 在 cache 里剥掉了 local 符号,只剩导出的。SE-0436 不要求这些成员写 `public`(ObjC 侧能否调用由头文件决定),Apple 大多没写,于是大多数成员没有名字。编译器合成的 `override init()` 取被实现类的访问级别(`lib/Sema/CodeSynthesis.cpp` 的 `configureInheritedDesignatedInitAttributes`,导入的 ObjC 类是 public),所以它经常是唯一导出的成员。 +3. **ivar 编码规则**(`lib/IRGen/GenClass.cpp` 的 `buildIvar`): + - `""`:这个存储属性不是 `@objc`,包括 `final` / `@nonobjc` 的 Swift 独有成员和 `lazy var` 的合成存储。它的类型可以是任何东西,ObjC 类也可以。 + - `"?"`:属性是 `@objc`,但存储类型不能直接用 ObjC 表示,包括桥接的 `String` / `Array` / `Dictionary` / `Set` / `Data`、`weak` 引用、`AnyObject.Type`、闭包、可选的 typed enum。编译器注释原话是 "used when ObjC classes are bridged to separate Swift types"。 + - 其余是真实编码。非可选的 typed enum(`NS_TYPED_ENUM`)拿到的是 `@"NSString"`,typedef 的名字不会进 ObjC 元数据。 +4. **三条编译期限制**(写探针 fixture 时被编译器拒绝后才知道): + - `@implementation` 的实例属性不能用 property wrapper,所以不会有 wrapper 生成的 `_x` 存储。 + - 存储属性不能用 library evolution 下大小可变的类型(`Date`、`URL` 都不行,`@frozen` 的 `Data` 可以),所以 `ivar_t` 里记的大小永远准确,可以当推断的校验条件。 + - 非 `final` 的成员即使是 `private` 也隐式 `@objc`,会拿到 `"?"` 编码并进 ObjC 属性表;Swift 独有的存储必须写成 `final` 或 `@nonobjc`。 + +## 剩下的路线 + +### 一、只用元数据的推断(不碰汇编,成本最低) + +1. **`"?"` 编码且有同名 ObjC 属性:推出桥接后的外层类型。** `NSString *` 占 16 字节的是 `String`(可不可选分不出,`String?` 也是 16 字节);占 8 字节的是包着 NSString 的 typed enum,名字拿不到。`NSArray *` / `NSDictionary *` / `NSSet *` 推到 `Array` / `Dictionary` / `Set`,元素类型丢了。26.6.2 AppKit 里 19 个能用 field offset global 核对答案的 `"?"` ivar 全部符合这条规则。 +2. **`$__lazy_storage_$_x` 且 `x` 是 ObjC 属性:类型是 `Optional`。** 这个前缀在 ObjC ivar 名里,strip 之后还在。 +3. **真实编码映射成 Swift 类型。** `q` → `Int`(也可能是 `NS_ENUM`,分不清),`B` → `Bool`,`{CGSize=dd}` → `CGSize`,`@"NSColor"` → `NSColor`(可不可选不知道)。现在 Swift 侧对这些也写「Swift type not recoverable」。 +4. **`weak` / `unowned` 关键字。** field offset global 的 mangled 类型不带引用的所有权修饰(普通类的这个信息在 field descriptor 里,而这类类没有),所以现在 dump 和 interface 都把 `weak var delegate` 打成普通 `var`。`@objc` 属性可以从 ObjC 属性特性 `W` 拿到,Swift 独有的只能看代码里的 `swift_unknownObjectWeak*`。 +5. **没有 Swift 符号的 ObjC 方法,在 interface 里一行都不出。** 可以列成注释,免得 Swift 侧看起来是空的;dump 的 `objcImplementationClasses` 段已经全列了。 +6. **按「类自己 extension 里嵌套的类型 + 大小」出候选。** `NSScreen._state`(304 字节)正好对上 AppKit 里唯一一个 304 字节的结构体 `NSScreen.(State in _939AF…)`,它就嵌套在 `NSScreen` 自己的 extension 里。但一般情况区分度很低:61 个没解出的 ivar 里 47 个是 8 字节的引用,大小说明不了任何问题;其余按大小各撞 6 到 39 个同尺寸结构体,纯数值结构体同尺寸时完全分不开。只能当带置信度的候选。 + +### 二、SDK 头文件(结果精确,但覆盖的类少) + +`@implementation` 的 Swift 成员必须和头文件导入后的声明一一对应,所以只要有头文件,名字、类型、nullable 都是准的,不是推断。`TypeIndexing` 已经在用 SourceKit 生成模块接口,可以复用。实测 38 个类里只有 6 个有公开头文件:NSGlassEffectView、NSGlassEffectContainerView、NSScreen、NSGradient、NSScrollEdgeEffectStyle、NSBackgroundExtensionView。其余私有类在公开 SDK 和本机的 15.5 内部 SDK 里都找不到。用的时候要注意 SDK 版本和二进制版本的差异。 + +### 三、运行时采样(RuntimeViewer 一侧) + +RuntimeViewer 在进程内时,可以直接读活对象的 ivar 值拿到动态类型。对引用类型的 ivar 最直接(没解出的 61 个里有 47 个),但需要现成的实例,拿到的可能是子类,值为 nil 或空集合单例时什么也拿不到。这不在离线库的范围内。 + +### 四、反汇编推断(已在 26.6.2 AppKit 与 strip 后的 fixture 上验证可行) + +ObjC 的 ivar 偏移在运行时可能被滑动,所以代码每次访问 ivar 都要先从它的 offset global 里取偏移,而 ivar 表里记的正是这个全局变量。「哪段代码碰了哪个 ivar」不需要任何符号就知道(IDA 直接把它们标成 `_OBJC_IVAR_$_Class.ivar`)。线索按可信度排: + +1. **代码需要类型元数据时,取的是 `__swift5_typeref` 里的 mangled name。** 调用形如 `__swift_instantiateConcreteTypeFromMangledNameV2(cache, {相对偏移, 长度})`,名字是数据,strip 删不掉,而且带泛型实参。实例:`NSApplicationSceneWorkspace.sceneHandlers` 在 `init` 里由一个特化的字典构造函数赋初值,它给字典分配存储时引用了 `_DictionaryStorage`。其中 `0x0C` 是指向 ObjC 协议的 symbolic reference,目标是两个相对地址,第二个指向不含 symbolic reference 的 `So25NSApplicationSceneHandler_p`。 +2. **ObjC 属性的 getter 直接转发这个 ivar。** `-[NSApplicationSceneWorkspace workspace]` 读的就是 `underlyingWorkspace`,为 nil 时 `brk`(强制解包失败),所以它是 `FBSWorkspace?`。 +3. **形状指纹。** `.cxx_destruct` 怎么释放它:`objc_release`、`swift_release`、在第几个字上 `swift_bridgeObjectRelease`、`swift_unknownObjectWeakDestroy`。`init` 给什么初值:空字符串是 `(0, 0xE000000000000000)`,`Bool?` 的 nil 是字节 `2`,空集合引用 libswiftCore 的 `_swiftEmpty*` 单例(导入符号永远有名字)。类没有 `.cxx_destruct`,说明所有 ivar 都是平凡类型。 +4. **具名 C 函数的签名能给字段定型。** `NSCoordinateSpace.coordinateSpace`(88 字节)从代码里还原出 `CGRect` 在 0、`Bool` 在 0x20、`CGAffineTransform` 在 0x28(最后一个是 `CGAffineTransformMakeScale()` 的返回值),默认值 `(.zero, false, .identity)`。但 AppKit 里没有任何名义类型是这个布局,多半是元组(没有类型描述符)或者定义在别的镜像,只能按结构渲染,不能声称知道它叫什么。 +5. **nullable(Swift 实现的 ObjC 成员)。** 桥接类型能精确推出:可选的 setter 在调 `_unconditionallyBridgeFromObjectiveC` 之前有一条 `CBZ`,getter 遇到 `.none` 返回 0,block 在 `_Block_copy` 之后同样判空。类类型的参数和返回值不管可不可选,编出来的代码完全一样(fixture 里 `setNumber:` 与 `setObject:` 逻辑相同,还和可选 typed enum 的 setter 共用一个编译器合并出来的函数),只能靠旁证:`init` 往 ivar 里存 nil 的一定可选,`weak` 的一定可选,getter 里 `brk` 强制解包的返回值一定非空。clang 编译的 ObjC 代码不受 nullable 注解影响,推不出。 + +成本:需要 ARM64 上的数据流跟踪(某个函数的返回值被存进了 self + ivar 偏移、那个函数用哪个 mangled name 取了元数据),结果取决于优化器怎么生成代码,输出要带证据档位(像现有的「只按名字」那一档)。`SwiftThunkAnalysis` 已有 Capstone 解码器和寄存器跟踪(给 kind-9 thunk 做符号求值用的),但现在只收集调用目标和代码里算出的地址。只支持 ARM64 不算限制:macOS 27 起系统二进制只有 arm64 和 arm64e。建议分层做:先做局部的模式匹配(`.cxx_destruct` / `init` 指纹、getter 转发),最后才做跨函数追到 `__swift5_typeref` 的关联。 + +### 真正解不出的 + +- 没有任何代码引用其元数据的自定义 struct / enum:只能拿到布局。 +- 平凡类型(`Int`、`Double`、元类型):析构时什么都不做,初值都是 0,除了大小什么都看不出。 +- clang 编译的 ObjC 成员的 nullable。 + +## 验收(动手时) + +- 每条推断都带证据档位:dump 全部打出来并标明来源,interface 默认只打有把握的(沿用「dump 信息最大化、interface 管可读性」)。 +- 用 field offset global 能核对的 ivar(26.6.2 AppKit 的 55 个)做对照集,推断结果与符号给出的类型逐条一致。 +- 回归测试用现场编译的 fixture,每种线索配一个 `-O` 加 `strip -x` 的变体钉住。 + +## 附:调研用的探针 fixture + +没有放进仓库。它是一对成员完全相同的 `@implementation` 类,一个全用默认访问级别、一个能写 `public` 的都写了,28 个存储属性覆盖三种编码的每一类(真实编码、桥接类型、`weak`、`Class`、闭包、typed enum、lazy 存储、`final` / `@nonobjc` 的 Swift 独有成员、`private` 的 `@objc` 成员),用 `-O` 编成 dylib,再复制一份 `strip -x`。结论:strip 后,internal 那个类的 ivar 一个类型都解不出;public 那个类除 lazy 存储和 `private` 成员外全部解出,因为这两者的 field offset global 永远是 local 符号。仓库里的回归测试(`ObjCImplementationFixture` 的 `Widget`)已经覆盖了 `private` 属性和 lazy 存储这两种情况。 + +## 关联 + +- [Internal/ObjCImplementationClassRecognition.md](../Documentations/Internal/ObjCImplementationClassRecognition.md)「边界与已知限制」 +- [Internal/ObjCMemberRecovery.md](../Documentations/Internal/ObjCMemberRecovery.md)(ObjC 方法表与 Swift 成员的联结) +- [Internal/ProjectEvolutionLog.md](../Documentations/Internal/ProjectEvolutionLog.md) 第 72 节 diff --git a/Scripts/run-rendering-ab-verification.py b/Scripts/run-rendering-ab-verification.py index 79017da34..7144d254d 100755 --- a/Scripts/run-rendering-ab-verification.py +++ b/Scripts/run-rendering-ab-verification.py @@ -13,7 +13,22 @@ Scripts/run-rendering-ab-verification.py [--output-root PATH] [--frameworks A,B,...] [--scenarios cache-15.5,sim-iOS-18.5,...] [--baseline-scratch PATH] [--candidate-scratch PATH] [--skip-image-part] - [--jobs N] [--baseline-cache PATH | --no-baseline-cache] + [--jobs N] [--baseline-cache PATH | --no-baseline-cache] [--skip-build] + +Building: + - By default the harness builds both sides itself: `swift build -c release + --product swift-section` before the renders, then `swift test -c release` + for the MachOImage part. Neither goes through a build queue. + - --skip-build builds nothing, so the caller can run every build through + the machine's queue first. Each side needs ONE prebuild: `swift test -c + release --filter NoSuchTestForPrebuild` when the MachOImage part runs (it + builds the CLI too; the filter matches no test), `swift build -c release + --product swift-section` when it does not. Running both on one scratch + path recompiles the package twice: `swift test` turns testability on for + the whole build, `swift build -c release` leaves it off. + - A missing CLI stops the run before anything renders and names the + prebuild. Nothing checks that a product matches its checkout's current + sources. Wall clock: - The two release builds run concurrently, and the CLI render pairs run @@ -50,6 +65,7 @@ import json import os import platform +import shlex import shutil import subprocess import sys @@ -58,12 +74,14 @@ DEFAULT_FRAMEWORK_NAMES = ["SwiftUI", "SwiftUICore", "SwiftData", "Combine", "ActivityKit", "WidgetKit"] -# The archive names its directories by plain OS version. Both entries are -# checked for an arm64e cache and silently skipped when absent, so a machine -# carrying only one of them still runs that leg. -ARCHIVED_CACHE_DIRECTORIES = [ - Path("/Volumes/DyldSharedCaches/macOS/26.6.2"), - Path("/Volumes/DyldSharedCaches/macOS/15.5"), +# The archive names its directories by plain OS version, and the machines this +# runs on archive the 26.x cache under different patch versions. Each slot +# takes the first candidate carrying an arm64e cache; a slot with none is +# reported and skipped, so a machine carrying only some of them still runs +# those legs. +ARCHIVED_CACHE_DIRECTORY_CANDIDATES = [ + [Path("/Volumes/DyldSharedCaches/macOS/26.6.2"), Path("/Volumes/DyldSharedCaches/macOS/26.6")], + [Path("/Volumes/DyldSharedCaches/macOS/15.5")], ] SIMULATOR_RUNTIME_SEARCH_DIRECTORIES = [ @@ -91,6 +109,9 @@ def parse_arguments() -> argparse.Namespace: help="SwiftPM scratch path for the candidate build (default: /.build).") parser.add_argument("--skip-image-part", action="store_true", help="Skip the MachOImage (RenderingVerificationTests) part.") + parser.add_argument("--skip-build", action="store_true", + help="Build nothing: use each side's prebuilt /release/swift-section and, for the " + "MachOImage part, its prebuilt release test bundles.") parser.add_argument("--scenarios", default="", help="Comma-separated scenario names to run (cache-15.5, cache-current-system, " "sim-iOS-18.5, machoimage-current, ...); default: every scenario.") @@ -135,11 +156,19 @@ def runs_scenario(self, scenario_name: str) -> bool: selected = getattr(self.arguments, "scenario_names", set()) return not selected or scenario_name in selected + def runs_macho_image_part(self) -> bool: + return not self.arguments.skip_image_part and self.runs_scenario("machoimage-current") + # --- Building ----------------------------------------------------------- def build_both_sides(self) -> None: """The two sides build concurrently: separate checkouts, separate - scratch paths, no shared state.""" + scratch paths, no shared state. With --skip-build nothing is built + (see `use_prebuilt_command_line_interfaces`).""" + if self.arguments.skip_build: + self.use_prebuilt_command_line_interfaces() + return + def build(side: str, checkout: Path, scratch: Path) -> tuple[str, int]: print(f"Building release swift-section for {checkout} ...") log_file = self.output_root / f"build-{side}.log" @@ -158,9 +187,50 @@ def build(side: str, checkout: Path, scratch: Path) -> tuple[str, int]: if return_code != 0: sys.exit(f"error: release build failed for {side} (log: {self.output_root / f'build-{side}.log'})") for side, _, scratch in self.sides(): - self.command_line_interfaces[side] = scratch / "release" / "swift-section" + self.command_line_interfaces[side] = self.command_line_interface_path(scratch) print(f"Built {side}: {self.command_line_interfaces[side]}") + def use_prebuilt_command_line_interfaces(self) -> None: + """--skip-build: the caller built both sides before the run, through + the machine's build queue. The harness's own `swift build -c release` + runs outside that queue, and on the throttled machine it rebuilt both + sides in full, concurrently: the queue caps a release build at + `--jobs 8`, which reaches swiftc as `-num-threads 8`, so a build + without the cap reuses nothing. Nothing here checks that a product is + current — a checkout edited after its prebuild renders as it was.""" + missing_sides = [(side, checkout, scratch) for side, checkout, scratch in self.sides() + if not self.command_line_interface_path(scratch).is_file()] + if missing_sides: + message_lines = ["error: --skip-build found no prebuilt swift-section; prebuild each missing side first:"] + for side, checkout, scratch in missing_sides: + message_lines.append(f" {side}: {self.command_line_interface_path(scratch)}") + message_lines.append(f" {self.prebuild_command(checkout, scratch)}") + sys.exit("\n".join(message_lines)) + for side, _, scratch in self.sides(): + product = self.command_line_interface_path(scratch) + self.command_line_interfaces[side] = product + # The build time is the one staleness hint on offer: a product + # older than the checkout's last edit renders the old sources. + built_at = datetime.datetime.fromtimestamp(product.stat().st_mtime) + print(f"Using prebuilt {side}: {product} (built {built_at:%Y-%m-%d %H:%M:%S})") + + @staticmethod + def command_line_interface_path(scratch: Path) -> Path: + """SwiftPM points `/release` at the release products under + either build system, so the CLI is found at the same place.""" + return scratch / "release" / "swift-section" + + def prebuild_command(self, checkout: Path, scratch: Path) -> str: + """The one prebuild a side needs for this run. `swift test` builds + every product, this CLI included, and turns testability on for the + whole build while `swift build -c release` leaves it off: running both + on one scratch path recompiles the package twice, and the later one + replaces the CLI anyway. The filter matches no test, so it only builds.""" + location = f"--package-path {shlex.quote(str(checkout))} --scratch-path {shlex.quote(str(scratch))}" + if self.runs_macho_image_part(): + return f"queued-build swift test -c release --filter NoSuchTestForPrebuild {location}" + return f"queued-build swift build -c release --product swift-section {location}" + def sides(self) -> list[tuple[str, Path, Path]]: return [ ("baseline", self.arguments.baseline_checkout, self.arguments.baseline_scratch), @@ -312,8 +382,14 @@ def image_path_inside_cache(self, cache_directory: Path, framework_name: str) -> return None def run_dyld_cache_part(self) -> None: - available_cache_directories = [directory for directory in ARCHIVED_CACHE_DIRECTORIES - if (directory / "dyld_shared_cache_arm64e").is_file()] + available_cache_directories = [] + for candidate_directories in ARCHIVED_CACHE_DIRECTORY_CANDIDATES: + cache_directory = next((directory for directory in candidate_directories + if (directory / "dyld_shared_cache_arm64e").is_file()), None) + if cache_directory is None: + print(f"[skip] no archived cache in any of: {', '.join(str(directory) for directory in candidate_directories)}") + else: + available_cache_directories.append(cache_directory) if not available_cache_directories: print("No archived cache found - falling back to the current system's dyld shared cache.") for framework_name in self.arguments.framework_names: @@ -380,7 +456,7 @@ def run_macho_image_part(self) -> None: shared cache slide — which is also why this part is never served from the baseline cache. The two sides run concurrently (separate scratch paths; the renders happen inside each `swift test` process).""" - if not self.runs_scenario("machoimage-current"): + if not self.runs_macho_image_part(): return with concurrent.futures.ThreadPoolExecutor(max_workers=2) as pool: list(pool.map(lambda entry: self.run_macho_image_side(*entry), self.sides())) @@ -396,13 +472,18 @@ def run_macho_image_side(self, side: str, checkout: Path, scratch: Path) -> None "MACHO_SWIFT_SECTION_SILENT_TEST": "1", }) log_file = self.output_root / "machoimage-current" / f"{side}.test.log" + command = [ + "swift", "test", "-c", "release", + "--package-path", str(checkout), + "--scratch-path", str(scratch), + "--filter", "RenderingVerificationTests", + ] + if self.arguments.skip_build: + # The release test bundles were prebuilt together with the CLI + # (`prebuild_command`); a missing one fails the invocation below. + command.append("--skip-build") with open(log_file, "w") as log_handle: - completed = subprocess.run([ - "swift", "test", "-c", "release", - "--package-path", str(checkout), - "--scratch-path", str(scratch), - "--filter", "RenderingVerificationTests", - ], env=environment, stdout=log_handle, stderr=subprocess.STDOUT) + completed = subprocess.run(command, env=environment, stdout=log_handle, stderr=subprocess.STDOUT) print(f"[{side}] machoimage-current exit={completed.returncode}") if completed.returncode != 0: # Unlike the CLI scenarios (which degrade to paired .skip @@ -480,8 +561,7 @@ def main() -> None: run.run_dyld_cache_part() run.run_simulator_part() run.execute_pending_jobs() - if not arguments.skip_image_part: - run.run_macho_image_part() + run.run_macho_image_part() difference_count, examined_pair_count = run.compare_all_pairs() if run.hard_failure_messages: diff --git a/Scripts/test-run-rendering-ab-verification.py b/Scripts/test-run-rendering-ab-verification.py index 18eac4187..ab52b1ee0 100755 --- a/Scripts/test-run-rendering-ab-verification.py +++ b/Scripts/test-run-rendering-ab-verification.py @@ -189,5 +189,133 @@ def testASubstringMatchIsNotAHit(self) -> None: self.assertIsNone(self.resolve("ActivityKit")) +class SkipBuildTests(unittest.TestCase): + """`--skip-build` lets every build of a round go through the caller's own + build queue. Without it the harness runs `swift build -c release` for both + sides itself, concurrently and outside `queued-build`: on the throttled + 10-core machine that rebuilt both sides in full, because the queue caps a + release build at `--jobs 8` (swiftc `-num-threads 8`) and the harness's + uncapped command line matched nothing the queue had built. + + `subprocess.run` is the harness's only process boundary, so recording it + shows every command a code path would launch; answering success keeps the + default path's own bookkeeping intact.""" + + def setUp(self) -> None: + self.temporary_directory = tempfile.TemporaryDirectory() + root = Path(self.temporary_directory.name) + self.output_root = root / "output" + self.output_root.mkdir() + self.baseline_checkout = root / "baseline-checkout" + self.candidate_checkout = root / "candidate-checkout" + self.baseline_scratch = root / "baseline-scratch" + self.candidate_scratch = root / "candidate-scratch" + self.launched_commands: list[list[str]] = [] + self.original_subprocess_run = HARNESS.subprocess.run + HARNESS.subprocess.run = self.recordLaunchedCommand + + def tearDown(self) -> None: + HARNESS.subprocess.run = self.original_subprocess_run + self.temporary_directory.cleanup() + + def recordLaunchedCommand(self, command: list[str], **keyword_arguments) -> SimpleNamespace: + self.launched_commands.append(list(command)) + return SimpleNamespace(returncode=0) + + def makeRun(self, skip_build: bool, skip_image_part: bool = False, + scenario_names: frozenset[str] = frozenset()) -> "HARNESS.VerificationRun": + return HARNESS.VerificationRun(SimpleNamespace( + output_root=self.output_root, + skip_build=skip_build, + skip_image_part=skip_image_part, + scenario_names=set(scenario_names), + baseline_checkout=self.baseline_checkout, + candidate_checkout=self.candidate_checkout, + baseline_scratch=self.baseline_scratch, + candidate_scratch=self.candidate_scratch, + framework_names=["SwiftUI"], + )) + + def writePrebuiltCommandLineInterface(self, scratch: Path) -> Path: + product = scratch / "release" / "swift-section" + product.parent.mkdir(parents=True) + product.write_text("") + return product + + def testPrebuiltProductsOnBothSidesAreUsedWithoutLaunchingABuild(self) -> None: + baseline_product = self.writePrebuiltCommandLineInterface(self.baseline_scratch) + candidate_product = self.writePrebuiltCommandLineInterface(self.candidate_scratch) + run = self.makeRun(skip_build=True) + + run.build_both_sides() + + self.assertEqual(self.launched_commands, []) + self.assertEqual(run.command_line_interfaces, {"baseline": baseline_product, "candidate": candidate_product}) + + def testAMissingPrebuiltProductStopsTheRunAndNamesItsPath(self) -> None: + """Checked before anything runs: a missing CLI would otherwise stop the + run at its first render with a bare FileNotFoundError traceback, which + says neither which side is missing nor how to prebuild it.""" + self.writePrebuiltCommandLineInterface(self.baseline_scratch) + run = self.makeRun(skip_build=True) + + with self.assertRaises(SystemExit) as raised: + run.build_both_sides() + + self.assertIn(str(self.candidate_scratch / "release" / "swift-section"), str(raised.exception.code)) + self.assertEqual(self.launched_commands, []) + + def testEachMissingSideIsGivenTheOnePrebuildThisRunNeeds(self) -> None: + """`swift test` builds every product, the CLI included, but turns + testability on for the whole build while `swift build -c release` + leaves it off, so prebuilding one scratch path with both recompiles + the package twice. A run with the MachOImage part needs only the + former; a run without it needs only the latter.""" + cases = [ + ("the MachOImage part runs", {}, + "queued-build swift test -c release --filter NoSuchTestForPrebuild"), + ("--skip-image-part", {"skip_image_part": True}, + "queued-build swift build -c release --product swift-section"), + ("--scenarios without machoimage-current", {"scenario_names": frozenset({"cache-15.5"})}, + "queued-build swift build -c release --product swift-section"), + ] + for label, run_options, expected_prebuild in cases: + with self.subTest(label): + run = self.makeRun(skip_build=True, **run_options) + + with self.assertRaises(SystemExit) as raised: + run.build_both_sides() + + suggested_commands = [line.strip() for line in str(raised.exception.code).splitlines() + if line.strip().startswith("queued-build ")] + self.assertEqual(suggested_commands, [ + f"{expected_prebuild} --package-path {self.baseline_checkout} --scratch-path {self.baseline_scratch}", + f"{expected_prebuild} --package-path {self.candidate_checkout} --scratch-path {self.candidate_scratch}", + ]) + + def testTheImagePartRunsThePrebuiltTestBundlesWithoutBuilding(self) -> None: + run = self.makeRun(skip_build=True) + + run.run_macho_image_side("candidate", self.candidate_checkout, self.candidate_scratch) + + self.assertEqual(len(self.launched_commands), 1) + self.assertEqual(self.launched_commands[0][:2], ["swift", "test"]) + self.assertIn("--skip-build", self.launched_commands[0]) + + def testWithoutTheFlagBothSidesAreStillBuilt(self) -> None: + run = self.makeRun(skip_build=False) + + run.build_both_sides() + + self.assertEqual([command[:2] for command in self.launched_commands], [["swift", "build"], ["swift", "build"]]) + + def testWithoutTheFlagTheImagePartStillBuildsItsTests(self) -> None: + run = self.makeRun(skip_build=False) + + run.run_macho_image_side("candidate", self.candidate_checkout, self.candidate_scratch) + + self.assertNotIn("--skip-build", self.launched_commands[0]) + + if __name__ == "__main__": unittest.main(verbosity=2) diff --git a/Sources/MachOSwiftSection/Exported.swift b/Sources/ABI/MachOSwiftSection/Exported.swift similarity index 100% rename from Sources/MachOSwiftSection/Exported.swift rename to Sources/ABI/MachOSwiftSection/Exported.swift diff --git a/Sources/MachOSwiftSection/Extensions/Array+.swift b/Sources/ABI/MachOSwiftSection/Extensions/Array+.swift similarity index 100% rename from Sources/MachOSwiftSection/Extensions/Array+.swift rename to Sources/ABI/MachOSwiftSection/Extensions/Array+.swift diff --git a/Sources/MachOSwiftSection/Extensions/MachORepresentable+.swift b/Sources/ABI/MachOSwiftSection/Extensions/MachORepresentable+.swift similarity index 100% rename from Sources/MachOSwiftSection/Extensions/MachORepresentable+.swift rename to Sources/ABI/MachOSwiftSection/Extensions/MachORepresentable+.swift diff --git a/Sources/MachOSwiftSection/Extensions/String+.swift b/Sources/ABI/MachOSwiftSection/Extensions/String+.swift similarity index 100% rename from Sources/MachOSwiftSection/Extensions/String+.swift rename to Sources/ABI/MachOSwiftSection/Extensions/String+.swift diff --git a/Sources/MachOSwiftSection/MachOFile+Swift.swift b/Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift similarity index 94% rename from Sources/MachOSwiftSection/MachOFile+Swift.swift rename to Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift index 8c6151bd1..17c977ab2 100644 --- a/Sources/MachOSwiftSection/MachOFile+Swift.swift +++ b/Sources/ABI/MachOSwiftSection/MachOFile+Swift.swift @@ -17,31 +17,31 @@ extension MachOFile { extension MachOFile.Swift: SwiftSectionRepresentable { public var types: [TypeContextWrapper] { get throws { - try typeContextDescriptors.map { try TypeContextWrapper.forTypeContextDescriptorWrapper($0, in: machO) } + try typeContextDescriptors.map { try TypeContextWrapper.forTypeContextDescriptorWrapper($0, in: machO.context) } } } public var protocols: [`Protocol`] { get throws { - try protocolDescriptors.map { try Protocol(descriptor: $0, in: machO) } + try protocolDescriptors.map { try Protocol(descriptor: $0, in: machO.context) } } } public var protocolConformances: [ProtocolConformance] { get throws { - try protocolConformanceDescriptors.map { try ProtocolConformance(descriptor: $0, in: machO) } + try protocolConformanceDescriptors.map { try ProtocolConformance(descriptor: $0, in: machO.context) } } } public var associatedTypes: [AssociatedType] { get throws { - try associatedTypeDescriptors.map { try AssociatedType(descriptor: $0, in: machO) } + try associatedTypeDescriptors.map { try AssociatedType(descriptor: $0, in: machO.context) } } } public var builtinTypes: [BuiltinType] { get throws { - try builtinTypeDescriptors.map { try BuiltinType(descriptor: $0, in: machO) } + try builtinTypeDescriptors.map { try BuiltinType(descriptor: $0, in: machO.context) } } } @@ -138,21 +138,21 @@ extension MachOFile.Swift { let (offset, size) = try _sectionOffsetAndSize(of: swiftMachOSection) let pointerSize: Int = MemoryLayout>.size let data: [AnyLocatableLayoutWrapper>] = try machO.readWrapperElements(offset: offset, numberOfElements: size / pointerSize) - return try data.map { try $0.layout.resolve(from: $0.offset, in: machO) } + return try data.map { try $0.layout.resolve(at: $0.offset, in: machO.context) } } private func _readTypeMetadataRecords(from swiftMachOSection: MachOSwiftSectionName) throws -> [ContextDescriptorWrapper] { let (offset, size) = try _sectionOffsetAndSize(of: swiftMachOSection) let recordSize = TypeMetadataRecord.layoutSize let records: [TypeMetadataRecord] = try machO.readWrapperElements(offset: offset, numberOfElements: size / recordSize) - return try records.compactMap { try $0.contextDescriptor(in: machO) } + return try records.compactMap { try $0.contextDescriptor(in: machO.context) } } private func _readProtocolRecords(from swiftMachOSection: MachOSwiftSectionName) throws -> [ProtocolDescriptor] { let (offset, size) = try _sectionOffsetAndSize(of: swiftMachOSection) let recordSize = ProtocolRecord.layoutSize let records: [ProtocolRecord] = try machO.readWrapperElements(offset: offset, numberOfElements: size / recordSize) - return try records.compactMap { try $0.protocolDescriptor(in: machO) } + return try records.compactMap { try $0.protocolDescriptor(in: machO.context) } } /// Reads a section that is a flat, gapless array of fixed-size records — diff --git a/Sources/MachOSwiftSection/MachOImage+Swift.swift b/Sources/ABI/MachOSwiftSection/MachOImage+Swift.swift similarity index 94% rename from Sources/MachOSwiftSection/MachOImage+Swift.swift rename to Sources/ABI/MachOSwiftSection/MachOImage+Swift.swift index 837a5c02f..e5657f212 100644 --- a/Sources/MachOSwiftSection/MachOImage+Swift.swift +++ b/Sources/ABI/MachOSwiftSection/MachOImage+Swift.swift @@ -17,31 +17,31 @@ extension MachOImage { extension MachOImage.Swift: SwiftSectionRepresentable { public var types: [TypeContextWrapper] { get throws { - try typeContextDescriptors.map { try TypeContextWrapper.forTypeContextDescriptorWrapper($0, in: machO) } + try typeContextDescriptors.map { try TypeContextWrapper.forTypeContextDescriptorWrapper($0, in: machO.context) } } } public var protocols: [`Protocol`] { get throws { - try protocolDescriptors.map { try Protocol(descriptor: $0, in: machO) } + try protocolDescriptors.map { try Protocol(descriptor: $0, in: machO.context) } } } public var protocolConformances: [ProtocolConformance] { get throws { - try protocolConformanceDescriptors.map { try ProtocolConformance(descriptor: $0, in: machO) } + try protocolConformanceDescriptors.map { try ProtocolConformance(descriptor: $0, in: machO.context) } } } public var associatedTypes: [AssociatedType] { get throws { - try associatedTypeDescriptors.map { try AssociatedType(descriptor: $0, in: machO) } + try associatedTypeDescriptors.map { try AssociatedType(descriptor: $0, in: machO.context) } } } public var builtinTypes: [BuiltinType] { get throws { - try builtinTypeDescriptors.map { try BuiltinType(descriptor: $0, in: machO) } + try builtinTypeDescriptors.map { try BuiltinType(descriptor: $0, in: machO.context) } } } @@ -136,21 +136,21 @@ extension MachOImage.Swift { let (offset, size) = try _sectionOffsetAndSize(of: swiftMachOSection) let pointerSize: Int = MemoryLayout>.size let data: [AnyLocatableLayoutWrapper>] = try machO.readWrapperElements(offset: offset, numberOfElements: size / pointerSize) - return try data.map { try $0.layout.resolve(from: $0.offset, in: machO) } + return try data.map { try $0.layout.resolve(at: $0.offset, in: machO.context) } } private func _readTypeMetadataRecords(from swiftMachOSection: MachOSwiftSectionName) throws -> [ContextDescriptorWrapper] { let (offset, size) = try _sectionOffsetAndSize(of: swiftMachOSection) let recordSize = TypeMetadataRecord.layoutSize let records: [TypeMetadataRecord] = try machO.readWrapperElements(offset: offset, numberOfElements: size / recordSize) - return try records.compactMap { try $0.contextDescriptor(in: machO) } + return try records.compactMap { try $0.contextDescriptor(in: machO.context) } } private func _readProtocolRecords(from swiftMachOSection: MachOSwiftSectionName) throws -> [ProtocolDescriptor] { let (offset, size) = try _sectionOffsetAndSize(of: swiftMachOSection) let recordSize = ProtocolRecord.layoutSize let records: [ProtocolRecord] = try machO.readWrapperElements(offset: offset, numberOfElements: size / recordSize) - return try records.compactMap { try $0.protocolDescriptor(in: machO) } + return try records.compactMap { try $0.protocolDescriptor(in: machO.context) } } /// Reads a section that is a flat, gapless array of fixed-size records — diff --git a/Sources/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionFlags.swift b/Sources/ABI/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionFlags.swift diff --git a/Sources/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionRecord.swift b/Sources/ABI/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionRecord.swift similarity index 81% rename from Sources/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionRecord.swift index 4b5599c71..9b3cac169 100644 --- a/Sources/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/AccessibleFunction/AccessibleFunctionRecord.swift @@ -45,57 +45,64 @@ extension AccessibleFunctionRecord { public var isDistributed: Bool { layout.flags.contains(.isDistributed) } } -// MARK: - MachO Reading +// MARK: - ReadingContext Support extension AccessibleFunctionRecord { /// The lookup key the runtime matches an incoming call target against. /// Not a mangled name in the demangler's sense — it is whatever string /// the emitter chose, so it is read as a plain C string. - public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { - try layout.name.resolve(from: offset(of: \.name), in: machO) + public func name(in context: some ReadingContext) throws -> String { + try layout.name.resolve(at: try context.addressFromOffset(offset(of: \.name)), in: context) } /// The function's Swift type, mangled. This is what tells a caller how to /// build the arguments the abstracted entry point expects. - public func functionType(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.functionType.resolve(from: offset(of: \.functionType), in: machO) + public func functionType(in context: some ReadingContext) throws -> MangledName { + try layout.functionType.resolve(at: try context.addressFromOffset(offset(of: \.functionType)), in: context) } /// The generic environment describing the function's generic signature, /// or `nil` for a non-generic function — the only nullable pointer in the /// record. - public func genericEnvironment(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericEnvironment? { + public func genericEnvironment(in context: some ReadingContext) throws -> GenericEnvironment? { guard let genericEnvironmentOffset = resolvedDirectOffset(from: \.genericEnvironment) else { return nil } - return try GenericEnvironment.resolve(from: genericEnvironmentOffset, in: machO) + return try GenericEnvironment.resolve(at: try context.addressFromOffset(genericEnvironmentOffset), in: context) + } + + /// The entry point's location as an address in `context` (a file offset + /// for `MachOContext`, a pointer in-process). The pointer is non-nullable + /// in the ABI, so `nil` means the record is malformed. + public func functionAddress(in context: Context) throws -> Context.Address? { + guard let functionOffset = resolvedDirectOffset(from: \.function) else { return nil } + return try context.addressFromOffset(functionOffset) } } +// MARK: - Deprecated Mach-O and pointer forms + extension AccessibleFunctionRecord { - public func name() throws -> String { - try layout.name.resolve(from: pointer(of: \.name)) + @available(*, deprecated, message: "Pass a ReadingContext: name(in: machO.context).") + public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try name(in: machO.context) } - public func functionType() throws -> MangledName { - try layout.functionType.resolve(from: pointer(of: \.functionType)) + @available(*, deprecated, message: "Pass a ReadingContext: functionType(in: machO.context).") + public func functionType(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try functionType(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension AccessibleFunctionRecord { - public func name(in context: some ReadingContext) throws -> String { - try layout.name.resolve(at: try context.addressFromOffset(offset(of: \.name)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: genericEnvironment(in: machO.context).") + public func genericEnvironment(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericEnvironment? { + try genericEnvironment(in: machO.context) } - public func functionType(in context: some ReadingContext) throws -> MangledName { - try layout.functionType.resolve(at: try context.addressFromOffset(offset(of: \.functionType)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: name(in: .inProcess).") + public func name() throws -> String { + try name(in: InProcessContext.shared) } - /// The entry point's location as an address in `context` (a file offset - /// for `MachOContext`, a pointer in-process). The pointer is non-nullable - /// in the ABI, so `nil` means the record is malformed. - public func functionAddress(in context: Context) throws -> Context.Address? { - guard let functionOffset = resolvedDirectOffset(from: \.function) else { return nil } - return try context.addressFromOffset(functionOffset) + @available(*, deprecated, message: "Pass a ReadingContext: functionType(in: .inProcess).") + public func functionType() throws -> MangledName { + try functionType(in: InProcessContext.shared) } } diff --git a/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift new file mode 100644 index 000000000..e666772e3 --- /dev/null +++ b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift @@ -0,0 +1,47 @@ +import Foundation +import MachOKit +import MachOBase + +public struct AnonymousContext: TopLevelType, ContextProtocol { + public let descriptor: AnonymousContextDescriptor + public let genericContext: GenericContext? + public let mangledName: MangledName? +} + +// MARK: - ReadingContext Support + +extension AnonymousContext { + public init(descriptor: AnonymousContextDescriptor, in context: some ReadingContext) throws { + self.descriptor = descriptor + var currentOffset = descriptor.offset + descriptor.layoutSize + + let genericContext = try descriptor.genericContext(in: context) + if let genericContext { + currentOffset += genericContext.size + } + self.genericContext = genericContext + + if descriptor.hasMangledName { + let mangledNamePointerAddress = try context.addressFromOffset(currentOffset) + let mangledNamePointer: RelativeDirectPointer = try context.readElement(at: mangledNamePointerAddress) + self.mangledName = try mangledNamePointer.resolve(at: mangledNamePointerAddress, in: context) + currentOffset += MemoryLayout>.size + } else { + self.mangledName = nil + } + } +} + +// MARK: - Deprecated Mach-O and pointer forms + +extension AnonymousContext { + @available(*, deprecated, message: "Pass a ReadingContext: AnonymousContext(descriptor:in: machO.context).") + public init(descriptor: AnonymousContextDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: AnonymousContext(descriptor:in: .inProcess).") + public init(descriptor: AnonymousContextDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift similarity index 59% rename from Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift index f0fb1e138..eb5dd675b 100644 --- a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Anonymous/AnonymousContextDescriptorProtocol.swift @@ -4,31 +4,6 @@ import MachOBase public protocol AnonymousContextDescriptorProtocol: ContextDescriptorProtocol where Layout: AnonymousContextDescriptorLayout {} extension AnonymousContextDescriptorProtocol { - public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { - guard hasMangledName else { - return nil - } - var currentOffset = offset + layoutSize - if let genericContext = try genericContext(in: machO) { - currentOffset += genericContext.size - } - let mangledNamePointer: RelativeDirectPointer = try machO.readElement(offset: currentOffset) - return try mangledNamePointer.resolve(from: currentOffset, in: machO) - } - - public func mangledName() throws -> MangledName? { - guard hasMangledName else { - return nil - } - var currentOffset = layoutSize - if let genericContext = try genericContext() { - currentOffset += genericContext.size - } - let pointer = try asPointer - let mangledNamePointer: RelativeDirectPointer = try pointer.readElement(offset: currentOffset) - return try mangledNamePointer.resolve(from: pointer.advanced(by: currentOffset)) - } - public func mangledName(in context: some ReadingContext) throws -> MangledName? { guard hasMangledName else { return nil @@ -41,7 +16,7 @@ extension AnonymousContextDescriptorProtocol { let mangledNamePointer: RelativeDirectPointer = try context.readElement(at: mangledNamePointerAddress) return try mangledNamePointer.resolve(at: mangledNamePointerAddress, in: context) } - + public var hasMangledName: Bool { guard let kindSpecificFlags = layout.flags.kindSpecificFlags, case .anonymous(let anonymousContextDescriptorFlags) = kindSpecificFlags else { return false @@ -49,3 +24,17 @@ extension AnonymousContextDescriptorProtocol { return anonymousContextDescriptorFlags.hasMangledName } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension AnonymousContextDescriptorProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: machO.context).") + public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { + try mangledName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: .inProcess).") + public func mangledName() throws -> MangledName? { + try mangledName(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift b/Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift similarity index 64% rename from Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift rename to Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift index 8af1f329d..f416c068b 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift +++ b/Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedType.swift @@ -10,20 +10,6 @@ public struct AssociatedType: TopLevelType { public let protocolTypeName: MangledName public let records: [AssociatedTypeRecord] - - public init(descriptor: AssociatedTypeDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - self.conformingTypeName = try descriptor.conformingTypeName(in: machO) - self.protocolTypeName = try descriptor.protocolTypeName(in: machO) - self.records = try descriptor.associatedTypeRecords(in: machO) - } - - public init(descriptor: AssociatedTypeDescriptor) throws { - self.descriptor = descriptor - self.conformingTypeName = try descriptor.conformingTypeName() - self.protocolTypeName = try descriptor.protocolTypeName() - self.records = try descriptor.associatedTypeRecords() - } } // MARK: - ReadingContext Support @@ -36,3 +22,17 @@ extension AssociatedType { self.records = try descriptor.associatedTypeRecords(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension AssociatedType { + @available(*, deprecated, message: "Pass a ReadingContext: AssociatedType(descriptor:in: machO.context).") + public init(descriptor: AssociatedTypeDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: AssociatedType(descriptor:in: .inProcess).") + public init(descriptor: AssociatedTypeDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift similarity index 67% rename from Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift index cc9319c64..d98fe86bd 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedTypeDescriptor.swift @@ -12,50 +12,56 @@ public struct AssociatedTypeDescriptor: ResolvableLocatableLayoutWrapper { } } +extension AssociatedTypeDescriptor: TopLevelDescriptor { + public var actualSize: Int { layoutSize + (layout.numAssociatedTypes * layout.associatedTypeRecordSize).cast() } +} + +// MARK: - ReadingContext Support + extension AssociatedTypeDescriptor { - public func conformingTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.conformingTypeName.resolve(from: offset(of: \.conformingTypeName), in: machO) + public func conformingTypeName(in context: some ReadingContext) throws -> MangledName { + return try layout.conformingTypeName.resolve(at: try context.addressFromOffset(offset(of: \.conformingTypeName)), in: context) } - public func protocolTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.protocolTypeName.resolve(from: offset(of: \.protocolTypeName), in: machO) + public func protocolTypeName(in context: some ReadingContext) throws -> MangledName { + return try layout.protocolTypeName.resolve(at: try context.addressFromOffset(offset(of: \.protocolTypeName)), in: context) } - public func associatedTypeRecords(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [AssociatedTypeRecord] { - return try machO.readWrapperElements(offset: offset + layoutSize, numberOfElements: layout.numAssociatedTypes.cast()) + public func associatedTypeRecords(in context: some ReadingContext) throws -> [AssociatedTypeRecord] { + return try context.readWrapperElements(at: try context.addressFromOffset(offset + layoutSize), numberOfElements: layout.numAssociatedTypes.cast()) } } +// MARK: - Deprecated Mach-O and pointer forms + extension AssociatedTypeDescriptor { - public func conformingTypeName() throws -> MangledName { - return try layout.conformingTypeName.resolve(from: pointer(of: \.conformingTypeName)) + @available(*, deprecated, message: "Pass a ReadingContext: conformingTypeName(in: machO.context).") + public func conformingTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try conformingTypeName(in: machO.context) } - public func protocolTypeName() throws -> MangledName { - return try layout.protocolTypeName.resolve(from: pointer(of: \.protocolTypeName)) + @available(*, deprecated, message: "Pass a ReadingContext: protocolTypeName(in: machO.context).") + public func protocolTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try protocolTypeName(in: machO.context) } - public func associatedTypeRecords() throws -> [AssociatedTypeRecord] { - return try asPointer.readWrapperElements(offset: layoutSize, numberOfElements: layout.numAssociatedTypes.cast()) + @available(*, deprecated, message: "Pass a ReadingContext: associatedTypeRecords(in: machO.context).") + public func associatedTypeRecords(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [AssociatedTypeRecord] { + try associatedTypeRecords(in: machO.context) } -} - -extension AssociatedTypeDescriptor: TopLevelDescriptor { - public var actualSize: Int { layoutSize + (layout.numAssociatedTypes * layout.associatedTypeRecordSize).cast() } -} -// MARK: - ReadingContext Support - -extension AssociatedTypeDescriptor { - public func conformingTypeName(in context: some ReadingContext) throws -> MangledName { - return try layout.conformingTypeName.resolve(at: try context.addressFromOffset(offset(of: \.conformingTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: conformingTypeName(in: .inProcess).") + public func conformingTypeName() throws -> MangledName { + try conformingTypeName(in: InProcessContext.shared) } - public func protocolTypeName(in context: some ReadingContext) throws -> MangledName { - return try layout.protocolTypeName.resolve(at: try context.addressFromOffset(offset(of: \.protocolTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: protocolTypeName(in: .inProcess).") + public func protocolTypeName() throws -> MangledName { + try protocolTypeName(in: InProcessContext.shared) } - public func associatedTypeRecords(in context: some ReadingContext) throws -> [AssociatedTypeRecord] { - return try context.readWrapperElements(at: try context.addressFromOffset(offset + layoutSize), numberOfElements: layout.numAssociatedTypes.cast()) + @available(*, deprecated, message: "Pass a ReadingContext: associatedTypeRecords(in: .inProcess).") + public func associatedTypeRecords() throws -> [AssociatedTypeRecord] { + try associatedTypeRecords(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift b/Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift similarity index 65% rename from Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift index 7d9bd9095..e51cd6ce5 100644 --- a/Sources/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/AssociatedType/AssociatedTypeRecord.swift @@ -10,34 +10,38 @@ public struct AssociatedTypeRecord: ResolvableLocatableLayoutWrapper { } } +// MARK: - ReadingContext Support + extension AssociatedTypeRecord { - public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { - return try layout.name.resolve(from: offset(of: \.name), in: machO) + public func name(in context: some ReadingContext) throws -> String { + return try layout.name.resolve(at: try context.addressFromOffset(offset(of: \.name)), in: context) } - public func substitutedTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.substitutedTypeName.resolve(from: offset(of: \.substitutedTypeName), in: machO) + public func substitutedTypeName(in context: some ReadingContext) throws -> MangledName { + return try layout.substitutedTypeName.resolve(at: try context.addressFromOffset(offset(of: \.substitutedTypeName)), in: context) } } +// MARK: - Deprecated Mach-O and pointer forms + extension AssociatedTypeRecord { - public func name() throws -> String { - return try layout.name.resolve(from: pointer(of: \.name)) + @available(*, deprecated, message: "Pass a ReadingContext: name(in: machO.context).") + public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try name(in: machO.context) } - public func substitutedTypeName() throws -> MangledName { - return try layout.substitutedTypeName.resolve(from: pointer(of: \.substitutedTypeName)) + @available(*, deprecated, message: "Pass a ReadingContext: substitutedTypeName(in: machO.context).") + public func substitutedTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try substitutedTypeName(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension AssociatedTypeRecord { - public func name(in context: some ReadingContext) throws -> String { - return try layout.name.resolve(at: try context.addressFromOffset(offset(of: \.name)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: name(in: .inProcess).") + public func name() throws -> String { + try name(in: InProcessContext.shared) } - public func substitutedTypeName(in context: some ReadingContext) throws -> MangledName { - return try layout.substitutedTypeName.resolve(at: try context.addressFromOffset(offset(of: \.substitutedTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: substitutedTypeName(in: .inProcess).") + public func substitutedTypeName() throws -> MangledName { + try substitutedTypeName(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift b/Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift similarity index 59% rename from Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift rename to Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift index 96aa3cb96..1fddb7b61 100644 --- a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift +++ b/Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinType.swift @@ -6,16 +6,6 @@ public struct BuiltinType: TopLevelType { public let descriptor: BuiltinTypeDescriptor public let typeName: MangledName? - - public init(descriptor: BuiltinTypeDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - self.typeName = try descriptor.typeName(in: machO) - } - - public init(descriptor: BuiltinTypeDescriptor) throws { - self.descriptor = descriptor - self.typeName = try descriptor.typeName() - } } // MARK: - ReadingContext Support @@ -26,3 +16,17 @@ extension BuiltinType { self.typeName = try descriptor.typeName(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension BuiltinType { + @available(*, deprecated, message: "Pass a ReadingContext: BuiltinType(descriptor:in: machO.context).") + public init(descriptor: BuiltinTypeDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: BuiltinType(descriptor:in: .inProcess).") + public init(descriptor: BuiltinTypeDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift similarity index 77% rename from Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift index 0e6f9dc41..73f817844 100644 --- a/Sources/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/BuiltinType/BuiltinTypeDescriptor.swift @@ -14,14 +14,6 @@ public struct BuiltinTypeDescriptor: ResolvableLocatableLayoutWrapper, TopLevelD } extension BuiltinTypeDescriptor { - public func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { - return try layout.typeName.resolve(from: offset(of: \.typeName), in: machO) - } - - public func typeName() throws -> MangledName? { - return try layout.typeName.resolve(from: pointer(of: \.typeName)) - } - public var isBitwiseTakable: Bool { return (layout.alignmentAndFlags >> 16) & 0x1 != 0 } @@ -42,3 +34,17 @@ extension BuiltinTypeDescriptor { return try layout.typeName.resolve(at: try context.addressFromOffset(offset(of: \.typeName)), in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension BuiltinTypeDescriptor { + @available(*, deprecated, message: "Pass a ReadingContext: typeName(in: machO.context).") + public func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { + try typeName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeName(in: .inProcess).") + public func typeName() throws -> MangledName? { + try typeName(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Capture/CaptureDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Capture/CaptureDescriptor.swift similarity index 83% rename from Sources/MachOSwiftSection/Models/Capture/CaptureDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Capture/CaptureDescriptor.swift index e88861edd..7706a3d14 100644 --- a/Sources/MachOSwiftSection/Models/Capture/CaptureDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Capture/CaptureDescriptor.swift @@ -72,43 +72,40 @@ extension CaptureDescriptor { } } -// MARK: - MachO Reading +// MARK: - ReadingContext Support extension CaptureDescriptor { - public func captureTypeRecords(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [CaptureTypeRecord] { + public func captureTypeRecords(in context: some ReadingContext) throws -> [CaptureTypeRecord] { guard captureTypeCount > 0 else { return [] } - return try machO.readWrapperElements(offset: captureTypeRecordsOffset, numberOfElements: captureTypeCount) + return try context.readWrapperElements(at: try context.addressFromOffset(captureTypeRecordsOffset), numberOfElements: captureTypeCount) } - public func metadataSourceRecords(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [MetadataSourceRecord] { + public func metadataSourceRecords(in context: some ReadingContext) throws -> [MetadataSourceRecord] { guard metadataSourceCount > 0 else { return [] } - return try machO.readWrapperElements(offset: metadataSourceRecordsOffset, numberOfElements: metadataSourceCount) + return try context.readWrapperElements(at: try context.addressFromOffset(metadataSourceRecordsOffset), numberOfElements: metadataSourceCount) } } +// MARK: - Deprecated Mach-O and pointer forms + extension CaptureDescriptor { - public func captureTypeRecords() throws -> [CaptureTypeRecord] { - guard captureTypeCount > 0 else { return [] } - return try asPointer.readWrapperElements(offset: MemoryLayout.size, numberOfElements: captureTypeCount) + @available(*, deprecated, message: "Pass a ReadingContext: captureTypeRecords(in: machO.context).") + public func captureTypeRecords(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [CaptureTypeRecord] { + try captureTypeRecords(in: machO.context) } - public func metadataSourceRecords() throws -> [MetadataSourceRecord] { - guard metadataSourceCount > 0 else { return [] } - let offsetFromStart = MemoryLayout.size + captureTypeCount * MemoryLayout.size - return try asPointer.readWrapperElements(offset: offsetFromStart, numberOfElements: metadataSourceCount) + @available(*, deprecated, message: "Pass a ReadingContext: metadataSourceRecords(in: machO.context).") + public func metadataSourceRecords(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [MetadataSourceRecord] { + try metadataSourceRecords(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension CaptureDescriptor { - public func captureTypeRecords(in context: some ReadingContext) throws -> [CaptureTypeRecord] { - guard captureTypeCount > 0 else { return [] } - return try context.readWrapperElements(at: try context.addressFromOffset(captureTypeRecordsOffset), numberOfElements: captureTypeCount) + @available(*, deprecated, message: "Pass a ReadingContext: captureTypeRecords(in: .inProcess).") + public func captureTypeRecords() throws -> [CaptureTypeRecord] { + try captureTypeRecords(in: InProcessContext.shared) } - public func metadataSourceRecords(in context: some ReadingContext) throws -> [MetadataSourceRecord] { - guard metadataSourceCount > 0 else { return [] } - return try context.readWrapperElements(at: try context.addressFromOffset(metadataSourceRecordsOffset), numberOfElements: metadataSourceCount) + @available(*, deprecated, message: "Pass a ReadingContext: metadataSourceRecords(in: .inProcess).") + public func metadataSourceRecords() throws -> [MetadataSourceRecord] { + try metadataSourceRecords(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Capture/CaptureTypeRecord.swift b/Sources/ABI/MachOSwiftSection/Models/Capture/CaptureTypeRecord.swift similarity index 74% rename from Sources/MachOSwiftSection/Models/Capture/CaptureTypeRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/Capture/CaptureTypeRecord.swift index 504f77526..dc6d9897e 100644 --- a/Sources/MachOSwiftSection/Models/Capture/CaptureTypeRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Capture/CaptureTypeRecord.swift @@ -16,22 +16,24 @@ public struct CaptureTypeRecord: ResolvableLocatableLayoutWrapper { } } -extension CaptureTypeRecord { - public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machO) - } -} +// MARK: - ReadingContext Support extension CaptureTypeRecord { - public func mangledTypeName() throws -> MangledName { - try layout.mangledTypeName.resolve(from: pointer(of: \.mangledTypeName)) + public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { + try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension CaptureTypeRecord { - public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { - try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: machO.context).") + public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledTypeName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: .inProcess).") + public func mangledTypeName() throws -> MangledName { + try mangledTypeName(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Capture/MetadataSourceRecord.swift b/Sources/ABI/MachOSwiftSection/Models/Capture/MetadataSourceRecord.swift similarity index 80% rename from Sources/MachOSwiftSection/Models/Capture/MetadataSourceRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/Capture/MetadataSourceRecord.swift index 21832b8fe..399b388c3 100644 --- a/Sources/MachOSwiftSection/Models/Capture/MetadataSourceRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Capture/MetadataSourceRecord.swift @@ -32,37 +32,41 @@ public struct MetadataSourceRecord: ResolvableLocatableLayoutWrapper { } } +// MARK: - ReadingContext Support + extension MetadataSourceRecord { /// The type this entry supplies metadata for — a real mangled type name. - public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machO) + public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { + try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) } /// The recipe for recovering that metadata, unparsed. See the type's /// documentation for why. - public func mangledMetadataSource(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.mangledMetadataSource.resolve(from: offset(of: \.mangledMetadataSource), in: machO) + public func mangledMetadataSource(in context: some ReadingContext) throws -> MangledName { + try layout.mangledMetadataSource.resolve(at: try context.addressFromOffset(offset(of: \.mangledMetadataSource)), in: context) } } +// MARK: - Deprecated Mach-O and pointer forms + extension MetadataSourceRecord { - public func mangledTypeName() throws -> MangledName { - try layout.mangledTypeName.resolve(from: pointer(of: \.mangledTypeName)) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: machO.context).") + public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledTypeName(in: machO.context) } - public func mangledMetadataSource() throws -> MangledName { - try layout.mangledMetadataSource.resolve(from: pointer(of: \.mangledMetadataSource)) + @available(*, deprecated, message: "Pass a ReadingContext: mangledMetadataSource(in: machO.context).") + public func mangledMetadataSource(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledMetadataSource(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension MetadataSourceRecord { - public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { - try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: .inProcess).") + public func mangledTypeName() throws -> MangledName { + try mangledTypeName(in: InProcessContext.shared) } - public func mangledMetadataSource(in context: some ReadingContext) throws -> MangledName { - try layout.mangledMetadataSource.resolve(at: try context.addressFromOffset(offset(of: \.mangledMetadataSource)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledMetadataSource(in: .inProcess).") + public func mangledMetadataSource() throws -> MangledName { + try mangledMetadataSource(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKind.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKind.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKind.swift diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKindSpecificFlags.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKindSpecificFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKindSpecificFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorKindSpecificFlags.swift diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift similarity index 53% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift index ee2425763..3c6d28e0c 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorProtocol.swift @@ -3,16 +3,6 @@ import MachOBase @dynamicMemberLookup public protocol ContextDescriptorProtocol: ResolvableLocatableLayoutWrapper where Layout: ContextDescriptorLayout { - func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? - func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? - func moduleContextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> (any ModuleContextDescriptorProtocol)? - func isCImportedContextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Bool - - func genericContext() throws -> GenericContext? - func parent() throws -> SymbolOrElement? - func moduleContextDescriptor() throws -> (any ModuleContextDescriptorProtocol)? - func isCImportedContextDescriptor() throws -> Bool - func genericContext(in context: some ReadingContext) throws -> GenericContext? func parent(in context: some ReadingContext) throws -> SymbolOrElement? func moduleContextDescriptor(in context: some ReadingContext) throws -> (any ModuleContextDescriptorProtocol)? @@ -22,109 +12,85 @@ public protocol ContextDescriptorProtocol: ResolvableLocatableLayoutWrapper wher } extension ContextDescriptorProtocol { - + public subscript(dynamicMember keyPath: KeyPath) -> T { layout.flags[keyPath: keyPath] } - - public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + + public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { guard layout.flags.kind != .module, layout.parent.isValid else { return nil } - return try layout.parent.resolve(from: offset + layout.offset(of: .parent), in: machO).asOptional + let baseAddress = try context.addressFromOffset(offset) + let address = context.advanceAddress(baseAddress, by: layout.offset(of: .parent).cast()) + return try layout.parent.resolve(at: address, in: context).asOptional } - public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { + public func genericContext(in context: some ReadingContext) throws -> GenericContext? { guard layout.flags.isGeneric else { return nil } - return try GenericContext(contextDescriptor: self, in: machO) + return try GenericContext(contextDescriptor: self, in: context) } - public func moduleContextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> (any ModuleContextDescriptorProtocol)? { + public func moduleContextDescriptor(in context: some ReadingContext) throws -> (any ModuleContextDescriptorProtocol)? { if let module = self as? (any ModuleContextDescriptorProtocol) { return module } else { - var parent: SymbolOrElement? = try parent(in: machO) + var parent: SymbolOrElement? = try parent(in: context) while let currentParent = parent { if let module = currentParent.resolved?.contextDescriptor as? (any ModuleContextDescriptorProtocol) { return module } - parent = try currentParent.resolved?.parent(in: machO) + parent = try currentParent.resolved?.parent(in: context) } return nil } } - public func isCImportedContextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Bool { - guard let moduleContextDescriptor = try moduleContextDescriptor(in: machO) else { return false } - let moduleName = try moduleContextDescriptor.name(in: machO) + public func isCImportedContextDescriptor(in context: some ReadingContext) throws -> Bool { + guard let moduleContextDescriptor = try moduleContextDescriptor(in: context) else { return false } + let moduleName = try moduleContextDescriptor.name(in: context) return moduleName == CImportedModuleNames.cSynthesized || moduleName == CImportedModuleNames.objectiveC } } +// MARK: - Deprecated Mach-O and pointer forms + extension ContextDescriptorProtocol { - public func parent() throws -> SymbolOrElement? { - guard layout.flags.kind != .module, layout.parent.isValid else { return nil } - return try layout.parent.resolve(from: layout.pointer(from: asPointer, of: .parent)).asOptional + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: machO.context).") + public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try parent(in: machO.context) } - public func genericContext() throws -> GenericContext? { - guard layout.flags.isGeneric else { return nil } - return try GenericContext(contextDescriptor: self) + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: machO.context).") + public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { + try genericContext(in: machO.context) } - public func moduleContextDescriptor() throws -> (any ModuleContextDescriptorProtocol)? { - if let module = self as? (any ModuleContextDescriptorProtocol) { - return module - } else { - var parent: SymbolOrElement? = try parent() - while let currentParent = parent { - if let module = currentParent.resolved?.contextDescriptor as? (any ModuleContextDescriptorProtocol) { - return module - } - parent = try currentParent.resolved?.parent() - } - return nil - } + @available(*, deprecated, message: "Pass a ReadingContext: moduleContextDescriptor(in: machO.context).") + public func moduleContextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> (any ModuleContextDescriptorProtocol)? { + try moduleContextDescriptor(in: machO.context) } - public func isCImportedContextDescriptor() throws -> Bool { - guard let moduleContextDescriptor = try moduleContextDescriptor() else { return false } - let moduleName = try moduleContextDescriptor.name() - return moduleName == CImportedModuleNames.cSynthesized || moduleName == CImportedModuleNames.objectiveC + @available(*, deprecated, message: "Pass a ReadingContext: isCImportedContextDescriptor(in: machO.context).") + public func isCImportedContextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Bool { + try isCImportedContextDescriptor(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension ContextDescriptorProtocol { - public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { - guard layout.flags.kind != .module, layout.parent.isValid else { return nil } - let baseAddress = try context.addressFromOffset(offset) - let address = context.advanceAddress(baseAddress, by: layout.offset(of: .parent).cast()) - return try layout.parent.resolve(at: address, in: context).asOptional + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: .inProcess).") + public func parent() throws -> SymbolOrElement? { + try parent(in: InProcessContext.shared) } - public func genericContext(in context: some ReadingContext) throws -> GenericContext? { - guard layout.flags.isGeneric else { return nil } - return try GenericContext(contextDescriptor: self, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: .inProcess).") + public func genericContext() throws -> GenericContext? { + try genericContext(in: InProcessContext.shared) } - public func moduleContextDescriptor(in context: some ReadingContext) throws -> (any ModuleContextDescriptorProtocol)? { - if let module = self as? (any ModuleContextDescriptorProtocol) { - return module - } else { - var parent: SymbolOrElement? = try parent(in: context) - while let currentParent = parent { - if let module = currentParent.resolved?.contextDescriptor as? (any ModuleContextDescriptorProtocol) { - return module - } - parent = try currentParent.resolved?.parent(in: context) - } - return nil - } + @available(*, deprecated, message: "Pass a ReadingContext: moduleContextDescriptor(in: .inProcess).") + public func moduleContextDescriptor() throws -> (any ModuleContextDescriptorProtocol)? { + try moduleContextDescriptor(in: InProcessContext.shared) } - public func isCImportedContextDescriptor(in context: some ReadingContext) throws -> Bool { - guard let moduleContextDescriptor = try moduleContextDescriptor(in: context) else { return false } - let moduleName = try moduleContextDescriptor.name(in: context) - return moduleName == CImportedModuleNames.cSynthesized || moduleName == CImportedModuleNames.objectiveC + @available(*, deprecated, message: "Pass a ReadingContext: isCImportedContextDescriptor(in: .inProcess).") + public func isCImportedContextDescriptor() throws -> Bool { + try isCImportedContextDescriptor(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift similarity index 76% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift index 772e8685e..e624023e0 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextDescriptorWrapper.swift @@ -1,7 +1,9 @@ import MachOKit import MachOBase import SwiftStdlibToolbox +import FoundationToolbox +@Loggable(.private, subsystem: "com.machoswiftsection.macho-swift-section", category: "ContextDescriptorWrapper") public enum ContextDescriptorWrapper { case type(TypeContextDescriptorWrapper) case `protocol`(ProtocolDescriptor) @@ -128,22 +130,6 @@ public enum ContextDescriptorWrapper { } } - public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try contextDescriptor.parent(in: machO) - } - - public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { - return try contextDescriptor.genericContext(in: machO) - } - - public func parent() throws -> SymbolOrElement? { - return try contextDescriptor.parent() - } - - public func genericContext() throws -> GenericContext? { - return try contextDescriptor.genericContext() - } - // MARK: - ReadingContext Support public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { @@ -215,68 +201,6 @@ extension ContextDescriptorWrapper: Resolvable { case invalidContextDescriptor } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - let contextDescriptor: ContextDescriptor = try machO.readWrapperElement(offset: offset) - switch contextDescriptor.flags.kind { - case .class, - .struct, - .enum: - return try .type(.resolve(from: offset, in: machO)) - case .protocol: - return try .protocol(machO.readWrapperElement(offset: offset)) - case .anonymous: - return try .anonymous(machO.readWrapperElement(offset: offset)) - case .extension: - return try .extension(machO.readWrapperElement(offset: offset)) - case .module: - return try .module(machO.readWrapperElement(offset: offset)) - case .opaqueType: - return try .opaqueType(machO.readWrapperElement(offset: offset)) - default: - throw ResolutionError.invalidContextDescriptor - } - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - let contextDescriptor: ContextDescriptor = try .resolve(from: ptr) - switch contextDescriptor.flags.kind { - case .class, - .struct, - .enum: - return try .type(.resolve(from: ptr)) - case .protocol: - return try .protocol(.resolve(from: ptr)) - case .anonymous: - return try .anonymous(.resolve(from: ptr)) - case .extension: - return try .extension(.resolve(from: ptr)) - case .module: - return try .module(.resolve(from: ptr)) - case .opaqueType: - return try .opaqueType(.resolve(from: ptr)) - default: - throw ResolutionError.invalidContextDescriptor - } - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { - do { - return try resolve(from: offset, in: machO) as Self - } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") - return nil - } - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self? { - do { - return try resolve(from: ptr) as Self - } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") - return nil - } - } - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { let contextDescriptor: ContextDescriptor = try context.readWrapperElement(at: address) switch contextDescriptor.flags.kind { @@ -303,8 +227,52 @@ extension ContextDescriptorWrapper: Resolvable { do { return try resolve(at: address, in: context) as Self } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") + #log(.error, "context descriptor at \(String(describing: address), privacy: .public) unresolvable, read as absent: \(String(describing: error), privacy: .public)") return nil } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ContextDescriptorWrapper { + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: machO.context).") + public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try parent(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: machO.context).") + public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { + try genericContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: .inProcess).") + public func parent() throws -> SymbolOrElement? { + try parent(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: .inProcess).") + public func genericContext() throws -> GenericContext? { + try genericContext(in: InProcessContext.shared) + } + + @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: 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) + } +} diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextProtocol.swift similarity index 69% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/ContextProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextProtocol.swift index edbba515d..3e850d267 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextProtocol.swift @@ -8,20 +8,24 @@ public protocol ContextProtocol: Sendable { var descriptor: Descriptor { get } } -extension ContextProtocol { - public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - try descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - } +// MARK: - ReadingContext Support - public func parent() throws -> SymbolOrElement? { - try descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } +extension ContextProtocol { + public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { + try descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ContextProtocol { - public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { - try descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: machO.context).") + public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try parent(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: .inProcess).") + public func parent() throws -> SymbolOrElement? { + try parent(in: InProcessContext.shared) } } diff --git a/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextWrapper.swift new file mode 100644 index 000000000..82fd29f5c --- /dev/null +++ b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/ContextWrapper.swift @@ -0,0 +1,115 @@ +import Foundation +import MachOKit +import FoundationToolbox +import MachOBase + +@CaseCheckable(.public) +@AssociatedValue(.public) +public enum ContextWrapper: Resolvable { + case type(TypeContextWrapper) + case `protocol`(`Protocol`) + case anonymous(AnonymousContext) + case `extension`(ExtensionContext) + case module(ModuleContext) + case opaqueType(OpaqueType) + + public var context: any ContextProtocol { + switch self { + case .type(let typeWrapper): + switch typeWrapper { + case .enum(let `enum`): + return `enum` + case .struct(let `struct`): + return `struct` + case .class(let `class`): + return `class` + } + case .protocol(let protocolWrapper): + return protocolWrapper + case .anonymous(let anonymousContext): + return anonymousContext + case .extension(let extensionContext): + return extensionContext + case .module(let moduleContext): + return moduleContext + case .opaqueType(let opaqueType): + return opaqueType + } + } +} + +// MARK: - ReadingContext Support + +extension ContextWrapper { + public static func forContextDescriptorWrapper(_ contextDescriptorWrapper: ContextDescriptorWrapper, in context: some ReadingContext) throws -> Self { + switch contextDescriptorWrapper { + case .type(let typeContextDescriptorWrapper): + switch typeContextDescriptorWrapper { + case .enum(let enumDescriptor): + return try .type(.enum(.init(descriptor: enumDescriptor, in: context))) + case .struct(let structDescriptor): + return try .type(.struct(.init(descriptor: structDescriptor, in: context))) + case .class(let classDescriptor): + return try .type(.class(.init(descriptor: classDescriptor, in: context))) + } + case .protocol(let protocolDescriptor): + return try .protocol(.init(descriptor: protocolDescriptor, in: context)) + case .anonymous(let anonymousContextDescriptor): + return try .anonymous(.init(descriptor: anonymousContextDescriptor, in: context)) + case .extension(let extensionContextDescriptor): + return try .extension(.init(descriptor: extensionContextDescriptor, in: context)) + case .module(let moduleContextDescriptor): + return try .module(.init(descriptor: moduleContextDescriptor, in: context)) + case .opaqueType(let opaqueTypeDescriptor): + return try .opaqueType(.init(descriptor: opaqueTypeDescriptor, in: context)) + } + } + + public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { + switch self { + case .type(let typeWrapper): + switch typeWrapper { + case .enum(let `enum`): + return try `enum`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + case .struct(let `struct`): + return try `struct`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + case .class(let `class`): + return try `class`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + } + case .protocol(let `protocol`): + return try `protocol`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + case .anonymous(let anonymousContext): + return try anonymousContext.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + case .extension(let extensionContext): + return try extensionContext.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + case .module(let moduleContext): + return try moduleContext.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + case .opaqueType(let opaqueType): + return try opaqueType.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } + } + } +} + +// MARK: - Deprecated Mach-O and pointer forms + +extension ContextWrapper { + @available(*, deprecated, message: "Pass a ReadingContext: forContextDescriptorWrapper(_:in: machO.context).") + public static func forContextDescriptorWrapper(_ contextDescriptorWrapper: ContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Self { + try forContextDescriptorWrapper(contextDescriptorWrapper, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: machO.context).") + public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try parent(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: forContextDescriptorWrapper(_:in: .inProcess).") + public static func forContextDescriptorWrapper(_ contextDescriptorWrapper: ContextDescriptorWrapper) throws -> Self { + try forContextDescriptorWrapper(contextDescriptorWrapper, in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: .inProcess).") + public func parent() throws -> SymbolOrElement? { + try parent(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift similarity index 64% rename from Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift index d90a72421..e42903bd1 100644 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ContextDescriptor/NamedContextDescriptorProtocol.swift @@ -4,33 +4,37 @@ import MachOBase public protocol NamedContextDescriptorProtocol: ContextDescriptorProtocol where Layout: NamedContextDescriptorLayout {} extension NamedContextDescriptorProtocol { - public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { - try layout.name.resolve(from: offset + layout.offset(of: .name), in: machO) + public func name(in context: some ReadingContext) throws -> String { + let baseAddress = try context.addressFromOffset(offset + layout.offset(of: .name)) + return try layout.name.resolve(at: baseAddress, in: context) } - public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.name.resolveAny(from: offset + layout.offset(of: .name), in: machO) + public func mangledName(in context: some ReadingContext) throws -> MangledName { + let baseAddress = try context.addressFromOffset(offset + layout.offset(of: .name)) + return try layout.name.resolveAny(at: baseAddress, in: context) } +} - public func name() throws -> String { - try layout.name.resolve(from: layout.pointer(from: asPointer, of: .name)) - } +// MARK: - Deprecated Mach-O and pointer forms - public func mangledName() throws -> MangledName { - try layout.name.resolveAny(from: layout.pointer(from: asPointer, of: .name)) +extension NamedContextDescriptorProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: name(in: machO.context).") + public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try name(in: machO.context) } -} -// MARK: - ReadingContext Support + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: machO.context).") + public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledName(in: machO.context) + } -extension NamedContextDescriptorProtocol { - public func name(in context: some ReadingContext) throws -> String { - let baseAddress = try context.addressFromOffset(offset + layout.offset(of: .name)) - return try layout.name.resolve(at: baseAddress, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: name(in: .inProcess).") + public func name() throws -> String { + try name(in: InProcessContext.shared) } - public func mangledName(in context: some ReadingContext) throws -> MangledName { - let baseAddress = try context.addressFromOffset(offset + layout.offset(of: .name)) - return try layout.name.resolveAny(at: baseAddress, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: .inProcess).") + public func mangledName() throws -> MangledName { + try mangledName(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/DispatchClass/DispatchClassMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/DispatchClass/DispatchClassMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/DispatchClass/DispatchClassMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/DispatchClass/DispatchClassMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExistentialMetatypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialMetatypeMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ExistentialType/ExistentialMetatypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialMetatypeMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeFlags.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeFlags.swift diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadata.swift similarity index 69% rename from Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadata.swift index 6ab562dbd..3f727b966 100644 --- a/Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadata.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadata.swift @@ -37,38 +37,6 @@ extension ExistentialTypeMetadata { } -extension ExistentialTypeMetadata { - public func superclassConstraint(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ConstMetadataPointer? { - guard layout.flags.hasSuperclassConstraint else { return nil } - return try .resolve(from: offset + layoutSize, in: machO) - } - - public func protocols(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [ProtocolDescriptorRef] { - guard layout.numberOfProtocols != .zero else { return [] } - var offset = offset + layoutSize - if layout.flags.hasSuperclassConstraint { - offset.offset(of: ConstMetadataPointer.self) - } - return try machO.readElements(offset: offset, numberOfElements: layout.numberOfProtocols.cast()) - } -} - -extension ExistentialTypeMetadata { - public func superclassConstraint() throws -> ConstMetadataPointer? { - guard layout.flags.hasSuperclassConstraint else { return nil } - return try .resolve(from: .init(bitPattern: offset + layoutSize)) - } - - public func protocols() throws -> [ProtocolDescriptorRef] { - guard layout.numberOfProtocols != .zero else { return [] } - var offset = layoutSize - if layout.flags.hasSuperclassConstraint { - offset.offset(of: ConstMetadataPointer.self) - } - return try asPointer.readElements(offset: offset, numberOfElements: layout.numberOfProtocols.cast()) - } -} - public enum ExistentialTypeRepresentation { case opaque case `class` @@ -92,3 +60,27 @@ extension ExistentialTypeMetadata { return try context.readElements(at: try context.addressFromOffset(offset), numberOfElements: layout.numberOfProtocols.cast()) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ExistentialTypeMetadata { + @available(*, deprecated, message: "Pass a ReadingContext: superclassConstraint(in: machO.context).") + public func superclassConstraint(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ConstMetadataPointer? { + try superclassConstraint(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: protocols(in: machO.context).") + public func protocols(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [ProtocolDescriptorRef] { + try protocols(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: superclassConstraint(in: .inProcess).") + public func superclassConstraint() throws -> ConstMetadataPointer? { + try superclassConstraint(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: protocols(in: .inProcess).") + public func protocols() throws -> [ProtocolDescriptorRef] { + try protocols(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExistentialTypeMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift similarity index 76% rename from Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift index 540e23d78..a2652489a 100644 --- a/Sources/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/ExtendedExistentialTypeShape.swift @@ -11,24 +11,26 @@ public struct ExtendedExistentialTypeShape: ResolvableLocatableLayoutWrapper { } } -extension ExtendedExistentialTypeShape { - public func existentialType(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.existentialType.resolve(from: offset(of: \.existentialType), in: machO) - } -} +// MARK: - ReadingContext Support extension ExtendedExistentialTypeShape { - public func existentialType() throws -> MangledName { - try layout.existentialType.resolve(from: pointer(of: \.existentialType)) + public func existentialType(in context: some ReadingContext) throws -> MangledName { + let baseAddress = try context.addressFromOffset(offset(of: \.existentialType)) + return try layout.existentialType.resolve(at: baseAddress, in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ExtendedExistentialTypeShape { - public func existentialType(in context: some ReadingContext) throws -> MangledName { - let baseAddress = try context.addressFromOffset(offset(of: \.existentialType)) - return try layout.existentialType.resolve(at: baseAddress, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: existentialType(in: machO.context).") + public func existentialType(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try existentialType(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: existentialType(in: .inProcess).") + public func existentialType() throws -> MangledName { + try existentialType(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift similarity index 73% rename from Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift rename to Sources/ABI/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift index 0852ba80a..7f6a009a0 100644 --- a/Sources/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ExistentialType/NonUniqueExtendedExistentialTypeShape.swift @@ -10,24 +10,25 @@ public struct NonUniqueExtendedExistentialTypeShape: ResolvableLocatableLayoutWr } } +// MARK: - ReadingContext Support + extension NonUniqueExtendedExistentialTypeShape { - public func existentialType(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.localCopy.existentialType.resolve(from: offset(of: \.localCopy.existentialType), in: machO) + public func existentialType(in context: some ReadingContext) throws -> MangledName { + let baseAddress = try context.addressFromOffset(offset(of: \.localCopy.existentialType)) + return try layout.localCopy.existentialType.resolve(at: baseAddress, in: context) } } +// MARK: - Deprecated Mach-O and pointer forms extension NonUniqueExtendedExistentialTypeShape { - public func existentialType() throws -> MangledName { - try layout.localCopy.existentialType.resolve(from: pointer(of: \.localCopy.existentialType)) + @available(*, deprecated, message: "Pass a ReadingContext: existentialType(in: machO.context).") + public func existentialType(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try existentialType(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension NonUniqueExtendedExistentialTypeShape { - public func existentialType(in context: some ReadingContext) throws -> MangledName { - let baseAddress = try context.addressFromOffset(offset(of: \.localCopy.existentialType)) - return try layout.localCopy.existentialType.resolve(at: baseAddress, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: existentialType(in: .inProcess).") + public func existentialType() throws -> MangledName { + try existentialType(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift b/Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContext.swift similarity index 65% rename from Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift rename to Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContext.swift index da5efa188..8e4beff44 100644 --- a/Sources/MachOSwiftSection/Models/Extension/ExtensionContext.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContext.swift @@ -8,18 +8,6 @@ public struct ExtensionContext: TopLevelType, ContextProtocol { public let genericContext: GenericContext? public let extendedContextMangledName: MangledName? - - public init(descriptor: ExtensionContextDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - self.extendedContextMangledName = try descriptor.extendedContext(in: machO) - self.genericContext = try descriptor.genericContext(in: machO) - } - - public init(descriptor: ExtensionContextDescriptor) throws { - self.descriptor = descriptor - self.extendedContextMangledName = try descriptor.extendedContext() - self.genericContext = try descriptor.genericContext() - } } // MARK: - ReadingContext Support @@ -31,3 +19,17 @@ extension ExtensionContext { self.genericContext = try descriptor.genericContext(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ExtensionContext { + @available(*, deprecated, message: "Pass a ReadingContext: ExtensionContext(descriptor:in: machO.context).") + public init(descriptor: ExtensionContextDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: ExtensionContext(descriptor:in: .inProcess).") + public init(descriptor: ExtensionContextDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift similarity index 74% rename from Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift index f5a6e1639..5f35e6c66 100644 --- a/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptor.swift @@ -11,23 +11,25 @@ public struct ExtensionContextDescriptor: ExtensionContextDescriptorProtocol { } } -extension ExtensionContextDescriptorProtocol { - public func extendedContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { - try layout.extendedContext.resolve(from: offset + layout.offset(of: .extendedContext), in: machO) - } -} +// MARK: - ReadingContext Support extension ExtensionContextDescriptorProtocol { - public func extendedContext() throws -> MangledName? { - try layout.extendedContext.resolve(from: layout.pointer(from: asPointer, of: .extendedContext)) + public func extendedContext(in context: some ReadingContext) throws -> MangledName? { + let baseAddress = try context.addressFromOffset(offset) + return try layout.extendedContext.resolve(at: context.advanceAddress(baseAddress, by: layout.offset(of: .extendedContext)), in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ExtensionContextDescriptorProtocol { - public func extendedContext(in context: some ReadingContext) throws -> MangledName? { - let baseAddress = try context.addressFromOffset(offset) - return try layout.extendedContext.resolve(at: context.advanceAddress(baseAddress, by: layout.offset(of: .extendedContext)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: extendedContext(in: machO.context).") + public func extendedContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { + try extendedContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: extendedContext(in: .inProcess).") + public func extendedContext() throws -> MangledName? { + try extendedContext(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Extension/ExtensionContextDescriptorProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift similarity index 69% rename from Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift index 87bc243aa..32f4e1049 100644 --- a/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptor.swift @@ -17,40 +17,40 @@ extension FieldDescriptor { public var kind: FieldDescriptorKind { .init(rawValue: layout.kind)! } } +// MARK: - ReadingContext Support + extension FieldDescriptor { - public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machO) + public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { + return try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) } - public func records(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [FieldRecord] { + public func records(in context: some ReadingContext) throws -> [FieldRecord] { guard layout.fieldRecordSize != 0 else { return [] } let offset = offset + MemoryLayout.size - return try machO.readWrapperElements(offset: offset, numberOfElements: layout.numFields.cast()) + return try context.readWrapperElements(at: try context.addressFromOffset(offset), numberOfElements: layout.numFields.cast()) } } +// MARK: - Deprecated Mach-O and pointer forms + extension FieldDescriptor { - public func mangledTypeName() throws -> MangledName { - return try layout.mangledTypeName.resolve(from: pointer(of: \.mangledTypeName)) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: machO.context).") + public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledTypeName(in: machO.context) } - public func records() throws -> [FieldRecord] { - guard layout.fieldRecordSize != 0 else { return [] } - let offset = MemoryLayout.size - return try asPointer.readWrapperElements(offset: offset, numberOfElements: layout.numFields.cast()) + @available(*, deprecated, message: "Pass a ReadingContext: records(in: machO.context).") + public func records(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [FieldRecord] { + try records(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension FieldDescriptor { - public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { - return try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: .inProcess).") + public func mangledTypeName() throws -> MangledName { + try mangledTypeName(in: InProcessContext.shared) } - public func records(in context: some ReadingContext) throws -> [FieldRecord] { - guard layout.fieldRecordSize != 0 else { return [] } - let offset = offset + MemoryLayout.size - return try context.readWrapperElements(at: try context.addressFromOffset(offset), numberOfElements: layout.numFields.cast()) + @available(*, deprecated, message: "Pass a ReadingContext: records(in: .inProcess).") + public func records() throws -> [FieldRecord] { + try records(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptorKind.swift b/Sources/ABI/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptorKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptorKind.swift rename to Sources/ABI/MachOSwiftSection/Models/FieldDescriptor/FieldDescriptorKind.swift diff --git a/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift b/Sources/ABI/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift similarity index 72% rename from Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift index a38e4f3ef..a571b13b7 100644 --- a/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/FieldRecord/FieldRecord.swift @@ -11,9 +11,11 @@ public struct FieldRecord: ResolvableLocatableLayoutWrapper { } } +// MARK: - ReadingContext Support + extension FieldRecord { - public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.mangledTypeName.resolve(from: offset(of: \.mangledTypeName), in: machO) + public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { + return try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) } /// The field's name, or `""` when the record carries none. A null name @@ -21,32 +23,32 @@ extension FieldRecord { /// type) for an enum element that is unavailable at run time, while the /// element keeps its tag. Reading through the null pointer would /// otherwise decode the record's own bytes as the name. - public func fieldName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + public func fieldName(in context: some ReadingContext) throws -> String { guard !layout.fieldName.isNull else { return "" } - return try layout.fieldName.resolve(from: offset(of: \.fieldName), in: machO) + return try layout.fieldName.resolve(at: try context.addressFromOffset(offset(of: \.fieldName)), in: context) } } +// MARK: - Deprecated Mach-O and pointer forms + extension FieldRecord { - public func mangledTypeName() throws -> MangledName { - return try layout.mangledTypeName.resolve(from: pointer(of: \.mangledTypeName)) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: machO.context).") + public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledTypeName(in: machO.context) } - public func fieldName() throws -> String { - guard !layout.fieldName.isNull else { return "" } - return try layout.fieldName.resolve(from: pointer(of: \.fieldName)) + @available(*, deprecated, message: "Pass a ReadingContext: fieldName(in: machO.context).") + public func fieldName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try fieldName(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension FieldRecord { - public func mangledTypeName(in context: some ReadingContext) throws -> MangledName { - return try layout.mangledTypeName.resolve(at: try context.addressFromOffset(offset(of: \.mangledTypeName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: .inProcess).") + public func mangledTypeName() throws -> MangledName { + try mangledTypeName(in: InProcessContext.shared) } - public func fieldName(in context: some ReadingContext) throws -> String { - guard !layout.fieldName.isNull else { return "" } - return try layout.fieldName.resolve(at: try context.addressFromOffset(offset(of: \.fieldName)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: fieldName(in: .inProcess).") + public func fieldName() throws -> String { + try fieldName(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/FieldRecord/FieldRecordFlags.swift b/Sources/ABI/MachOSwiftSection/Models/FieldRecord/FieldRecordFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/FieldRecord/FieldRecordFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/FieldRecord/FieldRecordFlags.swift diff --git a/Sources/MachOSwiftSection/Models/ForeignType/ForeignClassMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignClassMetadata.swift similarity index 70% rename from Sources/MachOSwiftSection/Models/ForeignType/ForeignClassMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignClassMetadata.swift index 19a77e576..0ac827b3f 100644 --- a/Sources/MachOSwiftSection/Models/ForeignType/ForeignClassMetadata.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignClassMetadata.swift @@ -11,20 +11,24 @@ public struct ForeignClassMetadata: MetadataProtocol { } } -extension ForeignClassMetadata { - public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor { - try layout.descriptor.resolve(in: machO) - } +// MARK: - ReadingContext Support - public func classDescriptor() throws -> ClassDescriptor { - try layout.descriptor.resolve() +extension ForeignClassMetadata { + public func classDescriptor(in context: some ReadingContext) throws -> ClassDescriptor { + try layout.descriptor.resolve(in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ForeignClassMetadata { - public func classDescriptor(in context: some ReadingContext) throws -> ClassDescriptor { - try layout.descriptor.resolve(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: machO.context).") + public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor { + try classDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: .inProcess).") + public func classDescriptor() throws -> ClassDescriptor { + try classDescriptor(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ForeignType/ForeignClassMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignClassMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ForeignType/ForeignClassMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignClassMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadata.swift similarity index 69% rename from Sources/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadata.swift index ecb471255..0eeb6a0cd 100644 --- a/Sources/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadata.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadata.swift @@ -10,20 +10,24 @@ public struct ForeignReferenceTypeMetadata: MetadataProtocol { } } -extension ForeignReferenceTypeMetadata { - public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor { - try layout.descriptor.resolve(in: machO) - } +// MARK: - ReadingContext Support - public func classDescriptor() throws -> ClassDescriptor { - try layout.descriptor.resolve() +extension ForeignReferenceTypeMetadata { + public func classDescriptor(in context: some ReadingContext) throws -> ClassDescriptor { + try layout.descriptor.resolve(in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ForeignReferenceTypeMetadata { - public func classDescriptor(in context: some ReadingContext) throws -> ClassDescriptor { - try layout.descriptor.resolve(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: machO.context).") + public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor { + try classDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: .inProcess).") + public func classDescriptor() throws -> ClassDescriptor { + try classDescriptor(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/ForeignType/ForeignReferenceTypeMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionParameterOwnership.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionParameterOwnership.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Function/FunctionParameterOwnership.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionParameterOwnership.swift diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionParameterTypeFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionParameterTypeFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Function/FunctionParameterTypeFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionParameterTypeFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionTypeDifferentiabilityKind.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeDifferentiabilityKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Function/FunctionTypeDifferentiabilityKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeDifferentiabilityKind.swift diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionTypeExtendedFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeExtendedFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Function/FunctionTypeExtendedFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeExtendedFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionTypeFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Function/FunctionTypeFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionTypeMetadata+TrailingObjects.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeMetadata+TrailingObjects.swift similarity index 95% rename from Sources/MachOSwiftSection/Models/Function/FunctionTypeMetadata+TrailingObjects.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeMetadata+TrailingObjects.swift index ec3d56602..497c01e76 100644 --- a/Sources/MachOSwiftSection/Models/Function/FunctionTypeMetadata+TrailingObjects.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeMetadata+TrailingObjects.swift @@ -134,7 +134,11 @@ extension FunctionTypeMetadata { /// The extended flag word, or `nil` when the record carries none. public func extendedFlags(in context: some ReadingContext) throws -> FunctionTypeExtendedFlags? { guard let extendedFlagsOffset else { return nil } - return try context.readElement(at: try context.addressFromOffset(extendedFlagsOffset)) + // Annotated: asking for the optional directly would read the + // Optional's in-memory shape, one tag byte past the flag word — the + // padding the runtime leaves unwritten. + let extendedFlags: FunctionTypeExtendedFlags = try context.readElement(at: try context.addressFromOffset(extendedFlagsOffset)) + return extendedFlags } /// Location of the thrown error type, or `nil` when the function does not diff --git a/Sources/MachOSwiftSection/Models/Function/FunctionTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Function/FunctionTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Function/FunctionTypeMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/FunctionPointer/AsyncFunctionPointer.swift b/Sources/ABI/MachOSwiftSection/Models/FunctionPointer/AsyncFunctionPointer.swift similarity index 96% rename from Sources/MachOSwiftSection/Models/FunctionPointer/AsyncFunctionPointer.swift rename to Sources/ABI/MachOSwiftSection/Models/FunctionPointer/AsyncFunctionPointer.swift index 32a2e44ac..da1d63028 100644 --- a/Sources/MachOSwiftSection/Models/FunctionPointer/AsyncFunctionPointer.swift +++ b/Sources/ABI/MachOSwiftSection/Models/FunctionPointer/AsyncFunctionPointer.swift @@ -22,7 +22,7 @@ import MachOBase /// Layout mirrors `swift::AsyncFunctionPointer` (`swift/ABI/Executor.h`). /// There is no section listing these records — they live in `__TEXT,__const` /// and are reached by symbol or by another descriptor's relative pointer, so -/// the only entry is `AsyncFunctionPointer.resolve(from:in:)` with an offset +/// the only entry is `AsyncFunctionPointer.resolve(at:in:)` with an address /// the caller already has. See also ``CoroFunctionPointer``, the same idea for /// callee-allocated coroutines. @LocatableLayoutWrapping diff --git a/Sources/MachOSwiftSection/Models/FunctionPointer/CoroFunctionPointer.swift b/Sources/ABI/MachOSwiftSection/Models/FunctionPointer/CoroFunctionPointer.swift similarity index 97% rename from Sources/MachOSwiftSection/Models/FunctionPointer/CoroFunctionPointer.swift rename to Sources/ABI/MachOSwiftSection/Models/FunctionPointer/CoroFunctionPointer.swift index cf462343a..ac1e85180 100644 --- a/Sources/MachOSwiftSection/Models/FunctionPointer/CoroFunctionPointer.swift +++ b/Sources/ABI/MachOSwiftSection/Models/FunctionPointer/CoroFunctionPointer.swift @@ -27,7 +27,7 @@ import MachOBase /// /// There is no section listing these records — they live in `__TEXT,__const` /// and are reached by symbol or by another descriptor's relative pointer, so -/// the only entry is `CoroFunctionPointer.resolve(from:in:)`. +/// the only entry is `CoroFunctionPointer.resolve(at:in:)`. @LocatableLayoutWrapping public struct CoroFunctionPointer: ResolvableLocatableLayoutWrapper { public struct Layout: LayoutProtocol { diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericContext.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift similarity index 94% rename from Sources/MachOSwiftSection/Models/Generic/GenericContext.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift index 15df189c0..0b5bb7308 100644 --- a/Sources/MachOSwiftSection/Models/Generic/GenericContext.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContext.swift @@ -89,28 +89,6 @@ public struct TargetGenericContext [GenericRequirementDescriptor] { - let parentRequirements = parentRequirements.flatMap { $0 } - var currentRequirements: [GenericRequirementDescriptor] = [] - for requirement in requirements { - if !parentRequirements.contains(where: { $0.isContentEqual(to: requirement, in: machO) }) { - currentRequirements.append(requirement) - } - } - return currentRequirements - } - - public func uniqueCurrentRequirementsInProcess() -> [GenericRequirementDescriptor] { - let parentRequirements = parentRequirements.flatMap { $0 } - var currentRequirements: [GenericRequirementDescriptor] = [] - for requirement in requirements { - if !parentRequirements.contains(where: { $0.isContentEqual(to: requirement) }) { - currentRequirements.append(requirement) - } - } - return currentRequirements - } - public func asGenericContext() -> GenericContext { .init( offset: offset, @@ -141,14 +119,6 @@ public struct TargetGenericContext [GenericRequirementDescriptor] { + uniqueCurrentRequirements(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: uniqueCurrentRequirements(in: .inProcess).") + public func uniqueCurrentRequirementsInProcess() -> [GenericRequirementDescriptor] { + uniqueCurrentRequirements(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericContextDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContextDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericContextDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericContextDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeaderProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeaderProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeaderProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericContextDescriptorHeaderProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericEnvironment.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericEnvironment.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericEnvironment.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericEnvironment.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericEnvironmentFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericEnvironmentFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericEnvironmentFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericEnvironmentFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericPackKind.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericPackKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericPackKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericPackKind.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericPackShapeDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericPackShapeDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericPackShapeDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericPackShapeDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericPackShapeHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericPackShapeHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericPackShapeHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericPackShapeHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericParamDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericParamDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericParamDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericParamDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericParamKind.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericParamKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericParamKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericParamKind.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirement.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirement.swift similarity index 65% rename from Sources/MachOSwiftSection/Models/Generic/GenericRequirement.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirement.swift index 8b61111ab..d1fd9ebaa 100644 --- a/Sources/MachOSwiftSection/Models/Generic/GenericRequirement.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirement.swift @@ -8,18 +8,6 @@ public struct GenericRequirement: Sendable, TopLevelType { public let paramManagledName: MangledName public let content: ResolvedGenericRequirementContent - - public init(descriptor: GenericRequirementDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - self.paramManagledName = try descriptor.paramMangledName(in: machO) - self.content = try descriptor.resolvedContent(in: machO) - } - - public init(descriptor: GenericRequirementDescriptor) throws { - self.descriptor = descriptor - self.paramManagledName = try descriptor.paramMangledName() - self.content = try descriptor.resolvedContent() - } } // MARK: - ReadingContext Support @@ -31,3 +19,17 @@ extension GenericRequirement { self.content = try descriptor.resolvedContent(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension GenericRequirement { + @available(*, deprecated, message: "Pass a ReadingContext: GenericRequirement(descriptor:in: machO.context).") + public init(descriptor: GenericRequirementDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: GenericRequirement(descriptor:in: .inProcess).") + public init(descriptor: GenericRequirementDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementContent.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementContent.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericRequirementContent.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementContent.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift similarity index 61% rename from Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift index 7c82d88dc..87b4b23eb 100644 --- a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementDescriptor.swift @@ -38,103 +38,83 @@ extension GenericRequirementDescriptor { } } +// MARK: - ReadingContext Support + extension GenericRequirementDescriptor { - public func isContentEqual(to other: GenericRequirementDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) -> Bool { - guard let lhsResolvedParam = try? paramMangledName(in: machO), let rhsResolvedParam = try? other.paramMangledName(in: machO) else { return false } - guard let lhsResolvedContent = try? resolvedContent(in: machO), let rhsResolvedContent = try? other.resolvedContent(in: machO) else { return false } + public func isContentEqual(to other: GenericRequirementDescriptor, in context: some ReadingContext) -> Bool { + guard let lhsResolvedParam = try? paramMangledName(in: context), let rhsResolvedParam = try? other.paramMangledName(in: context) else { return false } + guard let lhsResolvedContent = try? resolvedContent(in: context), let rhsResolvedContent = try? other.resolvedContent(in: context) else { return false } return layout.flags == other.flags && lhsResolvedParam == rhsResolvedParam && lhsResolvedContent == rhsResolvedContent } - public func paramMangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.param.resolve(from: offset(of: \.param), in: machO) + public func paramMangledName(in context: some ReadingContext) throws -> MangledName { + let baseAddress = try context.addressFromOffset(offset(of: \.param)) + return try layout.param.resolve(at: baseAddress, in: context) } - public func type(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try RelativeDirectPointer(relativeOffset: layout.content).resolve(from: offset(of: \.content), in: machO) + public func type(in context: some ReadingContext) throws -> MangledName { + let baseAddress = try context.addressFromOffset(offset(of: \.content)) + return try RelativeDirectPointer(relativeOffset: layout.content).resolve(at: baseAddress, in: context) } - public func resolvedContent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedGenericRequirementContent { - let offset = offset(of: \.content) + public func resolvedContent(in context: some ReadingContext) throws -> ResolvedGenericRequirementContent { + let contentOffset = offset(of: \.content) + let baseAddress = try context.addressFromOffset(contentOffset) switch content { case .type(let relativeDirectPointer): - return try .type(relativeDirectPointer.resolve(from: offset, in: machO)) + return try .type(relativeDirectPointer.resolve(at: baseAddress, in: context)) case .protocol(let relativeProtocolDescriptorPointer): - return try .protocol(relativeProtocolDescriptorPointer.resolve(from: offset, in: machO)) + return try .protocol(relativeProtocolDescriptorPointer.resolve(at: baseAddress, in: context)) case .layout(let genericRequirementLayoutKind): return .layout(genericRequirementLayoutKind) case .conformance(let relativeIndirectablePointer): - return try .conformance(relativeIndirectablePointer.resolve(from: offset, in: machO)) + return try .conformance(relativeIndirectablePointer.resolve(at: baseAddress, in: context)) case .invertedProtocols(let invertedProtocols): return .invertedProtocols(invertedProtocols) } } } +// MARK: - Deprecated Mach-O and pointer forms + extension GenericRequirementDescriptor { - public func isContentEqual(to other: GenericRequirementDescriptor) -> Bool { - guard let lhsResolvedParam = try? paramMangledName(), let rhsResolvedParam = try? other.paramMangledName() else { return false } - guard let lhsResolvedContent = try? resolvedContent(), let rhsResolvedContent = try? other.resolvedContent() else { return false } - return layout.flags == other.flags && lhsResolvedParam == rhsResolvedParam && lhsResolvedContent == rhsResolvedContent + @available(*, deprecated, message: "Pass a ReadingContext: isContentEqual(to:in: machO.context).") + public func isContentEqual(to other: GenericRequirementDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) -> Bool { + isContentEqual(to: other, in: machO.context) } - public func paramMangledName() throws -> MangledName { - return try layout.param.resolve(from: pointer(of: \.param)) + @available(*, deprecated, message: "Pass a ReadingContext: paramMangledName(in: machO.context).") + public func paramMangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try paramMangledName(in: machO.context) } - public func type() throws -> MangledName { - return try RelativeDirectPointer(relativeOffset: layout.content).resolve(from: pointer(of: \.content)) + @available(*, deprecated, message: "Pass a ReadingContext: type(in: machO.context).") + public func type(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try type(in: machO.context) } - public func resolvedContent() throws -> ResolvedGenericRequirementContent { - let pointer = try pointer(of: \.content) - switch content { - case .type(let relativeDirectPointer): - return try .type(relativeDirectPointer.resolve(from: pointer)) - case .protocol(let relativeProtocolDescriptorPointer): - return try .protocol(relativeProtocolDescriptorPointer.resolve(from: pointer)) - case .layout(let genericRequirementLayoutKind): - return .layout(genericRequirementLayoutKind) - case .conformance(let relativeIndirectablePointer): - return try .conformance(relativeIndirectablePointer.resolve(from: pointer)) - case .invertedProtocols(let invertedProtocols): - return .invertedProtocols(invertedProtocols) - } + @available(*, deprecated, message: "Pass a ReadingContext: resolvedContent(in: machO.context).") + public func resolvedContent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedGenericRequirementContent { + try resolvedContent(in: machO.context) } -} -// MARK: - ReadingContext Support - -extension GenericRequirementDescriptor { - public func isContentEqual(to other: GenericRequirementDescriptor, in context: some ReadingContext) -> Bool { - guard let lhsResolvedParam = try? paramMangledName(in: context), let rhsResolvedParam = try? other.paramMangledName(in: context) else { return false } - guard let lhsResolvedContent = try? resolvedContent(in: context), let rhsResolvedContent = try? other.resolvedContent(in: context) else { return false } - return layout.flags == other.flags && lhsResolvedParam == rhsResolvedParam && lhsResolvedContent == rhsResolvedContent + @available(*, deprecated, message: "Pass a ReadingContext: isContentEqual(to:in: .inProcess).") + public func isContentEqual(to other: GenericRequirementDescriptor) -> Bool { + isContentEqual(to: other, in: InProcessContext.shared) } - public func paramMangledName(in context: some ReadingContext) throws -> MangledName { - let baseAddress = try context.addressFromOffset(offset(of: \.param)) - return try layout.param.resolve(at: baseAddress, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: paramMangledName(in: .inProcess).") + public func paramMangledName() throws -> MangledName { + try paramMangledName(in: InProcessContext.shared) } - public func type(in context: some ReadingContext) throws -> MangledName { - let baseAddress = try context.addressFromOffset(offset(of: \.content)) - return try RelativeDirectPointer(relativeOffset: layout.content).resolve(at: baseAddress, in: context) + @available(*, deprecated, message: "Pass a ReadingContext: type(in: .inProcess).") + public func type() throws -> MangledName { + try type(in: InProcessContext.shared) } - public func resolvedContent(in context: some ReadingContext) throws -> ResolvedGenericRequirementContent { - let contentOffset = offset(of: \.content) - let baseAddress = try context.addressFromOffset(contentOffset) - switch content { - case .type(let relativeDirectPointer): - return try .type(relativeDirectPointer.resolve(at: baseAddress, in: context)) - case .protocol(let relativeProtocolDescriptorPointer): - return try .protocol(relativeProtocolDescriptorPointer.resolve(at: baseAddress, in: context)) - case .layout(let genericRequirementLayoutKind): - return .layout(genericRequirementLayoutKind) - case .conformance(let relativeIndirectablePointer): - return try .conformance(relativeIndirectablePointer.resolve(at: baseAddress, in: context)) - case .invertedProtocols(let invertedProtocols): - return .invertedProtocols(invertedProtocols) - } + @available(*, deprecated, message: "Pass a ReadingContext: resolvedContent(in: .inProcess).") + public func resolvedContent() throws -> ResolvedGenericRequirementContent { + try resolvedContent(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericRequirementFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementKind.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericRequirementKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementKind.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericRequirementLayoutKind.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementLayoutKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericRequirementLayoutKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericRequirementLayoutKind.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericValueDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericValueDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericValueDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericValueDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericValueHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericValueHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericValueHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericValueHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericValueType.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericValueType.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericValueType.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericValueType.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/GenericWitnessTable.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/GenericWitnessTable.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/GenericWitnessTable.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/GenericWitnessTable.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericClassMetadataPattern.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericClassMetadataPattern.swift similarity index 87% rename from Sources/MachOSwiftSection/Models/Generic/Pattern/GenericClassMetadataPattern.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericClassMetadataPattern.swift index 43276e5c2..6d2733657 100644 --- a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericClassMetadataPattern.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericClassMetadataPattern.swift @@ -57,8 +57,17 @@ extension GenericClassMetadataPattern { /// The immediate-members partial pattern, or `nil` when the flags say /// there is none. It follows the extra-data pattern when both are /// present. - public func immediateMembersPattern(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericMetadataPartialPattern? { + public func immediateMembersPattern(in context: some ReadingContext) throws -> GenericMetadataPartialPattern? { guard hasImmediateMembersPattern else { return nil } - return try partialPatterns(in: machO).last + return try partialPatterns(in: context).last + } +} + +// MARK: - Deprecated Mach-O form + +extension GenericClassMetadataPattern { + @available(*, deprecated, message: "Pass a ReadingContext: immediateMembersPattern(in: machO.context).") + public func immediateMembersPattern(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericMetadataPartialPattern? { + try immediateMembersPattern(in: machO.context) } } diff --git a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPartialPattern.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPartialPattern.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPartialPattern.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPartialPattern.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternProtocol.swift similarity index 86% rename from Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternProtocol.swift index 8cf1e6079..d23f21c50 100644 --- a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericMetadataPatternProtocol.swift @@ -56,11 +56,6 @@ extension GenericMetadataPatternProtocol { + numberOfTrailingPartialPatterns * MemoryLayout.size } - public func partialPatterns(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [GenericMetadataPartialPattern] { - guard numberOfTrailingPartialPatterns > 0 else { return [] } - return try machO.readWrapperElements(offset: partialPatternsOffset, numberOfElements: numberOfTrailingPartialPatterns) - } - public func partialPatterns(in context: some ReadingContext) throws -> [GenericMetadataPartialPattern] { guard numberOfTrailingPartialPatterns > 0 else { return [] } return try context.readWrapperElements(at: try context.addressFromOffset(partialPatternsOffset), numberOfElements: numberOfTrailingPartialPatterns) @@ -68,8 +63,22 @@ extension GenericMetadataPatternProtocol { /// The extra-data partial pattern, or `nil` when the flags say there is /// none. Always the first trailing pattern when present. - public func extraDataPattern(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericMetadataPartialPattern? { + public func extraDataPattern(in context: some ReadingContext) throws -> GenericMetadataPartialPattern? { guard hasExtraDataPattern else { return nil } - return try partialPatterns(in: machO).first + return try partialPatterns(in: context).first + } +} + +// MARK: - Deprecated Mach-O form + +extension GenericMetadataPatternProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: partialPatterns(in: machO.context).") + public func partialPatterns(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [GenericMetadataPartialPattern] { + try partialPatterns(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: extraDataPattern(in: machO.context).") + public func extraDataPattern(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericMetadataPartialPattern? { + try extraDataPattern(in: machO.context) } } diff --git a/Sources/MachOSwiftSection/Models/Generic/Pattern/GenericValueMetadataPattern.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericValueMetadataPattern.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/Pattern/GenericValueMetadataPattern.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/GenericValueMetadataPattern.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/Pattern/ResilientClassMetadataPattern.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/ResilientClassMetadataPattern.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/Pattern/ResilientClassMetadataPattern.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/Pattern/ResilientClassMetadataPattern.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/TypeGenericContext.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/TypeGenericContext.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/TypeGenericContext.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/TypeGenericContext.swift diff --git a/Sources/MachOSwiftSection/Models/Generic/TypeGenericContextDescriptorHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Generic/TypeGenericContextDescriptorHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Generic/TypeGenericContextDescriptorHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Generic/TypeGenericContextDescriptorHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Heap/GenericBoxHeapMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Heap/GenericBoxHeapMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Heap/GenericBoxHeapMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Heap/GenericBoxHeapMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Heap/HeapLocalVariableMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Heap/HeapLocalVariableMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Heap/HeapLocalVariableMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Heap/HeapLocalVariableMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/KeyPath/KeyPathComponentHeader.swift b/Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComponentHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/KeyPath/KeyPathComponentHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComponentHeader.swift diff --git a/Sources/MachOSwiftSection/Models/KeyPath/KeyPathComponentKind.swift b/Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComponentKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/KeyPath/KeyPathComponentKind.swift rename to Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComponentKind.swift diff --git a/Sources/MachOSwiftSection/Models/KeyPath/KeyPathComputedIdentifier.swift b/Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComputedIdentifier.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/KeyPath/KeyPathComputedIdentifier.swift rename to Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComputedIdentifier.swift diff --git a/Sources/MachOSwiftSection/Models/KeyPath/KeyPathComputedPropertyBody.swift b/Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComputedPropertyBody.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/KeyPath/KeyPathComputedPropertyBody.swift rename to Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathComputedPropertyBody.swift diff --git a/Sources/MachOSwiftSection/Models/KeyPath/KeyPathStoredFieldOffset.swift b/Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathStoredFieldOffset.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/KeyPath/KeyPathStoredFieldOffset.swift rename to Sources/ABI/MachOSwiftSection/Models/KeyPath/KeyPathStoredFieldOffset.swift diff --git a/Sources/MachOSwiftSection/Models/KeyPath/PropertyDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/KeyPath/PropertyDescriptor.swift similarity index 77% rename from Sources/MachOSwiftSection/Models/KeyPath/PropertyDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/KeyPath/PropertyDescriptor.swift index d09db41bb..d2b364f1e 100644 --- a/Sources/MachOSwiftSection/Models/KeyPath/PropertyDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/KeyPath/PropertyDescriptor.swift @@ -22,7 +22,7 @@ import MachOBase /// There is no section listing property descriptors: they live in /// `__TEXT,__const` (or `__DATA_CONST,__const` once they carry relative /// pointers) and are reached only by symbol or by a pattern's relative -/// pointer. Get an offset first, then `PropertyDescriptor.resolve(from:in:)`. +/// pointer. Get an offset first, then `PropertyDescriptor.resolve(at:in:)`. @LocatableLayoutWrapping public struct PropertyDescriptor: ResolvableLocatableLayoutWrapper { public struct Layout: LayoutProtocol { @@ -95,71 +95,55 @@ extension PropertyDescriptor { } } +// MARK: - ReadingContext Support + extension PropertyDescriptor { /// The stored property's field offset, reading the body word when the /// header only carried a sentinel. `nil` when the descriptor is trivial /// or its component is not a stored one. - public func storedFieldOffset(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> KeyPathStoredFieldOffset? { + public func storedFieldOffset(in context: some ReadingContext) throws -> KeyPathStoredFieldOffset? { guard !isTrivial, let kind = header.storedFieldOffsetKind else { return nil } - return try storedFieldOffset(kind: kind, bodyWord: try UInt32.resolve(from: bodyOffset, in: machO)) + let bodyAddress = try context.addressFromOffset(bodyOffset) + return try storedFieldOffset(kind: kind, bodyWord: try UInt32.resolve(at: bodyAddress, in: context)) } /// The computed component's identifier, getter and setter. `nil` when the /// descriptor is trivial or its component is not a computed one. - public func computedPropertyBody(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> KeyPathComputedPropertyBody? { + public func computedPropertyBody(in context: some ReadingContext) throws -> KeyPathComputedPropertyBody? { guard !isTrivial, header.kind == .computed else { return nil } - let rawIdentifier: RelativeOffset = try RelativeOffset.resolve(from: bodyOffset, in: machO) - let getter: RelativeOffset = try RelativeOffset.resolve(from: bodyOffset + getterFieldRelativeOffset, in: machO) + let bodyAddress = try context.addressFromOffset(bodyOffset) + let getterAddress = context.advanceAddress(bodyAddress, by: getterFieldRelativeOffset) + let rawIdentifier: RelativeOffset = try RelativeOffset.resolve(at: bodyAddress, in: context) + let getter: RelativeOffset = try RelativeOffset.resolve(at: getterAddress, in: context) var setter: RelativeOffset? if header.isComputedSettable { - setter = try RelativeOffset.resolve(from: bodyOffset + settableSetterFieldRelativeOffset, in: machO) + let setterAddress = context.advanceAddress(bodyAddress, by: settableSetterFieldRelativeOffset) + setter = try RelativeOffset.resolve(at: setterAddress, in: context) } return computedPropertyBody(rawIdentifier: rawIdentifier, getter: getter, setter: setter) } } -// MARK: - In-Process Support +// MARK: - Deprecated Mach-O and pointer forms extension PropertyDescriptor { - public func storedFieldOffset() throws -> KeyPathStoredFieldOffset? { - guard !isTrivial, let kind = header.storedFieldOffsetKind else { return nil } - let bodyPointer = try asPointer.advanced(by: MemoryLayout.size) - return try storedFieldOffset(kind: kind, bodyWord: try UInt32.resolve(from: bodyPointer)) + @available(*, deprecated, message: "Pass a ReadingContext: storedFieldOffset(in: machO.context).") + public func storedFieldOffset(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> KeyPathStoredFieldOffset? { + try storedFieldOffset(in: machO.context) } - public func computedPropertyBody() throws -> KeyPathComputedPropertyBody? { - guard !isTrivial, header.kind == .computed else { return nil } - let bodyPointer = try asPointer.advanced(by: MemoryLayout.size) - let rawIdentifier: RelativeOffset = try RelativeOffset.resolve(from: bodyPointer) - let getter: RelativeOffset = try RelativeOffset.resolve(from: bodyPointer.advanced(by: getterFieldRelativeOffset)) - var setter: RelativeOffset? - if header.isComputedSettable { - setter = try RelativeOffset.resolve(from: bodyPointer.advanced(by: settableSetterFieldRelativeOffset)) - } - return computedPropertyBody(rawIdentifier: rawIdentifier, getter: getter, setter: setter) + @available(*, deprecated, message: "Pass a ReadingContext: computedPropertyBody(in: machO.context).") + public func computedPropertyBody(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> KeyPathComputedPropertyBody? { + try computedPropertyBody(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension PropertyDescriptor { - public func storedFieldOffset(in context: some ReadingContext) throws -> KeyPathStoredFieldOffset? { - guard !isTrivial, let kind = header.storedFieldOffsetKind else { return nil } - let bodyAddress = try context.addressFromOffset(bodyOffset) - return try storedFieldOffset(kind: kind, bodyWord: try UInt32.resolve(at: bodyAddress, in: context)) + @available(*, deprecated, message: "Pass a ReadingContext: storedFieldOffset(in: .inProcess).") + public func storedFieldOffset() throws -> KeyPathStoredFieldOffset? { + try storedFieldOffset(in: InProcessContext.shared) } - public func computedPropertyBody(in context: some ReadingContext) throws -> KeyPathComputedPropertyBody? { - guard !isTrivial, header.kind == .computed else { return nil } - let bodyAddress = try context.addressFromOffset(bodyOffset) - let getterAddress = context.advanceAddress(bodyAddress, by: getterFieldRelativeOffset) - let rawIdentifier: RelativeOffset = try RelativeOffset.resolve(at: bodyAddress, in: context) - let getter: RelativeOffset = try RelativeOffset.resolve(at: getterAddress, in: context) - var setter: RelativeOffset? - if header.isComputedSettable { - let setterAddress = context.advanceAddress(bodyAddress, by: settableSetterFieldRelativeOffset) - setter = try RelativeOffset.resolve(at: setterAddress, in: context) - } - return computedPropertyBody(rawIdentifier: rawIdentifier, getter: getter, setter: setter) + @available(*, deprecated, message: "Pass a ReadingContext: computedPropertyBody(in: .inProcess).") + public func computedPropertyBody() throws -> KeyPathComputedPropertyBody? { + try computedPropertyBody(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Mangling/CImportedModuleNames.swift b/Sources/ABI/MachOSwiftSection/Models/Mangling/CImportedModuleNames.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Mangling/CImportedModuleNames.swift rename to Sources/ABI/MachOSwiftSection/Models/Mangling/CImportedModuleNames.swift diff --git a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift b/Sources/ABI/MachOSwiftSection/Models/Mangling/MangledName.swift similarity index 62% rename from Sources/MachOSwiftSection/Models/Mangling/MangledName.swift rename to Sources/ABI/MachOSwiftSection/Models/Mangling/MangledName.swift index 85fe236bf..dcab9c9ad 100644 --- a/Sources/MachOSwiftSection/Models/Mangling/MangledName.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Mangling/MangledName.swift @@ -119,71 +119,21 @@ public struct MangledName: Sendable, Hashable { } extension MangledName: Resolvable { - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - try resolve(from: offset, for: machO) - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - var mangledName = try resolve(from: 0, for: ptr) - mangledName.startOffset = ptr.bitPattern.int - mangledName.endOffset = ptr.bitPattern.int + mangledName.endOffset - mangledName.elements = mangledName.elements.map { element in - switch element { - case .string: - return element - case .lookup(let lookup): - return .lookup(.init(offset: ptr.advanced(by: lookup.offset).bitPattern.int, reference: lookup.reference)) - } - } - return mangledName - } - - private static func resolve(from offset: Int, for reader: some Readable) throws -> MangledName { - var elements: [MangledName.Element] = [] - var currentOffset = offset - var currentString = "" - while true { - let value: UInt8 = try reader.readElement(offset: currentOffset) - if value == 0xFF {} - else if value == 0 { - if currentString.count > 0 { - elements.append(.string(currentString)) - currentString = "" - } - currentOffset.offset(of: UInt8.self) - break - } else if value >= 0x01, value <= 0x17 { - if currentString.count > 0 { - elements.append(.string(currentString)) - currentString = "" - } - let reference: Int32 = try reader.readElement(offset: currentOffset + 1) - let offset = Int(offset + (currentOffset - offset)) - elements.append(.lookup(.init(offset: offset, reference: .relative(.init(kind: value, relativeOffset: reference + 1))))) - currentOffset.offset(of: Int32.self) - } else if value >= 0x18, value <= 0x1F { - if currentString.count > 0 { - elements.append(.string(currentString)) - currentString = "" - } - let reference: UInt64 = try reader.readElement(offset: currentOffset + 1) - let offset = Int(offset + (currentOffset - offset)) - elements.append(.lookup(.init(offset: offset, reference: .absolute(.init(kind: value, reference: reference))))) - currentOffset.offset(of: UInt64.self) - } else { - currentString.append(String(format: "%c", value)) - } - currentOffset.offset(of: UInt8.self) - } - - return .init(elements: elements, startOffset: offset, endOffset: currentOffset) - } - + /// Parses the mangled name that starts at `address`. + /// + /// Every offset in the result — the start, the end and each lookup + /// element's — is `offsetFromAddress(address)` plus a distance from the + /// start: a file offset in a `MachOContext`, an absolute pointer bit + /// pattern in `InProcessContext`, which `RuntimeFunctions` hands to the + /// runtime as the name's start. A context that strips tag bits when it + /// reads therefore never mixes a tagged start with untagged offsets. public static func resolve(at address: Context.Address, in context: Context) throws -> MangledName { + let startOffset = try context.offsetFromAddress(address) var elements: [MangledName.Element] = [] - var currentAddress = address + var distanceFromStart = 0 var currentString = "" while true { + let currentAddress = context.advanceAddress(address, by: distanceFromStart) let value: UInt8 = try context.readElement(at: currentAddress) if value == 0xFF {} else if value == 0 { @@ -191,7 +141,7 @@ extension MangledName: Resolvable { elements.append(.string(currentString)) currentString = "" } - currentAddress = context.advanceAddress(currentAddress, of: UInt8.self) + distanceFromStart.offset(of: UInt8.self) break } else if value >= 0x01, value <= 0x17 { if currentString.count > 0 { @@ -199,25 +149,37 @@ extension MangledName: Resolvable { currentString = "" } let reference: Int32 = try context.readElement(at: context.advanceAddress(currentAddress, by: 1)) - let offset = try context.offsetFromAddress(currentAddress) - elements.append(.lookup(.init(offset: offset, reference: .relative(.init(kind: value, relativeOffset: reference + 1))))) - currentAddress = context.advanceAddress(currentAddress, of: Int32.self) + elements.append(.lookup(.init(offset: startOffset + distanceFromStart, reference: .relative(.init(kind: value, relativeOffset: reference + 1))))) + distanceFromStart.offset(of: Int32.self) } else if value >= 0x18, value <= 0x1F { if currentString.count > 0 { elements.append(.string(currentString)) currentString = "" } let reference: UInt64 = try context.readElement(at: context.advanceAddress(currentAddress, by: 1)) - let offset = try context.offsetFromAddress(currentAddress) - elements.append(.lookup(.init(offset: offset, reference: .absolute(.init(kind: value, reference: reference))))) - currentAddress = context.advanceAddress(currentAddress, of: UInt64.self) + elements.append(.lookup(.init(offset: startOffset + distanceFromStart, reference: .absolute(.init(kind: value, reference: reference))))) + distanceFromStart.offset(of: UInt64.self) } else { currentString.append(String(format: "%c", value)) } - currentAddress = context.advanceAddress(currentAddress, of: UInt8.self) + distanceFromStart.offset(of: UInt8.self) } - return .init(elements: elements, startOffset: try context.offsetFromAddress(address), endOffset: try context.offsetFromAddress(currentAddress)) + return .init(elements: elements, startOffset: startOffset, endOffset: startOffset + distanceFromStart) + } +} + +// MARK: - Deprecated Mach-O and pointer forms + +extension MangledName { + @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) } } diff --git a/Sources/MachOSwiftSection/Models/Mangling/MangledNameKind.swift b/Sources/ABI/MachOSwiftSection/Models/Mangling/MangledNameKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Mangling/MangledNameKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Mangling/MangledNameKind.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/BorrowTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/BorrowTypeMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/BorrowTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/BorrowTypeMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/BorrowTypeMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/BorrowTypeMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/BorrowTypeMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/BorrowTypeMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadataAccessorsListEntry.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadataAccessorsListEntry.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadataAccessorsListEntry.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadataAccessorsListEntry.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasCachingOnceToken.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasCachingOnceToken.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasCachingOnceToken.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasCachingOnceToken.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListCount.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListCount.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListCount.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListCount.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListEntry.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListEntry.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListEntry.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/CanonicalSpecializedMetadatasListEntry.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/FixedArrayTypeMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/FullMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/FullMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/FullMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/FullMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefix.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefix.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefix.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefix.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderPrefixProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/HeapMetadataHeaderProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBase.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBase.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBase.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBase.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderBaseProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataHeaderProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefix.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefix.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefix.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefix.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Headers/TypeMetadataLayoutPrefixProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/HeapMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/HeapMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/HeapMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/HeapMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/HeapMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/HeapMetadataProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/HeapMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/HeapMetadataProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/Metadata.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/Metadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/Metadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/Metadata.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataAccessorFunction.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataAccessorFunction.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataAccessorFunction.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataAccessorFunction.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataBounds.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataBounds.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataBounds.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataBounds.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataBoundsLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataBoundsLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataBoundsLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataBoundsLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataBoundsProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataBoundsProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataBoundsProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataBoundsProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataInitialization/ForeignMetadataInitialization.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataInitialization/ForeignMetadataInitialization.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataInitialization/ForeignMetadataInitialization.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataInitialization/ForeignMetadataInitialization.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataInitialization/SingletonMetadataInitialization.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataInitialization/SingletonMetadataInitialization.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataInitialization/SingletonMetadataInitialization.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataInitialization/SingletonMetadataInitialization.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataKind.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataKind.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift similarity index 58% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift index bef0e2e1c..df0a327fa 100644 --- a/Sources/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataProtocol.swift @@ -20,24 +20,6 @@ extension MetadataProtocol { } } -extension MetadataProtocol { - public func asMetadataWrapper(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MetadataWrapper { - try .resolve(from: offset, in: machO) - } - - public func asMetadataWrapper() throws -> MetadataWrapper { - try .resolve(from: .init(bitPattern: offset)) - } - - public func asMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Metadata { - try .resolve(from: offset, in: machO) - } - - public func asMetadata() throws -> Metadata { - try .resolve(from: .init(bitPattern: offset)) - } -} - extension MetadataProtocol { public var kind: MetadataKind { .enumeratedMetadataKind(layout.kind) @@ -51,28 +33,6 @@ extension MetadataProtocol { } } -extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { - public func asFullMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> FullMetadata { - try FullMetadata.resolve(from: offset - HeaderType.layoutSize, in: machO) - } - - public func valueWitnesses(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ValueWitnessTable { - let fullMetadata = try asFullMetadata(in: machO) - return try fullMetadata.layout.header.valueWitnesses.resolve(in: machO) - } -} - -extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { - public func asFullMetadata() throws -> FullMetadata { - try FullMetadata.resolve(from: asPointer - HeaderType.layoutSize) - } - - public func valueWitnesses() throws -> ValueWitnessTable { - let fullMetadata = try asFullMetadata() - return try fullMetadata.layout.header.valueWitnesses.resolve() - } -} - extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { public var isAnyExistentialType: Bool { switch kind { @@ -83,59 +43,6 @@ extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { return false } } - - public func typeLayout(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeLayout { - try valueWitnesses(in: machO).typeLayout - } - - public func typeLayout() throws -> TypeLayout { - try valueWitnesses().typeLayout - } - - public func typeContextDescriptorWrapper() throws -> TypeContextDescriptorWrapper? { - let ptr = try asPointer - switch kind { - case .class: - let cls = try AnyClassMetadataObjCInterop.resolve(from: ptr) - if cls.isPureObjC { - return nil - } else { - return try .class(ClassMetadataObjCInterop.resolve(from: ptr).descriptor()!) - } - case .struct, - .enum, - .optional: - return try ValueMetadata.resolve(from: ptr).descriptor().asTypeContextDescriptorWrapper - case .foreignClass: - return try .class(ForeignClassMetadata.resolve(from: ptr).classDescriptor()) - case .foreignReferenceType: - return try .class(ForeignReferenceTypeMetadata.resolve(from: ptr).classDescriptor()) - default: - return nil - } - } - - public func typeContextDescriptorWrapper(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeContextDescriptorWrapper? { - switch kind { - case .class: - let cls = try AnyClassMetadataObjCInterop.resolve(from: offset, in: machO) - if cls.isPureObjC { - return nil - } else { - return try .class(ClassMetadataObjCInterop.resolve(from: offset, in: machO).descriptor(in: machO)!) - } - case .struct, - .enum, - .optional: - return try ValueMetadata.resolve(from: offset, in: machO).descriptor(in: machO).asTypeContextDescriptorWrapper - case .foreignClass: - return try .class(ForeignClassMetadata.resolve(from: offset, in: machO).classDescriptor(in: machO)) - case .foreignReferenceType: - return try .class(ForeignReferenceTypeMetadata.resolve(from: offset, in: machO).classDescriptor(in: machO)) - default: - return nil - } - } } // MARK: - ReadingContext Support @@ -152,7 +59,10 @@ extension MetadataProtocol { extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { public func asFullMetadata(in context: some ReadingContext) throws -> FullMetadata { - try FullMetadata.resolve(at: try context.addressFromOffset(offset - HeaderType.layoutSize), in: context) + // The metadata's own address first: in process that conversion is + // what rejects a null metadata, and the header sits in front of it. + let metadataAddress = try context.addressFromOffset(offset) + return try FullMetadata.resolve(at: context.advanceAddress(metadataAddress, by: -HeaderType.layoutSize), in: context) } public func valueWitnesses(in context: some ReadingContext) throws -> ValueWitnessTable { @@ -167,24 +77,93 @@ extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { } public func typeContextDescriptorWrapper(in context: some ReadingContext) throws -> TypeContextDescriptorWrapper? { + // Converted before the switch, so a null metadata throws in process + // whatever its kind. + let address = try context.addressFromOffset(offset) switch kind { case .class: - let cls = try AnyClassMetadataObjCInterop.resolve(at: try context.addressFromOffset(offset), in: context) + let cls = try AnyClassMetadataObjCInterop.resolve(at: address, in: context) if cls.isPureObjC { return nil } else { - return try .class(ClassMetadataObjCInterop.resolve(at: try context.addressFromOffset(offset), in: context).descriptor(in: context)!) + return try .class(ClassMetadataObjCInterop.resolve(at: address, in: context).descriptor(in: context)!) } case .struct, .enum, .optional: - return try ValueMetadata.resolve(at: try context.addressFromOffset(offset), in: context).descriptor(in: context).asTypeContextDescriptorWrapper + return try ValueMetadata.resolve(at: address, in: context).descriptor(in: context).asTypeContextDescriptorWrapper case .foreignClass: - return try .class(ForeignClassMetadata.resolve(at: try context.addressFromOffset(offset), in: context).classDescriptor(in: context)) + return try .class(ForeignClassMetadata.resolve(at: address, in: context).classDescriptor(in: context)) case .foreignReferenceType: - return try .class(ForeignReferenceTypeMetadata.resolve(at: try context.addressFromOffset(offset), in: context).classDescriptor(in: context)) + return try .class(ForeignReferenceTypeMetadata.resolve(at: address, in: context).classDescriptor(in: context)) default: return nil } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension MetadataProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: asMetadataWrapper(in: machO.context).") + public func asMetadataWrapper(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MetadataWrapper { + try asMetadataWrapper(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: asMetadataWrapper(in: .inProcess).") + public func asMetadataWrapper() throws -> MetadataWrapper { + try asMetadataWrapper(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: asMetadata(in: machO.context).") + public func asMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Metadata { + try asMetadata(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: asMetadata(in: .inProcess).") + public func asMetadata() throws -> Metadata { + try asMetadata(in: InProcessContext.shared) + } +} + +extension MetadataProtocol where HeaderType: TypeMetadataHeaderBaseProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: asFullMetadata(in: machO.context).") + public func asFullMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> FullMetadata { + try asFullMetadata(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: valueWitnesses(in: machO.context).") + public func valueWitnesses(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ValueWitnessTable { + try valueWitnesses(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: asFullMetadata(in: .inProcess).") + public func asFullMetadata() throws -> FullMetadata { + try asFullMetadata(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: valueWitnesses(in: .inProcess).") + public func valueWitnesses() throws -> ValueWitnessTable { + try valueWitnesses(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeLayout(in: machO.context).") + public func typeLayout(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeLayout { + try typeLayout(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeLayout(in: .inProcess).") + public func typeLayout() throws -> TypeLayout { + try typeLayout(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeContextDescriptorWrapper(in: .inProcess).") + public func typeContextDescriptorWrapper() throws -> TypeContextDescriptorWrapper? { + try typeContextDescriptorWrapper(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeContextDescriptorWrapper(in: machO.context).") + public func typeContextDescriptorWrapper(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeContextDescriptorWrapper? { + try typeContextDescriptorWrapper(in: machO.context) + } +} diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataRequest.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataRequest.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataRequest.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataRequest.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataResponse.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataResponse.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataResponse.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataResponse.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataState.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataState.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetadataState.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataState.swift diff --git a/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift new file mode 100644 index 000000000..041a63cde --- /dev/null +++ b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift @@ -0,0 +1,214 @@ +import Foundation +import MachOBase +import SwiftStdlibToolbox + +@CaseCheckable(.public) +@AssociatedValue(.public) +public enum MetadataWrapper: Resolvable { + case `class`(ClassMetadataObjCInterop) + case `struct`(StructMetadata) + case `enum`(EnumMetadata) + case optional(EnumMetadata) + case foreignClass(ForeignClassMetadata) + case foreignReferenceType(ForeignReferenceTypeMetadata) + case opaque(OpaqueMetadata) + case tuple(TupleTypeMetadata) + case function(FunctionTypeMetadata) + case existential(ExistentialTypeMetadata) + case metatype(MetatypeMetadata) + case objcClassWrapper(ObjCClassWrapperMetadata) + case existentialMetatype(ExistentialMetatypeMetadata) + case extendedExistential(ExtendedExistentialTypeMetadata) + case fixedArray(FixedArrayTypeMetadata) + case borrow(BorrowTypeMetadata) + case heapLocalVariable(HeapLocalVariableMetadata) + case heapGenericLocalVariable(GenericBoxHeapMetadata) + case errorObject(EnumMetadata) + case task(DispatchClassMetadata) + case job(DispatchClassMetadata) + + public var anyMetadata: any MetadataProtocol { + switch self { + case .class(let classMetadataObjCInterop): + return classMetadataObjCInterop + case .struct(let structMetadata): + return structMetadata + case .enum(let enumMetadata): + return enumMetadata + case .optional(let enumMetadata): + return enumMetadata + case .foreignClass(let foreignClassMetadata): + return foreignClassMetadata + case .foreignReferenceType(let foreignReferenceTypeMetadata): + return foreignReferenceTypeMetadata + case .opaque(let opaqueMetadata): + return opaqueMetadata + case .tuple(let tupleTypeMetadata): + return tupleTypeMetadata + case .function(let functionTypeMetadata): + return functionTypeMetadata + case .existential(let existentialTypeMetadata): + return existentialTypeMetadata + case .metatype(let metatypeMetadata): + return metatypeMetadata + case .objcClassWrapper(let objCClassWrapperMetadata): + return objCClassWrapperMetadata + case .existentialMetatype(let existentialMetatypeMetadata): + return existentialMetatypeMetadata + case .extendedExistential(let extendedExistentialTypeMetadata): + return extendedExistentialTypeMetadata + case .fixedArray(let fixedArrayTypeMetadata): + return fixedArrayTypeMetadata + case .borrow(let borrowTypeMetadata): + return borrowTypeMetadata + case .heapLocalVariable(let heapLocalVariableMetadata): + return heapLocalVariableMetadata + case .heapGenericLocalVariable(let genericBoxHeapMetadata): + return genericBoxHeapMetadata + case .errorObject(let enumMetadata): + return enumMetadata + case .task(let dispatchClassMetadata): + return dispatchClassMetadata + case .job(let dispatchClassMetadata): + return dispatchClassMetadata + } + } +} + +// MARK: - ReadingContext Support + +extension MetadataWrapper { + // On arm64e the value-witness-table slot in a live `TargetFullMetadata` + // header is PAC-signed (`__ptrauth_swift_value_witness_table`). Every leg + // below is safe as long as it dereferences through `Pointer.resolve` — + // `PointerProtocol.resolve(in:)` / `InProcessContext` strip pointer tags on + // every in-process read (evolution proposal 0004). Do not replace these + // with raw pointer arithmetic. + public func valueWitnessTable(in context: some ReadingContext) throws -> ValueWitnessTable { + switch self { + case .class(let classMetadataObjCInterop): + return try classMetadataObjCInterop.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .struct(let structMetadata): + return try structMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .enum(let enumMetadata): + return try enumMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .optional(let enumMetadata): + return try enumMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .foreignClass(let foreignClassMetadata): + return try foreignClassMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .foreignReferenceType(let foreignReferenceTypeMetadata): + return try foreignReferenceTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .opaque(let opaqueMetadata): + return try opaqueMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .tuple(let tupleTypeMetadata): + return try tupleTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .function(let functionTypeMetadata): + return try functionTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .existential(let existentialTypeMetadata): + return try existentialTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .metatype(let metatypeMetadata): + return try metatypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .objcClassWrapper(let objCClassWrapperMetadata): + return try objCClassWrapperMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .existentialMetatype(let existentialMetatypeMetadata): + return try existentialMetatypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .extendedExistential(let extendedExistentialTypeMetadata): + return try extendedExistentialTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .fixedArray(let fixedArrayTypeMetadata): + return try fixedArrayTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .borrow(let borrowTypeMetadata): + return try borrowTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .heapLocalVariable(let heapLocalVariableMetadata): + return try heapLocalVariableMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .heapGenericLocalVariable(let genericBoxHeapMetadata): + return try genericBoxHeapMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .errorObject(let enumMetadata): + return try enumMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .task(let dispatchClassMetadata): + return try dispatchClassMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + case .job(let dispatchClassMetadata): + return try dispatchClassMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) + } + } + + public static func resolve(at address: Context.Address, in context: Context) throws -> Self { + let metadata = try context.readWrapperElement(at: address) as Metadata + switch metadata.kind { + case .class: + return try .class(context.readWrapperElement(at: address)) + case .struct: + return try .struct(context.readWrapperElement(at: address)) + case .enum: + return try .enum(context.readWrapperElement(at: address)) + case .optional: + return try .optional(context.readWrapperElement(at: address)) + case .foreignClass: + return try .foreignClass(context.readWrapperElement(at: address)) + case .foreignReferenceType: + return try .foreignReferenceType(context.readWrapperElement(at: address)) + case .opaque: + return try .opaque(context.readWrapperElement(at: address)) + case .tuple: + return try .tuple(context.readWrapperElement(at: address)) + case .function: + return try .function(context.readWrapperElement(at: address)) + case .existential: + return try .existential(context.readWrapperElement(at: address)) + case .metatype: + return try .metatype(context.readWrapperElement(at: address)) + case .objcClassWrapper: + return try .objcClassWrapper(context.readWrapperElement(at: address)) + case .existentialMetatype: + return try .existentialMetatype(context.readWrapperElement(at: address)) + case .extendedExistential: + return try .extendedExistential(context.readWrapperElement(at: address)) + case .fixedArray: + return try .fixedArray(context.readWrapperElement(at: address)) + case .borrow: + return try .borrow(context.readWrapperElement(at: address)) + case .heapLocalVariable: + return try .heapLocalVariable(context.readWrapperElement(at: address)) + case .heapGenericLocalVariable: + return try .heapGenericLocalVariable(context.readWrapperElement(at: address)) + case .errorObject: + return try .errorObject(context.readWrapperElement(at: address)) + case .task: + return try .task(context.readWrapperElement(at: address)) + case .job: + return try .job(context.readWrapperElement(at: address)) + case .lastEnumerated: + throw MachOSwiftSectionError.unknownMetadataKind(rawValue: UInt(metadata.kind.rawValue)) + } + } +} + +// MARK: - Deprecated Mach-O and pointer forms + +extension MetadataWrapper { + @available(*, deprecated, message: "Pass a ReadingContext: anyMetadata.asMetadata(in: .inProcess).") + public var metadata: Metadata { + get throws { + try anyMetadata.asMetadata(in: InProcessContext.shared) + } + } + + @available(*, deprecated, message: "Pass a ReadingContext: valueWitnessTable(in: machO.context).") + public func valueWitnessTable(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ValueWitnessTable { + try valueWitnessTable(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: valueWitnessTable(in: .inProcess).") + public func valueWitnessTable() throws -> ValueWitnessTable { + try valueWitnessTable(in: InProcessContext.shared) + } + + @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) + } +} diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetatypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetatypeMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetatypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetatypeMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetatypeMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/MetatypeMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/MetatypeMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/MetatypeMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Metadata/SingletonMetadataPointer.swift b/Sources/ABI/MachOSwiftSection/Models/Metadata/SingletonMetadataPointer.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Metadata/SingletonMetadataPointer.swift rename to Sources/ABI/MachOSwiftSection/Models/Metadata/SingletonMetadataPointer.swift diff --git a/Sources/MachOSwiftSection/Models/Misc/SpecialPointerAuthDiscriminators.swift b/Sources/ABI/MachOSwiftSection/Models/Misc/SpecialPointerAuthDiscriminators.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Misc/SpecialPointerAuthDiscriminators.swift rename to Sources/ABI/MachOSwiftSection/Models/Misc/SpecialPointerAuthDiscriminators.swift diff --git a/Sources/MachOSwiftSection/Models/Module/ModuleContext.swift b/Sources/ABI/MachOSwiftSection/Models/Module/ModuleContext.swift similarity index 59% rename from Sources/MachOSwiftSection/Models/Module/ModuleContext.swift rename to Sources/ABI/MachOSwiftSection/Models/Module/ModuleContext.swift index 7c6ab29e2..5ab2d4c62 100644 --- a/Sources/MachOSwiftSection/Models/Module/ModuleContext.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Module/ModuleContext.swift @@ -6,16 +6,6 @@ public struct ModuleContext: TopLevelType, ContextProtocol { public let descriptor: ModuleContextDescriptor public let name: String - - public init(descriptor: ModuleContextDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - self.name = try descriptor.name(in: machO) - } - - public init(descriptor: ModuleContextDescriptor) throws { - self.descriptor = descriptor - self.name = try descriptor.name() - } } // MARK: - ReadingContext Support @@ -26,3 +16,17 @@ extension ModuleContext { self.name = try descriptor.name(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ModuleContext { + @available(*, deprecated, message: "Pass a ReadingContext: ModuleContext(descriptor:in: machO.context).") + public init(descriptor: ModuleContextDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: ModuleContext(descriptor:in: .inProcess).") + public init(descriptor: ModuleContextDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Module/ModuleContextDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Module/ModuleContextDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Module/ModuleContextDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Module/ModuleContextDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Module/ModuleContextDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Module/ModuleContextDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Module/ModuleContextDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Module/ModuleContextDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Module/ModuleContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Module/ModuleContextDescriptorProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Module/ModuleContextDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Module/ModuleContextDescriptorProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/OpaqueType/OpaqueMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueMetadata.swift diff --git a/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift b/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift new file mode 100644 index 000000000..8c7fd368e --- /dev/null +++ b/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift @@ -0,0 +1,62 @@ +import Foundation +import MachOKit +import MachOBase + +public struct OpaqueType: TopLevelType, ContextProtocol { + public let descriptor: OpaqueTypeDescriptor + + public let genericContext: GenericContext? + + public let underlyingTypeArgumentMangledNames: [MangledName] + + public let invertedProtocols: InvertibleProtocolSet? +} + +// MARK: - ReadingContext Support + +extension OpaqueType { + public init(descriptor: OpaqueTypeDescriptor, in context: some ReadingContext) throws { + self.descriptor = descriptor + var currentOffset = descriptor.offset + descriptor.layoutSize + + let genericContext = try descriptor.genericContext(in: context) + + if let genericContext { + currentOffset += genericContext.size + } + self.genericContext = genericContext + + if descriptor.numUnderlyingTypeArguments > 0 { + let underlyingTypeArgumentMangledNamePointers: [RelativeDirectPointer] = try context.readElements(at: try context.addressFromOffset(currentOffset), numberOfElements: descriptor.numUnderlyingTypeArguments) + var underlyingTypeArgumentMangledNames: [MangledName] = [] + for underlyingTypeArgumentMangledNamePointer in underlyingTypeArgumentMangledNamePointers { + try underlyingTypeArgumentMangledNames.append(underlyingTypeArgumentMangledNamePointer.resolve(at: try context.addressFromOffset(currentOffset), in: context)) + currentOffset += MemoryLayout>.size + } + self.underlyingTypeArgumentMangledNames = underlyingTypeArgumentMangledNames + } else { + self.underlyingTypeArgumentMangledNames = [] + } + + if descriptor.flags.contains(.hasInvertibleProtocols) { + self.invertedProtocols = try context.readElement(at: try context.addressFromOffset(currentOffset)) as InvertibleProtocolSet + currentOffset.offset(of: InvertibleProtocolSet.self) + } else { + self.invertedProtocols = nil + } + } +} + +// MARK: - Deprecated Mach-O and pointer forms + +extension OpaqueType { + @available(*, deprecated, message: "Pass a ReadingContext: OpaqueType(descriptor:in: machO.context).") + public init(descriptor: OpaqueTypeDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: OpaqueType(descriptor:in: .inProcess).") + public init(descriptor: OpaqueTypeDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/OpaqueType/OpaqueTypeDescriptorProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolKind.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolKind.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolSet.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolSet.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolSet.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolSet.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolsRequirementCount.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolsRequirementCount.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolsRequirementCount.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/Invertible/InvertibleProtocolsRequirementCount.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift similarity index 61% rename from Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift index 5b73c6966..4d5ff218d 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/ObjC/ObjCProtocolPrefix.swift @@ -10,32 +10,38 @@ public struct ObjCProtocolPrefix: ResolvableLocatableLayoutWrapper { } } +// MARK: - ReadingContext Support + extension ObjCProtocolPrefix { - public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { - try layout.name.resolve(in: machO) + public func name(in context: some ReadingContext) throws -> String { + try layout.name.resolve(in: context) } - public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.name.resolveAny(in: machO) + public func mangledName(in context: some ReadingContext) throws -> MangledName { + try layout.name.resolveAny(in: context) } +} - public func name() throws -> String { - try layout.name.resolve() - } +// MARK: - Deprecated Mach-O and pointer forms - public func mangledName() throws -> MangledName { - try layout.name.resolveAny() +extension ObjCProtocolPrefix { + @available(*, deprecated, message: "Pass a ReadingContext: name(in: machO.context).") + public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try name(in: machO.context) } -} -// MARK: - ReadingContext Support + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: machO.context).") + public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledName(in: machO.context) + } -extension ObjCProtocolPrefix { - public func name(in context: some ReadingContext) throws -> String { - try layout.name.resolve(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: name(in: .inProcess).") + public func name() throws -> String { + try name(in: InProcessContext.shared) } - public func mangledName(in context: some ReadingContext) throws -> MangledName { - try layout.name.resolveAny(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: .inProcess).") + public func mangledName() throws -> MangledName { + try mangledName(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift similarity index 72% rename from Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift index aa77c845b..6125585d1 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/ObjC/RelativeObjCProtocolPrefix.swift @@ -10,16 +10,6 @@ public struct RelativeObjCProtocolPrefix: ResolvableLocatableLayoutWrapper { } } -extension RelativeObjCProtocolPrefix { - public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.mangledName.resolve(from: offset(of: \.mangledName), in: machO) - } - - public func mangledName() throws -> MangledName { - return try layout.mangledName.resolve(from: pointer(of: \.mangledName)) - } -} - // MARK: - ReadingContext Support extension RelativeObjCProtocolPrefix { @@ -28,3 +18,17 @@ extension RelativeObjCProtocolPrefix { return try layout.mangledName.resolve(at: baseAddress, in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension RelativeObjCProtocolPrefix { + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: machO.context).") + public func mangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: mangledName(in: .inProcess).") + public func mangledName() throws -> MangledName { + try mangledName(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/Protocol.swift similarity index 52% rename from Sources/MachOSwiftSection/Models/Protocol/Protocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/Protocol.swift index d96736434..06f44f848 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/Protocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/Protocol.swift @@ -32,57 +32,6 @@ public struct `Protocol`: TopLevelType, ContextProtocol { public var numberOfRequirementsInSignature: Int { descriptor.numRequirementsInSignature.cast() } - - public init(descriptor: ProtocolDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - guard let protocolFlags = descriptor.flags.kindSpecificFlags?.protocolFlags else { - throw Error.invalidProtocolDescriptor - } - self.descriptor = descriptor - self.protocolFlags = protocolFlags - self.name = try descriptor.name(in: machO) - var currentOffset = descriptor.offset + descriptor.layoutSize - if descriptor.numRequirementsInSignature > 0 { - let requirementInSignatures = try machO.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirementsInSignature.cast()) as [GenericRequirementDescriptor] - self.requirementInSignatures = try requirementInSignatures.map { try .init(descriptor: $0, in: machO) } - currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.numRequirementsInSignature.cast()) - currentOffset.align(to: 4) - } else { - self.requirementInSignatures = [] - } - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: machO) - } - - public init(descriptor: ProtocolDescriptor) throws { - guard let protocolFlags = descriptor.flags.kindSpecificFlags?.protocolFlags else { - throw Error.invalidProtocolDescriptor - } - self.descriptor = descriptor - self.protocolFlags = protocolFlags - self.name = try descriptor.name() - var currentOffset = descriptor.layoutSize - let pointer = try descriptor.asPointer - if descriptor.numRequirementsInSignature > 0 { - let requirementInSignatures = try pointer.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirementsInSignature.cast()) as [GenericRequirementDescriptor] - self.requirementInSignatures = try requirementInSignatures.map { try .init(descriptor: $0) } - currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.numRequirementsInSignature.cast()) - currentOffset.align(to: 4) - } else { - self.requirementInSignatures = [] - } - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: pointer) - } - - private mutating func initialize(descriptor: ProtocolDescriptor, currentOffset: inout Int, in reader: some Readable) throws { - if descriptor.numRequirements > 0 { - let baseRequirementOffset = currentOffset - ProtocolRequirement.layoutSize - baseRequirement = try reader.readWrapperElement(offset: baseRequirementOffset) as ProtocolBaseRequirement - requirements = try reader.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.numRequirements.cast()) as [ProtocolRequirement] - currentOffset.offset(of: ProtocolRequirement.self, numbersOfElements: descriptor.numRequirements.cast()) - } else { - baseRequirement = nil - requirements = [] - } - } } // MARK: - ReadingContext Support @@ -119,3 +68,17 @@ extension `Protocol` { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension `Protocol` { + @available(*, deprecated, message: "Pass a ReadingContext: Protocol(descriptor:in: machO.context).") + public init(descriptor: ProtocolDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: Protocol(descriptor:in: .inProcess).") + public init(descriptor: ProtocolDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolClassConstraint.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolClassConstraint.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolClassConstraint.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolClassConstraint.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolContextDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolContextDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolContextDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolContextDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift similarity index 80% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift index 1a765c019..b35d45abe 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptor.swift @@ -23,23 +23,25 @@ public struct ProtocolDescriptor: ProtocolDescriptorProtocol { } } +// MARK: - ReadingContext Support + extension ProtocolDescriptor { - public func associatedTypes(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [String] { - guard layout.associatedTypes.isValid else { return [] } - return try layout.associatedTypes.resolve(from: offset(of: \.associatedTypes), in: machO).components(separatedBy: " ") - } - - public func associatedTypes() throws -> [String] { + public func associatedTypes(in context: some ReadingContext) throws -> [String] { guard layout.associatedTypes.isValid else { return [] } - return try layout.associatedTypes.resolve(from: pointer(of: \.associatedTypes)).components(separatedBy: " ") + return try layout.associatedTypes.resolve(at: try context.addressFromOffset(offset(of: \.associatedTypes)), in: context).components(separatedBy: " ") } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ProtocolDescriptor { - public func associatedTypes(in context: some ReadingContext) throws -> [String] { - guard layout.associatedTypes.isValid else { return [] } - return try layout.associatedTypes.resolve(at: try context.addressFromOffset(offset(of: \.associatedTypes)), in: context).components(separatedBy: " ") + @available(*, deprecated, message: "Pass a ReadingContext: associatedTypes(in: machO.context).") + public func associatedTypes(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [String] { + try associatedTypes(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: associatedTypes(in: .inProcess).") + public func associatedTypes() throws -> [String] { + try associatedTypes(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift similarity index 68% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift index c5547e052..2297d72c1 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorRef.swift @@ -30,58 +30,56 @@ public struct ProtocolDescriptorRef { } } +// MARK: - ReadingContext Support + extension ProtocolDescriptorRef { - public func objcProtocol(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ObjCProtocolPrefix { - try Pointer(address: storage & ~Bits.isObjC).resolve(in: machO) + public func objcProtocol(in context: some ReadingContext) throws -> ObjCProtocolPrefix { + try Pointer(address: storage & ~Bits.isObjC).resolve(in: context) } - public func swiftProtocol(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolDescriptor { - try Pointer(address: storage).resolve(in: machO) + public func swiftProtocol(in context: some ReadingContext) throws -> ProtocolDescriptor { + try Pointer(address: storage).resolve(in: context) } - public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + public func name(in context: some ReadingContext) throws -> String { if isObjC { - return try objcProtocol(in: machO).name(in: machO) + return try objcProtocol(in: context).name(in: context) } else { - return try swiftProtocol(in: machO).name(in: machO) + return try swiftProtocol(in: context).name(in: context) } } } +// MARK: - Deprecated Mach-O and pointer forms + extension ProtocolDescriptorRef { - public func objcProtocol() throws -> ObjCProtocolPrefix { - try Pointer(address: storage & ~Bits.isObjC).resolve() + @available(*, deprecated, message: "Pass a ReadingContext: objcProtocol(in: machO.context).") + public func objcProtocol(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ObjCProtocolPrefix { + try objcProtocol(in: machO.context) } - public func swiftProtocol() throws -> ProtocolDescriptor { - try Pointer(address: storage).resolve() + @available(*, deprecated, message: "Pass a ReadingContext: swiftProtocol(in: machO.context).") + public func swiftProtocol(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolDescriptor { + try swiftProtocol(in: machO.context) } - public func name() throws -> String { - if isObjC { - return try objcProtocol().name() - } else { - return try swiftProtocol().name() - } + @available(*, deprecated, message: "Pass a ReadingContext: name(in: machO.context).") + public func name(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> String { + try name(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension ProtocolDescriptorRef { - public func objcProtocol(in context: some ReadingContext) throws -> ObjCProtocolPrefix { - try Pointer(address: storage & ~Bits.isObjC).resolve(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: objcProtocol(in: .inProcess).") + public func objcProtocol() throws -> ObjCProtocolPrefix { + try objcProtocol(in: InProcessContext.shared) } - public func swiftProtocol(in context: some ReadingContext) throws -> ProtocolDescriptor { - try Pointer(address: storage).resolve(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: swiftProtocol(in: .inProcess).") + public func swiftProtocol() throws -> ProtocolDescriptor { + try swiftProtocol(in: InProcessContext.shared) } - public func name(in context: some ReadingContext) throws -> String { - if isObjC { - return try objcProtocol(in: context).name(in: context) - } else { - return try swiftProtocol(in: context).name(in: context) - } + @available(*, deprecated, message: "Pass a ReadingContext: name(in: .inProcess).") + public func name() throws -> String { + try name(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorWithObjCInterop.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorWithObjCInterop.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDescriptorWithObjCInterop.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDescriptorWithObjCInterop.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolDispatchStrategy.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDispatchStrategy.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolDispatchStrategy.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolDispatchStrategy.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRecord.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRecord.swift similarity index 87% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRecord.swift index 4ff06f6e1..32b91a7dd 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRecord.swift @@ -20,16 +20,19 @@ public struct ProtocolRecord: ResolvableLocatableLayoutWrapper { } } +// MARK: - ReadingContext Support + extension ProtocolRecord { - public func protocolDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolDescriptor? { - try layout.protocol.resolve(from: offset(of: \.protocol), in: machO) + public func protocolDescriptor(in context: some ReadingContext) throws -> ProtocolDescriptor? { + try layout.protocol.resolve(at: try context.addressFromOffset(offset(of: \.protocol)), in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O form extension ProtocolRecord { - public func protocolDescriptor(in context: some ReadingContext) throws -> ProtocolDescriptor? { - try layout.protocol.resolve(at: try context.addressFromOffset(offset(of: \.protocol)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: protocolDescriptor(in: machO.context).") + public func protocolDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolDescriptor? { + try protocolDescriptor(in: machO.context) } } diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRequirement.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirementFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRequirementFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirementFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRequirementFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirementKind.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRequirementKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolRequirementKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolRequirementKind.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ProtocolWitnessTable.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolWitnessTable.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ProtocolWitnessTable.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ProtocolWitnessTable.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ResilientWitness.swift similarity index 63% rename from Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ResilientWitness.swift index fe58714a8..fc38ee546 100644 --- a/Sources/MachOSwiftSection/Models/Protocol/ResilientWitness.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Protocol/ResilientWitness.swift @@ -11,14 +11,6 @@ public struct ResilientWitness: ResolvableLocatableLayoutWrapper { } extension ResilientWitness { - public func requirement(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try layout.requirement.resolve(from: offset(of: \.requirement), in: machO).asOptional - } - - public func requirement() throws -> SymbolOrElement? { - return try layout.requirement.resolve(from: pointer(of: \.requirement)).asOptional - } - /// File offset of the witness implementation, or `nil` for a null /// pointer. Pure pointer arithmetic on the descriptor's own offset; /// symbol attribution is `SwiftInspection`'s `implementationSymbols(in:)`, @@ -27,13 +19,11 @@ extension ResilientWitness { resolvedDirectOffset(from: \.implementation) } - /// MachO-only debug formatter (`nil` for a null pointer); no - /// `ReadingContext` mirror exists because `addressString(forOffset:)` is a - /// MachO display helper (not a data read) and has no counterpart on the - /// unified `ReadingContext` abstraction — the context-flavored - /// ``implementationAddress(in:)-swift.method`` below returns the typed - /// address instead. - public func implementationAddress(in machO: some MachOSwiftSectionRepresentableWithCache) -> String? { + /// The witness implementation's address formatted for display (`nil` for + /// a null pointer). A Mach-O display helper rather than a data read, so it + /// takes the Mach-O itself; ``implementationAddress(in:)`` answers the + /// typed address in a `ReadingContext` instead. + public func implementationAddressString(in machO: some MachOSwiftSectionRepresentableWithCache) -> String? { return implementationOffset.map { machO.addressString(forOffset: $0) } } } @@ -52,3 +42,22 @@ extension ResilientWitness { return try context.addressFromOffset(implementationOffset) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ResilientWitness { + @available(*, deprecated, message: "Pass a ReadingContext: requirement(in: machO.context).") + public func requirement(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try requirement(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: requirement(in: .inProcess).") + public func requirement() throws -> SymbolOrElement? { + try requirement(in: InProcessContext.shared) + } + + @available(*, deprecated, renamed: "implementationAddressString(in:)", message: "The Mach-O form formats the address for display; implementationAddress(in:) with a ReadingContext answers the typed address.") + public func implementationAddress(in machO: some MachOSwiftSectionRepresentableWithCache) -> String? { + implementationAddressString(in: machO) + } +} diff --git a/Sources/MachOSwiftSection/Models/Protocol/ResilientWitnessesHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/ResilientWitnessesHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/ResilientWitnessesHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/ResilientWitnessesHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Protocol/SpecialProtocolKind.swift b/Sources/ABI/MachOSwiftSection/Models/Protocol/SpecialProtocolKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Protocol/SpecialProtocolKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Protocol/SpecialProtocolKind.swift diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/GlobalActorReference.swift b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/GlobalActorReference.swift similarity index 82% rename from Sources/MachOSwiftSection/Models/ProtocolConformance/GlobalActorReference.swift rename to Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/GlobalActorReference.swift index 19126050b..d56c7febe 100644 --- a/Sources/MachOSwiftSection/Models/ProtocolConformance/GlobalActorReference.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/GlobalActorReference.swift @@ -21,20 +21,24 @@ public struct GlobalActorReference: LocatableLayoutWrapper { } } -extension GlobalActorReference { - public func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - try layout.type.resolve(from: offset(of: \.type), in: machO) - } +// MARK: - ReadingContext Support - public func typeName() throws -> MangledName { - try layout.type.resolve(from: pointer(of: \.type)) +extension GlobalActorReference { + public func typeName(in context: some ReadingContext) throws -> MangledName { + try layout.type.resolve(at: try context.addressFromOffset(offset(of: \.type)), in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension GlobalActorReference { - public func typeName(in context: some ReadingContext) throws -> MangledName { - try layout.type.resolve(at: try context.addressFromOffset(offset(of: \.type)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: typeName(in: machO.context).") + public func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try typeName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeName(in: .inProcess).") + public func typeName() throws -> MangledName { + try typeName(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift similarity index 58% rename from Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift rename to Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift index b2500bf85..4e85474c4 100644 --- a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformance.swift @@ -41,95 +41,6 @@ public struct ProtocolConformance: TopLevelType { public private(set) var genericWitnessTable: GenericWitnessTable? public private(set) var globalActorReference: GlobalActorReference? - - public init(descriptor: ProtocolConformanceDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - - self.protocol = try descriptor.protocolDescriptor(in: machO) - - self.typeReference = try descriptor.resolvedTypeReference(in: machO) - - self.witnessTablePattern = try descriptor.witnessTablePattern(in: machO) - - var currentOffset = descriptor.offset + descriptor.layoutSize - - if descriptor.flags.isRetroactive { - let retroactiveContextPointer: RelativeContextPointer = try machO.readElement(offset: currentOffset) - self.retroactiveContextDescriptor = try retroactiveContextPointer.resolve(from: currentOffset, in: machO).asOptional - currentOffset.offset(of: RelativeIndirectablePointer>.self) - } else { - self.retroactiveContextDescriptor = nil - } - - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: machO) - } - - public init(descriptor: ProtocolConformanceDescriptor) throws { - self.descriptor = descriptor - - self.protocol = try descriptor.protocolDescriptor() - - self.typeReference = try descriptor.resolvedTypeReference() - - self.witnessTablePattern = try descriptor.witnessTablePattern() - - var currentOffset = descriptor.layoutSize - - let pointer = try descriptor.asPointer - - if descriptor.flags.isRetroactive { - let retroactiveContextPointer: RelativeContextPointer = try pointer.readElement(offset: currentOffset) - self.retroactiveContextDescriptor = try retroactiveContextPointer.resolve(from: pointer.advanced(by: currentOffset)).asOptional - currentOffset.offset(of: RelativeIndirectablePointer>.self) - } else { - self.retroactiveContextDescriptor = nil - } - - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: pointer) - } - - private mutating func initialize(descriptor: ProtocolConformanceDescriptor, currentOffset: inout Int, in reader: some Readable) throws { - if descriptor.flags.numConditionalRequirements > 0 { - conditionalRequirements = try reader.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.flags.numConditionalRequirements.cast()) as [GenericRequirementDescriptor] - currentOffset.offset(of: GenericRequirementDescriptor.self, numbersOfElements: descriptor.flags.numConditionalRequirements.cast()) - } else { - conditionalRequirements = [] - } - - if descriptor.flags.numConditionalPackShapeDescriptors > 0 { - conditionalPackShapeDescriptors = try reader.readWrapperElements(offset: currentOffset, numberOfElements: descriptor.flags.numConditionalPackShapeDescriptors.cast()) as [GenericPackShapeDescriptor] - currentOffset.offset(of: GenericPackShapeDescriptor.self, numbersOfElements: descriptor.flags.numConditionalPackShapeDescriptors.cast()) - } else { - conditionalPackShapeDescriptors = [] - } - - if descriptor.flags.hasResilientWitnesses { - let header: ResilientWitnessesHeader = try reader.readWrapperElement(offset: currentOffset) - resilientWitnessesHeader = header - currentOffset.offset(of: ResilientWitnessesHeader.self) - resilientWitnesses = try reader.readWrapperElements(offset: currentOffset, numberOfElements: header.numWitnesses.cast()) as [ResilientWitness] - currentOffset.offset(of: ResilientWitness.self, numbersOfElements: header.numWitnesses.cast()) - } else { - resilientWitnessesHeader = nil - resilientWitnesses = [] - } - - if descriptor.flags.hasGenericWitnessTable { - let genericWitnessTable: GenericWitnessTable = try reader.readWrapperElement(offset: currentOffset) - self.genericWitnessTable = genericWitnessTable - currentOffset.offset(of: GenericWitnessTable.self) - } else { - genericWitnessTable = nil - } - - if descriptor.flags.hasGlobalActorIsolation { - let globalActorReference: GlobalActorReference = try reader.readWrapperElement(offset: currentOffset) - self.globalActorReference = globalActorReference - currentOffset.offset(of: GlobalActorReference.self) - } else { - globalActorReference = nil - } - } } // MARK: - ReadingContext Support @@ -200,3 +111,17 @@ extension ProtocolConformance { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ProtocolConformance { + @available(*, deprecated, message: "Pass a ReadingContext: ProtocolConformance(descriptor:in: machO.context).") + public init(descriptor: ProtocolConformanceDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: ProtocolConformance(descriptor:in: .inProcess).") + public init(descriptor: ProtocolConformanceDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift similarity index 68% rename from Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift index f7c6a8f0a..d477ead83 100644 --- a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceDescriptor.swift @@ -18,47 +18,52 @@ extension ProtocolConformanceDescriptor { } } +// MARK: - ReadingContext Support + extension ProtocolConformanceDescriptor { - public func protocolDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - try layout.protocolDescriptor.resolve(from: offset(of: \.protocolDescriptor), in: machO).asOptional + public func protocolDescriptor(in context: some ReadingContext) throws -> SymbolOrElement? { + try layout.protocolDescriptor.resolve(at: try context.addressFromOffset(offset(of: \.protocolDescriptor)), in: context).asOptional } - public func resolvedTypeReference(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedTypeReference { - let offset = offset(of: \.typeReference) - return try typeReference.resolve(at: offset, in: machO) + public func resolvedTypeReference(in context: some ReadingContext) throws -> ResolvedTypeReference { + return try typeReference.resolve(at: offset(of: \.typeReference), in: context) } - public func witnessTablePattern(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolWitnessTable? { - try layout.witnessTablePattern.resolve(from: offset(of: \.witnessTablePattern), in: machO) + public func witnessTablePattern(in context: some ReadingContext) throws -> ProtocolWitnessTable? { + try layout.witnessTablePattern.resolve(at: try context.addressFromOffset(offset(of: \.witnessTablePattern)), in: context) } } +// MARK: - Deprecated Mach-O and pointer forms + extension ProtocolConformanceDescriptor { - public func protocolDescriptor() throws -> SymbolOrElement? { - try layout.protocolDescriptor.resolve(from: pointer(of: \.protocolDescriptor)).asOptional + @available(*, deprecated, message: "Pass a ReadingContext: protocolDescriptor(in: machO.context).") + public func protocolDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try protocolDescriptor(in: machO.context) } - public func resolvedTypeReference() throws -> ResolvedTypeReference { - return try typeReference.resolve(from: pointer(of: \.typeReference)) + @available(*, deprecated, message: "Pass a ReadingContext: resolvedTypeReference(in: machO.context).") + public func resolvedTypeReference(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedTypeReference { + try resolvedTypeReference(in: machO.context) } - public func witnessTablePattern() throws -> ProtocolWitnessTable? { - try layout.witnessTablePattern.resolve(from: pointer(of: \.witnessTablePattern)) + @available(*, deprecated, message: "Pass a ReadingContext: witnessTablePattern(in: machO.context).") + public func witnessTablePattern(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolWitnessTable? { + try witnessTablePattern(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension ProtocolConformanceDescriptor { - public func protocolDescriptor(in context: some ReadingContext) throws -> SymbolOrElement? { - try layout.protocolDescriptor.resolve(at: try context.addressFromOffset(offset(of: \.protocolDescriptor)), in: context).asOptional + @available(*, deprecated, message: "Pass a ReadingContext: protocolDescriptor(in: .inProcess).") + public func protocolDescriptor() throws -> SymbolOrElement? { + try protocolDescriptor(in: InProcessContext.shared) } - public func resolvedTypeReference(in context: some ReadingContext) throws -> ResolvedTypeReference { - return try typeReference.resolve(at: offset(of: \.typeReference), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: resolvedTypeReference(in: .inProcess).") + public func resolvedTypeReference() throws -> ResolvedTypeReference { + try resolvedTypeReference(in: InProcessContext.shared) } - public func witnessTablePattern(in context: some ReadingContext) throws -> ProtocolWitnessTable? { - try layout.witnessTablePattern.resolve(at: try context.addressFromOffset(offset(of: \.witnessTablePattern)), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: witnessTablePattern(in: .inProcess).") + public func witnessTablePattern() throws -> ProtocolWitnessTable? { + try witnessTablePattern(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceFlags.swift b/Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/ProtocolConformance/ProtocolConformanceFlags.swift diff --git a/Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadata.swift similarity index 75% rename from Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadata.swift index 6e581e621..5be8e863a 100644 --- a/Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadata.swift +++ b/Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadata.swift @@ -17,20 +17,24 @@ public struct TupleTypeMetadata: MetadataProtocol { } } -extension TupleTypeMetadata { - public func elements(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [Element] { - try machO.readElements(offset: offset + layoutSize, numberOfElements: layout.numberOfElements.cast()) - } +// MARK: - ReadingContext Support - public func elements() throws -> [Element] { - try asPointer.readElements(offset: layoutSize, numberOfElements: layout.numberOfElements.cast()) +extension TupleTypeMetadata { + public func elements(in context: some ReadingContext) throws -> [Element] { + try context.readElements(at: try context.addressFromOffset(offset + layoutSize), numberOfElements: layout.numberOfElements.cast()) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension TupleTypeMetadata { - public func elements(in context: some ReadingContext) throws -> [Element] { - try context.readElements(at: try context.addressFromOffset(offset + layoutSize), numberOfElements: layout.numberOfElements.cast()) + @available(*, deprecated, message: "Pass a ReadingContext: elements(in: machO.context).") + public func elements(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [Element] { + try elements(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: elements(in: .inProcess).") + public func elements() throws -> [Element] { + try elements(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadataElementLayout.swift b/Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadataElementLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadataElementLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadataElementLayout.swift diff --git a/Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/TupleType/TupleTypeMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/TupleType/TupleTypeMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Class.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Class.swift similarity index 59% rename from Sources/MachOSwiftSection/Models/Type/Class/Class.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Class.swift index f948e8ded..6c8f39e5b 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Class.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Class.swift @@ -45,135 +45,6 @@ public struct Class: TopLevelType, ContextProtocol { public private(set) var singletonMetadataPointer: SingletonMetadataPointer? public private(set) var methodDefaultOverrideTableHeader: MethodDefaultOverrideTableHeader? public private(set) var methodDefaultOverrideDescriptors: [MethodDefaultOverrideDescriptor] = [] - - public init(descriptor: ClassDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - let genericContext = try descriptor.typeGenericContext(in: machO) - self.genericContext = genericContext - var currentOffset = descriptor.offset + descriptor.layoutSize - if let genericContext { - currentOffset += genericContext.size - } - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: machO) - } - - public init(descriptor: ClassDescriptor) throws { - self.descriptor = descriptor - let genericContext = try descriptor.typeGenericContext() - self.genericContext = genericContext - var currentOffset = descriptor.layoutSize - if let genericContext { - currentOffset += genericContext.size - } - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: descriptor.asPointer) - } - - private mutating func initialize(descriptor: ClassDescriptor, currentOffset: inout Int, in reader: some Readable) throws { - if descriptor.hasResilientSuperclass { - let resilientSuperclass: ResilientSuperclass = try reader.readWrapperElement(offset: currentOffset) - self.resilientSuperclass = resilientSuperclass - currentOffset.offset(of: ResilientSuperclass.self) - } else { - self.resilientSuperclass = nil - } - - if descriptor.hasForeignMetadataInitialization { - let foreignMetadataInitialization: ForeignMetadataInitialization = try reader.readWrapperElement(offset: currentOffset) - self.foreignMetadataInitialization = foreignMetadataInitialization - currentOffset.offset(of: ForeignMetadataInitialization.self) - } else { - self.foreignMetadataInitialization = nil - } - - if descriptor.hasSingletonMetadataInitialization { - let singletonMetadataInitialization: SingletonMetadataInitialization = try reader.readWrapperElement(offset: currentOffset) - self.singletonMetadataInitialization = singletonMetadataInitialization - currentOffset.offset(of: SingletonMetadataInitialization.self) - } else { - self.singletonMetadataInitialization = nil - } - - if descriptor.hasVTable { - let vTableDescriptorHeader: VTableDescriptorHeader = try reader.readWrapperElement(offset: currentOffset) - self.vTableDescriptorHeader = vTableDescriptorHeader - currentOffset.offset(of: VTableDescriptorHeader.self) - let methodDescriptors: [MethodDescriptor] = try reader.readWrapperElements(offset: currentOffset, numberOfElements: vTableDescriptorHeader.vTableSize.cast()) - self.methodDescriptors = methodDescriptors - currentOffset.offset(of: MethodDescriptor.self, numbersOfElements: vTableDescriptorHeader.vTableSize.cast()) - } else { - self.vTableDescriptorHeader = nil - self.methodDescriptors = [] - } - - if descriptor.hasOverrideTable { - let overrideTableHeader: OverrideTableHeader = try reader.readWrapperElement(offset: currentOffset) - self.overrideTableHeader = overrideTableHeader - currentOffset.offset(of: OverrideTableHeader.self) - let methodOverrideDescriptors: [MethodOverrideDescriptor] = try reader.readWrapperElements(offset: currentOffset, numberOfElements: overrideTableHeader.numEntries.cast()) - self.methodOverrideDescriptors = methodOverrideDescriptors - currentOffset.offset(of: MethodOverrideDescriptor.self, numbersOfElements: overrideTableHeader.numEntries.cast()) - } else { - self.overrideTableHeader = nil - self.methodOverrideDescriptors = [] - } - - if descriptor.hasObjCResilientClassStub { - let objcResilientClassStubInfo: ObjCResilientClassStubInfo = try reader.readWrapperElement(offset: currentOffset) - self.objcResilientClassStubInfo = objcResilientClassStubInfo - currentOffset.offset(of: ObjCResilientClassStubInfo.self) - } else { - self.objcResilientClassStubInfo = nil - } - - if descriptor.hasCanonicalMetadataPrespecializations { - let count: CanonicalSpecializedMetadatasListCount = try reader.readElement(offset: currentOffset) - self.canonicalSpecializedMetadatasListCount = count - currentOffset.offset(of: CanonicalSpecializedMetadatasListCount.self) - let countValue = count.rawValue - let canonicalSpecializedMetadatas: [CanonicalSpecializedMetadatasListEntry] = try reader.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) - self.canonicalSpecializedMetadatas = canonicalSpecializedMetadatas - currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) - let canonicalSpecializedMetadataAccessors: [CanonicalSpecializedMetadataAccessorsListEntry] = try reader.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) - self.canonicalSpecializedMetadataAccessors = canonicalSpecializedMetadataAccessors - currentOffset.offset(of: CanonicalSpecializedMetadataAccessorsListEntry.self, numbersOfElements: countValue.cast()) - let canonicalSpecializedMetadatasCachingOnceToken: CanonicalSpecializedMetadatasCachingOnceToken = try reader.readWrapperElement(offset: currentOffset) - self.canonicalSpecializedMetadatasCachingOnceToken = canonicalSpecializedMetadatasCachingOnceToken - currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) - } else { - self.canonicalSpecializedMetadatasListCount = nil - self.canonicalSpecializedMetadatas = [] - self.canonicalSpecializedMetadataAccessors = [] - self.canonicalSpecializedMetadatasCachingOnceToken = nil - } - - if descriptor.flags.contains(.hasInvertibleProtocols) { - let invertibleProtocolSet: InvertibleProtocolSet = try reader.readElement(offset: currentOffset) - self.invertibleProtocolSet = invertibleProtocolSet - currentOffset.offset(of: InvertibleProtocolSet.self) - } else { - self.invertibleProtocolSet = nil - } - - if descriptor.hasSingletonMetadataPointer { - let singletonMetadataPointer: SingletonMetadataPointer = try reader.readWrapperElement(offset: currentOffset) - self.singletonMetadataPointer = singletonMetadataPointer - currentOffset.offset(of: SingletonMetadataPointer.self) - } else { - self.singletonMetadataPointer = nil - } - - if descriptor.hasDefaultOverrideTable { - let methodDefaultOverrideTableHeader: MethodDefaultOverrideTableHeader = try reader.readWrapperElement(offset: currentOffset) - self.methodDefaultOverrideTableHeader = methodDefaultOverrideTableHeader - currentOffset.offset(of: MethodDefaultOverrideTableHeader.self) - let methodDefaultOverrideDescriptors: [MethodDefaultOverrideDescriptor] = try reader.readWrapperElements(offset: currentOffset, numberOfElements: methodDefaultOverrideTableHeader.numEntries.cast()) - self.methodDefaultOverrideDescriptors = methodDefaultOverrideDescriptors - currentOffset.offset(of: MethodDefaultOverrideDescriptor.self, numbersOfElements: methodDefaultOverrideTableHeader.numEntries.cast()) - } else { - self.methodDefaultOverrideTableHeader = nil - self.methodDefaultOverrideDescriptors = [] - } - } } // MARK: - ReadingContext Support @@ -297,3 +168,17 @@ extension Class { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension Class { + @available(*, deprecated, message: "Pass a ReadingContext: Class(descriptor:in: machO.context).") + public init(descriptor: ClassDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: Class(descriptor:in: .inProcess).") + public init(descriptor: ClassDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift similarity index 84% rename from Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift index 00cb08e34..7330fb258 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassDescriptor.swift @@ -26,23 +26,6 @@ extension ClassDescriptor { } return resilientSuperclassReferenceKind } - - public func resilientMetadataBounds(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StoredClassMetadataBounds { - return try RelativeDirectPointer(relativeOffset: Int32(bitPattern: layout.metadataNegativeSizeInWordsOrResilientMetadataBounds)).resolve(from: offset(of: \.metadataNegativeSizeInWordsOrResilientMetadataBounds), in: machO) - } - - - public func resilientMetadataBounds() throws -> StoredClassMetadataBounds { - return try RelativeDirectPointer(relativeOffset: Int32(bitPattern: layout.metadataNegativeSizeInWordsOrResilientMetadataBounds)).resolve(from: pointer(of: \.metadataNegativeSizeInWordsOrResilientMetadataBounds)) - } - - public func superclassTypeMangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { - try layout.superclassType.resolve(from: offset(of: \.superclassType), in: machO) - } - - public func superclassTypeMangledName() throws -> MangledName? { - try layout.superclassType.resolve(from: pointer(of: \.superclassType)) - } } extension ClassDescriptor { @@ -103,3 +86,27 @@ extension ClassDescriptor { try layout.superclassType.resolve(at: try context.addressFromOffset(offset(of: \.superclassType)), in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension ClassDescriptor { + @available(*, deprecated, message: "Pass a ReadingContext: resilientMetadataBounds(in: machO.context).") + public func resilientMetadataBounds(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StoredClassMetadataBounds { + try resilientMetadataBounds(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: superclassTypeMangledName(in: machO.context).") + public func superclassTypeMangledName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName? { + try superclassTypeMangledName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: resilientMetadataBounds(in: .inProcess).") + public func resilientMetadataBounds() throws -> StoredClassMetadataBounds { + try resilientMetadataBounds(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: superclassTypeMangledName(in: .inProcess).") + public func superclassTypeMangledName() throws -> MangledName? { + try superclassTypeMangledName(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/ClassDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/ClassFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/ClassFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/ClassFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/ExtraClassDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/ExtraClassDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/ExtraClassDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/ExtraClassDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocol.swift similarity index 63% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocol.swift index 9788ecc2e..609f94c55 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocol.swift @@ -4,20 +4,24 @@ import MachOBase public protocol AnyClassMetadataProtocol: HeapMetadataProtocol where Layout: AnyClassMetadataLayout {} -extension AnyClassMetadataProtocol { - public func asFinalClassMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> AnyClassMetadata { - try .resolve(from: offset, in: machO) - } +// MARK: - ReadingContext Support - public func asFinalClassMetadata() throws -> AnyClassMetadata { - try .resolve(from: asPointer) +extension AnyClassMetadataProtocol { + public func asFinalClassMetadata(in context: some ReadingContext) throws -> AnyClassMetadata { + try .resolve(at: try context.addressFromOffset(offset), in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension AnyClassMetadataProtocol { - public func asFinalClassMetadata(in context: some ReadingContext) throws -> AnyClassMetadata { - try .resolve(at: try context.addressFromOffset(offset), in: context) + @available(*, deprecated, message: "Pass a ReadingContext: asFinalClassMetadata(in: machO.context).") + public func asFinalClassMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> AnyClassMetadata { + try asFinalClassMetadata(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: asFinalClassMetadata(in: .inProcess).") + public func asFinalClassMetadata() throws -> AnyClassMetadata { + try asFinalClassMetadata(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInterop.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInterop.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInterop.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInterop.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocol.swift similarity index 66% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocol.swift index 67014da31..3302d2088 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocol.swift @@ -5,24 +5,6 @@ import MachOBase public protocol AnyClassMetadataObjCInteropProtocol: HeapMetadataProtocol where Layout: AnyClassMetadataObjCInteropLayout {} extension AnyClassMetadataObjCInteropProtocol { - public func asFinalClassMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassMetadataObjCInterop { - try .resolve(from: offset, in: machO) - } - - public func asFinalClassMetadata() throws -> ClassMetadataObjCInterop { - try .resolve(from: asPointer) - } -} - -extension AnyClassMetadataObjCInteropProtocol { - public func superclass(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> AnyClassMetadataObjCInterop? { - try layout.superclass.resolve(in: machO) - } - - public func superclass() throws -> AnyClassMetadataObjCInterop? { - try layout.superclass.resolve() - } - public var isPureObjC: Bool { !isTypeMetadata } @@ -43,3 +25,27 @@ extension AnyClassMetadataObjCInteropProtocol { try layout.superclass.resolve(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension AnyClassMetadataObjCInteropProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: asFinalClassMetadata(in: machO.context).") + public func asFinalClassMetadata(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassMetadataObjCInterop { + try asFinalClassMetadata(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: superclass(in: machO.context).") + public func superclass(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> AnyClassMetadataObjCInterop? { + try superclass(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: asFinalClassMetadata(in: .inProcess).") + public func asFinalClassMetadata() throws -> ClassMetadataObjCInterop { + try asFinalClassMetadata(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: superclass(in: .inProcess).") + public func superclass() throws -> AnyClassMetadataObjCInterop? { + try superclass(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBounds.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBounds.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBounds.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBounds.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/ClassMetadataBoundsProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/StoredClassMetadataBounds.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/StoredClassMetadataBounds.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/StoredClassMetadataBounds.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/Bounds/StoredClassMetadataBounds.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadata/ClassMetadataProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInterop.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInterop.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInterop.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInterop.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropProtocol.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift similarity index 62% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift index a4713a894..5bf6a0f8e 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/FinalClassMetadataProtocol.swift @@ -4,30 +4,6 @@ import MachOBase public protocol FinalClassMetadataProtocol: HeapMetadataProtocol {} -extension FinalClassMetadataProtocol where Layout: FinalClassMetadataLayout { - public func fieldOffsets(for descriptor: ClassDescriptor? = nil, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [StoredPointer] { - guard let descriptor = try descriptor ?? layout.descriptor.resolve(in: machO) else { return [] } - guard descriptor.fieldOffsetVectorOffset != .zero else { return [] } - let offset = offset.offseting(of: StoredPointer.self, numbersOfElements: descriptor.fieldOffsetVectorOffset.cast()) - return try machO.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) - } - - public func fieldOffsets(for descriptor: ClassDescriptor? = nil) throws -> [StoredPointer] { - guard let descriptor = try descriptor ?? layout.descriptor.resolve() else { return [] } - guard descriptor.fieldOffsetVectorOffset != .zero else { return [] } - let offset = Int.zero.offseting(of: StoredPointer.self, numbersOfElements: descriptor.fieldOffsetVectorOffset.cast()) - return try asPointer.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) - } - - public func descriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { - try layout.descriptor.resolve(in: machO) - } - - public func descriptor() throws -> ClassDescriptor? { - try layout.descriptor.resolve() - } -} - // MARK: - ReadingContext Support extension FinalClassMetadataProtocol where Layout: FinalClassMetadataLayout { @@ -42,3 +18,27 @@ extension FinalClassMetadataProtocol where Layout: FinalClassMetadataLayout { try layout.descriptor.resolve(in: context) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension FinalClassMetadataProtocol where Layout: FinalClassMetadataLayout { + @available(*, deprecated, message: "Pass a ReadingContext: fieldOffsets(in: machO.context).") + public func fieldOffsets(for descriptor: ClassDescriptor? = nil, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [StoredPointer] { + try fieldOffsets(for: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: descriptor(in: machO.context).") + public func descriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { + try descriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: fieldOffsets(in: .inProcess).") + public func fieldOffsets(for descriptor: ClassDescriptor? = nil) throws -> [StoredPointer] { + try fieldOffsets(for: descriptor, in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: descriptor(in: .inProcess).") + public func descriptor() throws -> ClassDescriptor? { + try descriptor(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Metadata/ObjCClassWrapperMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ObjCClassWrapperMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Metadata/ObjCClassWrapperMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Metadata/ObjCClassWrapperMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift similarity index 74% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift index c88bfee5d..8d78f8f2d 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideDescriptor.swift @@ -12,14 +12,6 @@ public struct MethodDefaultOverrideDescriptor: ResolvableLocatableLayoutWrapper } extension MethodDefaultOverrideDescriptor { - public func originalMethodDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try layout.original.resolve(from: offset(of: \.original), in: machO).asOptional - } - - public func replacementMethodDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try layout.replacement.resolve(from: offset(of: \.replacement), in: machO).asOptional - } - /// File offset of the default-override implementation, or `nil` for a /// null pointer. See `MethodDescriptor.implementationOffset`. public var implementationOffset: Int? { @@ -27,16 +19,6 @@ extension MethodDefaultOverrideDescriptor { } } -extension MethodDefaultOverrideDescriptor { - public func originalMethodDescriptor() throws -> SymbolOrElement? { - return try layout.original.resolve(from: pointer(of: \.original)).asOptional - } - - public func replacementMethodDescriptor() throws -> SymbolOrElement? { - return try layout.replacement.resolve(from: pointer(of: \.replacement)).asOptional - } -} - // MARK: - ReadingContext Support extension MethodDefaultOverrideDescriptor { @@ -55,3 +37,27 @@ extension MethodDefaultOverrideDescriptor { return try context.addressFromOffset(implementationOffset) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension MethodDefaultOverrideDescriptor { + @available(*, deprecated, message: "Pass a ReadingContext: originalMethodDescriptor(in: machO.context).") + public func originalMethodDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try originalMethodDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: replacementMethodDescriptor(in: machO.context).") + public func replacementMethodDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try replacementMethodDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: originalMethodDescriptor(in: .inProcess).") + public func originalMethodDescriptor() throws -> SymbolOrElement? { + try originalMethodDescriptor(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: replacementMethodDescriptor(in: .inProcess).") + public func replacementMethodDescriptor() throws -> SymbolOrElement? { + try replacementMethodDescriptor(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideTableHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideTableHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideTableHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDefaultOverrideTableHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorKind.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorKind.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorWrapper.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorWrapper.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodDescriptorWrapper.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodImplementationPointer.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodImplementationPointer.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodImplementationPointer.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodImplementationPointer.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift similarity index 78% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift index a3b34eff8..d9da23b45 100644 --- a/Sources/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/MethodOverrideDescriptor.swift @@ -12,18 +12,6 @@ public struct MethodOverrideDescriptor: ResolvableLocatableLayoutWrapper { } extension MethodOverrideDescriptor { - public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try layout.`class`.resolve(from: offset(of: \.`class`), in: machO).asOptional - } - - public func methodDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try layout.method.resolve(from: offset(of: \.method), in: machO).asOptional - } - - public func methodDescriptor() throws -> SymbolOrElement? { - return try layout.method.resolve(from: pointer(of: \.method)).asOptional - } - /// File offset of the overriding implementation, or `nil` for a null /// pointer. See `MethodDescriptor.implementationOffset`. public var implementationOffset: Int? { @@ -49,3 +37,22 @@ extension MethodOverrideDescriptor { return try context.addressFromOffset(implementationOffset) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension MethodOverrideDescriptor { + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: machO.context).") + public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try classDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: methodDescriptor(in: machO.context).") + public func methodDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try methodDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: methodDescriptor(in: .inProcess).") + public func methodDescriptor() throws -> SymbolOrElement? { + try methodDescriptor(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/OverrideTableHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/OverrideTableHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/OverrideTableHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/OverrideTableHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Method/VTableDescriptorHeader.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/VTableDescriptorHeader.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Method/VTableDescriptorHeader.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Method/VTableDescriptorHeader.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Resilient/ObjCResilientClassStubInfo.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Resilient/ObjCResilientClassStubInfo.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Resilient/ObjCResilientClassStubInfo.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Resilient/ObjCResilientClassStubInfo.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Class/Resilient/ResilientSuperclass.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Class/Resilient/ResilientSuperclass.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Class/Resilient/ResilientSuperclass.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Class/Resilient/ResilientSuperclass.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/Enum.swift similarity index 60% rename from Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/Enum.swift index 4e455e968..40a5e0e57 100644 --- a/Sources/MachOSwiftSection/Models/Type/Enum/Enum.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/Enum.swift @@ -27,77 +27,6 @@ public struct Enum: TopLevelType, ContextProtocol { public private(set) var canonicalSpecializedMetadatasCachingOnceToken: CanonicalSpecializedMetadatasCachingOnceToken? public private(set) var invertibleProtocolSet: InvertibleProtocolSet? public private(set) var singletonMetadataPointer: SingletonMetadataPointer? - - public init(descriptor: EnumDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - var currentOffset = descriptor.offset + descriptor.layoutSize - let genericContext = try descriptor.typeGenericContext(in: machO) - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: machO) - } - - public init(descriptor: EnumDescriptor) throws { - self.descriptor = descriptor - var currentOffset = descriptor.layoutSize - let genericContext = try descriptor.typeGenericContext() - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: descriptor.asPointer) - } - - private mutating func initialize(descriptor: EnumDescriptor, currentOffset: inout Int, in reader: some Readable) throws { - - let typeFlags = try required(descriptor.flags.kindSpecificFlags?.typeFlags) - - if typeFlags.hasForeignMetadataInitialization { - self.foreignMetadataInitialization = try reader.readWrapperElement(offset: currentOffset) as ForeignMetadataInitialization - currentOffset.offset(of: ForeignMetadataInitialization.self) - } else { - self.foreignMetadataInitialization = nil - } - - if typeFlags.hasSingletonMetadataInitialization { - self.singletonMetadataInitialization = try reader.readWrapperElement(offset: currentOffset) as SingletonMetadataInitialization - currentOffset.offset(of: SingletonMetadataInitialization.self) - } else { - self.singletonMetadataInitialization = nil - } - - if descriptor.hasCanonicalMetadataPrespecializations { - let count: CanonicalSpecializedMetadatasListCount = try reader.readElement(offset: currentOffset) - currentOffset.offset(of: CanonicalSpecializedMetadatasListCount.self) - let countValue = count.rawValue - let canonicalMetadataPrespecializations: [CanonicalSpecializedMetadatasListEntry] = try reader.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) - currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) - self.canonicalSpecializedMetadatas = canonicalMetadataPrespecializations - self.canonicalSpecializedMetadatasListCount = count - self.canonicalSpecializedMetadatasCachingOnceToken = try reader.readWrapperElement(offset: currentOffset) as CanonicalSpecializedMetadatasCachingOnceToken - currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) - } else { - self.canonicalSpecializedMetadatas = [] - self.canonicalSpecializedMetadatasListCount = nil - self.canonicalSpecializedMetadatasCachingOnceToken = nil - } - - if descriptor.flags.hasInvertibleProtocols { - self.invertibleProtocolSet = try reader.readElement(offset: currentOffset) as InvertibleProtocolSet - currentOffset.offset(of: InvertibleProtocolSet.self) - } else { - self.invertibleProtocolSet = nil - } - - if descriptor.hasSingletonMetadataPointer { - self.singletonMetadataPointer = try reader.readWrapperElement(offset: currentOffset) as SingletonMetadataPointer - currentOffset.offset(of: SingletonMetadataPointer.self) - } else { - self.singletonMetadataPointer = nil - } - } } // MARK: - ReadingContext Support @@ -163,3 +92,17 @@ extension Enum { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension Enum { + @available(*, deprecated, message: "Pass a ReadingContext: Enum(descriptor:in: machO.context).") + public init(descriptor: EnumDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: Enum(descriptor:in: .inProcess).") + public init(descriptor: EnumDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/EnumDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Enum/EnumDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/EnumDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Enum/EnumDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/EnumFunctions.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataProtocol.swift similarity index 55% rename from Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataProtocol.swift index 6509bc28d..5aaeb68e1 100644 --- a/Sources/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/Metadata/EnumMetadataProtocol.swift @@ -3,47 +3,46 @@ import MachOBase public protocol EnumMetadataProtocol: ValueMetadataProtocol where Layout: EnumMetadataLayout {} -extension EnumMetadataProtocol { - public func enumDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> EnumDescriptor { - try layout.descriptor.resolve(in: machO).enum! - } +// MARK: - ReadingContext Support - public func enumDescriptor() throws -> EnumDescriptor { - try layout.descriptor.resolve().enum! +extension EnumMetadataProtocol { + public func enumDescriptor(in context: some ReadingContext) throws -> EnumDescriptor { + try descriptor(in: context).enum! } - public func payloadSize(descriptor: EnumDescriptor? = nil, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StoredSize? { - let descriptor = try descriptor ?? enumDescriptor(in: machO) + public func payloadSize(descriptor: EnumDescriptor? = nil, in context: some ReadingContext) throws -> StoredSize? { + let descriptor = try descriptor ?? enumDescriptor(in: context) guard descriptor.hasPayloadSizeOffset else { return nil } let offset = offset.offseting(of: StoredSize.self, numbersOfElements: descriptor.payloadSizeOffset) - return try machO.readElement(offset: offset) - } - - public func payloadSize(descriptor: EnumDescriptor? = nil) throws -> StoredSize? { - let descriptor = try descriptor ?? enumDescriptor() - guard descriptor.hasPayloadSizeOffset else { - return nil - } - let offset = Int.zero.offseting(of: StoredSize.self, numbersOfElements: descriptor.payloadSizeOffset) - return try asPointer.readElement(offset: offset) + // Annotated: asking for the optional directly would read the + // Optional's in-memory shape, one tag byte past the size word. + let payloadSize: StoredSize = try context.readElement(at: try context.addressFromOffset(offset)) + return payloadSize } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension EnumMetadataProtocol { - public func enumDescriptor(in context: some ReadingContext) throws -> EnumDescriptor { - try descriptor(in: context).enum! + @available(*, deprecated, message: "Pass a ReadingContext: enumDescriptor(in: machO.context).") + public func enumDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> EnumDescriptor { + try enumDescriptor(in: machO.context) } - public func payloadSize(descriptor: EnumDescriptor? = nil, in context: some ReadingContext) throws -> StoredSize? { - let descriptor = try descriptor ?? enumDescriptor(in: context) - guard descriptor.hasPayloadSizeOffset else { - return nil - } - let offset = offset.offseting(of: StoredSize.self, numbersOfElements: descriptor.payloadSizeOffset) - return try context.readElement(at: try context.addressFromOffset(offset)) + @available(*, deprecated, message: "Pass a ReadingContext: payloadSize(in: machO.context).") + public func payloadSize(descriptor: EnumDescriptor? = nil, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StoredSize? { + try payloadSize(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: enumDescriptor(in: .inProcess).") + public func enumDescriptor() throws -> EnumDescriptor { + try enumDescriptor(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSize(in: .inProcess).") + public func payloadSize(descriptor: EnumDescriptor? = nil) throws -> StoredSize? { + try payloadSize(descriptor: descriptor, in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Type/Enum/MultiPayloadEnumDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/MultiPayloadEnumDescriptor.swift similarity index 68% rename from Sources/MachOSwiftSection/Models/Type/Enum/MultiPayloadEnumDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Enum/MultiPayloadEnumDescriptor.swift index 5fc80d031..bf626e983 100644 --- a/Sources/MachOSwiftSection/Models/Type/Enum/MultiPayloadEnumDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Enum/MultiPayloadEnumDescriptor.swift @@ -12,64 +12,6 @@ public struct MultiPayloadEnumDescriptor: ResolvableLocatableLayoutWrapper { } extension MultiPayloadEnumDescriptor { - public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { - return try layout.mangledTypeName.resolve(from: offset, in: machO) - } - - public func contents(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [UInt32] { - return try machO.readElements(offset: offset(of: \.sizeFlags), numberOfElements: contentsSizeInWord.cast()) - } - - public func payloadSpareBits(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [UInt8] { - guard usesPayloadSpareBits else { return [] } - return try machO.readElements(offset: offset + MemoryLayout.size + MemoryLayout.size * payloadSpareBitsIndex, numberOfElements: payloadSpareBitMaskByteCount(in: machO).cast()) - } - - public func payloadSpareBitMaskByteOffset(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> UInt32 { - if usesPayloadSpareBits { - return try contents(in: machO)[payloadSpareBitMaskByteCountIndex] >> 16 - } else { - return 0 - } - } - - public func payloadSpareBitMaskByteCount(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> UInt32 { - if usesPayloadSpareBits { - return try contents(in: machO)[payloadSpareBitMaskByteCountIndex] & 0xFFFF - } else { - return 0 - } - } - - public func mangledTypeName() throws -> MangledName { - return try layout.mangledTypeName.resolve(from: asPointer) - } - - public func contents() throws -> [UInt32] { - return try pointer(of: \.sizeFlags).readElements(numberOfElements: contentsSizeInWord.cast()) - } - - public func payloadSpareBits() throws -> [UInt8] { - guard usesPayloadSpareBits else { return [] } - return try asPointer.readElements(offset: MemoryLayout.size + MemoryLayout.size * payloadSpareBitsIndex, numberOfElements: payloadSpareBitMaskByteCount().cast()) - } - - public func payloadSpareBitMaskByteOffset() throws -> UInt32 { - if usesPayloadSpareBits { - return try contents()[payloadSpareBitMaskByteCountIndex] >> 16 - } else { - return 0 - } - } - - public func payloadSpareBitMaskByteCount() throws -> UInt32 { - if usesPayloadSpareBits { - return try contents()[payloadSpareBitMaskByteCountIndex] & 0xFFFF - } else { - return 0 - } - } - /*@inlinable*/ public var contentsSizeInWord: UInt32 { layout.sizeFlags >> 16 @@ -140,3 +82,57 @@ extension MultiPayloadEnumDescriptor { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension MultiPayloadEnumDescriptor { + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: machO.context).") + public func mangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MangledName { + try mangledTypeName(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: contents(in: machO.context).") + public func contents(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [UInt32] { + try contents(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSpareBits(in: machO.context).") + public func payloadSpareBits(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [UInt8] { + try payloadSpareBits(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSpareBitMaskByteOffset(in: machO.context).") + public func payloadSpareBitMaskByteOffset(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> UInt32 { + try payloadSpareBitMaskByteOffset(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSpareBitMaskByteCount(in: machO.context).") + public func payloadSpareBitMaskByteCount(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> UInt32 { + try payloadSpareBitMaskByteCount(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: mangledTypeName(in: .inProcess).") + public func mangledTypeName() throws -> MangledName { + try mangledTypeName(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: contents(in: .inProcess).") + public func contents() throws -> [UInt32] { + try contents(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSpareBits(in: .inProcess).") + public func payloadSpareBits() throws -> [UInt8] { + try payloadSpareBits(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSpareBitMaskByteOffset(in: .inProcess).") + public func payloadSpareBitMaskByteOffset() throws -> UInt32 { + try payloadSpareBitMaskByteOffset(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: payloadSpareBitMaskByteCount(in: .inProcess).") + public func payloadSpareBitMaskByteCount() throws -> UInt32 { + try payloadSpareBitMaskByteCount(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/Struct.swift similarity index 56% rename from Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Struct/Struct.swift index 498104799..486e5a0c6 100644 --- a/Sources/MachOSwiftSection/Models/Type/Struct/Struct.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/Struct.swift @@ -12,86 +12,6 @@ public struct Struct: TopLevelType, ContextProtocol { public private(set) var canonicalSpecializedMetadatasCachingOnceToken: CanonicalSpecializedMetadatasCachingOnceToken? public private(set) var invertibleProtocolSet: InvertibleProtocolSet? public private(set) var singletonMetadataPointer: SingletonMetadataPointer? - - public init(descriptor: StructDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - - var currentOffset = descriptor.offset + descriptor.layoutSize - - let genericContext = try descriptor.typeGenericContext(in: machO) - - if let genericContext { - currentOffset += genericContext.size - } - - self.genericContext = genericContext - - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: machO) - } - - public init(descriptor: StructDescriptor) throws { - self.descriptor = descriptor - - var currentOffset = descriptor.layoutSize - - let genericContext = try descriptor.typeGenericContext() - - if let genericContext { - currentOffset += genericContext.size - } - - self.genericContext = genericContext - - try initialize(descriptor: descriptor, currentOffset: ¤tOffset, in: descriptor.asPointer) - } - - private mutating func initialize(descriptor: StructDescriptor, currentOffset: inout Int, in machO: some Readable) throws { - let typeFlags = try required(descriptor.flags.kindSpecificFlags?.typeFlags) - - if typeFlags.hasForeignMetadataInitialization { - foreignMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) as ForeignMetadataInitialization - currentOffset.offset(of: ForeignMetadataInitialization.self) - } else { - foreignMetadataInitialization = nil - } - - if typeFlags.hasSingletonMetadataInitialization { - singletonMetadataInitialization = try machO.readWrapperElement(offset: currentOffset) as SingletonMetadataInitialization - currentOffset.offset(of: SingletonMetadataInitialization.self) - } else { - singletonMetadataInitialization = nil - } - - if descriptor.hasCanonicalMetadataPrespecializations { - let count: CanonicalSpecializedMetadatasListCount = try machO.readElement(offset: currentOffset) - currentOffset.offset(of: CanonicalSpecializedMetadatasListCount.self) - let countValue = count.rawValue - let canonicalMetadataPrespecializations: [CanonicalSpecializedMetadatasListEntry] = try machO.readWrapperElements(offset: currentOffset, numberOfElements: countValue.cast()) - currentOffset.offset(of: CanonicalSpecializedMetadatasListEntry.self, numbersOfElements: countValue.cast()) - canonicalSpecializedMetadatas = canonicalMetadataPrespecializations - canonicalSpecializedMetadatasListCount = count - canonicalSpecializedMetadatasCachingOnceToken = try machO.readWrapperElement(offset: currentOffset) as CanonicalSpecializedMetadatasCachingOnceToken - currentOffset.offset(of: CanonicalSpecializedMetadatasCachingOnceToken.self) - } else { - canonicalSpecializedMetadatas = [] - canonicalSpecializedMetadatasListCount = nil - canonicalSpecializedMetadatasCachingOnceToken = nil - } - - if descriptor.flags.hasInvertibleProtocols { - invertibleProtocolSet = try machO.readElement(offset: currentOffset) as InvertibleProtocolSet - currentOffset.offset(of: InvertibleProtocolSet.self) - } else { - invertibleProtocolSet = nil - } - - if descriptor.hasSingletonMetadataPointer { - singletonMetadataPointer = try machO.readWrapperElement(offset: currentOffset) as SingletonMetadataPointer - currentOffset.offset(of: SingletonMetadataPointer.self) - } else { - singletonMetadataPointer = nil - } - } } // MARK: - ReadingContext Support @@ -161,3 +81,17 @@ extension Struct { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension Struct { + @available(*, deprecated, message: "Pass a ReadingContext: Struct(descriptor:in: machO.context).") + public init(descriptor: StructDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { + try self.init(descriptor: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: Struct(descriptor:in: .inProcess).") + public init(descriptor: StructDescriptor) throws { + try self.init(descriptor: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/StructDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Struct/StructDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructDescriptor.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/StructDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Struct/StructDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/Struct/StructMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadataProtocol.swift similarity index 62% rename from Sources/MachOSwiftSection/Models/Type/Struct/StructMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadataProtocol.swift index 58c250e33..c87a0a6f8 100644 --- a/Sources/MachOSwiftSection/Models/Type/Struct/StructMetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/Struct/StructMetadataProtocol.swift @@ -3,32 +3,6 @@ import MachOBase public protocol StructMetadataProtocol: ValueMetadataProtocol where Layout: StructMetadataLayout {} -extension StructMetadataProtocol { - - public func structDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StructDescriptor { - try descriptor(in: machO).struct! - } - - public func structDescriptor() throws -> StructDescriptor { - try descriptor().struct! - } - - public func fieldOffsets(for descriptor: StructDescriptor? = nil, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [UInt32] { - let descriptor = try descriptor ?? structDescriptor(in: machO) - guard descriptor.fieldOffsetVector != .zero else { return [] } - // Metadata.offset + fieldOffset (eg. 2 * 8) - let offset = offset + (descriptor.fieldOffsetVector.cast() * MemoryLayout.size) - return try machO.readElements(offset: offset, numberOfElements: descriptor.numFields.cast()) - } - - public func fieldOffsets(for descriptor: StructDescriptor? = nil) throws -> [UInt32] { - let descriptor = try descriptor ?? structDescriptor() - guard descriptor.fieldOffsetVector != .zero else { return [] } - // Metadata.offset + fieldOffset (eg. 2 * 8) - return try asPointer.advanced(by: descriptor.fieldOffsetVector.cast() * MemoryLayout.size).readElements(numberOfElements: descriptor.numFields.cast()) - } -} - // MARK: - ReadingContext Support extension StructMetadataProtocol { @@ -44,3 +18,27 @@ extension StructMetadataProtocol { return try context.readElements(at: try context.addressFromOffset(offset), numberOfElements: descriptor.numFields.cast()) } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension StructMetadataProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: structDescriptor(in: machO.context).") + public func structDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StructDescriptor { + try structDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: fieldOffsets(in: machO.context).") + public func fieldOffsets(for descriptor: StructDescriptor? = nil, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [UInt32] { + try fieldOffsets(for: descriptor, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: structDescriptor(in: .inProcess).") + public func structDescriptor() throws -> StructDescriptor { + try structDescriptor(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: fieldOffsets(in: .inProcess).") + public func fieldOffsets(for descriptor: StructDescriptor? = nil) throws -> [UInt32] { + try fieldOffsets(for: descriptor, in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift similarity index 67% rename from Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift index dd1dbc8f4..aede640f0 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptor.swift @@ -13,55 +13,55 @@ public struct TypeContextDescriptor: TypeContextDescriptorProtocol { } } +// MARK: - ReadingContext Support + extension TypeContextDescriptor { - public func enumDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> EnumDescriptor? { + public func enumDescriptor(in context: some ReadingContext) throws -> EnumDescriptor? { guard layout.flags.kind == .enum else { return nil } - return try machO.readWrapperElement(offset: offset) as EnumDescriptor + return try context.readWrapperElement(at: try context.addressFromOffset(offset)) as EnumDescriptor } - public func structDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StructDescriptor? { + public func structDescriptor(in context: some ReadingContext) throws -> StructDescriptor? { guard layout.flags.kind == .struct else { return nil } - return try machO.readWrapperElement(offset: offset) as StructDescriptor + return try context.readWrapperElement(at: try context.addressFromOffset(offset)) as StructDescriptor } - public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { + public func classDescriptor(in context: some ReadingContext) throws -> ClassDescriptor? { guard layout.flags.kind == .class else { return nil } - return try machO.readWrapperElement(offset: offset) as ClassDescriptor + return try context.readWrapperElement(at: try context.addressFromOffset(offset)) as ClassDescriptor } } +// MARK: - Deprecated Mach-O and pointer forms + extension TypeContextDescriptor { - public func enumDescriptor() throws -> EnumDescriptor? { - guard layout.flags.kind == .enum else { return nil } - return try asPointer.readWrapperElement() as EnumDescriptor + @available(*, deprecated, message: "Pass a ReadingContext: enumDescriptor(in: machO.context).") + public func enumDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> EnumDescriptor? { + try enumDescriptor(in: machO.context) } - public func structDescriptor() throws -> StructDescriptor? { - guard layout.flags.kind == .struct else { return nil } - return try asPointer.readWrapperElement() as StructDescriptor + @available(*, deprecated, message: "Pass a ReadingContext: structDescriptor(in: machO.context).") + public func structDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> StructDescriptor? { + try structDescriptor(in: machO.context) } - public func classDescriptor() throws -> ClassDescriptor? { - guard layout.flags.kind == .class else { return nil } - return try asPointer.readWrapperElement() as ClassDescriptor + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: machO.context).") + public func classDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { + try classDescriptor(in: machO.context) } -} - -// MARK: - ReadingContext Support -extension TypeContextDescriptor { - public func enumDescriptor(in context: some ReadingContext) throws -> EnumDescriptor? { - guard layout.flags.kind == .enum else { return nil } - return try context.readWrapperElement(at: try context.addressFromOffset(offset)) as EnumDescriptor + @available(*, deprecated, message: "Pass a ReadingContext: enumDescriptor(in: .inProcess).") + public func enumDescriptor() throws -> EnumDescriptor? { + try enumDescriptor(in: InProcessContext.shared) } - public func structDescriptor(in context: some ReadingContext) throws -> StructDescriptor? { - guard layout.flags.kind == .struct else { return nil } - return try context.readWrapperElement(at: try context.addressFromOffset(offset)) as StructDescriptor + @available(*, deprecated, message: "Pass a ReadingContext: structDescriptor(in: .inProcess).") + public func structDescriptor() throws -> StructDescriptor? { + try structDescriptor(in: InProcessContext.shared) } - public func classDescriptor(in context: some ReadingContext) throws -> ClassDescriptor? { - guard layout.flags.kind == .class else { return nil } - return try context.readWrapperElement(at: try context.addressFromOffset(offset)) as ClassDescriptor + @available(*, deprecated, message: "Pass a ReadingContext: classDescriptor(in: .inProcess).") + public func classDescriptor() throws -> ClassDescriptor? { + try classDescriptor(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorFlags.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorFlags.swift diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift similarity index 66% rename from Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift index 87cc69acc..7303aefca 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorProtocol.swift @@ -3,49 +3,6 @@ import MachOBase public protocol TypeContextDescriptorProtocol: NamedContextDescriptorProtocol where Layout: TypeContextDescriptorLayout {} -extension TypeContextDescriptorProtocol { - public func metadataAccessorFunction(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MetadataAccessorFunction? { - guard let machOImage = machO as? MachOImage else { return nil } - let offset = layout.accessFunctionPtr.resolveDirectOffset(from: offset + layout.offset(of: .accessFunctionPtr)) - return .init(ptr: machOImage.ptr + UnsafeRawPointer.Stride(offset)) - } - - public func fieldDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> FieldDescriptor { - try layout.fieldDescriptor.resolve(from: offset + layout.offset(of: .fieldDescriptor), in: machO) - } - - public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { - guard layout.flags.isGeneric else { return nil } - return try typeGenericContext(in: machO)?.asGenericContext() - } - - public func typeGenericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeGenericContext? { - guard layout.flags.isGeneric else { return nil } - return try .init(contextDescriptor: self, in: machO) - } -} - -extension TypeContextDescriptorProtocol { - public func metadataAccessorFunction() throws -> MetadataAccessorFunction? { - let ptr = try layout.pointer(from: asPointer, of: .accessFunctionPtr) - return try .init(ptr: layout.accessFunctionPtr.resolveDirectOffset(from: ptr)) - } - - public func fieldDescriptor() throws -> FieldDescriptor { - return try layout.fieldDescriptor.resolve(from: layout.pointer(from: asPointer, of: .fieldDescriptor)) - } - - public func genericContext() throws -> GenericContext? { - guard layout.flags.isGeneric else { return nil } - return try typeGenericContext()?.asGenericContext() - } - - public func typeGenericContext() throws -> TypeGenericContext? { - guard layout.flags.isGeneric else { return nil } - return try .init(contextDescriptor: self) - } -} - // MARK: - ReadingContext Support extension TypeContextDescriptorProtocol { @@ -64,10 +21,13 @@ extension TypeContextDescriptorProtocol { return try layout.fieldDescriptor.resolve(at: address, in: context) } + /// The type's metadata accessor, or `nil` when `context` is not mapped + /// into this process (a `MachOContext` over a `MachOFile`). The target is + /// computed from the relative offset already in `layout`, so a context + /// that cannot vend a runtime pointer answers `nil` without reading. public func metadataAccessorFunction(in context: some ReadingContext) throws -> MetadataAccessorFunction? { let fieldAddress = try context.addressFromOffset(offset + layout.offset(of: .accessFunctionPtr)) - let relativeOffset: Int32 = try context.readElement(at: fieldAddress) - let targetAddress = context.advanceAddress(fieldAddress, by: Int(relativeOffset)) + let targetAddress = try layout.accessFunctionPtr.resolveDirectAddress(at: fieldAddress, in: context) return try context.runtimePointer(at: targetAddress).map { MetadataAccessorFunction(ptr: $0) } } } @@ -107,31 +67,6 @@ extension TypeContextDescriptorProtocol { extension TypeContextDescriptorProtocol { /// The C-import identity components that follow the descriptor's name, /// or `nil` when `hasImportInfo` is not set. See ``TypeImportInfo``. - public func typeImportInfo(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeImportInfo? { - guard hasImportInfo else { return nil } - return try typeImportInfo(in: MachOContext(machO)) - } - - /// In-process variant of ``typeImportInfo(in:)-swift.method``. - public func typeImportInfo() throws -> TypeImportInfo? { - guard hasImportInfo else { return nil } - let nameFieldPointer = try layout.pointer(from: asPointer, of: .name) - var cursor = try layout.name.resolveDirectOffset(from: nameFieldPointer) - var components: [String] = [] - // The first string is the user-facing name the descriptor's `name` - // already vends; the components follow it, and an empty string ends - // the sequence. - var current = String(cString: cursor.assumingMemoryBound(to: CChar.self)) - while true { - cursor = cursor.advanced(by: current.utf8.count + 1) - current = String(cString: cursor.assumingMemoryBound(to: CChar.self)) - if current.isEmpty { break } - components.append(current) - } - return TypeImportInfo(components: components) - } - - /// `ReadingContext` variant of ``typeImportInfo(in:)-swift.method``. public func typeImportInfo(in context: some ReadingContext) throws -> TypeImportInfo? { guard hasImportInfo else { return nil } let nameFieldAddress = try context.addressFromOffset(offset + layout.offset(of: .name)) @@ -150,3 +85,62 @@ extension TypeContextDescriptorProtocol { return TypeImportInfo(components: components) } } + +// MARK: - Deprecated Mach-O and pointer forms + +// `ContextDescriptorProtocol` declares both old `genericContext` forms too. +// They stay here so a call on a type descriptor binds to the same declaration +// as before. The forward goes through the `ContextDescriptorProtocol` +// requirement, whose witness for a type descriptor is this protocol's +// `genericContext(in:)` — the one that reads the type generic context header. +extension TypeContextDescriptorProtocol { + @available(*, deprecated, message: "Pass a ReadingContext: metadataAccessorFunction(in: machO.context).") + public func metadataAccessorFunction(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> MetadataAccessorFunction? { + try metadataAccessorFunction(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: fieldDescriptor(in: machO.context).") + public func fieldDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> FieldDescriptor { + try fieldDescriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: machO.context).") + public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { + try genericContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeGenericContext(in: machO.context).") + public func typeGenericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeGenericContext? { + try typeGenericContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeImportInfo(in: machO.context).") + public func typeImportInfo(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeImportInfo? { + try typeImportInfo(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: metadataAccessorFunction(in: .inProcess).") + public func metadataAccessorFunction() throws -> MetadataAccessorFunction? { + try metadataAccessorFunction(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: fieldDescriptor(in: .inProcess).") + public func fieldDescriptor() throws -> FieldDescriptor { + try fieldDescriptor(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: .inProcess).") + public func genericContext() throws -> GenericContext? { + try genericContext(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeGenericContext(in: .inProcess).") + public func typeGenericContext() throws -> TypeGenericContext? { + try typeGenericContext(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeImportInfo(in: .inProcess).") + public func typeImportInfo() throws -> TypeImportInfo? { + try typeImportInfo(in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorWrapper.swift similarity index 69% rename from Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorWrapper.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorWrapper.swift index ba3727093..82cd394e9 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeContextDescriptorWrapper.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextDescriptorWrapper.swift @@ -1,9 +1,11 @@ import MachOKit import MachOBase import SwiftStdlibToolbox +import FoundationToolbox @CaseCheckable(.public) @AssociatedValue(.public) +@Loggable(.private, subsystem: "com.machoswiftsection.macho-swift-section", category: "TypeContextDescriptorWrapper") public enum TypeContextDescriptorWrapper { case `enum`(EnumDescriptor) case `struct`(StructDescriptor) @@ -42,30 +44,6 @@ public enum TypeContextDescriptorWrapper { } } - public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try contextDescriptor.parent(in: machO) - } - - public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { - return try contextDescriptor.genericContext(in: machO) - } - - public func typeGenericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeGenericContext? { - return try typeContextDescriptor.typeGenericContext(in: machO) - } - - public func parent() throws -> SymbolOrElement? { - return try contextDescriptor.parent() - } - - public func genericContext() throws -> GenericContext? { - return try contextDescriptor.genericContext() - } - - public func typeGenericContext() throws -> TypeGenericContext? { - return try typeContextDescriptor.typeGenericContext() - } - // MARK: - ReadingContext Support public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { @@ -101,52 +79,6 @@ extension TypeContextDescriptorWrapper: Resolvable { case invalidTypeContextDescriptor } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - let contextDescriptor: ContextDescriptor = try machO.readWrapperElement(offset: offset) - switch contextDescriptor.flags.kind { - case .class: - return try .class(machO.readWrapperElement(offset: offset)) - case .enum: - return try .enum(machO.readWrapperElement(offset: offset)) - case .struct: - return try .struct(machO.readWrapperElement(offset: offset)) - default: - throw ResolutionError.invalidTypeContextDescriptor - } - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { - do { - return try resolve(from: offset, in: machO) as Self - } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") - return nil - } - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - let contextDescriptor = try ContextDescriptor.resolve(from: ptr) - switch contextDescriptor.flags.kind { - case .class: - return try .class(.resolve(from: ptr)) - case .enum: - return try .enum(.resolve(from: ptr)) - case .struct: - return try .struct(.resolve(from: ptr)) - default: - throw ResolutionError.invalidTypeContextDescriptor - } - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self? { - do { - return try resolve(from: ptr) as Self - } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") - return nil - } - } - // MARK: - ReadingContext Support public static func resolve(at address: Context.Address, in context: Context) throws -> Self { @@ -167,7 +99,7 @@ extension TypeContextDescriptorWrapper: Resolvable { do { return try resolve(at: address, in: context) as Self } catch { - print("Error resolving TypeContextDescriptorWrapper: \(error)") + #log(.error, "type context descriptor at \(String(describing: address), privacy: .public) unresolvable, read as absent: \(String(describing: error), privacy: .public)") return nil } } @@ -175,6 +107,7 @@ extension TypeContextDescriptorWrapper: Resolvable { @CaseCheckable(.public) @AssociatedValue(.public) +@Loggable(.private, subsystem: "com.machoswiftsection.macho-swift-section", category: "ValueTypeDescriptorWrapper") public enum ValueTypeDescriptorWrapper { case `enum`(EnumDescriptor) case `struct`(StructDescriptor) @@ -206,22 +139,6 @@ public enum ValueTypeDescriptorWrapper { } } - public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - return try contextDescriptor.parent(in: machO) - } - - public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { - return try contextDescriptor.genericContext(in: machO) - } - - public func parent() throws -> SymbolOrElement? { - return try contextDescriptor.parent() - } - - public func genericContext() throws -> GenericContext? { - return try contextDescriptor.genericContext() - } - // MARK: - ReadingContext Support public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { @@ -251,66 +168,120 @@ extension ValueTypeDescriptorWrapper: Resolvable { case invalidTypeContextDescriptor } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - let contextDescriptor: ContextDescriptor = try machO.readWrapperElement(offset: offset) + public static func resolve(at address: Context.Address, in context: Context) throws -> Self { + let contextDescriptor: ContextDescriptor = try context.readWrapperElement(at: address) switch contextDescriptor.flags.kind { case .enum: - return try .enum(machO.readWrapperElement(offset: offset)) + return try .enum(context.readWrapperElement(at: address)) case .struct: - return try .struct(machO.readWrapperElement(offset: offset)) + return try .struct(context.readWrapperElement(at: address)) default: throw ResolutionError.invalidTypeContextDescriptor } } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { + public static func resolve(at address: Context.Address, in context: Context) throws -> Self? { do { - return try resolve(from: offset, in: machO) as Self + return try resolve(at: address, in: context) as Self } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") + #log(.error, "value type descriptor at \(String(describing: address), privacy: .public) unresolvable, read as absent: \(String(describing: error), privacy: .public)") return nil } } +} + +// MARK: - Deprecated Mach-O and pointer forms +extension TypeContextDescriptorWrapper { + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: machO.context).") + public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try parent(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: machO.context).") + public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { + try genericContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeGenericContext(in: machO.context).") + public func typeGenericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeGenericContext? { + try typeGenericContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: .inProcess).") + public func parent() throws -> SymbolOrElement? { + try parent(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: .inProcess).") + public func genericContext() throws -> GenericContext? { + try genericContext(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: typeGenericContext(in: .inProcess).") + public func typeGenericContext() throws -> TypeGenericContext? { + try typeGenericContext(in: InProcessContext.shared) + } + + @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 { - let contextDescriptor = try ContextDescriptor.resolve(from: ptr) - switch contextDescriptor.flags.kind { - case .enum: - return try .enum(.resolve(from: ptr)) - case .struct: - return try .struct(.resolve(from: ptr)) - default: - throw ResolutionError.invalidTypeContextDescriptor - } + 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? { - do { - return try resolve(from: ptr) as Self - } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") - return nil - } + try resolve(at: ptr, in: InProcessContext.shared) } - - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - let contextDescriptor: ContextDescriptor = try context.readWrapperElement(at: address) - switch contextDescriptor.flags.kind { - case .enum: - return try .enum(context.readWrapperElement(at: address)) - case .struct: - return try .struct(context.readWrapperElement(at: address)) - default: - throw ResolutionError.invalidTypeContextDescriptor - } +} + +extension ValueTypeDescriptorWrapper { + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: machO.context).") + public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { + try parent(in: machO.context) } - public static func resolve(at address: Context.Address, in context: Context) throws -> Self? { - do { - return try resolve(at: address, in: context) as Self - } catch { - print("Error resolving ContextDescriptorWrapper: \(error)") - return nil - } + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: machO.context).") + public func genericContext(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> GenericContext? { + try genericContext(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: parent(in: .inProcess).") + public func parent() throws -> SymbolOrElement? { + try parent(in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: genericContext(in: .inProcess).") + public func genericContext() throws -> GenericContext? { + try genericContext(in: InProcessContext.shared) + } + + @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) } } diff --git a/Sources/MachOSwiftSection/Models/Type/TypeContextWrapper.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextWrapper.swift similarity index 70% rename from Sources/MachOSwiftSection/Models/Type/TypeContextWrapper.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeContextWrapper.swift index f3566fc17..bdb757bd0 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeContextWrapper.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/TypeContextWrapper.swift @@ -27,33 +27,11 @@ public enum TypeContextWrapper: Sendable { public func asPointerWrapper(in machO: MachOImage) throws -> Self { switch self { case .enum(let `enum`): - return try .enum(.init(descriptor: `enum`.descriptor.asPointerWrapper(in: machO))) + return try .enum(.init(descriptor: `enum`.descriptor.asPointerWrapper(in: machO), in: InProcessContext.shared)) case .struct(let `struct`): - return try .struct(.init(descriptor: `struct`.descriptor.asPointerWrapper(in: machO))) + return try .struct(.init(descriptor: `struct`.descriptor.asPointerWrapper(in: machO), in: InProcessContext.shared)) case .class(let `class`): - return try .class(.init(descriptor: `class`.descriptor.asPointerWrapper(in: machO))) - } - } - - public static func forTypeContextDescriptorWrapper(_ typeContextDescriptorWrapper: TypeContextDescriptorWrapper) throws -> Self { - switch typeContextDescriptorWrapper { - case .enum(let enumDescriptor): - return try .enum(.init(descriptor: enumDescriptor)) - case .struct(let structDescriptor): - return try .struct(.init(descriptor: structDescriptor)) - case .class(let classDescriptor): - return try .class(.init(descriptor: classDescriptor)) - } - } - - public static func forTypeContextDescriptorWrapper(_ typeContextDescriptorWrapper: TypeContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Self { - switch typeContextDescriptorWrapper { - case .enum(let enumDescriptor): - return try .enum(.init(descriptor: enumDescriptor, in: machO)) - case .struct(let structDescriptor): - return try .struct(.init(descriptor: structDescriptor, in: machO)) - case .class(let classDescriptor): - return try .class(.init(descriptor: classDescriptor, in: machO)) + return try .class(.init(descriptor: `class`.descriptor.asPointerWrapper(in: machO), in: InProcessContext.shared)) } } } @@ -72,3 +50,17 @@ extension TypeContextWrapper { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension TypeContextWrapper { + @available(*, deprecated, message: "Pass a ReadingContext: forTypeContextDescriptorWrapper(_:in: .inProcess).") + public static func forTypeContextDescriptorWrapper(_ typeContextDescriptorWrapper: TypeContextDescriptorWrapper) throws -> Self { + try forTypeContextDescriptorWrapper(typeContextDescriptorWrapper, in: InProcessContext.shared) + } + + @available(*, deprecated, message: "Pass a ReadingContext: forTypeContextDescriptorWrapper(_:in: machO.context).") + public static func forTypeContextDescriptorWrapper(_ typeContextDescriptorWrapper: TypeContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Self { + try forTypeContextDescriptorWrapper(typeContextDescriptorWrapper, in: machO.context) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/TypeImportInfo.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeImportInfo.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/TypeImportInfo.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeImportInfo.swift diff --git a/Sources/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift similarity index 75% rename from Sources/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift index c1b0bd5b0..8ffa010ae 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/TypeMetadataRecord.swift @@ -37,24 +37,6 @@ extension TypeMetadataRecord { /// list with it — the iOS 26.5 simulator's `libswiftSynchronization` /// registers a record for `libswiftCore/_$sSqMn` (`Swift.Optional`) and /// used to dump with no types at all. - public func contextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ContextDescriptorWrapper? { - let fieldOffset = offset(of: \.nominalTypeDescriptor) - let relativeOffset = layout.nominalTypeDescriptor.relativeOffset - switch typeKind { - case .directTypeDescriptor: - let pointer = RelativeDirectPointer(relativeOffset: relativeOffset) - return try pointer.resolve(from: fieldOffset, in: machO) - case .indirectTypeDescriptor: - if let machOFile = machO as? MachOFile, machOFile.resolveBind(fileOffset: fieldOffset + Int(relativeOffset)) != nil { - return nil - } - let pointer = RelativeIndirectPointer>(relativeOffset: relativeOffset) - return try pointer.resolve(from: fieldOffset, in: machO) - case .directObjCClassName, .indirectObjCClass: - return nil - } - } - public func contextDescriptor(in context: some ReadingContext) throws -> ContextDescriptorWrapper? { let fieldOffset = offset(of: \.nominalTypeDescriptor) let relativeOffset = layout.nominalTypeDescriptor.relativeOffset @@ -64,9 +46,22 @@ extension TypeMetadataRecord { return try pointer.resolve(at: context.addressFromOffset(fieldOffset), in: context) case .indirectTypeDescriptor: let pointer = RelativeIndirectPointer>(relativeOffset: relativeOffset) - return try pointer.resolve(at: context.addressFromOffset(fieldOffset), in: context) + let fieldAddress = try context.addressFromOffset(fieldOffset) + if let resolver = context.bindRebaseResolver, resolver.resolveBind(fileOffset: try context.offsetFromAddress(pointer.resolveDirectAddress(at: fieldAddress, in: context))) != nil { + return nil + } + return try pointer.resolve(at: fieldAddress, in: context) case .directObjCClassName, .indirectObjCClass: return nil } } } + +// MARK: - Deprecated Mach-O form + +extension TypeMetadataRecord { + @available(*, deprecated, message: "Pass a ReadingContext: contextDescriptor(in: machO.context).") + public func contextDescriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ContextDescriptorWrapper? { + try contextDescriptor(in: machO.context) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/TypeReference.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeReference.swift similarity index 64% rename from Sources/MachOSwiftSection/Models/Type/TypeReference.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeReference.swift index 97800619c..9b4570531 100644 --- a/Sources/MachOSwiftSection/Models/Type/TypeReference.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/TypeReference.swift @@ -19,32 +19,6 @@ public enum TypeReference: Sendable { return .indirectObjCClass(.init(relativeOffset: relativeOffset)) } } - - public func resolve(at offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedTypeReference { - switch self { - case .directTypeDescriptor(let relativeDirectPointer): - return try .directTypeDescriptor(relativeDirectPointer.resolve(from: offset, in: machO)) - case .indirectTypeDescriptor(let relativeIndirectPointer): - return try .indirectTypeDescriptor(relativeIndirectPointer.resolve(from: offset, in: machO).resolve(in: machO).asOptional) - case .directObjCClassName(let relativeDirectPointer): - return try .directObjCClassName(relativeDirectPointer.resolve(from: offset, in: machO)) - case .indirectObjCClass(let relativeIndirectPointer): - return try .indirectObjCClass(relativeIndirectPointer.resolve(from: offset, in: machO).resolve(in: machO).asOptional) - } - } - - public func resolve(from ptr: UnsafeRawPointer) throws -> ResolvedTypeReference { - switch self { - case .directTypeDescriptor(let relativeDirectPointer): - return try .directTypeDescriptor(relativeDirectPointer.resolve(from: ptr)) - case .indirectTypeDescriptor(let relativeIndirectPointer): - return try .indirectTypeDescriptor(relativeIndirectPointer.resolve(from: ptr).resolve().asOptional) - case .directObjCClassName(let relativeDirectPointer): - return try .directObjCClassName(relativeDirectPointer.resolve(from: ptr)) - case .indirectObjCClass(let relativeIndirectPointer): - return try .indirectObjCClass(relativeIndirectPointer.resolve(from: ptr).resolve().asOptional) - } - } } public enum ResolvedTypeReference: Sendable { @@ -70,3 +44,17 @@ extension TypeReference { } } } + +// MARK: - Deprecated Mach-O and pointer forms + +extension TypeReference { + @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") + public func resolve(at offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedTypeReference { + try resolve(at: offset, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: Int(bitPattern: pointer), in: .inProcess).") + public func resolve(from ptr: UnsafeRawPointer) throws -> ResolvedTypeReference { + try resolve(at: Int(bitPattern: ptr), in: InProcessContext.shared) + } +} diff --git a/Sources/MachOSwiftSection/Models/Type/TypeReferenceKind.swift b/Sources/ABI/MachOSwiftSection/Models/Type/TypeReferenceKind.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/TypeReferenceKind.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/TypeReferenceKind.swift diff --git a/Sources/MachOSwiftSection/Models/Type/ValueMetadata.swift b/Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadata.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/ValueMetadata.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadata.swift diff --git a/Sources/MachOSwiftSection/Models/Type/ValueMetadataLayout.swift b/Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadataLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/Type/ValueMetadataLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadataLayout.swift diff --git a/Sources/MachOSwiftSection/Models/Type/ValueMetadataProtocol.swift b/Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadataProtocol.swift similarity index 64% rename from Sources/MachOSwiftSection/Models/Type/ValueMetadataProtocol.swift rename to Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadataProtocol.swift index 3e1df5243..268f2cf1a 100644 --- a/Sources/MachOSwiftSection/Models/Type/ValueMetadataProtocol.swift +++ b/Sources/ABI/MachOSwiftSection/Models/Type/ValueMetadataProtocol.swift @@ -3,20 +3,24 @@ import MachOKit public protocol ValueMetadataProtocol: MetadataProtocol where Layout: ValueMetadataLayout {} -extension ValueMetadataProtocol { - public func descriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ValueTypeDescriptorWrapper { - try layout.descriptor.resolve(in: machO) - } +// MARK: - ReadingContext Support - public func descriptor() throws -> ValueTypeDescriptorWrapper { - try layout.descriptor.resolve() +extension ValueMetadataProtocol { + public func descriptor(in context: some ReadingContext) throws -> ValueTypeDescriptorWrapper { + try layout.descriptor.resolve(in: context) } } -// MARK: - ReadingContext Support +// MARK: - Deprecated Mach-O and pointer forms extension ValueMetadataProtocol { - public func descriptor(in context: some ReadingContext) throws -> ValueTypeDescriptorWrapper { - try layout.descriptor.resolve(in: context) + @available(*, deprecated, message: "Pass a ReadingContext: descriptor(in: machO.context).") + public func descriptor(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ValueTypeDescriptorWrapper { + try descriptor(in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: descriptor(in: .inProcess).") + public func descriptor() throws -> ValueTypeDescriptorWrapper { + try descriptor(in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Models/ValueWitnessTable/TypeLayout.swift b/Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/TypeLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ValueWitnessTable/TypeLayout.swift rename to Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/TypeLayout.swift diff --git a/Sources/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessFlags.swift b/Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessFlags.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessFlags.swift rename to Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessFlags.swift diff --git a/Sources/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessTable.swift b/Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessTable.swift similarity index 100% rename from Sources/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessTable.swift rename to Sources/ABI/MachOSwiftSection/Models/ValueWitnessTable/ValueWitnessTable.swift diff --git a/Sources/MachOSwiftSection/Pointer/ContextPointer.swift b/Sources/ABI/MachOSwiftSection/Pointer/ContextPointer.swift similarity index 100% rename from Sources/MachOSwiftSection/Pointer/ContextPointer.swift rename to Sources/ABI/MachOSwiftSection/Pointer/ContextPointer.swift diff --git a/Sources/MachOSwiftSection/Pointer/RelativePointers.swift b/Sources/ABI/MachOSwiftSection/Pointer/RelativePointers.swift similarity index 100% rename from Sources/MachOSwiftSection/Pointer/RelativePointers.swift rename to Sources/ABI/MachOSwiftSection/Pointer/RelativePointers.swift diff --git a/Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift b/Sources/ABI/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift similarity index 64% rename from Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift rename to Sources/ABI/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift index 5fd1fe2f0..0aeb3bb5c 100644 --- a/Sources/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift +++ b/Sources/ABI/MachOSwiftSection/Pointer/RelativeProtocolDescriptorPointer.swift @@ -22,9 +22,16 @@ public enum RelativeProtocolDescriptorPointer: Sendable, Equatable { return .init(relativeOffsetPlusIndirectAndInt: relativeContextPointerIntPair.relativeOffsetPlusIndirectAndInt) } } +} - public func protocolDescriptorRef(from offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolDescriptorRef { - let storedPointer = try rawPointer.resolveIndirectType(from: offset, in: machO).address +// MARK: - ReadingContext Support + +extension RelativeProtocolDescriptorPointer { + /// The protocol reference in the indirection slot that the relative + /// pointer stored at `address` targets, marked Objective-C or Swift + /// after this pointer's case. + public func protocolDescriptorRef(at address: Context.Address, in context: Context) throws -> ProtocolDescriptorRef { + let storedPointer = try rawPointer.resolveIndirectType(at: address, in: context).address if isObjC { return .forObjC(storedPointer) } else { @@ -32,43 +39,36 @@ public enum RelativeProtocolDescriptorPointer: Sendable, Equatable { } } - public func resolve(from offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement { + public func resolve(at address: Context.Address, in context: Context) throws -> SymbolOrElement { switch self { case .objcPointer(let relativeIndirectablePointerIntPair): - return try relativeIndirectablePointerIntPair.resolve(from: offset, in: machO).map { .objc($0) } + return try relativeIndirectablePointerIntPair.resolve(at: address, in: context).map { .objc($0) } case .swiftPointer(let relativeContextPointerIntPair): - return try relativeContextPointerIntPair.resolve(from: offset, in: machO).map { .swift($0) } + return try relativeContextPointerIntPair.resolve(at: address, in: context).map { .swift($0) } } } +} - public func protocolDescriptorRef(from ptr: UnsafeRawPointer) throws -> ProtocolDescriptorRef { - let storedPointer = try rawPointer.resolveIndirectType(from: ptr).address - if isObjC { - return .forObjC(storedPointer) - } else { - return .forSwift(storedPointer) - } +// MARK: - Deprecated Mach-O and pointer forms + +extension RelativeProtocolDescriptorPointer { + @available(*, deprecated, message: "Pass a ReadingContext: protocolDescriptorRef(at: offset, in: machO.context).") + public func protocolDescriptorRef(from offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolDescriptorRef { + try protocolDescriptorRef(at: offset, in: machO.context) } - public func resolve(from ptr: UnsafeRawPointer) throws -> SymbolOrElement { - switch self { - case .objcPointer(let relativeIndirectablePointerIntPair): - return try relativeIndirectablePointerIntPair.resolve(from: ptr).map { .objc($0) } - case .swiftPointer(let relativeContextPointerIntPair): - return try relativeContextPointerIntPair.resolve(from: ptr).map { .swift($0) } - } + @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: offset, in: machO.context).") + public func resolve(from offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement { + try resolve(at: offset, in: machO.context) } -} -// MARK: - ReadingContext Support + @available(*, deprecated, message: "Pass a ReadingContext: protocolDescriptorRef(at: pointer, in: .inProcess).") + public func protocolDescriptorRef(from ptr: UnsafeRawPointer) throws -> ProtocolDescriptorRef { + try protocolDescriptorRef(at: ptr, in: InProcessContext.shared) + } -extension RelativeProtocolDescriptorPointer { - public func resolve(at address: Context.Address, in context: Context) throws -> SymbolOrElement { - switch self { - case .objcPointer(let relativeIndirectablePointerIntPair): - return try relativeIndirectablePointerIntPair.resolve(at: address, in: context).map { .objc($0) } - case .swiftPointer(let relativeContextPointerIntPair): - return try relativeContextPointerIntPair.resolve(at: address, in: context).map { .swift($0) } - } + @available(*, deprecated, message: "Pass a ReadingContext: resolve(at: pointer, in: .inProcess).") + public func resolve(from ptr: UnsafeRawPointer) throws -> SymbolOrElement { + try resolve(at: ptr, in: InProcessContext.shared) } } diff --git a/Sources/MachOSwiftSection/Protocols/FlagSet.swift b/Sources/ABI/MachOSwiftSection/Protocols/FlagSet.swift similarity index 100% rename from Sources/MachOSwiftSection/Protocols/FlagSet.swift rename to Sources/ABI/MachOSwiftSection/Protocols/FlagSet.swift diff --git a/Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift b/Sources/ABI/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift similarity index 100% rename from Sources/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift rename to Sources/ABI/MachOSwiftSection/Protocols/MachOSwiftSectionRepresentableWithCache.swift diff --git a/Sources/MachOSwiftSection/Protocols/RuntimeProtocol.swift b/Sources/ABI/MachOSwiftSection/Protocols/RuntimeProtocol.swift similarity index 100% rename from Sources/MachOSwiftSection/Protocols/RuntimeProtocol.swift rename to Sources/ABI/MachOSwiftSection/Protocols/RuntimeProtocol.swift diff --git a/Sources/MachOSwiftSection/Protocols/SwiftSectionRepresentable.swift b/Sources/ABI/MachOSwiftSection/Protocols/SwiftSectionRepresentable.swift similarity index 100% rename from Sources/MachOSwiftSection/Protocols/SwiftSectionRepresentable.swift rename to Sources/ABI/MachOSwiftSection/Protocols/SwiftSectionRepresentable.swift diff --git a/Sources/MachOSwiftSection/Protocols/TopLevelDescriptor.swift b/Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift similarity index 100% rename from Sources/MachOSwiftSection/Protocols/TopLevelDescriptor.swift rename to Sources/ABI/MachOSwiftSection/Protocols/TopLevelDescriptor.swift diff --git a/Sources/MachOSwiftSection/Protocols/TopLevelType.swift b/Sources/ABI/MachOSwiftSection/Protocols/TopLevelType.swift similarity index 100% rename from Sources/MachOSwiftSection/Protocols/TopLevelType.swift rename to Sources/ABI/MachOSwiftSection/Protocols/TopLevelType.swift diff --git a/Sources/MachOSwiftSection/Runtime/RuntimeFunctions.swift b/Sources/ABI/MachOSwiftSection/Runtime/RuntimeFunctions.swift similarity index 95% rename from Sources/MachOSwiftSection/Runtime/RuntimeFunctions.swift rename to Sources/ABI/MachOSwiftSection/Runtime/RuntimeFunctions.swift index 7d256fe52..6e830c777 100644 --- a/Sources/MachOSwiftSection/Runtime/RuntimeFunctions.swift +++ b/Sources/ABI/MachOSwiftSection/Runtime/RuntimeFunctions.swift @@ -74,7 +74,7 @@ public enum RuntimeFunctions { /// Returns `nil` if the metadata's descriptor pointer is null (pure ObjC /// class instance — no Swift descriptor to substitute against). public static func getTypeByMangledNameInContext(_ mangledTypeName: MangledName, specializedFrom metadata: ClassMetadataObjCInterop, in machOImage: MachOImage) throws -> Any.Type? { - guard let descriptor = try metadata.descriptor() else { return nil } + guard let descriptor = try metadata.descriptor(in: InProcessContext.shared) else { return nil } let metadataPointer = try metadata.asPointer let descriptorPointer = try UnsafeRawPointer(bitPattern: UInt(metadata.layout.descriptor.address)) let genericArgumentOffsetWords: Int @@ -82,7 +82,7 @@ public enum RuntimeFunctions { // The runtime fills `immediateMembersOffset` (bytes) when the // class metadata is realized; by the time we hold the in-process // metadata pointer here, it is current. - let bounds = try descriptor.resilientMetadataBounds() + let bounds = try descriptor.resilientMetadataBounds(in: InProcessContext.shared) genericArgumentOffsetWords = Int(bounds.layout.immediateMembersOffset) / MemoryLayout.size } else { genericArgumentOffsetWords = Int(descriptor.nonResilientImmediateMembersOffset) @@ -95,12 +95,12 @@ public enum RuntimeFunctions { /// `getTypeByMangledNameInContext(_:specializedFrom:in:)`. See the /// value-type sibling above for the rationale. public static func getTypeByMangledNameInContext(_ mangledTypeName: MangledName, specializedFrom metadata: ClassMetadataObjCInterop) throws -> Any.Type? { - guard let descriptor = try metadata.descriptor() else { return nil } + guard let descriptor = try metadata.descriptor(in: InProcessContext.shared) else { return nil } let metadataPointer = try metadata.asPointer let descriptorPointer = try UnsafeRawPointer(bitPattern: UInt(metadata.layout.descriptor.address)) let genericArgumentOffsetWords: Int if descriptor.hasResilientSuperclass { - let bounds = try descriptor.resilientMetadataBounds() + let bounds = try descriptor.resilientMetadataBounds(in: InProcessContext.shared) genericArgumentOffsetWords = Int(bounds.layout.immediateMembersOffset) / MemoryLayout.size } else { genericArgumentOffsetWords = Int(descriptor.nonResilientImmediateMembersOffset) @@ -111,18 +111,18 @@ public enum RuntimeFunctions { public static func conformsToProtocol(metatype: Any.Type, protocolType: Any.Type) throws -> ProtocolWitnessTable? { let existentialTypeMetadataInProcess = try ExistentialTypeMetadata.createInProcess(protocolType) - let protocols = try existentialTypeMetadataInProcess.protocols() + let protocols = try existentialTypeMetadataInProcess.protocols(in: InProcessContext.shared) guard let protocolRef = protocols.first else { return nil } guard !protocolRef.isObjC else { return nil } let metadataInProcess = try Metadata.createInProcess(metatype) - let protocolDescriptor = try protocolRef.swiftProtocol() + let protocolDescriptor = try protocolRef.swiftProtocol(in: InProcessContext.shared) return try conformsToProtocol(metadata: metadataInProcess, protocolDescriptor: protocolDescriptor) } public static func conformsToProtocol(metadata: Metadata, protocolDescriptor: ProtocolDescriptor, in machOImage: MachOImage) throws -> ProtocolWitnessTable? { guard let witnessTablePointer = MachOSwiftSectionC.swift_conformsToProtocol(metadata.pointer(in: machOImage), protocolDescriptor.pointer(in: machOImage)) else { return nil } let offset = witnessTablePointer.bitPattern.uint - machOImage.ptr.bitPattern.uint - return try .resolve(from: .init(offset), in: machOImage) + return try .resolve(at: Int(offset), in: machOImage.context) } public static func conformsToProtocol(metadata: Metadata, protocolDescriptor: ProtocolDescriptor) throws -> ProtocolWitnessTable? { diff --git a/Sources/MachOSwiftSection/Utils/AnyLocatableLayoutWrapper.swift b/Sources/ABI/MachOSwiftSection/Utils/AnyLocatableLayoutWrapper.swift similarity index 100% rename from Sources/MachOSwiftSection/Utils/AnyLocatableLayoutWrapper.swift rename to Sources/ABI/MachOSwiftSection/Utils/AnyLocatableLayoutWrapper.swift diff --git a/Sources/MachOSwiftSection/Utils/MachOSwiftSectionError.swift b/Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionError.swift similarity index 100% rename from Sources/MachOSwiftSection/Utils/MachOSwiftSectionError.swift rename to Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionError.swift diff --git a/Sources/MachOSwiftSection/Utils/MachOSwiftSectionName.swift b/Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionName.swift similarity index 100% rename from Sources/MachOSwiftSection/Utils/MachOSwiftSectionName.swift rename to Sources/ABI/MachOSwiftSection/Utils/MachOSwiftSectionName.swift diff --git a/Sources/MachOSwiftSection/Utils/ResolvableLocatableLayoutWrapper.swift b/Sources/ABI/MachOSwiftSection/Utils/ResolvableLocatableLayoutWrapper.swift similarity index 100% rename from Sources/MachOSwiftSection/Utils/ResolvableLocatableLayoutWrapper.swift rename to Sources/ABI/MachOSwiftSection/Utils/ResolvableLocatableLayoutWrapper.swift diff --git a/Sources/MachOSwiftSection/Utils/RuntimeLayout.swift b/Sources/ABI/MachOSwiftSection/Utils/RuntimeLayout.swift similarity index 100% rename from Sources/MachOSwiftSection/Utils/RuntimeLayout.swift rename to Sources/ABI/MachOSwiftSection/Utils/RuntimeLayout.swift diff --git a/Sources/MachOSwiftSectionC/CallAccessor.c b/Sources/ABI/MachOSwiftSectionC/CallAccessor.c similarity index 100% rename from Sources/MachOSwiftSectionC/CallAccessor.c rename to Sources/ABI/MachOSwiftSectionC/CallAccessor.c diff --git a/Sources/MachOSwiftSectionC/Functions.c b/Sources/ABI/MachOSwiftSectionC/Functions.c similarity index 100% rename from Sources/MachOSwiftSectionC/Functions.c rename to Sources/ABI/MachOSwiftSectionC/Functions.c diff --git a/Sources/MachOSwiftSectionC/ValueWitnessTable.c b/Sources/ABI/MachOSwiftSectionC/ValueWitnessTable.c similarity index 100% rename from Sources/MachOSwiftSectionC/ValueWitnessTable.c rename to Sources/ABI/MachOSwiftSectionC/ValueWitnessTable.c diff --git a/Sources/MachOSwiftSectionC/include/CallAccessor.h b/Sources/ABI/MachOSwiftSectionC/include/CallAccessor.h similarity index 100% rename from Sources/MachOSwiftSectionC/include/CallAccessor.h rename to Sources/ABI/MachOSwiftSectionC/include/CallAccessor.h diff --git a/Sources/MachOSwiftSectionC/include/Functions.h b/Sources/ABI/MachOSwiftSectionC/include/Functions.h similarity index 100% rename from Sources/MachOSwiftSectionC/include/Functions.h rename to Sources/ABI/MachOSwiftSectionC/include/Functions.h diff --git a/Sources/MachOSwiftSectionC/include/ValueWitnessTable.h b/Sources/ABI/MachOSwiftSectionC/include/ValueWitnessTable.h similarity index 100% rename from Sources/MachOSwiftSectionC/include/ValueWitnessTable.h rename to Sources/ABI/MachOSwiftSectionC/include/ValueWitnessTable.h diff --git a/Sources/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift b/Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift similarity index 98% rename from Sources/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift rename to Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift index 8f01fef85..ead37925a 100644 --- a/Sources/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift +++ b/Sources/Analysis/SwiftInspection/AnonymousContextPrivateDiscriminatorIndex.swift @@ -118,9 +118,9 @@ package final class AnonymousContextPrivateDiscriminatorIndex: @unchecked Sendab } private static func anonymousContextMember(at offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) -> AnonymousContextMember? { - guard let referencedContext = try? ContextDescriptorWrapper.resolve(from: offset, in: machO), - case .element(.anonymous(let anonymousContext))? = try? referencedContext.parent(in: machO), - let name = try? referencedContext.namedContextDescriptor?.name(in: machO) + guard let referencedContext = try? ContextDescriptorWrapper.resolve(at: offset, in: machO.context), + case .element(.anonymous(let anonymousContext))? = try? referencedContext.parent(in: machO.context), + let name = try? referencedContext.namedContextDescriptor?.name(in: machO.context) else { return nil } return AnonymousContextMember(anonymousContextOffset: anonymousContext.offset, name: name) } diff --git a/Sources/SwiftInspection/BitMask.swift b/Sources/Analysis/SwiftInspection/BitMask.swift similarity index 100% rename from Sources/SwiftInspection/BitMask.swift rename to Sources/Analysis/SwiftInspection/BitMask.swift diff --git a/Sources/SwiftInspection/ClassHierarchyDumper.swift b/Sources/Analysis/SwiftInspection/ClassHierarchyDumper.swift similarity index 85% rename from Sources/SwiftInspection/ClassHierarchyDumper.swift rename to Sources/Analysis/SwiftInspection/ClassHierarchyDumper.swift index 671ad0d9c..a7d34fdb9 100644 --- a/Sources/SwiftInspection/ClassHierarchyDumper.swift +++ b/Sources/Analysis/SwiftInspection/ClassHierarchyDumper.swift @@ -20,8 +20,8 @@ public struct ClassHierarchyDumper { public func dump(for classDescriptor: ClassDescriptor) throws -> [String] { var classes: [String] = [] - if let metadataAccessor = try `classDescriptor`.metadataAccessorFunction(in: machO), !`classDescriptor`.flags.isGeneric { - let metadata = try metadataAccessor(request: .init()).value.resolve(in: machO) + if let metadataAccessor = try `classDescriptor`.metadataAccessorFunction(in: machO.context), !`classDescriptor`.flags.isGeneric { + let metadata = try metadataAccessor(request: .init()).value.resolve(in: machO.context) switch metadata { case .class(let classMetadataObjCInterop): try perform(classMetadata: classMetadataObjCInterop, classDescriptor: `classDescriptor`, classes: &classes) @@ -42,13 +42,13 @@ public struct ClassHierarchyDumper { } private func perform(classMetadata: ClassMetadataObjCInterop, classDescriptor: ClassDescriptor, classes: inout [String]) throws { - try classes.append(classDescriptor.name(in: machO)) - if let superclassMetadata = try classMetadata.superclass(in: machO) { + try classes.append(classDescriptor.name(in: machO.context)) + if let superclassMetadata = try classMetadata.superclass(in: machO.context) { if superclassMetadata.isPureObjC { - let objcClass = try ObjCClass64.resolve(from: superclassMetadata.offset, in: machO) + let objcClass = try ObjCClass64.resolve(at: superclassMetadata.offset, in: machO.context) try perform(objcClass: objcClass, classes: &classes) - } else if let superclassDescriptor = try superclassMetadata.asFinalClassMetadata(in: machO).descriptor(in: machO) { - try perform(classMetadata: superclassMetadata.asFinalClassMetadata(in: machO), classDescriptor: superclassDescriptor, classes: &classes) + } else if let superclassDescriptor = try superclassMetadata.asFinalClassMetadata(in: machO.context).descriptor(in: machO.context) { + try perform(classMetadata: superclassMetadata.asFinalClassMetadata(in: machO.context), classDescriptor: superclassDescriptor, classes: &classes) } } } diff --git a/Sources/SwiftInspection/CustomObjCClassName.swift b/Sources/Analysis/SwiftInspection/CustomObjCClassName.swift similarity index 100% rename from Sources/SwiftInspection/CustomObjCClassName.swift rename to Sources/Analysis/SwiftInspection/CustomObjCClassName.swift diff --git a/Sources/SwiftInspection/EnumLayoutCalculator.swift b/Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift similarity index 100% rename from Sources/SwiftInspection/EnumLayoutCalculator.swift rename to Sources/Analysis/SwiftInspection/EnumLayoutCalculator.swift diff --git a/Sources/SwiftInspection/Extensions/Descriptor+ImplementationSymbols.swift b/Sources/Analysis/SwiftInspection/Extensions/Descriptor+ImplementationSymbols.swift similarity index 100% rename from Sources/SwiftInspection/Extensions/Descriptor+ImplementationSymbols.swift rename to Sources/Analysis/SwiftInspection/Extensions/Descriptor+ImplementationSymbols.swift diff --git a/Sources/SwiftInspection/Extensions/Descriptor+MethodDescriptorSymbols.swift b/Sources/Analysis/SwiftInspection/Extensions/Descriptor+MethodDescriptorSymbols.swift similarity index 100% rename from Sources/SwiftInspection/Extensions/Descriptor+MethodDescriptorSymbols.swift rename to Sources/Analysis/SwiftInspection/Extensions/Descriptor+MethodDescriptorSymbols.swift diff --git a/Sources/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift b/Sources/Analysis/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift similarity index 100% rename from Sources/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift rename to Sources/Analysis/SwiftInspection/Extensions/MachORepresentableWithCache+ReaderKinds.swift diff --git a/Sources/SwiftInspection/Extensions/Node+DeclarationContext.swift b/Sources/Analysis/SwiftInspection/Extensions/Node+DeclarationContext.swift similarity index 100% rename from Sources/SwiftInspection/Extensions/Node+DeclarationContext.swift rename to Sources/Analysis/SwiftInspection/Extensions/Node+DeclarationContext.swift diff --git a/Sources/SwiftInspection/NodeTypeNaming.swift b/Sources/Analysis/SwiftInspection/NodeTypeNaming.swift similarity index 100% rename from Sources/SwiftInspection/NodeTypeNaming.swift rename to Sources/Analysis/SwiftInspection/NodeTypeNaming.swift diff --git a/Sources/SwiftInspection/ObjCAncestorResolver.swift b/Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift similarity index 100% rename from Sources/SwiftInspection/ObjCAncestorResolver.swift rename to Sources/Analysis/SwiftInspection/ObjCAncestorResolver.swift diff --git a/Sources/SwiftInspection/ObjCClassHierarchy.swift b/Sources/Analysis/SwiftInspection/ObjCClassHierarchy.swift similarity index 100% rename from Sources/SwiftInspection/ObjCClassHierarchy.swift rename to Sources/Analysis/SwiftInspection/ObjCClassHierarchy.swift diff --git a/Sources/SwiftInspection/ObjCClassMethodIndex.swift b/Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift similarity index 100% rename from Sources/SwiftInspection/ObjCClassMethodIndex.swift rename to Sources/Analysis/SwiftInspection/ObjCClassMethodIndex.swift diff --git a/Sources/SwiftInspection/ObjCImplementationClassFacts.swift b/Sources/Analysis/SwiftInspection/ObjCImplementationClassFacts.swift similarity index 89% rename from Sources/SwiftInspection/ObjCImplementationClassFacts.swift rename to Sources/Analysis/SwiftInspection/ObjCImplementationClassFacts.swift index 88df5adb0..42d797797 100644 --- a/Sources/SwiftInspection/ObjCImplementationClassFacts.swift +++ b/Sources/Analysis/SwiftInspection/ObjCImplementationClassFacts.swift @@ -113,6 +113,19 @@ public final class ObjCImplementationClassFacts: Sendable { public var isObjCVisible: Bool { !typeEncoding.isEmpty } + + /// The prefix the compiler gives the storage of a `lazy var`. + public static let lazyStorageNamePrefix = "$__lazy_storage_$_" + + /// The `lazy var` this ivar is the synthesized storage of — `summary` + /// for `$__lazy_storage_$_summary` — read off the Swift name or, once + /// the field-offset symbol is stripped, off the ObjC ivar name, which + /// spells the same; `nil` for any other ivar. + public var lazyPropertyName: String? { + let storageName = swiftPropertyName ?? name + guard storageName.hasPrefix(Self.lazyStorageNamePrefix) else { return nil } + return String(storageName.dropFirst(Self.lazyStorageNamePrefix.count)) + } } /// One entry of a method list, with the Swift symbols found at its @@ -172,6 +185,13 @@ public final class ObjCImplementationClassFacts: Sendable { public func instanceVariable(forSwiftPropertyNamed name: String) -> InstanceVariable? { instanceVariables.first { $0.swiftPropertyName == name } } + + /// The ivar that stores the Swift property `name`: the one joined with + /// that name, else the storage of a `lazy var` so named, whose name is + /// never the property's own. + public func storageInstanceVariable(forPropertyNamed name: String) -> InstanceVariable? { + instanceVariable(forSwiftPropertyNamed: name) ?? instanceVariables.first { $0.lazyPropertyName == name } + } } extension ObjCImplementationClassFacts.Evidence.Reason: CustomStringConvertible { diff --git a/Sources/SwiftInspection/ObjCImplementationClassIndex.swift b/Sources/Analysis/SwiftInspection/ObjCImplementationClassIndex.swift similarity index 94% rename from Sources/SwiftInspection/ObjCImplementationClassIndex.swift rename to Sources/Analysis/SwiftInspection/ObjCImplementationClassIndex.swift index 808ce261c..25e5d247a 100644 --- a/Sources/SwiftInspection/ObjCImplementationClassIndex.swift +++ b/Sources/Analysis/SwiftInspection/ObjCImplementationClassIndex.swift @@ -157,7 +157,7 @@ package final class ObjCImplementationClassIndex: @unchecked Sendable { evidence.metadataAccessorSymbolNameByClassName[className] = symbol.symbol.name } - // `…vpWvd`: global(fieldOffset(directness, variable(extension(module, class), identifier, type))). + // `…vpWvd`: global(fieldOffset(directness, variable(extension(module, class), name, type))). for symbol in symbolIndexStore.symbols(of: .fieldOffset, in: machO) { guard let fieldOffsetNode = symbol.demangledNode.children.first, fieldOffsetNode.children.count == 2 @@ -165,11 +165,11 @@ package final class ObjCImplementationClassIndex: @unchecked Sendable { let variableNode = fieldOffsetNode.children[1] guard variableNode.kind == .variable, variableNode.children.count == 3 else { continue } let contextNode = variableNode.children[0] - let identifierNode = variableNode.children[1] + let nameNode = variableNode.children[1] let typeNode = variableNode.children[2] guard contextNode.kind == .extension, contextNode.children.count >= 2, let className = cImportedClassName(ofClassNode: contextNode.children[1]), - identifierNode.kind == .identifier, let propertyName = identifierNode.text + let propertyName = declaredName(ofVariableNameNode: nameNode) else { continue } let moduleNode = contextNode.children[0] let implementingModuleName = moduleNode.kind == .module ? moduleNode.text : nil @@ -189,6 +189,23 @@ package final class ObjCImplementationClassIndex: @unchecked Sendable { } return evidence } + + /// The name a `variable` node's name child spells: an `identifier`, or + /// the name inside a `privateDeclName` (discriminator, name) — what a + /// `private` / `fileprivate` property gets, and so does the storage of + /// every `lazy var`, which the compiler makes private whatever the + /// property's own access level. + private static func declaredName(ofVariableNameNode node: NodeReference) -> String? { + switch node.kind { + case .identifier: + return node.text + case .privateDeclName: + guard node.children.count == 2, node.children[1].kind == .identifier else { return nil } + return node.children[1].text + default: + return nil + } + } } private static func build(in machO: MachO) -> Storage { @@ -414,8 +431,11 @@ extension MachOFile: ObjCImplementationClassReading { } /// On a file the reader follows a rebase into another image of the same - /// dyld cache; a bind (a standalone file's dependency) resolves to - /// nothing, and is told apart from a root class by the bound name. + /// dyld cache, and a bind the file satisfies from its own exports (what + /// `-interposable` links a simulator runtime's frameworks with). A bind + /// into another image (a standalone file's dependency) resolves to + /// nothing, and is told apart from a root class by the bound name, which + /// the reader gives for chained fixups and `LC_DYLD_INFO` opcodes alike. func superclassLocation(of classObject: ObjCClass64) -> ObjCSuperclassLocation { // Explicitly typed: `superClass(in:)` also has a deprecated overload // returning a bare `Self?`. @@ -426,15 +446,6 @@ extension MachOFile: ObjCImplementationClassReading { if let superclassName = classObject.superClassName(in: self), !superclassName.isEmpty { return .unresolvable(superclassName) } - // A zero slot is a root class only when it is not a bind. The ObjC - // reader names a chained-fixup bind but reads a legacy `LC_DYLD_INFO` - // bind (pre-iOS 16 / macOS 12 deployment targets — the iOS 15.5 - // simulator runtime's frameworks) as an empty slot, which once made - // every such chain look complete and every UIKit override an - // `@objc(name)`; MachOKitExtensions resolves both formats. - if !isLoadedFromDyldCache, let bindSymbolName = resolveBind(fileOffset: classObject.offset + Self.superclassFieldOffset) { - return .unresolvable(bindSymbolName.replacingOccurrences(of: "_OBJC_CLASS_$_", with: "")) - } // A Swift class is never an ObjC root class (its ObjC superclass is // `_SwiftObject` at the very least), so a superclass the reader can // neither follow nor name is unresolvable, not absent. @@ -444,8 +455,6 @@ extension MachOFile: ObjCImplementationClassReading { return .root } - private static let superclassFieldOffset = MemoryLayout.offset(of: \.superclass) ?? MemoryLayout.size - func metaClass(of classObject: ObjCClass64) -> ObjCClass64? { classObject.metaClass(in: self)?.1 } @@ -502,22 +511,16 @@ extension MachOFile: ObjCImplementationClassReading { objc.categories64 } - /// The ObjC reader names a chained-fixup bind but reads a legacy - /// `LC_DYLD_INFO` bind (pre-macOS 12 / iOS 16 deployment targets) as an - /// empty slot — the same gap `superclassLocation(of:)` closes for the - /// superclass — so the bind stream is consulted for the name. + /// The reader names a class bound in from another image for chained + /// fixups and `LC_DYLD_INFO` opcodes alike. func targetClassName(of category: ObjCCategory64) -> String? { - if let name = category.className(in: self), !name.isEmpty { - return name - } - guard !isLoadedFromDyldCache, let bindSymbolName = resolveBind(fileOffset: category.offset + Self.categoryClassFieldOffset) else { return nil } - return bindSymbolName.replacingOccurrences(of: "_OBJC_CLASS_$_", with: "") + guard let name = category.className(in: self), !name.isEmpty else { return nil } + return name } - private static let categoryClassFieldOffset = MemoryLayout.offset(of: \.cls) ?? MemoryLayout.size - - /// A rebase into another image of the same cache resolves; a standalone - /// file's bind does not. + /// A rebase into another image of the same cache resolves, and so does a + /// bind the file satisfies from its own exports; a bind into another image + /// does not. func targetClass(of category: ObjCCategory64) -> (any ObjCImplementationClassReading, ObjCClass64)? { let resolved: (MachOFile, ObjCClass64)? = category.class(in: self) guard let (classMachO, classObject) = resolved else { return nil } diff --git a/Sources/SwiftInspection/ObjCMember.swift b/Sources/Analysis/SwiftInspection/ObjCMember.swift similarity index 100% rename from Sources/SwiftInspection/ObjCMember.swift rename to Sources/Analysis/SwiftInspection/ObjCMember.swift diff --git a/Sources/SwiftInspection/ObjCMemberShape.swift b/Sources/Analysis/SwiftInspection/ObjCMemberShape.swift similarity index 97% rename from Sources/SwiftInspection/ObjCMemberShape.swift rename to Sources/Analysis/SwiftInspection/ObjCMemberShape.swift index e337d7c9b..876dec74f 100644 --- a/Sources/SwiftInspection/ObjCMemberShape.swift +++ b/Sources/Analysis/SwiftInspection/ObjCMemberShape.swift @@ -370,8 +370,21 @@ public struct ObjCMemberShape: Sendable, Hashable { // MARK: - Node reading + /// The declared name: an `identifier` child, or the name inside a + /// `privateDeclName` (discriminator, name), which is what a `private` / + /// `fileprivate` member spells. private static func declaredName(of node: Node) -> String? { - node.children.first { $0.kind == .identifier }?.text + for child in node.children { + switch child.kind { + case .identifier: + return child.text + case .privateDeclName where child.children.count == 2 && child.children[1].kind == .identifier: + return child.children[1].text + default: + continue + } + } + return nil } private static func labels(of node: Node) -> [String?] { diff --git a/Sources/SwiftInspection/RuntimeEnumCaseProjector.swift b/Sources/Analysis/SwiftInspection/RuntimeEnumCaseProjector.swift similarity index 100% rename from Sources/SwiftInspection/RuntimeEnumCaseProjector.swift rename to Sources/Analysis/SwiftInspection/RuntimeEnumCaseProjector.swift diff --git a/Sources/SwiftInspection/RuntimeMetadataTypeBuilder.swift b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift similarity index 98% rename from Sources/SwiftInspection/RuntimeMetadataTypeBuilder.swift rename to Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift index 35f3a3d29..7469cfe97 100644 --- a/Sources/SwiftInspection/RuntimeMetadataTypeBuilder.swift +++ b/Sources/Analysis/SwiftInspection/RuntimeMetadataTypeBuilder.swift @@ -165,7 +165,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { )) ) else { return nil } guard let existentialMetadata = try? ExistentialTypeMetadata.createInProcess(existentialType), - let reference = try? existentialMetadata.protocols().first else { + let reference = try? existentialMetadata.protocols(in: .inProcess).first else { return nil } return reference @@ -269,7 +269,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { ) -> BuiltType { let contextWrapper: ContextDescriptorWrapper do { - contextWrapper = try ContextDescriptorWrapper.resolve(from: descriptorPointer) + contextWrapper = try ContextDescriptorWrapper.resolve(at: descriptorPointer, in: .inProcess) } catch { return .failure(TypeLookupError("cannot read context descriptor: \(error)")) } @@ -291,7 +291,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { let genericContext: GenericContext? do { - genericContext = try typeWrapper.genericContext() + genericContext = try typeWrapper.genericContext(in: .inProcess) } catch { return .failure(TypeLookupError("cannot read generic context: \(error)")) } @@ -312,7 +312,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { } do { - guard let accessorFunction = try typeWrapper.typeContextDescriptor.metadataAccessorFunction() else { + guard let accessorFunction = try typeWrapper.typeContextDescriptor.metadataAccessorFunction(in: .inProcess) else { return .failure(TypeLookupError("type context descriptor at \(descriptorPointer) has no metadata accessor")) } let keyMetadatas = try keyMetadataTypes.map { try Metadata.createInProcess($0) } @@ -321,8 +321,8 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { metadatas: keyMetadatas, witnessTables: witnessTables ) - let responseMetadata = try response.value.resolve() - return .success(Self.anyType(fromMetadataPointer: try responseMetadata.metadata.asPointer)) + let responseMetadata = try response.value.resolve(in: .inProcess) + return .success(Self.anyType(fromMetadataPointer: try responseMetadata.anyMetadata.asMetadata(in: .inProcess).asPointer)) } catch { return .failure(TypeLookupError("metadata accessor invocation failed: \(error)")) } @@ -395,7 +395,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { let requirement: GenericRequirement do { - requirement = try GenericRequirement(descriptor: requirementDescriptor) + requirement = try GenericRequirement(descriptor: requirementDescriptor, in: .inProcess) } catch { return .failure(TypeLookupError("cannot read generic requirement: \(error)")) } @@ -407,7 +407,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { let subjectNode: Node do { - subjectNode = try SymbolicDemangler.demangleType(for: requirement.paramManagledName) + subjectNode = try SymbolicDemangler.demangleType(for: requirement.paramManagledName, in: .inProcess) } catch { return .failure(TypeLookupError("cannot demangle requirement subject: \(error)")) } @@ -481,10 +481,10 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { guard let parentType else { return .success([]) } do { let parentMetadata = try Metadata.createInProcess(parentType) - guard let parentWrapper = try parentMetadata.typeContextDescriptorWrapper() else { + guard let parentWrapper = try parentMetadata.typeContextDescriptorWrapper(in: .inProcess) else { return .success([]) } - guard let parentGenericContext = try parentWrapper.genericContext() else { + guard let parentGenericContext = try parentWrapper.genericContext(in: .inProcess) else { return .success([]) } // Reconstructing written arguments for non-key parameters (ones a @@ -515,13 +515,13 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { case .struct, .enum, .optional: return metadataPointer.advanced(by: MemoryLayout.size) case .class: - let classMetadata = try ClassMetadataObjCInterop.resolve(from: metadataPointer) - guard let classDescriptor = try classMetadata.descriptor() else { + let classMetadata = try ClassMetadataObjCInterop.resolve(at: metadataPointer, in: .inProcess) + guard let classDescriptor = try classMetadata.descriptor(in: .inProcess) else { throw TypeLookupError("parent class metadata has no Swift descriptor") } let immediateMembersOffsetInWords: Int if classDescriptor.hasResilientSuperclass { - let bounds = try classDescriptor.resilientMetadataBounds() + let bounds = try classDescriptor.resilientMetadataBounds(in: .inProcess) immediateMembersOffsetInWords = Int(bounds.layout.immediateMembersOffset) / MemoryLayout.size } else { immediateMembersOffsetInWords = Int(classDescriptor.nonResilientImmediateMembersOffset) @@ -555,9 +555,9 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { return .failure(TypeLookupError("associated type '\(member)' of an Objective-C protocol cannot be resolved")) } do { - let protocolDescriptor = try protocolDecl.swiftProtocol() - let declaredProtocol = try MachOSwiftSection.Protocol(descriptor: protocolDescriptor) - let associatedTypeNames = try protocolDescriptor.associatedTypes() + let protocolDescriptor = try protocolDecl.swiftProtocol(in: .inProcess) + let declaredProtocol = try MachOSwiftSection.Protocol(descriptor: protocolDescriptor, in: .inProcess) + let associatedTypeNames = try protocolDescriptor.associatedTypes(in: .inProcess) guard let associatedTypeIndex = associatedTypeNames.firstIndex(of: member) else { return .failure(TypeLookupError("protocol declares no associated type named '\(member)'")) } @@ -584,7 +584,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { baseRequirement: baseRequirement, associatedTypeRequirement: accessFunctionRequirements[associatedTypeIndex] ) - let witnessMetadata = try response.value.resolve().metadata + let witnessMetadata = try response.value.resolve(in: .inProcess).anyMetadata.asMetadata(in: .inProcess) return .success(Self.anyType(fromMetadataPointer: try witnessMetadata.asPointer)) } catch { return .failure(TypeLookupError("associated type witness resolution failed: \(error)")) @@ -648,7 +648,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { for reference in protocolReferences where classConstraint == .any { if reference.isObjC { classConstraint = .class - } else if let descriptor = try? reference.swiftProtocol(), + } else if let descriptor = try? reference.swiftProtocol(in: .inProcess), descriptor.flags.kindSpecificFlags?.protocolFlags?.classConstraint == .class { classConstraint = .class } @@ -941,7 +941,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { private func boundGenericStandardLibraryType(of instantiation: Any.Type, arguments: [BuiltType]) -> BuiltType { let descriptorPointer: UnsafeRawPointer do { - guard let wrapper = try Metadata.createInProcess(instantiation).typeContextDescriptorWrapper() else { + guard let wrapper = try Metadata.createInProcess(instantiation).typeContextDescriptorWrapper(in: .inProcess) else { return .failure(TypeLookupError("cannot locate the standard library descriptor via \(instantiation)")) } descriptorPointer = try wrapper.typeContextDescriptor.asPointer @@ -1132,7 +1132,7 @@ public struct RuntimeMetadataTypeBuilder: TypeBuilder { ] var descriptorPointers: [String: UnsafeRawPointer] = [:] for (qualifiedName, instantiation) in knownInstantiations { - guard let wrapper = try? Metadata.createInProcess(instantiation).typeContextDescriptorWrapper(), + guard let wrapper = try? Metadata.createInProcess(instantiation).typeContextDescriptorWrapper(in: .inProcess), let descriptorPointer = try? wrapper.typeContextDescriptor.asPointer else { continue } descriptorPointers[qualifiedName] = descriptorPointer } diff --git a/Sources/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift b/Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift similarity index 100% rename from Sources/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift rename to Sources/Analysis/SwiftInspection/SharedCacheEvictionGroup+SwiftInspection.swift diff --git a/Sources/SwiftInspection/SpareBitAnalyzer.swift b/Sources/Analysis/SwiftInspection/SpareBitAnalyzer.swift similarity index 100% rename from Sources/SwiftInspection/SpareBitAnalyzer.swift rename to Sources/Analysis/SwiftInspection/SpareBitAnalyzer.swift diff --git a/Sources/SwiftInspection/SwiftClassObjectIndex.swift b/Sources/Analysis/SwiftInspection/SwiftClassObjectIndex.swift similarity index 95% rename from Sources/SwiftInspection/SwiftClassObjectIndex.swift rename to Sources/Analysis/SwiftInspection/SwiftClassObjectIndex.swift index 50ddd5f25..676305b05 100644 --- a/Sources/SwiftInspection/SwiftClassObjectIndex.swift +++ b/Sources/Analysis/SwiftInspection/SwiftClassObjectIndex.swift @@ -25,7 +25,7 @@ import Demangling /// its Swift metadata — the address points coincide. The flag word and the /// nominal type descriptor pointer are read straight off it. That pointer /// is absolute: a rebase or chained fixup in a file, signed on arm64e, so -/// it is read through its own field (`Pointer.resolve(from:in:)` resolves +/// it is read through its own field (`Pointer.resolve(at:in:)` resolves /// the rebase first); `descriptor(in:)` would take the undecoded value a /// cache image stores. /// - A non-generic class with a superclass in another resilience domain (the @@ -135,14 +135,16 @@ package final class SwiftClassObjectIndex: @unchecked Sendable { // Route 1: the class list, where a Swift class object is its metadata. for classObject in machO.objcImplementationClassObjects() ?? [] where classObject.isSwift { - guard let classFlags: UInt32 = try? machO.readElement(offset: classObject.offset + classFlagsFieldOffset), + // `as UInt32`: bound to an optional, the `try?` read would take + // the Optional's in-memory shape, one tag byte past the flag word. + guard let classFlags = try? machO.readElement(offset: classObject.offset + classFlagsFieldOffset) as UInt32, classFlags & ClassFlags.hasCustomObjCName.rawValue != 0, classFlags & staticSpecializationClassFlags == 0 else { continue } let descriptor: ClassDescriptor do { - let descriptorPointer = try Pointer.resolve(from: classObject.offset + ClassMetadataObjCInterop.descriptorOffset, in: machO) - guard let resolvedDescriptor = try descriptorPointer.resolve(in: machO), resolvedDescriptor.layout.flags.kind == .class else { + let descriptorPointer = try Pointer.resolve(at: classObject.offset + ClassMetadataObjCInterop.descriptorOffset, in: machO.context) + guard let resolvedDescriptor = try descriptorPointer.resolve(in: machO.context), resolvedDescriptor.layout.flags.kind == .class else { #log(.error, "skipped a renamed class object at offset \(classObject.offset, privacy: .public): its metadata names no class descriptor") continue } @@ -161,7 +163,7 @@ package final class SwiftClassObjectIndex: @unchecked Sendable { customObjCClassName: customObjCClassName(runtimeName: runtimeName, classFlags: classFlags, descriptor: descriptor), instanceStart: Int(readOnlyData.layout.instanceStart) ) - if let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(descriptor)), in: machO), + if let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(descriptor)), in: machO.context), let qualifiedName = NodeTypeNaming.nominalQualifiedName(ofDemangledRoot: contextNode) { customRuntimeNamesBySwiftQualifiedName[qualifiedName, default: []].append(runtimeName) } @@ -188,11 +190,11 @@ package final class SwiftClassObjectIndex: @unchecked Sendable { do { // The wrapper walks the trailing objects to the initialization // record; transient, like every other materialization. - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) guard let singletonMetadataInitialization = classWrapper.singletonMetadataInitialization, let patternOffset = singletonMetadataInitialization.resolvedDirectOffset(from: \.incompleteMetadata) else { return nil } - let pattern = try ResilientClassMetadataPattern.resolve(from: patternOffset, in: machO) + let pattern = try ResilientClassMetadataPattern.resolve(at: patternOffset, in: machO.context) let classFlags = pattern.layout.classFlags guard classFlags & ClassFlags.hasCustomObjCName.rawValue != 0, let readOnlyDataOffset = pattern.resolvedDirectOffset(from: \.data) diff --git a/Sources/SwiftInspection/SymbolicDemangler.swift b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift similarity index 87% rename from Sources/SwiftInspection/SymbolicDemangler.swift rename to Sources/Analysis/SwiftInspection/SymbolicDemangler.swift index 9133329e8..e9e498f6c 100644 --- a/Sources/SwiftInspection/SymbolicDemangler.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicDemangler.swift @@ -39,26 +39,6 @@ public typealias MetadataReader = SymbolicDemangler extension SymbolicDemangler { public nonisolated(unsafe) static var isCacheEnabled: Bool = true - public static func demangleType(for mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - if isCacheEnabled { - return try SymbolicDemanglerCache.shared.demangleType(for: mangledName, in: machO) - } else { - return try _demangleType(for: mangledName, in: machO) - } - } - - fileprivate static func _demangleType(for mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - return try demangle(for: mangledName, kind: .type, in: machO.context) - } - - public static func demangleType(for symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - if isCacheEnabled { - return try SymbolicDemanglerCache.shared.buildContextManglingForSymbol(symbol, in: machO) - } else { - return try _buildContextManglingForSymbol(symbol, in: machO.context) - } - } - public static func demangleSymbol(for symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { return SymbolIndexStore.shared.demangledNode(for: symbol, in: machO) } @@ -89,94 +69,12 @@ extension SymbolicDemangler { package static func cacheExists(for machO: some MachOSwiftSectionRepresentableWithCache) -> Bool { SymbolicDemanglerCache.shared.contains(in: machO) } - - public static func demangleContext(for context: ContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - if isCacheEnabled { - return try SymbolicDemanglerCache.shared.demangleContext(for: context, in: machO) - } else { - return try _demangleContext(for: context, in: machO) - } - } - - fileprivate static func _demangleContext(for context: ContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - return try required(buildContextMangling(context: context, in: machO.context)) - } - - public static func buildGenericSignature(for requirement: GenericRequirementDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - try buildGenericSignature(for: [requirement], in: machO) - } - - public static func buildGenericSignature(for requirements: GenericRequirementDescriptor..., in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - try buildGenericSignature(for: requirements, in: machO) - } - - public static func buildGenericSignature(for requirements: [GenericRequirementDescriptor], in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - return try buildGenericSignature(for: requirements, in: machO.context) - } } extension SymbolicDemangler { - public static func demangleType(for mangledName: MangledName) throws -> Node { - if isCacheEnabled { - return try SymbolicDemanglerCache.shared.demangleType(for: mangledName) - } else { - return try _demangleType(for: mangledName) - } - } - - fileprivate static func _demangleType(for mangledName: MangledName) throws -> Node { - return try demangle(for: mangledName, kind: .type, in: InProcessContext.shared) - } - - /// Demangles a type WITHOUT touching the shared node memo. - /// - /// The cached `demangleType(for:)` reads and fills the process-scoped - /// memo. Callers on deeply recursive paths — a dumper that demangles a - /// field type, resolves it, then demangles a nested field type — use this - /// entry to keep the memo out of the recursion; they trade memoization - /// for a fresh demangle. (The memo used to be a lazily built cache entry - /// whose re-entrant lookup trapped, which is where this entry comes from; - /// the memo is a plain static now, and the entry stays for the callers - /// that want no memoization.) - public static func demangleTypeUncached(for mangledName: MangledName) throws -> Node { - return try _demangleType(for: mangledName) - } - - public static func demangleType(for symbol: Symbol) throws -> Node? { - if isCacheEnabled { - return try SymbolicDemanglerCache.shared.buildContextManglingForSymbol(symbol) - } else { - return try _buildContextManglingForSymbol(symbol, in: InProcessContext.shared) - } - } - public static func demangleSymbol(for symbol: Symbol) throws -> Node? { return try demangleAsNodeTransient(symbol.name) } - - public static func demangleContext(for context: ContextDescriptorWrapper) throws -> Node { - if isCacheEnabled { - return try SymbolicDemanglerCache.shared.demangleContext(for: context) - } else { - return try _demangleContext(for: context) - } - } - - fileprivate static func _demangleContext(for context: ContextDescriptorWrapper) throws -> Node { - return try required(buildContextMangling(context: context, in: InProcessContext.shared)) - } - - public static func buildGenericSignature(for requirement: GenericRequirementDescriptor) throws -> Node? { - try buildGenericSignature(for: [requirement]) - } - - public static func buildGenericSignature(for requirements: GenericRequirementDescriptor...) throws -> Node? { - try buildGenericSignature(for: requirements) - } - - public static func buildGenericSignature(for requirements: [GenericRequirementDescriptor]) throws -> Node? { - return try buildGenericSignature(for: requirements, in: InProcessContext.shared) - } } // MARK: - Symbol Lookup Protocol @@ -244,11 +142,55 @@ extension SymbolicDemangler { // MARK: - ReadingContext Support extension SymbolicDemangler { + /// Memoized in the scope `context` declares (`SymbolicDemanglerCache`): + /// per image for a Mach-O context, process-wide for the in-process one, + /// not at all for a context without identity. public static func demangleType(for mangledName: MangledName, in context: some ReadingContext) throws -> Node { + if isCacheEnabled { + return try SymbolicDemanglerCache.shared.demangleType(for: mangledName, in: context) + } else { + return try _demangleType(for: mangledName, in: context) + } + } + + fileprivate static func _demangleType(for mangledName: MangledName, in context: some ReadingContext) throws -> Node { return try demangle(for: mangledName, kind: .type, in: context) } + /// Demangles a type WITHOUT touching the shared node memo. + /// + /// The cached `demangleType(for:in:)` reads and fills the memo. Callers + /// on deeply recursive paths — a dumper that demangles a field type, + /// resolves it, then demangles a nested field type — use this entry to + /// keep the memo out of the recursion; they trade memoization for a + /// fresh demangle. (The process-wide memo used to be a lazily built cache + /// entry whose re-entrant lookup trapped, which is where this entry comes + /// from; the memo is a plain static now, and the entry stays for the + /// callers that want no memoization.) + public static func demangleTypeUncached(for mangledName: MangledName, in context: some ReadingContext) throws -> Node { + return try _demangleType(for: mangledName, in: context) + } + + /// The context mangling a descriptor symbol names, memoized like the + /// mangled-name form of `demangleType(for:in:)`. + public static func demangleType(for symbol: Symbol, in context: some ReadingContext) throws -> Node? { + if isCacheEnabled { + return try SymbolicDemanglerCache.shared.buildContextManglingForSymbol(symbol, in: context) + } else { + return try _buildContextManglingForSymbol(symbol, in: context) + } + } + + /// Memoized like the mangled-name form of `demangleType(for:in:)`. public static func demangleContext(for contextWrapper: ContextDescriptorWrapper, in context: some ReadingContext) throws -> Node { + if isCacheEnabled { + return try SymbolicDemanglerCache.shared.demangleContext(for: contextWrapper, in: context) + } else { + return try _demangleContext(for: contextWrapper, in: context) + } + } + + fileprivate static func _demangleContext(for contextWrapper: ContextDescriptorWrapper, in context: some ReadingContext) throws -> Node { return try required(buildContextMangling(context: contextWrapper, in: context)) } @@ -678,10 +620,6 @@ extension SymbolicDemangler { /// under the right kind. A reference that lands on a bind symbol, a /// non-type context, or a mangling with no symbolic reference answers /// `nil`, and the caller keeps its tree-derived kind. - public static func extendedTypeContextDescriptor(forExtendedContext mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeContextDescriptorWrapper? { - try extendedTypeContextDescriptor(forExtendedContext: mangledName, in: machO.context) - } - public static func extendedTypeContextDescriptor(forExtendedContext mangledName: MangledName, in context: some ReadingContext) throws -> TypeContextDescriptorWrapper? { guard let lookup = mangledName.lookupElements.first, case .relative(let relativeReference) = lookup.reference, @@ -880,8 +818,20 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { fileprivate var nodeReferenceForSymbolName: [String: NodeReference?] = [:] } - private func storage(in machO: some MachORepresentableWithCache) -> Storage? { - cache.storage(in: machO) { _ in Storage() } + /// The memo `context` files entries under, as its cache scope declares: + /// the image's `SharedCache` entry (keyed like every other per-image + /// cache, so `removeCache(for:)` drops it with the image), the + /// process-wide storage, or none for a context without identity — its + /// addresses could collide with another image's, so nothing is memoized. + private func storage(for context: some ReadingContext) -> Storage? { + switch context.cacheScope { + case .image(let identifier): + return cache.resolve(key: SharedCacheKey(identifier: identifier)) { Storage() } + case .process: + return Self.processScopedStorage + case .uncached: + return nil + } } fileprivate func contains(in machO: some MachORepresentableWithCache) -> Bool { @@ -892,73 +842,125 @@ private final class SymbolicDemanglerCache: @unchecked Sendable { cache.remove(for: machO) } - func demangleType(for mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - if let reference = storage(in: machO)?.nodeReferenceForMangledNameBox[MangledNameBox(mangledName)] { - return reference.materialize() - } else { - let node = try SymbolicDemangler._demangleType(for: mangledName, in: machO) - storage(in: machO)?.nodeReferenceForMangledNameBox[MangledNameBox(mangledName)] = InternedNodeReferenceCache.shared.reference(interning: node, in: machO) - return node + func demangleType(for mangledName: MangledName, in context: some ReadingContext) throws -> Node { + guard let storage = storage(for: context) else { + return try SymbolicDemangler._demangleType(for: mangledName, in: context) } - } - - func demangleType(for mangledName: MangledName) throws -> Node { - if let reference = Self.processScopedStorage.nodeReferenceForMangledNameBox[MangledNameBox(mangledName)] { + let key = MangledNameBox(mangledName) + if let reference = storage.nodeReferenceForMangledNameBox[key] { return reference.materialize() } else { - let node = try SymbolicDemangler._demangleType(for: mangledName) - Self.processScopedStorage.nodeReferenceForMangledNameBox[MangledNameBox(mangledName)] = InternedNodeReferenceCache.shared.reference(interning: node) + let node = try SymbolicDemangler._demangleType(for: mangledName, in: context) + storage.nodeReferenceForMangledNameBox[key] = InternedNodeReferenceCache.shared.reference(interning: node, in: context) return node } } // MARK: - Context Descriptor Cache - func demangleContext(for context: ContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - let key = context.contextDescriptor.offset - if let reference = storage(in: machO)?.nodeReferenceForContextOffset[key] { - return reference.materialize() - } else { - let node = try SymbolicDemangler._demangleContext(for: context, in: machO) - storage(in: machO)?.nodeReferenceForContextOffset[key] = InternedNodeReferenceCache.shared.reference(interning: node, in: machO) - return node + func demangleContext(for contextWrapper: ContextDescriptorWrapper, in context: some ReadingContext) throws -> Node { + guard let storage = storage(for: context) else { + return try SymbolicDemangler._demangleContext(for: contextWrapper, in: context) } - } - - func demangleContext(for context: ContextDescriptorWrapper) throws -> Node { - let key = context.contextDescriptor.offset - if let reference = Self.processScopedStorage.nodeReferenceForContextOffset[key] { + let key = contextWrapper.contextDescriptor.offset + if let reference = storage.nodeReferenceForContextOffset[key] { return reference.materialize() } else { - let node = try SymbolicDemangler._demangleContext(for: context) - Self.processScopedStorage.nodeReferenceForContextOffset[key] = InternedNodeReferenceCache.shared.reference(interning: node) + let node = try SymbolicDemangler._demangleContext(for: contextWrapper, in: context) + storage.nodeReferenceForContextOffset[key] = InternedNodeReferenceCache.shared.reference(interning: node, in: context) return node } } // MARK: - Symbol Context Mangling Cache - func buildContextManglingForSymbol(_ symbol: Symbol, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { + func buildContextManglingForSymbol(_ symbol: Symbol, in context: some ReadingContext) throws -> Node? { + guard let storage = storage(for: context) else { + return try SymbolicDemangler._buildContextManglingForSymbol(symbol, in: context) + } let key = symbol.name - if let cachedVerdict = storage(in: machO)?.nodeReferenceForSymbolName[key] { + if let cachedVerdict = storage.nodeReferenceForSymbolName[key] { return cachedVerdict?.materialize() } else { - let node = try SymbolicDemangler._buildContextManglingForSymbol(symbol, in: machO.context) + let node = try SymbolicDemangler._buildContextManglingForSymbol(symbol, in: context) // updateValue: a plain subscript assignment of a nil verdict would // remove the key instead of caching the rejection. - storage(in: machO)?.nodeReferenceForSymbolName.updateValue(node.map { InternedNodeReferenceCache.shared.reference(interning: $0, in: machO) }, forKey: key) + storage.nodeReferenceForSymbolName.updateValue(node.map { InternedNodeReferenceCache.shared.reference(interning: $0, in: context) }, forKey: key) return node } } +} - func buildContextManglingForSymbol(_ symbol: Symbol) throws -> Node? { - let key = symbol.name - if let cachedVerdict = Self.processScopedStorage.nodeReferenceForSymbolName[key] { - return cachedVerdict?.materialize() - } else { - let node = try SymbolicDemangler._buildContextManglingForSymbol(symbol, in: InProcessContext.shared) - Self.processScopedStorage.nodeReferenceForSymbolName.updateValue(node.map { InternedNodeReferenceCache.shared.reference(interning: $0) }, forKey: key) - return node - } +// 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/SwiftInspection/SymbolicManglingIndex.swift b/Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift similarity index 99% rename from Sources/SwiftInspection/SymbolicManglingIndex.swift rename to Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift index 39175b68d..16657b580 100644 --- a/Sources/SwiftInspection/SymbolicManglingIndex.swift +++ b/Sources/Analysis/SwiftInspection/SymbolicManglingIndex.swift @@ -306,7 +306,7 @@ package final class SymbolicManglingIndex: @unchecked Sendable { referentCount: Int, in machO: some MachOSwiftSectionRepresentableWithCache ) -> [SymbolicManglingReference]? { - guard offset >= 0, let mangledName = try? MangledName.resolve(from: offset, in: machO) else { return nil } + guard offset >= 0, let mangledName = try? MangledName.resolve(at: offset, in: machO.context) else { return nil } let lookups = mangledName.lookupElements guard lookups.count == referentCount, referentCount <= Int(UInt16.max) else { return nil } var references: [SymbolicManglingReference] = [] diff --git a/Sources/SwiftInspection/Transformer+EnumLayoutProjection.swift b/Sources/Analysis/SwiftInspection/Transformer+EnumLayoutProjection.swift similarity index 100% rename from Sources/SwiftInspection/Transformer+EnumLayoutProjection.swift rename to Sources/Analysis/SwiftInspection/Transformer+EnumLayoutProjection.swift diff --git a/Sources/SwiftLayout/AggregateFieldLayout.swift b/Sources/Analysis/SwiftLayout/AggregateFieldLayout.swift similarity index 100% rename from Sources/SwiftLayout/AggregateFieldLayout.swift rename to Sources/Analysis/SwiftLayout/AggregateFieldLayout.swift diff --git a/Sources/SwiftLayout/BasicLayout.swift b/Sources/Analysis/SwiftLayout/BasicLayout.swift similarity index 100% rename from Sources/SwiftLayout/BasicLayout.swift rename to Sources/Analysis/SwiftLayout/BasicLayout.swift diff --git a/Sources/SwiftLayout/BuiltinTypeLayoutIndex.swift b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift similarity index 98% rename from Sources/SwiftLayout/BuiltinTypeLayoutIndex.swift rename to Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift index bc5f1faaa..451ce46aa 100644 --- a/Sources/SwiftLayout/BuiltinTypeLayoutIndex.swift +++ b/Sources/Analysis/SwiftLayout/BuiltinTypeLayoutIndex.swift @@ -44,8 +44,8 @@ public struct BuiltinTypeLayoutIndex: Sendable { builtinTypeDescriptors = [] } for descriptor in builtinTypeDescriptors { - guard let mangledTypeName = try descriptor.typeName(in: machO) else { continue } - let demangledNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machO) + guard let mangledTypeName = try descriptor.typeName(in: machO.context) else { continue } + let demangledNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context) // A record whose type reference is a *concrete* bound-generic // instantiation (`Foo`) describes only that instantiation; // under the generic-argument-free key it would be misattributed to diff --git a/Sources/SwiftLayout/ClassBoundGenericParameterAnalysis.swift b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift similarity index 96% rename from Sources/SwiftLayout/ClassBoundGenericParameterAnalysis.swift rename to Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift index 2b2c3aafd..496bf8340 100644 --- a/Sources/SwiftLayout/ClassBoundGenericParameterAnalysis.swift +++ b/Sources/Analysis/SwiftLayout/ClassBoundGenericParameterAnalysis.swift @@ -50,7 +50,7 @@ enum ClassBoundGenericParameterAnalysis { in image: ImageReference, imageUniverse: ImageUniverse ) -> RequirementSignatureLayoutFacts { - guard let genericContext = try? descriptor.genericContext(in: image.machO) else { return .empty } + guard let genericContext = try? descriptor.genericContext(in: image.machO.context) else { return .empty } var classBoundParameterKeys: Set = [] var concreteSameTypeSubstitutions: [GenericParameterKey: Node] = [:] for requirement in genericContext.requirements { @@ -93,8 +93,8 @@ enum ClassBoundGenericParameterAnalysis { in machO: some MachOSwiftSectionRepresentableWithCache ) -> Node? { guard - case .type(let rightHandSideName)? = try? requirement.resolvedContent(in: machO), - let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSideName, in: machO) + case .type(let rightHandSideName)? = try? requirement.resolvedContent(in: machO.context), + let rightHandSideNode = try? SymbolicDemangler.demangleType(for: rightHandSideName, in: machO.context) else { return nil } let unwrapped = rightHandSideNode.kind == .type ? (rightHandSideNode.firstChild ?? rightHandSideNode) : rightHandSideNode guard !nodeReferencesParameterOrMember(unwrapped) else { return nil } @@ -117,8 +117,8 @@ enum ClassBoundGenericParameterAnalysis { in machO: some MachOSwiftSectionRepresentableWithCache ) -> GenericParameterKey? { guard - let parameterMangledName = try? requirement.paramMangledName(in: machO), - let parameterNode = try? SymbolicDemangler.demangleType(for: parameterMangledName, in: machO) + let parameterMangledName = try? requirement.paramMangledName(in: machO.context), + let parameterNode = try? SymbolicDemangler.demangleType(for: parameterMangledName, in: machO.context) else { return nil } let unwrapped = parameterNode.kind == .type ? (parameterNode.firstChild ?? parameterNode) : parameterNode guard @@ -139,12 +139,12 @@ enum ClassBoundGenericParameterAnalysis { ) -> Bool { switch requirement.layout.flags.kind { case .layout: - guard case .layout(.class)? = try? requirement.resolvedContent(in: image.machO) else { return false } + guard case .layout(.class)? = try? requirement.resolvedContent(in: image.machO.context) else { return false } return true case .baseClass: return true case .protocol: - guard case .protocol(let protocolReference)? = try? requirement.resolvedContent(in: image.machO) else { return false } + guard case .protocol(let protocolReference)? = try? requirement.resolvedContent(in: image.machO.context) else { return false } return isClassBoundProtocolReference(protocolReference, in: image, imageUniverse: imageUniverse) default: // `sameType` to a concrete class is a genuine specialization, not a @@ -174,7 +174,7 @@ enum ClassBoundGenericParameterAnalysis { } case .symbol(let symbol): guard - let symbolNode = try? SymbolicDemangler.demangleType(for: symbol, in: image.machO), + let symbolNode = try? SymbolicDemangler.demangleType(for: symbol, in: image.machO.context), let protocolNode = symbolNode.kind == .protocol ? symbolNode : symbolNode.first(of: .protocol), let qualifiedProtocolName = NodeTypeNaming.protocolQualifiedName(of: protocolNode) else { return false } diff --git a/Sources/SwiftLayout/DependentMemberTypeBridge.swift b/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift similarity index 97% rename from Sources/SwiftLayout/DependentMemberTypeBridge.swift rename to Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift index b9f6b8ae6..9b9d3dbeb 100644 --- a/Sources/SwiftLayout/DependentMemberTypeBridge.swift +++ b/Sources/Analysis/SwiftLayout/DependentMemberTypeBridge.swift @@ -56,10 +56,10 @@ extension StaticTypeLayoutResolver { // Demangle the witness type in the image that declares the conformance // (its symbolic references are relative to that image). - let witnessTypeName = try witness.record.substitutedTypeName(in: witness.image.machO) + let witnessTypeName = try witness.record.substitutedTypeName(in: witness.image.machO.context) let witnessNode: Node do { - witnessNode = try SymbolicDemangler.demangleType(for: witnessTypeName, in: witness.image.machO) + witnessNode = try SymbolicDemangler.demangleType(for: witnessTypeName, in: witness.image.machO.context) } catch { throw LayoutResolutionError.unknown(.demangleFailure) } diff --git a/Sources/SwiftLayout/EnumLayoutBridge.swift b/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift similarity index 97% rename from Sources/SwiftLayout/EnumLayoutBridge.swift rename to Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift index a3c55d3e8..c9025a3a6 100644 --- a/Sources/SwiftLayout/EnumLayoutBridge.swift +++ b/Sources/Analysis/SwiftLayout/EnumLayoutBridge.swift @@ -152,8 +152,8 @@ extension StaticTypeLayoutResolver { { // Spare-bits strategy: the descriptor carries the common spare-bit // mask the compiler computed across all payloads. - let spareBytes = try multiPayloadDescriptor.payloadSpareBits(in: image.machO) - let spareBytesOffset = Int(try multiPayloadDescriptor.payloadSpareBitMaskByteOffset(in: image.machO)) + let spareBytes = try multiPayloadDescriptor.payloadSpareBits(in: image.machO.context) + let spareBytesOffset = Int(try multiPayloadDescriptor.payloadSpareBitMaskByteOffset(in: image.machO.context)) result = EnumLayoutCalculator.calculateMultiPayload( payloadSize: payloadSize, spareBytes: spareBytes, @@ -206,10 +206,10 @@ extension StaticTypeLayoutResolver { var isBitwiseTakable = true var isBitwiseBorrowable = true var isAddressableForDependencies = false - let records = try descriptor.fieldDescriptor(in: image.machO).records(in: image.machO) + let records = try descriptor.fieldDescriptor(in: image.machO.context).records(in: image.machO.context) for record in records { let isIndirect = record.layout.flags.contains(.isIndirectCase) - let mangledTypeName = try record.mangledTypeName(in: image.machO) + let mangledTypeName = try record.mangledTypeName(in: image.machO.context) guard isIndirect || !mangledTypeName.isEmpty else { continue } // empty case let payloadLayout = isIndirect ? StaticTypeLayout.pointerSized @@ -235,8 +235,8 @@ extension StaticTypeLayoutResolver { guard let descriptors = try? image.machO.swift.multiPayloadEnumDescriptors else { return nil } for descriptor in descriptors { guard - let mangledTypeName = try? descriptor.mangledTypeName(in: image.machO), - let node = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO), + let mangledTypeName = try? descriptor.mangledTypeName(in: image.machO.context), + let node = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO.context), NodeTypeNaming.nominalQualifiedName(of: node) == qualifiedTypeName else { continue } return descriptor @@ -274,13 +274,13 @@ extension StaticTypeLayoutResolver { in image: ImageReference, environment: GenericArgumentEnvironment = .empty ) throws -> StaticTypeLayout { - let fieldDescriptor = try descriptor.fieldDescriptor(in: image.machO) - let records = try fieldDescriptor.records(in: image.machO) + let fieldDescriptor = try descriptor.fieldDescriptor(in: image.machO.context) + let records = try fieldDescriptor.records(in: image.machO.context) for record in records { if record.layout.flags.contains(.isIndirectCase) { return .pointerSized } - let mangledTypeName = try record.mangledTypeName(in: image.machO) + let mangledTypeName = try record.mangledTypeName(in: image.machO.context) if !mangledTypeName.isEmpty { return try layout(forMangledTypeName: mangledTypeName, in: image, environment: environment) } @@ -315,7 +315,7 @@ extension StaticTypeLayoutResolver { let emptyCaseCount = descriptor.numberOfEmptyCases guard payloadCaseCount > 0 else { return nil } - let node = try SymbolicDemangler.demangleContext(for: .type(.enum(descriptor)), in: image.machO) + let node = try SymbolicDemangler.demangleContext(for: .type(.enum(descriptor)), in: image.machO.context) let layoutResult: EnumLayoutCalculator.LayoutResult if payloadCaseCount == 1 { let payload = try singlePayloadType(descriptor: descriptor, node: node, in: image, environment: environment) @@ -335,8 +335,8 @@ extension StaticTypeLayoutResolver { let multiPayloadDescriptor = multiPayloadEnumDescriptor(forQualifiedTypeName: qualifiedTypeName, in: image), multiPayloadDescriptor.usesPayloadSpareBits { - let spareBytes = try multiPayloadDescriptor.payloadSpareBits(in: image.machO) - let spareBytesOffset = Int(try multiPayloadDescriptor.payloadSpareBitMaskByteOffset(in: image.machO)) + let spareBytes = try multiPayloadDescriptor.payloadSpareBits(in: image.machO.context) + let spareBytesOffset = Int(try multiPayloadDescriptor.payloadSpareBitMaskByteOffset(in: image.machO.context)) layoutResult = EnumLayoutCalculator.calculateMultiPayload( payloadSize: payloadArea.size, spareBytes: spareBytes, @@ -354,8 +354,8 @@ extension StaticTypeLayoutResolver { } // Attach the source-level case names (field records store payload // cases first, then empty cases — the projections' tag order). - if let records = try? descriptor.fieldDescriptor(in: image.machO).records(in: image.machO), - let declaredCaseNames = try? records.map({ try $0.fieldName(in: image.machO) }) { + if let records = try? descriptor.fieldDescriptor(in: image.machO.context).records(in: image.machO.context), + let declaredCaseNames = try? records.map({ try $0.fieldName(in: image.machO.context) }) { return layoutResult.attachingDeclaredCaseNames(declaredCaseNames) } return layoutResult diff --git a/Sources/SwiftLayout/ExistentialLayoutBridge.swift b/Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift similarity index 100% rename from Sources/SwiftLayout/ExistentialLayoutBridge.swift rename to Sources/Analysis/SwiftLayout/ExistentialLayoutBridge.swift diff --git a/Sources/SwiftLayout/GenericArgumentEnvironment.swift b/Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift similarity index 100% rename from Sources/SwiftLayout/GenericArgumentEnvironment.swift rename to Sources/Analysis/SwiftLayout/GenericArgumentEnvironment.swift diff --git a/Sources/SwiftLayout/ImageReference.swift b/Sources/Analysis/SwiftLayout/ImageReference.swift similarity index 97% rename from Sources/SwiftLayout/ImageReference.swift rename to Sources/Analysis/SwiftLayout/ImageReference.swift index 0de89f7c2..3caee7a7b 100644 --- a/Sources/SwiftLayout/ImageReference.swift +++ b/Sources/Analysis/SwiftLayout/ImageReference.swift @@ -60,7 +60,7 @@ public final class ImageReference [NestedFieldOffset] { - guard let node = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: imageUniverse.rootImage.machO) else { + guard let node = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: imageUniverse.rootImage.machO.context) else { return [] } return nestedChildren( @@ -141,7 +141,7 @@ extension StaticLayoutCalculator { let environment = GenericArgumentEnvironment.make(forInstantiatedTypeNode: node) guard let aggregate = try? fieldLayout(ofStruct: structDescriptor, in: resolved.image, environment: environment), - let records = try? structDescriptor.fieldDescriptor(in: resolved.image.machO).records(in: resolved.image.machO) + let records = try? structDescriptor.fieldDescriptor(in: resolved.image.machO.context).records(in: resolved.image.machO.context) else { return [] } var children: [NestedFieldOffset] = [] @@ -181,14 +181,14 @@ extension StaticLayoutCalculator { let resolved = imageUniverse.resolveType(byQualifiedTypeName: qualifiedTypeName), let enumDescriptor = resolved.descriptor.enum, enumDescriptor.hasPayloadCases, - let records = try? enumDescriptor.fieldDescriptor(in: resolved.image.machO).records(in: resolved.image.machO) + let records = try? enumDescriptor.fieldDescriptor(in: resolved.image.machO.context).records(in: resolved.image.machO.context) else { return [] } let environment = GenericArgumentEnvironment.make(forInstantiatedTypeNode: node) let payloadRecords = records.prefix(enumDescriptor.numberOfPayloadCases) var children: [NestedFieldOffset] = [] for record in payloadRecords { - guard let mangledTypeName = try? record.mangledTypeName(in: resolved.image.machO), !mangledTypeName.isEmpty else { continue } + guard let mangledTypeName = try? record.mangledTypeName(in: resolved.image.machO.context), !mangledTypeName.isEmpty else { continue } // A payload occupies the enum's payload area, which begins at the // enum's own offset — every payload starts at `baseOffset`. children.append(makeNode( @@ -230,9 +230,9 @@ extension StaticLayoutCalculator { descendsIntoFieldType: Bool, byteWidth: Int? ) -> NestedFieldOffset { - let fieldName = ((try? record.fieldName(in: image.machO)).flatMap { $0.isEmpty ? nil : $0 }) ?? fallbackFieldName - let fieldTypeNode: Node? = (try? record.mangledTypeName(in: image.machO)).flatMap { mangledTypeName in - (try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO)).map { environment.substituting(in: $0) } + let fieldName = ((try? record.fieldName(in: image.machO.context)).flatMap { $0.isEmpty ? nil : $0 }) ?? fallbackFieldName + let fieldTypeNode: Node? = (try? record.mangledTypeName(in: image.machO.context)).flatMap { mangledTypeName in + (try? SymbolicDemangler.demangleType(for: mangledTypeName, in: image.machO.context)).map { environment.substituting(in: $0) } } let typeName = fieldTypeNode?.print(using: .default) ?? "" let children = descendsIntoFieldType ? (fieldTypeNode.map { diff --git a/Sources/SwiftLayout/ObjCClassIndex.swift b/Sources/Analysis/SwiftLayout/ObjCClassIndex.swift similarity index 100% rename from Sources/SwiftLayout/ObjCClassIndex.swift rename to Sources/Analysis/SwiftLayout/ObjCClassIndex.swift diff --git a/Sources/SwiftLayout/ObjCProtocolIndex.swift b/Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift similarity index 100% rename from Sources/SwiftLayout/ObjCProtocolIndex.swift rename to Sources/Analysis/SwiftLayout/ObjCProtocolIndex.swift diff --git a/Sources/SwiftLayout/StaticLayoutCalculator.swift b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift similarity index 98% rename from Sources/SwiftLayout/StaticLayoutCalculator.swift rename to Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift index 7fd790396..dccd1b8f2 100644 --- a/Sources/SwiftLayout/StaticLayoutCalculator.swift +++ b/Sources/Analysis/SwiftLayout/StaticLayoutCalculator.swift @@ -65,7 +65,7 @@ public struct StaticLayoutCalculator AggregateFieldLayout { let typeNode: Node do { - typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: imageUniverse.rootImage.machO) + typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: imageUniverse.rootImage.machO.context) } catch { throw LayoutResolutionError.unknown(.demangleFailure) } @@ -106,7 +106,7 @@ public struct StaticLayoutCalculator StaticTypeLayout { - let node = try SymbolicDemangler.demangleContext(for: typeDescriptor.asContextDescriptorWrapper, in: imageUniverse.rootImage.machO) + let node = try SymbolicDemangler.demangleContext(for: typeDescriptor.asContextDescriptorWrapper, in: imageUniverse.rootImage.machO.context) return try resolver.layout(forTypeNode: node, in: imageUniverse.rootImage) } @@ -173,7 +173,7 @@ public struct StaticLayoutCalculator StaticTypeLayout { let typeNode: Node do { - typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: originImage.machO) + typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: originImage.machO.context) } catch { throw LayoutResolutionError.unknown(.demangleFailure) } @@ -589,7 +589,7 @@ final class StaticTypeLayoutResolver StaticTypeLayout { let typeNode: Node do { - typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: originImage.machO) + typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: originImage.machO.context) } catch { throw LayoutResolutionError.unknown(.demangleFailure) } @@ -681,7 +681,7 @@ final class StaticTypeLayoutResolver (instanceSize: Int, alignmentMask: Int) { guard - let superclassMangledName = try descriptor.superclassTypeMangledName(in: image.machO), + let superclassMangledName = try descriptor.superclassTypeMangledName(in: image.machO.context), !superclassMangledName.isEmpty else { // Root class: sizeof(HeapObject) == isa + refcount == 16, 8-aligned. @@ -707,7 +707,7 @@ final class StaticTypeLayoutResolver, environment: GenericArgumentEnvironment = .empty ) throws -> [StaticTypeLayout] { - let fieldDescriptor = try descriptor.fieldDescriptor(in: image.machO) - let records = try fieldDescriptor.records(in: image.machO) + let fieldDescriptor = try descriptor.fieldDescriptor(in: image.machO.context) + let records = try fieldDescriptor.records(in: image.machO.context) var fieldLayouts: [StaticTypeLayout] = [] fieldLayouts.reserveCapacity(records.count) for record in records { - let mangledTypeName = try record.mangledTypeName(in: image.machO) + let mangledTypeName = try record.mangledTypeName(in: image.machO.context) let fieldLayout = try layout(forMangledTypeName: mangledTypeName, in: image, environment: environment) fieldLayouts.append(try Self.isRawLayoutStorageRecord(record, in: image) ? Self.rawLayoutStorage(likeTypeLayout: fieldLayout) : fieldLayout) } @@ -808,7 +808,7 @@ final class StaticTypeLayoutResolver) throws -> Bool { guard record.flags.contains(.isArtificial) else { return false } - return try record.fieldName(in: image.machO) == rawLayoutStorageFieldName + return try record.fieldName(in: image.machO.context) == rawLayoutStorageFieldName } static func rawLayoutStorage(likeTypeLayout: StaticTypeLayout) -> StaticTypeLayout { diff --git a/Sources/SwiftThunkAnalysis/Analysis/AccessorThunkAnalyzer.swift b/Sources/Analysis/SwiftThunkAnalysis/Analysis/AccessorThunkAnalyzer.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Analysis/AccessorThunkAnalyzer.swift rename to Sources/Analysis/SwiftThunkAnalysis/Analysis/AccessorThunkAnalyzer.swift diff --git a/Sources/SwiftThunkAnalysis/Analysis/AccessorThunkProgram.swift b/Sources/Analysis/SwiftThunkAnalysis/Analysis/AccessorThunkProgram.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Analysis/AccessorThunkProgram.swift rename to Sources/Analysis/SwiftThunkAnalysis/Analysis/AccessorThunkProgram.swift diff --git a/Sources/SwiftThunkAnalysis/Analysis/ThunkRegisterTracker.swift b/Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkRegisterTracker.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Analysis/ThunkRegisterTracker.swift rename to Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkRegisterTracker.swift diff --git a/Sources/SwiftThunkAnalysis/Analysis/ThunkTypeEvaluator.swift b/Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkTypeEvaluator.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Analysis/ThunkTypeEvaluator.swift rename to Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkTypeEvaluator.swift diff --git a/Sources/SwiftThunkAnalysis/Analysis/ThunkTypeExpression.swift b/Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkTypeExpression.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Analysis/ThunkTypeExpression.swift rename to Sources/Analysis/SwiftThunkAnalysis/Analysis/ThunkTypeExpression.swift diff --git a/Sources/SwiftThunkAnalysis/Instructions/CapstoneThunkDecoder.swift b/Sources/Analysis/SwiftThunkAnalysis/Instructions/CapstoneThunkDecoder.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Instructions/CapstoneThunkDecoder.swift rename to Sources/Analysis/SwiftThunkAnalysis/Instructions/CapstoneThunkDecoder.swift diff --git a/Sources/SwiftThunkAnalysis/Instructions/ThunkInstruction.swift b/Sources/Analysis/SwiftThunkAnalysis/Instructions/ThunkInstruction.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Instructions/ThunkInstruction.swift rename to Sources/Analysis/SwiftThunkAnalysis/Instructions/ThunkInstruction.swift diff --git a/Sources/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift rename to Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMembers.swift diff --git a/Sources/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift b/Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift rename to Sources/Analysis/SwiftThunkAnalysis/ObjCMembers/ObjCMethodThunkReferences.swift diff --git a/Sources/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkOwnerLayout.swift diff --git a/Sources/SwiftThunkAnalysis/Resolution/AccessorThunkReader.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkReader.swift similarity index 97% rename from Sources/SwiftThunkAnalysis/Resolution/AccessorThunkReader.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkReader.swift index 462bedb45..90013a00f 100644 --- a/Sources/SwiftThunkAnalysis/Resolution/AccessorThunkReader.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/AccessorThunkReader.swift @@ -123,18 +123,18 @@ public enum AccessorThunkReader: AccessorThunkReadingLogging { let descriptorOffset = MetadataAccessorIndex.index(for: machO).descriptorOffset(forAccessorOffset: offset) else { return nil } do { - let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(from: descriptorOffset, in: machO) + let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: descriptorOffset, in: machO.context) // This reading names the accessor alone, without the // arguments it was called with, so it is only right for a // type that takes none. A generic descriptor's unbound tree // would print as `_TaskValueModifier2A` once the owner's // parameters are substituted into it — a real-looking, wrong // type (measured on iOS 26.5 simulator SwiftUI). - if let genericContext = try descriptor.genericContext(in: machO), !genericContext.parameters.isEmpty { + if let genericContext = try descriptor.genericContext(in: machO.context), !genericContext.parameters.isEmpty { #log(.info, "the accessor at offset \(offset, privacy: .public) belongs to a generic type; its arguments were not read, so it is not named") return nil } - return try SymbolicDemangler.demangleContext(for: descriptor, in: machO) + return try SymbolicDemangler.demangleContext(for: descriptor, in: machO.context) } catch { #log(.info, "could not name the accessor at offset \(offset, privacy: .public): \(String(describing: error), privacy: .public)") return nil diff --git a/Sources/SwiftThunkAnalysis/Resolution/DependencyImageResolver.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/DependencyImageResolver.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Resolution/DependencyImageResolver.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/DependencyImageResolver.swift diff --git a/Sources/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift similarity index 97% rename from Sources/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift index dba68e0d8..29c04cf22 100644 --- a/Sources/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/MachOThunkEnvironment.swift @@ -127,15 +127,15 @@ package final class MachOThunkEnvironment: ThunkEvaluationEnvironment, MachOThun private lazy var ownRuntimeSymbolNamesByAddress: [UInt64: String] = { var namesByAddress: [UInt64: String] = [:] let wanted = Set(Self.namedRuntimeSymbols) - // `Symbol.offset` is a file offset; the segment table turns it into - // the address the thunk's instructions name. + // A symbol table entry's value is already the address the thunk's + // instructions name. Debug-map entries share the names and are skipped. if let symbols = machO.symbols64 { - for symbol in symbols where wanted.contains(symbol.name) { - if let address = addressSpace.address(forFileOffset: symbol.offset) { namesByAddress[address] = symbol.name } + for symbol in symbols where wanted.contains(symbol.name) && !symbol.nlist.isDebuggingEntry { + if let address = addressSpace.address(forSymbolValue: symbol.offset) { namesByAddress[address] = symbol.name } } } else if let symbols = machO.symbols32 { - for symbol in symbols where wanted.contains(symbol.name) { - if let address = addressSpace.address(forFileOffset: symbol.offset) { namesByAddress[address] = symbol.name } + for symbol in symbols where wanted.contains(symbol.name) && !symbol.nlist.isDebuggingEntry { + if let address = addressSpace.address(forSymbolValue: symbol.offset) { namesByAddress[address] = symbol.name } } } return namesByAddress @@ -431,8 +431,8 @@ package final class MachOThunkEnvironment: ThunkEvaluationEnvironment, MachOThun /// The accessor's key arguments, in generic-argument-layout order. private func accessorArgumentSlots(ofDescriptorAt descriptorOffset: Int, in image: MachOFile) -> [ThunkArgumentSlot]? { do { - let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(from: descriptorOffset, in: image) - guard let genericContext = try descriptor.genericContext(in: image) else { return [] } + let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: descriptorOffset, in: image.context) + guard let genericContext = try descriptor.genericContext(in: image.context) else { return [] } var slots: [ThunkArgumentSlot] = [] slots.append(contentsOf: repeatElement(.other, count: genericContext.typePacks.count)) for parameter in genericContext.parameters where parameter.hasKeyArgument { diff --git a/Sources/SwiftThunkAnalysis/Resolution/MetadataAccessorIndex.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/MetadataAccessorIndex.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Resolution/MetadataAccessorIndex.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/MetadataAccessorIndex.swift diff --git a/Sources/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/SharedCacheEvictionGroup+SwiftThunkAnalysis.swift diff --git a/Sources/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift similarity index 85% rename from Sources/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift index 95f1f73e0..a481c4790 100644 --- a/Sources/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkAddressSpace.swift @@ -91,8 +91,8 @@ package struct ThunkAddressSpace: Sendable { /// /// 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 running it through - /// ``address(forFileOffset:)`` lands inside `__LINKEDIT` (measured: + /// 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 @@ -112,17 +112,20 @@ package struct ThunkAddressSpace: Sendable { return nil } - /// A *file* offset (a symbol table entry's, a segment's) → address, - /// through the segment that contains it. Independent of the cache - /// convention on purpose: `Symbol.offset` is a file offset even inside a - /// shared cache, where ``offset(forAddress:)``'s accounting is not. An - /// export trie's offset is NOT one — see - /// ``address(forExportedSymbolOffset:)``. - package func address(forFileOffset fileOffset: Int) -> UInt64? { - for segment in segments where fileOffset >= segment.fileOffset && fileOffset < segment.fileOffset + segment.fileSize { - return segment.virtualMemoryAddress &+ UInt64(fileOffset - 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? { diff --git a/Sources/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift similarity index 96% rename from Sources/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift rename to Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift index de5aae622..370137c2c 100644 --- a/Sources/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift +++ b/Sources/Analysis/SwiftThunkAnalysis/Resolution/ThunkTypeNodeBuilder.swift @@ -94,8 +94,8 @@ package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { private func boundTypeNode(accessorAddress: UInt64, typeArguments: [ThunkTypeExpression]) -> Node? { guard let origin = environment.accessorOriginsByAddress[accessorAddress] else { return nil } do { - let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(from: origin.descriptorOffset, in: origin.machO) - let unboundNode = try SymbolicDemangler.demangleContext(for: descriptor, in: origin.machO) + let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: origin.descriptorOffset, in: origin.machO.context) + let unboundNode = try SymbolicDemangler.demangleContext(for: descriptor, in: origin.machO.context) guard let keyParameterCountsByLevel = try keyParameterCountsByNominalLevel(of: descriptor, in: origin.machO) else { return nil } var argumentNodes: [Node] = [] for typeArgument in typeArguments { @@ -130,12 +130,12 @@ package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { var current: ContextDescriptorWrapper? = descriptor while let context = current { if case .type = context { - let genericContext = try context.genericContext(in: image) + let genericContext = try context.genericContext(in: image.context) let ownParameters = genericContext?.currentParameters ?? [] guard ownParameters.allSatisfy(\.hasKeyArgument) else { return nil } countsInnermostFirst.append(ownParameters.count) } - current = try context.parent(in: image)?.resolved + current = try context.parent(in: image.context)?.resolved } return countsInnermostFirst.reversed() } @@ -179,8 +179,8 @@ package struct ThunkTypeNodeBuilder: ThunkTypeNodeBuildingLogging { do { let pointer: RelativeDirectPointer = try machO.readElement(offset: offset) guard pointer.isValid else { return nil } - let mangledName = try pointer.resolve(from: offset, in: machO) - return try SymbolicDemangler.demangleType(for: mangledName, in: machO) + let mangledName = try pointer.resolve(at: offset, in: machO.context) + return try SymbolicDemangler.demangleType(for: mangledName, in: machO.context) } catch { return nil } @@ -249,9 +249,9 @@ package enum MetadataNaming { let descriptorFieldOffset = offset + StructMetadata.descriptorOffset guard let descriptorOffset = machO.resolveRebase(fileOffset: descriptorFieldOffset) else { return nil } // Annotated because `ContextDescriptorWrapper` vends both a - // `Self`- and a `Self?`-returning `resolve(from:in:)`. - let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(from: Int(descriptorOffset), in: machO) - return try SymbolicDemangler.demangleContext(for: descriptor, in: machO) + // `Self`- and a `Self?`-returning `resolve(at:in:)`. + let descriptor: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: Int(descriptorOffset), in: machO.context) + return try SymbolicDemangler.demangleContext(for: descriptor, in: machO.context) } catch { return nil } diff --git a/Sources/SwiftThunkAnalysis/SwiftThunkAnalysis.swift b/Sources/Analysis/SwiftThunkAnalysis/SwiftThunkAnalysis.swift similarity index 100% rename from Sources/SwiftThunkAnalysis/SwiftThunkAnalysis.swift rename to Sources/Analysis/SwiftThunkAnalysis/SwiftThunkAnalysis.swift diff --git a/Sources/Commands/SwiftSectionKit/Environment/SwiftSectionEnvironment.swift b/Sources/Commands/SwiftSectionKit/Environment/SwiftSectionEnvironment.swift new file mode 100644 index 000000000..9c081141c --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Environment/SwiftSectionEnvironment.swift @@ -0,0 +1,29 @@ +import Foundation + +/// The tool a product says it was generated by. +public struct GeneratorIdentity: Sendable, Hashable { + public var name: String + public var version: String + + public init(name: String, version: String) { + self.name = name + self.version = version + } +} + +/// What a request stamps into its product without being asked to compute it: +/// who generated it, and when. +/// +/// Injected rather than read from the process so that a host stamps its own +/// name, and a test gets the same bytes on every run. +public struct SwiftSectionEnvironment: Sendable { + /// Stamped into interface headers and snapshot provenance. + public var generator: GeneratorIdentity + /// Stamped into snapshot provenance as `createdAt`. + public var currentDate: @Sendable () -> Date + + public init(generator: GeneratorIdentity, currentDate: @escaping @Sendable () -> Date = { Date() }) { + self.generator = generator + self.currentDate = currentDate + } +} diff --git a/Sources/swift-section/Models/Architecture.swift b/Sources/Commands/SwiftSectionKit/Inputs/Architecture.swift similarity index 71% rename from Sources/swift-section/Models/Architecture.swift rename to Sources/Commands/SwiftSectionKit/Inputs/Architecture.swift index 8863bb4c9..91c699ee2 100644 --- a/Sources/swift-section/Models/Architecture.swift +++ b/Sources/Commands/SwiftSectionKit/Inputs/Architecture.swift @@ -1,12 +1,12 @@ -import ArgumentParser import MachOKit -enum Architecture: String, ExpressibleByArgument, CaseIterable { +/// A slice of a fat (universal) binary. +public enum Architecture: String, CaseIterable, Sendable, Hashable { case x86_64 case arm64 case arm64e - var cpu: CPUSubType { + var cpuSubtype: CPUSubType { switch self { case .x86_64: return .x86(.x86_64_all) @@ -18,8 +18,8 @@ enum Architecture: String, ExpressibleByArgument, CaseIterable { } init?(cpu: CPU) { - guard let cpuType = cpu.type, let cpuSubType = cpu.subtype else { return nil } - switch (cpuType, cpuSubType) { + guard let cpuType = cpu.type, let cpuSubtype = cpu.subtype else { return nil } + switch (cpuType, cpuSubtype) { case (.x86_64, .x86(.x86_all)), (.x86_64, .x86(.x86_64_all)): self = .x86_64 case (.arm64, .arm64(.arm64_all)): diff --git a/Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift b/Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift new file mode 100644 index 000000000..262459986 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Inputs/MachOSource.swift @@ -0,0 +1,104 @@ +import Foundation +import MachOKit +import MachOFoundation + +/// An image inside a dyld shared cache, named one of the two ways a cache +/// indexes its images. +public enum DyldSharedCacheImage: Sendable, Hashable { + /// The image's name, as in `SwiftUICore`. + case name(String) + /// The image's install path, as in `/usr/lib/libobjc.A.dylib`. + case path(String) +} + +/// Where a Mach-O image comes from. +public enum MachOSource: Sendable, Hashable { + /// A thin or fat Mach-O file. `architecture` picks a fat binary's slice and + /// is ignored for a thin one. + case file(path: String, architecture: Architecture?) + /// One image of the dyld shared cache at `cachePath`. + case dyldSharedCache(cachePath: String, image: DyldSharedCacheImage) + /// One image of the running system's dyld shared cache. + case systemDyldSharedCache(image: DyldSharedCacheImage) +} + +public enum MachOSourceError: Error, LocalizedError, Sendable, Equatable { + /// A fat binary was given without an architecture to pick. + case fatBinaryRequiresArchitecture(availableArchitectures: [String]) + /// The fat binary has no slice of this architecture. + case architectureNotFound(Architecture) + case dyldSharedCacheImageNotFound(DyldSharedCacheImage) + /// The running system exposes no dyld shared cache to read (it takes + /// macOS 11 or later). + case systemDyldSharedCacheUnavailable + + public var errorDescription: String? { + switch self { + case .fatBinaryRequiresArchitecture(let availableArchitectures): + "The file is a fat (universal) binary; an architecture must be chosen. Available architectures: \(availableArchitectures.joined(separator: ", "))" + case .architectureNotFound(let architecture): + "The file has no \(architecture.rawValue) slice." + case .dyldSharedCacheImageNotFound(.name(let name)): + "The dyld shared cache has no image named '\(name)'." + case .dyldSharedCacheImageNotFound(.path(let path)): + "The dyld shared cache has no image at '\(path)'." + case .systemDyldSharedCacheUnavailable: + "The running system's dyld shared cache cannot be read; it takes macOS 11 or later." + } + } +} + +extension MachOSource { + /// Loads the image this source names. + /// + /// The one loader every request shares, so that the fat-binary handling + /// and the cache-image lookup cannot drift between them. A cache is read + /// through `FullDyldCache`, which maps the subcaches too: an image whose + /// sections live in a subcache read out of range through the main cache + /// file alone. + public func load() throws -> MachOFile { + switch self { + case .file(let path, let architecture): + let file = try File.loadFromFile(url: URL(fileURLWithPath: path)) + switch file { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + let machOFiles = try fatFile.machOFiles() + guard let architecture else { + let availableArchitectures = machOFiles.map { machOFile -> String in + Architecture(cpu: machOFile.header.cpu)?.rawValue ?? machOFile.header.cpu.description + } + throw MachOSourceError.fatBinaryRequiresArchitecture(availableArchitectures: availableArchitectures) + } + guard let machOFile = machOFiles.first(where: { $0.header.cpu.subtype == architecture.cpuSubtype }) else { + throw MachOSourceError.architectureNotFound(architecture) + } + return machOFile + } + case .dyldSharedCache(let cachePath, let image): + let dyldCache = try FullDyldCache(url: URL(fileURLWithPath: cachePath)) + return try image.machOFile(in: dyldCache) + case .systemDyldSharedCache(let image): + guard let dyldCache = FullDyldCache.cachedHost else { + throw MachOSourceError.systemDyldSharedCacheUnavailable + } + return try image.machOFile(in: dyldCache) + } + } +} + +extension DyldSharedCacheImage { + func machOFile(in dyldCache: FullDyldCache) throws -> MachOFile { + let machOFile: MachOFile? = switch self { + case .name(let name): + dyldCache.machOFile(by: .name(name)) + case .path(let path): + dyldCache.machOFile(by: .path(path)) + } + guard let machOFile else { + throw MachOSourceError.dyldSharedCacheImageNotFound(self) + } + return machOFile + } +} diff --git a/Sources/Commands/SwiftSectionKit/Inputs/SnapshotSource.swift b/Sources/Commands/SwiftSectionKit/Inputs/SnapshotSource.swift new file mode 100644 index 000000000..b6138bd62 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Inputs/SnapshotSource.swift @@ -0,0 +1,96 @@ +import Foundation + +/// Where a snapshot comes from, for `snapshot`, `diff` and `evolution`. +public enum SnapshotSource: Sendable, Hashable { + /// A snapshot document (JSON) or a binary to index on the spot. The file's + /// first non-whitespace byte tells them apart: a document begins with `{`, + /// every Mach-O, fat or cache file with a binary magic. + case path(String) +} + +public enum SnapshotSourceError: Error, LocalizedError, Sendable, Equatable { + /// An annotated interface renders from the live models, and a snapshot + /// document carries none; `path` names the document that was given. + case binaryRequired(path: String) + + public var errorDescription: String? { + switch self { + case .binaryRequired(let path): + "An annotated interface needs binaries; '\(path)' is a snapshot document, which carries no renderable interface." + } + } +} + +/// How `snapshot`, `diff` and `evolution` load an input that turns out to be a +/// binary. A snapshot document input ignores it. +public struct BinaryLoadingOptions: Sendable, Hashable { + /// The slice to pick from a fat binary. + public var architecture: Architecture? + /// When set, every binary input is a dyld shared cache, and this image is + /// extracted from each — the way to diff one framework across two OS + /// versions' caches. + public var dyldSharedCacheImage: DyldSharedCacheImage? + + public init(architecture: Architecture? = nil, dyldSharedCacheImage: DyldSharedCacheImage? = nil) { + self.architecture = architecture + self.dyldSharedCacheImage = dyldSharedCacheImage + } + + /// The Mach-O source a binary input at `path` names. + func machOSource(forBinaryAt path: String) -> MachOSource { + if let dyldSharedCacheImage { + return .dyldSharedCache(cachePath: path, image: dyldSharedCacheImage) + } else { + return .file(path: path, architecture: architecture) + } + } + + /// What provenance records after the input path, so that two images of + /// one cache stay distinguishable: " (SwiftUICore)". + var provenancePathSuffix: String { + switch dyldSharedCacheImage { + case .name(let name): + " (\(name))" + case .path(let path): + " (\(path))" + case nil: + "" + } + } +} + +extension SnapshotSource { + var path: String { + switch self { + case .path(let path): + path + } + } + + /// Whether the file is a snapshot document rather than a binary. One byte + /// decides: the first that is not whitespace. + func isSnapshotDocument() throws -> Bool { + let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) + defer { fileHandle.closeFile() } + let prefix = fileHandle.readData(ofLength: 64) + let firstNonWhitespace = prefix.first { byte in + byte != UInt8(ascii: " ") && byte != UInt8(ascii: "\n") + && byte != UInt8(ascii: "\r") && byte != UInt8(ascii: "\t") + } + return firstNonWhitespace == UInt8(ascii: "{") + } + + /// The axis label an input gets when nobody named it: its file name. + var defaultLabel: String { + URL(fileURLWithPath: path).lastPathComponent + } + + /// Throws ``SnapshotSourceError/binaryRequired(path:)`` for the first of + /// `sources` that is a snapshot document. Every input is checked before + /// any is loaded, so a mistake costs no indexing. + static func requireBinaries(_ sources: [SnapshotSource]) throws { + for source in sources where try source.isSnapshotDocument() { + throw SnapshotSourceError.binaryRequired(path: source.path) + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift new file mode 100644 index 000000000..b2726c91f --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCAPIRequests.swift @@ -0,0 +1,242 @@ +import Foundation +import MachOKit +import ObjCDiffing +import ObjCIndexing +import ObjCInterface +import ObjCMetadataSource + +/// `swift-section objc snapshot`: index a binary's ObjC API and persist it as a +/// baseline document — or relabel an existing document. +public struct ObjCAPISnapshotRequest: Sendable, Equatable { + public var source: SnapshotSource + public var binaryLoading: BinaryLoadingOptions + /// A human-readable version label stored in the provenance (`26.0`). + public var label: String? + public var destination: ProductDestination + + public init( + source: SnapshotSource, + binaryLoading: BinaryLoadingOptions = .init(), + label: String? = nil, + destination: ProductDestination = .output + ) { + self.source = source + self.binaryLoading = binaryLoading + self.label = label + self.destination = destination + } + + /// Produces the document, delivers its JSON, and returns it. + @discardableResult + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ObjCAPISnapshotDocument { + let document = try await ObjCAPISnapshotLoading.loadDocument( + from: source, + binaryLoading: binaryLoading, + label: label, + output: output, + environment: environment + ) + let encoded = try document.encoded() + switch destination { + case .output: + output.write(.data(encoded)) + case .file(let path): + try encoded.write(to: URL(fileURLWithPath: path), options: .atomic) + output.reportProgress("Snapshot written to \(path)") + } + return document + } +} + +/// `swift-section objc diff`: compare the ObjC API of two binaries, or of a +/// binary and a persisted baseline. +public struct ObjCAPIDiffRequest: Sendable, Equatable { + public enum Report: Sendable, Hashable { + /// The change list followed by the verdict line. + case changeList + /// The verdict line alone. It goes to the output even when the + /// destination is a file, as it always has on the command line. + case summary + /// The diff with provenance, as JSON. + case json + } + + public var old: SnapshotSource + public var new: SnapshotSource + public var binaryLoading: BinaryLoadingOptions + public var report: Report + public var destination: ProductDestination + + public init( + old: SnapshotSource, + new: SnapshotSource, + binaryLoading: BinaryLoadingOptions = .init(), + report: Report = .changeList, + destination: ProductDestination = .output + ) { + self.old = old + self.new = new + self.binaryLoading = binaryLoading + self.report = report + self.destination = destination + } + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ObjCAPIDiffOutcome { + let oldDocument = try await ObjCAPISnapshotLoading.loadDocument(from: old, binaryLoading: binaryLoading, label: nil, output: output, environment: environment) + let newDocument = try await ObjCAPISnapshotLoading.loadDocument(from: new, binaryLoading: binaryLoading, label: nil, output: output, environment: environment) + + output.reportProgress("Diffing…") + let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) + + let verdict = "API-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" + switch report { + case .json: + let encoded = String(decoding: try ObjCAPIJSON.encoder().encode(diff), as: UTF8.self) + try destination.deliver(encoded, to: output, announcingFileWith: { "Report written to \($0)" }) + case .summary: + output.write(.text(verdict)) + case .changeList: + try destination.deliver(ObjCAPIDiffReporter().report(diff) + "\n\n" + verdict, to: output, announcingFileWith: { "Report written to \($0)" }) + } + return ObjCAPIDiffOutcome(diff: diff) + } +} + +public struct ObjCAPIDiffOutcome: Sendable { + public var diff: ObjCAPIDiff + + public init(diff: ObjCAPIDiff) { + self.diff = diff + } + + public var hasBreakingChange: Bool { + diff.hasBreakingChange + } +} + +/// `swift-section objc evolution`: track the ObjC API of one binary across an +/// ordered series of versions. +public struct ObjCAPIEvolutionRequest: Sendable, Equatable { + public enum Report: Sendable, Hashable { + /// The full lineage report. + case lineage + /// The header and the per-transition summary. + case summary + /// The evolution as JSON. + case json + } + + /// The inputs in version order, oldest first. They are loaded one after + /// the other. + public var inputs: [SnapshotSource] + /// One label per input for the version axis. `nil` falls back to each + /// snapshot's stored label, then to the file name. + public var labels: [String]? + public var binaryLoading: BinaryLoadingOptions + public var report: Report + public var destination: ProductDestination + + public init( + inputs: [SnapshotSource], + labels: [String]? = nil, + binaryLoading: BinaryLoadingOptions = .init(), + report: Report = .lineage, + destination: ProductDestination = .output + ) { + self.inputs = inputs + self.labels = labels + self.binaryLoading = binaryLoading + self.report = report + self.destination = destination + } + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ObjCAPIEvolutionOutcome { + if let labels, labels.count != inputs.count { + throw ObjCAPIEvolutionError.labelCountMismatch(labelCount: labels.count, versionCount: inputs.count) + } + + var documents: [ObjCAPISnapshotDocument] = [] + for (inputIndex, input) in inputs.enumerated() { + documents.append(try await ObjCAPISnapshotLoading.loadDocument( + from: input, + binaryLoading: binaryLoading, + label: labels?[inputIndex], + output: output, + environment: environment + )) + } + + // A snapshot input may already carry a provenance label; a binary + // falls back to its file name, so that the axis is always readable. + let resolvedLabels = documents.enumerated().map { inputIndex, document in + document.provenance?.label ?? inputs[inputIndex].defaultLabel + } + + output.reportProgress("Tracking evolution…") + let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents, labels: resolvedLabels) + + let reportText: String = switch report { + case .json: + String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self) + case .summary: + ObjCAPIEvolutionReporter().summary(evolution) + case .lineage: + ObjCAPIEvolutionReporter().report(evolution) + } + try destination.deliver( + destination == .output ? reportText : reportText + "\n", + to: output, + announcingFileWith: { "Report written to \($0)" } + ) + return ObjCAPIEvolutionOutcome(evolution: evolution) + } +} + +public struct ObjCAPIEvolutionOutcome: Sendable { + public var evolution: ObjCAPIEvolution + + public init(evolution: ObjCAPIEvolution) { + self.evolution = evolution + } + + public var hasBreakingChange: Bool { + evolution.hasBreakingChange + } +} + +/// The ObjC counterpart of `ABISnapshotLoading`. +enum ObjCAPISnapshotLoading { + /// Loads `source` as a snapshot document. `label` overrides the + /// document's provenance label either way. + static func loadDocument( + from source: SnapshotSource, + binaryLoading: BinaryLoadingOptions, + label: String?, + output: some SwiftSectionOutput, + environment: SwiftSectionEnvironment + ) async throws -> ObjCAPISnapshotDocument { + if try source.isSnapshotDocument() { + output.reportProgress("Reading snapshot \(source.path)…") + var document = try ObjCAPISnapshotDocument.decode(from: Data(contentsOf: URL(fileURLWithPath: source.path))) + if let label { + var provenance = document.provenance ?? ObjCAPIProvenance() + provenance.label = label + document.provenance = provenance + } + return document + } + + output.reportProgress("Indexing \(source.path)…") + let machOFile = try binaryLoading.machOSource(forBinaryAt: source.path).load() + let indexer = ObjCInterfaceIndexer(machO: machOFile, imagePath: machOFile.imagePath) + try await indexer.prepare() + let snapshotBuilder = ObjCAPISnapshotBuilder(indexer: indexer) + let provenance = ObjCAPIProvenance( + label: label, + binaryPath: source.path + binaryLoading.provenancePathSuffix, + generatorVersion: environment.generator.version, + createdAt: environment.currentDate() + ) + return ObjCAPISnapshotDocument(provenance: provenance, snapshot: snapshotBuilder.snapshot()) + } +} diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCDumpRequest.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCDumpRequest.swift new file mode 100644 index 000000000..6e199e1c7 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCDumpRequest.swift @@ -0,0 +1,163 @@ +import Foundation +import MachOKit +import ObjCDeclarationRendering +import ObjCOutputTransformer +import OutputTransformer +import Semantic + +/// `swift-section objc dump`: print every Objective-C declaration in a binary. +public struct ObjCDumpRequest: Sendable, Equatable { + public var source: MachOSource + /// The kinds to print, in this order; `nil` prints all of them. Only kinds + /// named here are reported when empty — otherwise every dump of a + /// pure-Swift binary would note the kinds nobody asked for. + public var kinds: [ObjCDeclarationKind]? + /// Only declarations whose name contains this text, case-insensitively. + public var nameFilter: String? + public var generation: ObjCGenerationOptions + /// Other spellings for C primitive types (`double` → `CGFloat`). + public var cTypeReplacements: [ObjCPrimitiveTypePattern: String] + /// A custom ivar-offset comment. Giving one turns ivar offset comments on. + public var ivarOffsetComment: Transformer.ObjCIvarOffset? + /// Whether indexing progress is reported as diagnostics. + public var reportsIndexingProgress: Bool + /// How the diagnostics name the image; `nil` derives it from `source`. + public var imageDescription: String? + public var destination: ProductDestination + + public init( + source: MachOSource, + kinds: [ObjCDeclarationKind]? = nil, + nameFilter: String? = nil, + generation: ObjCGenerationOptions = .init(), + cTypeReplacements: [ObjCPrimitiveTypePattern: String] = [:], + ivarOffsetComment: Transformer.ObjCIvarOffset? = nil, + reportsIndexingProgress: Bool = false, + imageDescription: String? = nil, + destination: ProductDestination = .output + ) { + self.source = source + self.kinds = kinds + self.nameFilter = nameFilter + self.generation = generation + self.cTypeReplacements = cTypeReplacements + self.ivarOffsetComment = ivarOffsetComment + self.reportsIndexingProgress = reportsIndexingProgress + self.imageDescription = imageDescription + self.destination = destination + } + + /// Prints the declarations, then notes why the dump came out empty, if it + /// did. + @discardableResult + public func run(output: some SwiftSectionOutput) async throws -> Outcome { + let session = try await ObjCInterfaceSession.make( + source: source, + generation: generation, + cTypeReplacements: cTypeReplacements, + ivarOffsetComment: ivarOffsetComment, + reportsIndexingProgress: reportsIndexingProgress, + output: output + ) + + var nameCountByKind: [ObjCDeclarationKind: Int] = [:] + var emittedCount = 0 + var dumpedText = "" + + for kind in kinds ?? ObjCDeclarationKind.allCases { + let names = session.names(of: kind) + nameCountByKind[kind] = names.count + for name in names where matchesFilter(name) { + guard let interface = session.interface(of: kind, named: name) else { continue } + switch destination { + case .output: + output.write(.declarations(interface), declaring: .objc(kind, name: name)) + output.write(.text("")) + case .file: + dumpedText.append(interface.string) + dumpedText.append("\n\n") + } + emittedCount += 1 + } + } + + if case .file(let path) = destination { + try dumpedText.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + } + + // `session.isEmpty` walks every kind, so it is only consulted once the + // requested ones have already come back empty. + let isEntireIndexEmpty = nameCountByKind.values.allSatisfy { $0 == 0 } && session.isEmpty + let outcome = Outcome( + imageDescription: imageDescription ?? source.imageDescription, + explicitKinds: kinds, + nameCountByKind: nameCountByKind, + isEntireIndexEmpty: isEntireIndexEmpty, + filter: nameFilter, + emittedCount: emittedCount + ) + for note in Self.diagnosticNotes(for: outcome) { + output.reportNote(note) + } + return outcome + } + + /// What one dump actually found, as far as its diagnostics care. + public struct Outcome: Sendable, Equatable { + public var imageDescription: String + /// The kinds the request named, or `nil` when every kind was dumped by + /// default. + public var explicitKinds: [ObjCDeclarationKind]? + public var nameCountByKind: [ObjCDeclarationKind: Int] + public var isEntireIndexEmpty: Bool + public var filter: String? + public var emittedCount: Int + + public init( + imageDescription: String, + explicitKinds: [ObjCDeclarationKind]?, + nameCountByKind: [ObjCDeclarationKind: Int], + isEntireIndexEmpty: Bool, + filter: String?, + emittedCount: Int + ) { + self.imageDescription = imageDescription + self.explicitKinds = explicitKinds + self.nameCountByKind = nameCountByKind + self.isEntireIndexEmpty = isEntireIndexEmpty + self.filter = filter + self.emittedCount = emittedCount + } + } + + /// Why a dump produced nothing, in the caller's terms. + /// + /// Without these, three unrelated situations look the same — no product, + /// no diagnostic — and a binary that carries no Objective-C cannot be told + /// from one whose metadata failed to read. Pure, so that the wording can + /// be tested without running a dump. + public static func diagnosticNotes(for outcome: Outcome) -> [String] { + // Subsumes the per-kind notes: reporting each requested kind as empty + // would just be five ways of saying the same thing. + if outcome.isEntireIndexEmpty { + return ["no Objective-C metadata found in \(outcome.imageDescription)"] + } + + var notes: [String] = [] + for kind in outcome.explicitKinds ?? [] where outcome.nameCountByKind[kind, default: 0] == 0 { + notes.append("no \(kind.rawValue) found in \(outcome.imageDescription)") + } + + let totalNameCount = outcome.nameCountByKind.values.reduce(0, +) + if let filter = outcome.filter, !filter.isEmpty, outcome.emittedCount == 0, totalNameCount > 0 { + let declarationNoun = totalNameCount == 1 ? "declaration" : "declarations" + notes.append("--filter '\(filter)' matched none of the \(totalNameCount) \(declarationNoun) in \(outcome.imageDescription)") + } + return notes + } + + private func matchesFilter(_ name: String) -> Bool { + guard let nameFilter, !nameFilter.isEmpty else { return true } + return name.range(of: nameFilter, options: .caseInsensitive) != nil + } +} diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift new file mode 100644 index 000000000..f0637f9fc --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceRequest.swift @@ -0,0 +1,82 @@ +import Foundation +import ObjCDeclarationRendering +import ObjCOutputTransformer +import OutputTransformer + +/// `swift-section objc interface`: print the interface of one Objective-C +/// declaration. +public struct ObjCInterfaceRequest: Sendable, Equatable { + /// A class name (`NSString`), a protocol name (`NSCopying`), a category's + /// unique name in `ClassName(CategoryName)` form, or a struct or union + /// name. + public var declarationName: String + /// Only look among declarations of this kind; `nil` searches every kind, + /// in ``ObjCDeclarationKind`` order. Binaries do reuse a name across a + /// class, a protocol and a struct, and this is how a caller settles it. + public var kind: ObjCDeclarationKind? + public var source: MachOSource + public var generation: ObjCGenerationOptions + public var cTypeReplacements: [ObjCPrimitiveTypePattern: String] + /// A custom ivar-offset comment. Giving one turns ivar offset comments on. + public var ivarOffsetComment: Transformer.ObjCIvarOffset? + public var reportsIndexingProgress: Bool + public var destination: ProductDestination + + public init( + declarationName: String, + kind: ObjCDeclarationKind? = nil, + source: MachOSource, + generation: ObjCGenerationOptions = .init(), + cTypeReplacements: [ObjCPrimitiveTypePattern: String] = [:], + ivarOffsetComment: Transformer.ObjCIvarOffset? = nil, + reportsIndexingProgress: Bool = false, + destination: ProductDestination = .output + ) { + self.declarationName = declarationName + self.kind = kind + self.source = source + self.generation = generation + self.cTypeReplacements = cTypeReplacements + self.ivarOffsetComment = ivarOffsetComment + self.reportsIndexingProgress = reportsIndexingProgress + self.destination = destination + } + + public func run(output: some SwiftSectionOutput) async throws { + let session = try await ObjCInterfaceSession.make( + source: source, + generation: generation, + cTypeReplacements: cTypeReplacements, + ivarOffsetComment: ivarOffsetComment, + reportsIndexingProgress: reportsIndexingProgress, + output: output + ) + + // Searched in declaration-kind order rather than by guessing from the + // spelling: `Foo(Bar)` is unambiguous, but a bare name could be a + // class, a protocol or a struct. + for candidateKind in kind.map({ [$0] }) ?? ObjCDeclarationKind.allCases { + guard let interface = session.interface(of: candidateKind, named: declarationName) else { 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 { + case declarationNotFound(String) + + public var errorDescription: String? { + switch self { + case .declarationNotFound(let name): + "No class, protocol, category, struct or union named '\(name)' in this binary." + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift new file mode 100644 index 000000000..4355c2dcd --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/ObjC/ObjCInterfaceSession.swift @@ -0,0 +1,180 @@ +import Foundation +import MachOKit +import MachOKitExtensions +import ObjCDeclarationRendering +import ObjCIndexing +import ObjCInterface +import ObjCMetadataSource +import ObjCOutputTransformer +import OutputTransformer +import Semantic + +/// 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. +/// +/// The raw values are the names the command line spells them by. +public enum ObjCDeclarationKind: String, CaseIterable, Sendable, Hashable { + case classes + case protocols + case categories + case structs + case unions +} + +/// Everything `objc dump` and `objc interface` need once the request is known: +/// the loaded binary, a prepared index over it, and the builder plus the +/// per-request rendering arguments every interface call takes. +/// +/// Both requests do exactly the same setup, and getting it wrong in one of +/// them would show up as a silent difference in output rather than as an +/// error, so it lives in one place. +struct ObjCInterfaceSession { + let machOFile: MachOFile + let indexer: ObjCInterfaceIndexer + let builder: ObjCInterfaceBuilder + + private let options: ObjCGenerationOptions + private let cTypeReplacements: [ObjCPrimitiveTypePattern: String] + private let ivarOffsetCommentBuilder: (@Sendable (Int) -> String)? + + static func make( + source: MachOSource, + generation: ObjCGenerationOptions, + cTypeReplacements: [ObjCPrimitiveTypePattern: String], + ivarOffsetComment: Transformer.ObjCIvarOffset?, + reportsIndexingProgress: Bool, + output: some SwiftSectionOutput + ) async throws -> ObjCInterfaceSession { + let machOFile = try source.load() + + // The handler is bound at `init`, not at `prepare()`: events are + // delivered during the walk and nothing is retained afterwards, so + // there is no way to attach one later and recover them. + let eventHandler: (@Sendable (ObjCIndexingEvent) -> Void)? = reportsIndexingProgress + ? { @Sendable event in reportProgress(event, to: output) } + : nil + let indexer = ObjCInterfaceIndexer( + machO: machOFile, + imagePath: machOFile.imagePath, + eventHandler: eventHandler + ) + try await indexer.prepare() + + var options = generation + var ivarOffsetCommentBuilder: (@Sendable (Int) -> String)? + if let ivarOffsetComment { + ivarOffsetCommentBuilder = { offset in ivarOffsetComment.transform(.init(offset: offset)) } + // A custom ivar-offset wording on its own would otherwise be + // silently inert. + options.addIvarOffsetComments = true + } + + return ObjCInterfaceSession( + machOFile: machOFile, + indexer: indexer, + builder: ObjCInterfaceBuilder(indexer: indexer, machO: machOFile), + options: options, + cTypeReplacements: cTypeReplacements, + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ) + } + + // MARK: - Rendering + + func interface(of kind: ObjCDeclarationKind, named name: String) -> SemanticString? { + switch kind { + case .classes: + builder.classInterface( + named: name, + options: options, + cTypeReplacements: cTypeReplacements, + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ) + case .protocols: + builder.protocolInterface( + named: name, + options: options, + cTypeReplacements: cTypeReplacements, + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ) + case .categories: + builder.categoryInterface( + uniqueName: name, + options: options, + cTypeReplacements: cTypeReplacements, + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ) + case .structs: + builder.structInterface( + named: name, + options: options, + cTypeReplacements: cTypeReplacements, + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ) + case .unions: + builder.unionInterface( + named: name, + options: options, + cTypeReplacements: cTypeReplacements, + ivarOffsetCommentBuilder: ivarOffsetCommentBuilder + ) + } + } + + /// The declaration names of `kind`, sorted, so that two runs over the same + /// binary print the same thing. The index stores them in dictionaries, + /// whose iteration order is not stable across runs. + func names(of kind: ObjCDeclarationKind) -> [String] { + switch kind { + case .classes: indexer.classNames.sorted() + case .protocols: indexer.protocolNames.sorted() + case .categories: indexer.categoryNames.sorted() + case .structs: indexer.structNames.sorted() + case .unions: indexer.unionNames.sorted() + } + } + + /// Whether the index holds no declaration at all, of any kind. This is + /// what separates "this binary carries no Objective-C metadata" from "the + /// kinds asked for happen to be empty in it" — the two are otherwise + /// indistinguishable from an empty dump. + var isEmpty: Bool { + ObjCDeclarationKind.allCases.allSatisfy { names(of: $0).isEmpty } + } + + // MARK: - Progress + + private static func reportProgress(_ event: ObjCIndexingEvent, to output: some SwiftSectionOutput) { + guard case .progress(let phase, let itemDescription, let currentCount, let totalCount) = event else { + return + } + let phaseDescription = + switch phase { + case .indexingSubclasses: "Indexing subclasses" + case .indexingConformances: "Indexing conformances" + case .loadingClasses: "Loading classes" + case .loadingProtocols: "Loading protocols" + case .loadingCategories: "Loading categories" + } + var line = "\(phaseDescription) \(currentCount)/\(totalCount)" + if !itemDescription.isEmpty { + line += " \(itemDescription)" + } + output.reportProgress(line) + } +} + +extension MachOSource { + /// How a diagnostic names the image when the caller did not say: the + /// cache image's name or path, or the file's path. + var imageDescription: String { + switch self { + case .file(let path, _): + path + case .dyldSharedCache(_, .name(let name)), .systemDyldSharedCache(.name(let name)): + name + case .dyldSharedCache(_, .path(let path)), .systemDyldSharedCache(.path(let path)): + path + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/Output/DumpedDeclaration.swift b/Sources/Commands/SwiftSectionKit/Output/DumpedDeclaration.swift new file mode 100644 index 000000000..c610672db --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Output/DumpedDeclaration.swift @@ -0,0 +1,20 @@ +/// What one top-level piece of a `dump` or `objc dump` product declares. +/// +/// Handed to ``SwiftSectionOutput/write(_:declaring:)`` beside the piece, so +/// that a host can file each declaration on its own — one file per type, say — +/// without indexing the binary a second time. +/// +/// Built by the requests, not by a host: a later version may add a case, so do +/// not rely on switching over it exhaustively. +public enum DumpedDeclaration: Sendable, Hashable { + /// A Swift declaration from `section`, named as the dump prints it. A + /// protocol conformance and an associated type are named after the type + /// they extend, as their `extension` line spells it — for a type the image + /// declares, that type's own name, so the pieces of one type share it. + /// `nil` when the name could not be rendered although the declaration + /// itself was. + case swift(DumpSection, name: String?) + /// An Objective-C declaration of `kind`. A category is named + /// `ClassName(CategoryName)`, as the index names it. + case objc(ObjCDeclarationKind, name: String) +} diff --git a/Sources/Commands/SwiftSectionKit/Output/ProductDestination.swift b/Sources/Commands/SwiftSectionKit/Output/ProductDestination.swift new file mode 100644 index 000000000..80db98fc8 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Output/ProductDestination.swift @@ -0,0 +1,37 @@ +import Foundation + +/// Where a request's product goes. +public enum ProductDestination: Sendable, Hashable { + /// To the request's ``SwiftSectionOutput``, one piece at a time. + case output + /// Into the file at `path`, written once the product is complete. The + /// output then receives diagnostics only. + /// + /// A path rather than a `URL` because the diagnostics that announce the + /// write repeat it exactly as the caller spelled it; a `URL` normalizes a + /// trailing slash away and expands a tilde. + case file(path: String) +} + +extension ProductDestination { + /// Writes `text` to the file, or hands it to `output` as one piece. + /// + /// The two differ by a trailing newline — the output's pieces are printed + /// with one, the file gets `text` as is — which is how every command has + /// written its reports, kept byte for byte. + func deliver( + _ text: String, + to output: some SwiftSectionOutput, + announcingFileWith fileWrittenMessage: ((String) -> String)? = nil + ) throws { + switch self { + case .output: + output.write(.text(text)) + case .file(let path): + try text.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + if let fileWrittenMessage { + output.reportProgress(fileWrittenMessage(path)) + } + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionDiagnostic.swift b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionDiagnostic.swift new file mode 100644 index 000000000..4fb762175 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionDiagnostic.swift @@ -0,0 +1,28 @@ +/// Something a request says about its own progress, as opposed to the +/// product it produces. +/// +/// `message` is the line exactly as `swift-section` prints it, so a host that +/// shows diagnostics shows the same words the command line does. Some of +/// those words name command-line options — they were written for the command +/// line first. +public struct SwiftSectionDiagnostic: Sendable, Hashable { + public enum Severity: Sendable, Hashable, CaseIterable { + /// A step is starting or has finished ("Indexing old binary…"). + case progress + /// The request goes on, but with less than was asked for. + case warning + /// A fact about the result worth knowing ("no classes found in …"). + case note + /// One declaration could not be produced; the rest of the product + /// still is. + case error + } + + public var severity: Severity + public var message: String + + public init(severity: Severity, message: String) { + self.severity = severity + self.message = message + } +} diff --git a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionOutput.swift b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionOutput.swift new file mode 100644 index 000000000..bf0f10a1f --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionOutput.swift @@ -0,0 +1,66 @@ +import Foundation +import SwiftDeclaration + +/// Where a request's output goes. `swift-section` writes it to stdout and +/// stderr; a test records it. +/// +/// Three channels, kept apart so that a host never has to pick a product out +/// of a stream of progress lines: the product itself, the diagnostics about +/// producing it, and the handlers that hear about indexing degradations. +/// +/// A request that indexes several inputs side by side (`diff`, `evolution`) +/// calls this from several tasks at once, so an implementation must be safe to +/// call concurrently. +public protocol SwiftSectionOutput: Sendable { + /// One piece of the product, in order. Printed, every piece is followed by + /// a newline. + func write(_ product: SwiftSectionProduct) + + /// One top-level declaration of a `dump` or `objc dump`, with what it + /// declares; it takes that piece's place in the order of ``write(_:)``. + /// A request writing to a file hands no piece over, so this is not called + /// then either. + /// + /// The default hands `product` to ``write(_:)`` and drops `declaration`, + /// so an output that only prints is unaffected. + func write(_ product: SwiftSectionProduct, declaring declaration: DumpedDeclaration) + + /// A progress line, warning, note or per-declaration error. + func report(_ diagnostic: SwiftSectionDiagnostic) + + /// The indexing-event handlers for one indexed input. `label` names the + /// input when a request indexes several ("old", "new", a version label), + /// and is `nil` for a single-input request. + func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] +} + +extension SwiftSectionOutput { + /// The piece alone, as any other. + public func write(_ product: SwiftSectionProduct, declaring declaration: DumpedDeclaration) { + write(product) + } + + /// No handler: indexing degradations fall to `SwiftIndexEvents.Dispatcher`'s + /// os_log floor. + public func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] { + [] + } +} + +extension SwiftSectionOutput { + func reportProgress(_ message: String) { + report(SwiftSectionDiagnostic(severity: .progress, message: message)) + } + + func reportWarning(_ message: String) { + report(SwiftSectionDiagnostic(severity: .warning, message: message)) + } + + func reportNote(_ message: String) { + report(SwiftSectionDiagnostic(severity: .note, message: message)) + } + + func reportError(_ message: String) { + report(SwiftSectionDiagnostic(severity: .error, message: message)) + } +} diff --git a/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift new file mode 100644 index 000000000..6de8cf911 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Output/SwiftSectionProduct.swift @@ -0,0 +1,94 @@ +import Foundation +import Semantic + +/// One piece of what a request produces. +/// +/// Printed, every piece is followed by a newline — the one `print` adds, and +/// the one a snapshot's JSON has always been followed by. A host that collects +/// the pieces into a file reproduces `swift-section`'s stdout by doing the same. +public enum SwiftSectionProduct: Sendable { + /// Rendered declarations (`dump`, `interface`, `objc dump`, + /// `objc interface`), carrying the semantic types a terminal colors by. + case declarations(SemanticString) + /// Plain text: a report, JSON, a listing line. + case text(String) + /// An annotated interface, whose lines a terminal colors by their + /// annotation; ``InterfaceAnnotationStyle/lineKinds(of:)`` tells how. + case annotatedInterface(String, style: InterfaceAnnotationStyle) + /// Raw bytes: a snapshot document's JSON. + case data(Data) +} + +/// Which annotations an annotated interface carries. +public enum InterfaceAnnotationStyle: Sendable, Hashable { + /// `diff --interface`: `+` / `-` line prefixes. A unified diff also has two + /// file-header lines and `@@` hunk headers. + case diff(isUnifiedDiff: Bool) + /// `evolution --interface`: trailing `// [...]` lifecycle annotations, and + /// legend and warning comments at column 0. + case evolution +} + +/// What one line of an annotated interface reads as. +public enum AnnotatedLineKind: Sendable, Hashable { + case added + case removed + case modified + /// A unified diff's file and hunk headers; an evolution interface's legend + /// and warnings. + case header + case plain +} + +extension InterfaceAnnotationStyle { + /// The rule `swift-section` colors an annotated interface by, public so + /// that every host colors alike: one kind per line of `text`, split on + /// "\n" with empty lines kept. + public func lineKinds(of text: String) -> [AnnotatedLineKind] { + text.split(separator: "\n", omittingEmptySubsequences: false).enumerated().map { lineIndex, line in + lineKind(of: line, at: lineIndex) + } + } + + private func lineKind(of line: Substring, at lineIndex: Int) -> AnnotatedLineKind { + switch self { + case .diff(let isUnifiedDiff): + // In a unified diff the first two lines are the `--- old` / + // `+++ new` file headers and `@@ … @@` lines are hunk headers. + // They are told apart by position and prefix, so that an added or + // removed content line that happens to begin with `++` or `--` is + // never mistaken for a file header. + if isUnifiedDiff, lineIndex < 2 { + return .header + } else if isUnifiedDiff, line.hasPrefix("@@") { + return .header + } else if line.hasPrefix("+") { + return .added + } else if line.hasPrefix("-") { + return .removed + } else { + return .plain + } + case .evolution: + if line.hasPrefix("//") { + // The legend and warnings blocks sit at column 0. + return .header + } else if let annotationRange = line.range(of: "// [") { + // 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. + let annotation = line[annotationRange.lowerBound...] + if annotation.contains("removed in") { + return .removed + } else if annotation.contains("modified in") { + return .modified + } else { + return .added + } + } else { + return .plain + } + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift new file mode 100644 index 000000000..c377c9a0b --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIDiffRequest.swift @@ -0,0 +1,177 @@ +import Foundation +import MachOKit +import MachOFoundation +import SwiftDiffing +import SwiftIndexing +import SwiftInterface +import Utilities + +/// `swift-section diff`: compare the Swift ABI of two binaries, or of a binary +/// and a persisted baseline. +public struct ABIDiffRequest: Sendable, Equatable { + public enum Report: Sendable, Hashable { + /// The change list followed by the verdict line. + case changeList + /// The verdict line alone. It goes to the output even when the + /// destination is a file, as it always has on the command line. + case summary + /// The diff with provenance, as JSON. + case json + /// The full interface annotated with diff markers. Both sides must be + /// binaries: a snapshot document carries no renderable interface. With + /// `includesBreakingChangeVerdict`, the outcome also says whether the + /// diff breaks the ABI, at the cost of a change-list diff on top. + case annotatedInterface(format: AnnotatedDiffFormat, includesBreakingChangeVerdict: Bool) + } + + public var old: SnapshotSource + public var new: SnapshotSource + public var binaryLoading: BinaryLoadingOptions + public var report: Report + public var destination: ProductDestination + /// How many inputs index at once: `nil` is the processor count, and `1` + /// indexes the old side before the new one. Values below 1 count as 1. + public var maximumConcurrentPreparations: Int? + + public init( + old: SnapshotSource, + new: SnapshotSource, + binaryLoading: BinaryLoadingOptions = .init(), + report: Report = .changeList, + destination: ProductDestination = .output, + maximumConcurrentPreparations: Int? = nil + ) { + self.old = old + self.new = new + self.binaryLoading = binaryLoading + self.report = report + self.destination = destination + self.maximumConcurrentPreparations = maximumConcurrentPreparations + } + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ABIDiffOutcome { + let concurrencyWindow = maximumConcurrentPreparations ?? ProcessInfo.processInfo.activeProcessorCount + switch report { + case .annotatedInterface(let format, let includesBreakingChangeVerdict): + return try await runAnnotatedInterface( + format: format, + includesBreakingChangeVerdict: includesBreakingChangeVerdict, + concurrencyWindow: concurrencyWindow, + output: output + ) + case .changeList, .summary, .json: + return try await runChangeList(concurrencyWindow: concurrencyWindow, output: output, environment: environment) + } + } + + private func runAnnotatedInterface( + format: AnnotatedDiffFormat, + includesBreakingChangeVerdict: Bool, + concurrencyWindow: Int, + output: some SwiftSectionOutput + ) async throws -> ABIDiffOutcome { + try SnapshotSource.requireBinaries([old, new]) + + let oldMachOFile = try binaryLoading.machOSource(forBinaryAt: old.path).load() + let newMachOFile = try binaryLoading.machOSource(forBinaryAt: new.path).load() + + // The renderer hands each builder's dispatcher to its printers, so the + // handlers are what puts a dropped declaration in front of the host + // instead of on `Dispatcher`'s os_log floor. + let oldBuilder = SwiftDiffableInterfaceBuilder(eventHandlers: output.indexEventHandlers(forInputLabeled: "old"), in: oldMachOFile) + let newBuilder = SwiftDiffableInterfaceBuilder(eventHandlers: output.indexEventHandlers(forInputLabeled: "new"), in: newMachOFile) + // Old side first in the window, so a window of 1 is the historical + // order; a wider one indexes the two side by side. + output.reportProgress(concurrencyWindow > 1 ? "Indexing old and new binaries…" : "Indexing old binary, then new binary…") + _ = try await [oldBuilder, newBuilder].concurrentMap(maximumConcurrency: concurrencyWindow) { builder in + try await builder.prepare() + } + + let diff = includesBreakingChangeVerdict + ? ABIDiffer().diff(old: oldBuilder.abiModule(), new: newBuilder.abiModule()) + : nil + + output.reportProgress("Rendering annotated interface…") + let renderer = SwiftDiffableInterfaceRenderer(old: oldBuilder, new: newBuilder) + let diffFormat: DiffFormat = switch format { + case .inline: + .inline + case .unified: + .unified(oldLabel: old.path, newLabel: new.path) + case .markdownFenced: + .markdownFenced + } + let annotated = await renderer.printAnnotatedInterface(format: diffFormat) + + switch destination { + case .output: + output.write(.annotatedInterface(annotated.string, style: .diff(isUnifiedDiff: format == .unified))) + case .file(let path): + try annotated.string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + output.reportProgress("Annotated interface written to \(path)") + } + return ABIDiffOutcome(diff: diff) + } + + private func runChangeList( + concurrencyWindow: Int, + output: some SwiftSectionOutput, + environment: SwiftSectionEnvironment + ) async throws -> ABIDiffOutcome { + // Snapshot-based either way: each side is a binary, indexed and frozen + // here, or a persisted baseline, decoded with its format version + // validated. + let sides: [(source: SnapshotSource, label: String)] = [(old, "old"), (new, "new")] + let documents = try await sides.concurrentMap(maximumConcurrency: concurrencyWindow) { side in + try await ABISnapshotLoading.loadDocument( + from: side.source, + binaryLoading: binaryLoading, + label: nil, + indexingLabel: side.label, + output: output, + environment: environment + ) + } + + output.reportProgress("Diffing…") + let diff = ABIDiffer().diff(old: documents[0], new: documents[1]) + + let verdict = "ABI-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" + switch report { + case .json: + let encoded = String(decoding: try ABIJSON.encoder().encode(diff), as: UTF8.self) + try destination.deliver(encoded, to: output, announcingFileWith: { "Report written to \($0)" }) + case .summary: + output.write(.text(verdict)) + case .changeList, .annotatedInterface: + try destination.deliver(ABIDiffReporter().report(diff) + "\n\n" + verdict, to: output, announcingFileWith: { "Report written to \($0)" }) + } + return ABIDiffOutcome(diff: diff) + } +} + +/// How `diff --interface` marks the lines that changed. +public enum AnnotatedDiffFormat: Sendable, Hashable { + /// git-diff-style `+` / `-` / ` ` line prefixes. + case inline + /// A real unified diff (`--- old` / `+++ new` and `@@` hunks), consumable + /// by `git apply`, `patch` or `delta`. + case unified + /// The inline body wrapped in a Markdown ```` ```diff ```` fence. + case markdownFenced +} + +public struct ABIDiffOutcome: Sendable { + /// The change-list diff; `nil` only for an annotated interface requested + /// without the verdict. + public var diff: ABIDiff? + + public init(diff: ABIDiff?) { + self.diff = diff + } + + /// Whether the diff breaks the ABI; `nil` when it was not computed. + public var hasBreakingChange: Bool? { + diff?.hasBreakingChange + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift new file mode 100644 index 000000000..d940fa745 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/ABIEvolutionRequest.swift @@ -0,0 +1,259 @@ +import Foundation +import MachOKit +import MachOFoundation +import SwiftDiffing +import SwiftIndexing +import SwiftInterface +import Utilities + +/// `swift-section evolution`: track the Swift ABI of one module across an +/// ordered series of versions. +public struct ABIEvolutionRequest: Sendable, Equatable { + public enum Report: Sendable, Hashable { + /// The full lineage report. + case lineage + /// The header and the per-transition summary. + case summary + /// The evolution as JSON. + case json + /// The union interface annotated with per-declaration lifecycle + /// comments. Every input must be a binary. `availabilityAttributes` + /// says whether a lifecycle one attribute can express is also spelled + /// as that genuine `@available` attribute. + case annotatedInterface(availabilityAttributes: AvailabilityAttributes) + } + + /// Whether the annotated interface also spells lifecycles as genuine + /// `@available` attributes, and for which platform. + /// + /// A declaration gets the attribute line only when one attribute + /// 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 + /// `@available` can spell, or different ones, throw + /// ``AvailabilityPlatformInferenceError``. + case inferredPlatform + /// For this platform, spelled the way `@available` spells it: `iOS`, + /// `macOS`, `macCatalyst`. + case platform(String) + } + + /// The inputs in version order, oldest first. + public var inputs: [SnapshotSource] + /// One label per input for the version axis (`17.0`, `18.0`). `nil` + /// falls back to each snapshot's stored label, then to the file name. + public var labels: [String]? + public var binaryLoading: BinaryLoadingOptions + public var report: Report + public var destination: ProductDestination + /// How many inputs index at once: `nil` is the processor count, and `1` + /// indexes the versions one after the other, oldest first. Each input in + /// flight holds its indexed image in memory, which is what this trades + /// against. Values below 1 count as 1. + public var maximumConcurrentPreparations: Int? + + public init( + inputs: [SnapshotSource], + labels: [String]? = nil, + binaryLoading: BinaryLoadingOptions = .init(), + report: Report = .lineage, + destination: ProductDestination = .output, + maximumConcurrentPreparations: Int? = nil + ) { + self.inputs = inputs + self.labels = labels + self.binaryLoading = binaryLoading + self.report = report + self.destination = destination + self.maximumConcurrentPreparations = maximumConcurrentPreparations + } + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ABIEvolutionOutcome { + try ABISnapshotLoading.validateLabels(labels, inputCount: inputs.count) + let concurrencyWindow = maximumConcurrentPreparations ?? ProcessInfo.processInfo.activeProcessorCount + if case .annotatedInterface(let availabilityAttributes) = report { + return try await runAnnotatedInterface( + availabilityAttributes: availabilityAttributes, + concurrencyWindow: concurrencyWindow, + output: output + ) + } + + let explicitLabels = labels + let documents = try await Array(inputs.enumerated()).concurrentMap(maximumConcurrency: concurrencyWindow) { inputIndex, input in + try await ABISnapshotLoading.loadDocument( + from: input, + binaryLoading: binaryLoading, + label: explicitLabels?[inputIndex], + output: output, + environment: environment + ) + } + + // A snapshot input may already carry a provenance label; a binary + // falls back to its file name, so that the axis is always readable. + let resolvedLabels = documents.enumerated().map { inputIndex, document in + document.provenance?.label ?? inputs[inputIndex].defaultLabel + } + + output.reportProgress("Tracking evolution…") + let evolution = try ABIEvolutionBuilder().evolution(of: documents, labels: resolvedLabels) + + let reportText: String = switch report { + case .json: + String(decoding: try ABIJSON.encoder().encode(evolution), as: UTF8.self) + case .summary: + ABIEvolutionReporter().summary(evolution) + case .lineage, .annotatedInterface: + ABIEvolutionReporter().report(evolution) + } + // Unlike `diff`, the file gets the trailing newline too, so that the + // two destinations hold the same bytes. + try destination.deliver( + destination == .output ? reportText : reportText + "\n", + to: output, + announcingFileWith: { "Report written to \($0)" } + ) + return ABIEvolutionOutcome(evolution: evolution) + } + + /// The union interface with lifecycle annotations, rendered from the live + /// models of every version — which is why snapshot inputs are rejected + /// (the same constraint as `diff`'s annotated interface). + private func runAnnotatedInterface( + availabilityAttributes: AvailabilityAttributes, + concurrencyWindow: Int, + output: some SwiftSectionOutput + ) async throws -> ABIEvolutionOutcome { + 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 availabilityAnnotationPlatform = try availabilityAttributes.platform( + forInputsAt: inputs.map(\.path), + loadedAs: machOFiles + ) + + // The erased builder, because the version count is a runtime value + // here; the pack-generic `SwiftEvolutionInterfaceBuilder`'s arity is + // fixed at compile time. Each version's handlers reach its indexer and + // its printer alike. + let builder = try AnySwiftEvolutionInterfaceBuilder( + eventHandlersPerVersion: { _, label in output.indexEventHandlers(forInputLabeled: label) }, + versions: machOFiles, + labels: resolvedLabels, + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) + output.reportProgress("Indexing \(machOFiles.count) versions (\(min(concurrencyWindow, machOFiles.count)) at a time)…") + try await builder.prepare(maximumConcurrentPreparations: concurrencyWindow) + output.reportProgress("Rendering annotated interface…") + let annotated = try await builder.printAnnotatedInterface() + + switch destination { + case .output: + output.write(.annotatedInterface(annotated.string, style: .evolution)) + case .file(let path): + try annotated.string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + output.reportProgress("Annotated interface written to \(path)") + } + return ABIEvolutionOutcome(evolution: builder.evolution) + } +} + +/// Why ``ABIEvolutionRequest/AvailabilityAttributes/inferredPlatform`` found +/// no one platform to spell the attributes for. Naming the platform with +/// ``ABIEvolutionRequest/AvailabilityAttributes/platform(_:)`` avoids both. +public enum AvailabilityPlatformInferenceError: Error, LocalizedError, Sendable, Equatable { + /// The binary at `path` has no `LC_BUILD_VERSION`, or names a platform + /// `@available` has no spelling for, such as DriverKit. + case noPlatform(path: String) + /// The inputs name different platforms, spelled the `@available` way and + /// sorted. + case conflictingPlatforms([String]) + + public var errorDescription: String? { + switch self { + case .noPlatform(let path): + "No @available platform can be inferred from '\(path)': it has no LC_BUILD_VERSION, or names a platform @available has no spelling for." + case .conflictingPlatforms(let platforms): + "The inputs name different @available platforms (\(platforms.joined(separator: ", ")))." + } + } +} + +extension ABIEvolutionRequest.AvailabilityAttributes { + /// The platform the attributes 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.availabilitySpelling(of: buildPlatform) else { + throw AvailabilityPlatformInferenceError.noPlatform(path: path) + } + platforms.insert(platform) + } + if platforms.count > 1 { + throw AvailabilityPlatformInferenceError.conflictingPlatforms(platforms.sorted()) + } + // No inputs at all is left to the builder, which needs two. + return platforms.first + } + } + + /// How `@available` spells a Mach-O build platform, `nil` for one it has + /// no name for (DriverKit, bridgeOS, …). A simulator shares its device's + /// availability domain. + static func availabilitySpelling(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" + default: + nil + } + } +} + +public struct ABIEvolutionOutcome: Sendable { + /// The lineage; `nil` only if an annotated interface was rendered without + /// one. + public var evolution: ABIEvolution? + + public init(evolution: ABIEvolution?) { + self.evolution = evolution + } + + /// Whether any transition breaks the ABI. + public var hasBreakingChange: Bool { + evolution?.hasBreakingChange ?? false + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABISnapshotLoading.swift b/Sources/Commands/SwiftSectionKit/Swift/ABISnapshotLoading.swift new file mode 100644 index 000000000..4c58a08f7 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/ABISnapshotLoading.swift @@ -0,0 +1,60 @@ +import Foundation +import MachOKit +import MachOFoundation +import SwiftDiffing +import SwiftIndexing +import SwiftInterface + +/// The input plumbing `snapshot`, `diff` and `evolution` share: a source is +/// either a persisted document, decoded, or a binary, indexed and frozen with +/// its provenance stamped. One implementation, so the three cannot drift in +/// how they sniff, load, index or stamp. +enum ABISnapshotLoading { + /// Loads `source` as a snapshot document. + /// + /// `label` overrides the document's provenance label either way. + /// `indexingLabel` names the input to its indexing-event handlers — + /// inputs index concurrently, so an unlabeled line could not be + /// attributed — and defaults to `label`, then to the input's file name. + static func loadDocument( + from source: SnapshotSource, + binaryLoading: BinaryLoadingOptions, + label: String?, + indexingLabel: String? = nil, + output: some SwiftSectionOutput, + environment: SwiftSectionEnvironment + ) async throws -> ABISnapshotDocument { + if try source.isSnapshotDocument() { + output.reportProgress("Reading snapshot \(source.path)…") + var document = try ABISnapshotDocument.decode(from: Data(contentsOf: URL(fileURLWithPath: source.path))) + if let label { + var provenance = document.provenance ?? ABIProvenance() + provenance.label = label + document.provenance = provenance + } + return document + } + + output.reportProgress("Indexing \(source.path)…") + let machOFile = try binaryLoading.machOSource(forBinaryAt: source.path).load() + let builder = SwiftDiffableInterfaceBuilder( + eventHandlers: output.indexEventHandlers(forInputLabeled: indexingLabel ?? label ?? source.defaultLabel), + in: machOFile + ) + try await builder.prepare() + let provenance = ABIProvenance( + label: label, + binaryPath: source.path + binaryLoading.provenancePathSuffix, + generatorVersion: environment.generator.version, + createdAt: environment.currentDate() + ) + return ABISnapshotDocument(provenance: provenance, snapshot: builder.snapshot()) + } + + /// One label per input, or none at all. + static func validateLabels(_ labels: [String]?, inputCount: Int) throws { + if let labels, labels.count != inputCount { + throw ABIEvolutionError.labelCountMismatch(labelCount: labels.count, versionCount: inputCount) + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/ABISnapshotRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/ABISnapshotRequest.swift new file mode 100644 index 000000000..56be6861c --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/ABISnapshotRequest.swift @@ -0,0 +1,54 @@ +import Foundation +import MachODependencies +import SwiftDiffing + +/// `swift-section snapshot`: index a binary's Swift ABI and persist it as a +/// baseline document — or relabel an existing document. +public struct ABISnapshotRequest: Sendable, Equatable { + public var source: SnapshotSource + public var binaryLoading: BinaryLoadingOptions + /// Where the images a standalone binary links are looked for when a type + /// must be read out of another image's accessor thunk. Named paths are + /// consulted first; empty infers them from where the binary sits. + public var dependencySearchPaths: [DependencySearchPath] + /// A human-readable version label stored in the provenance (`17.0`). + public var label: String? + public var destination: ProductDestination + + public init( + source: SnapshotSource, + binaryLoading: BinaryLoadingOptions = .init(), + dependencySearchPaths: [DependencySearchPath] = [], + label: String? = nil, + destination: ProductDestination = .output + ) { + self.source = source + self.binaryLoading = binaryLoading + self.dependencySearchPaths = dependencySearchPaths + self.label = label + self.destination = destination + } + + /// Produces the document, delivers its JSON, and returns it. + @discardableResult + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws -> ABISnapshotDocument { + let document = try await withAccessorThunkResolver(searchPaths: dependencySearchPaths) { + try await ABISnapshotLoading.loadDocument( + from: source, + binaryLoading: binaryLoading, + label: label, + output: output, + environment: environment + ) + } + let encoded = try document.encoded() + switch destination { + case .output: + output.write(.data(encoded)) + case .file(let path): + try encoded.write(to: URL(fileURLWithPath: path), options: .atomic) + output.reportProgress("Snapshot written to \(path)") + } + return document + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/CommentTransformerApplication.swift b/Sources/Commands/SwiftSectionKit/Swift/CommentTransformerApplication.swift new file mode 100644 index 000000000..100bb04b2 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/CommentTransformerApplication.swift @@ -0,0 +1,55 @@ +import OutputTransformer +import SwiftOutputTransformer +import SwiftDeclarationRendering +import SwiftPrinting + +extension Transformer.SwiftConfiguration { + /// The comment kinds the enabled modules render. A module is only reached + /// once its comment kind is emitted, so enabling one implies emitting it — + /// passing a template is enough to see its output. + package struct CommentFlags { + package var printFieldOffset = false + package var printVTableOffset = false + package var printMemberAddress = false + package var printTypeLayout = false + package var printEnumLayout = false + } + + package var commentFlagsForEnabledModules: CommentFlags { + .init( + printFieldOffset: swiftFieldOffset.isEnabled, + printVTableOffset: swiftVTableOffset.isEnabled, + printMemberAddress: swiftMemberAddress.isEnabled, + printTypeLayout: swiftTypeLayout.isEnabled, + printEnumLayout: swiftEnumLayout.isEnabled + ) + } +} + +extension DeclarationRenderConfiguration { + /// Applies `transformers` and turns on the comment kinds its enabled + /// modules render, leaving every already-requested comment kind on. + package mutating func applyTransformersEnablingCommentKinds(_ transformers: Transformer.SwiftConfiguration) { + let commentFlags = transformers.commentFlagsForEnabledModules + printFieldOffset = printFieldOffset || commentFlags.printFieldOffset + printVTableOffset = printVTableOffset || commentFlags.printVTableOffset + printMemberAddress = printMemberAddress || commentFlags.printMemberAddress + printTypeLayout = printTypeLayout || commentFlags.printTypeLayout + printEnumLayout = printEnumLayout || commentFlags.printEnumLayout + applyTransformers(transformers) + } +} + +extension SwiftDeclarationPrintConfiguration { + /// Applies `transformers` and turns on the comment kinds its enabled + /// modules render, leaving every already-requested comment kind on. + package mutating func applyTransformersEnablingCommentKinds(_ transformers: Transformer.SwiftConfiguration) { + let commentFlags = transformers.commentFlagsForEnabledModules + printFieldOffset = printFieldOffset || commentFlags.printFieldOffset + printVTableOffset = printVTableOffset || commentFlags.printVTableOffset + printMemberAddress = printMemberAddress || commentFlags.printMemberAddress + printTypeLayout = printTypeLayout || commentFlags.printTypeLayout + printEnumLayout = printEnumLayout || commentFlags.printEnumLayout + applyTransformers(transformers) + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/DependencySearchPathUsage.swift b/Sources/Commands/SwiftSectionKit/Swift/DependencySearchPathUsage.swift new file mode 100644 index 000000000..4c0c89034 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/DependencySearchPathUsage.swift @@ -0,0 +1,35 @@ +import MachODependencies +import SwiftDeclarationRendering + +/// Runs `operation` with `searchPaths` in force for every kind-9 accessor-thunk +/// rewrite it performs, or unchanged when none were named. The task-local is +/// the one injection point the rendering layer offers. +nonisolated(nonsending) func withAccessorThunkResolver( + searchPaths: [DependencySearchPath], + _ operation: nonisolated(nonsending) () async throws -> Result +) async rethrows -> Result { + guard !searchPaths.isEmpty else { return try await operation() } + return try await AccessorThunkResolution.$taskResolver.withValue( + DisassemblingAccessorThunkResolver(searchPaths: searchPaths), + operation: operation + ) +} + +extension Array where Element == DependencySearchPath { + /// How the static (offline) layout engine resolves cross-module types: the + /// named paths first, the running system's shared cache as the fallback, + /// so that a binary is laid out against the OS whose cache was named + /// rather than the host's. With no path named, the library default. + var staticLayoutDependencyResolution: StaticLayoutDependencyResolution { + guard !isEmpty else { return .default } + return .dependencyClosure(searchPaths: self + [.systemDyldSharedCache]) + } + + /// The same paths for the indexer's cross-image facts (a stored field + /// whose type is a property wrapper from another image; a class's ObjC + /// ancestors behind a bind): the named ones first, the running system's + /// cache as the fallback. + var indexingSearchPaths: [DependencySearchPath] { + self + [.systemDyldSharedCache] + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift new file mode 100644 index 000000000..a1c09ef7d --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/DumpRequest.swift @@ -0,0 +1,482 @@ +import Foundation +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDump +import Demangling +import SwiftInspection +import OutputTransformer +import SwiftOutputTransformer +import SwiftDeclarationRendering +import SwiftPrinting +import Semantic + +/// A part of a binary's Swift metadata that `dump` can print. +public enum DumpSection: String, CaseIterable, Sendable, Hashable { + case types + case protocols + case protocolConformances + case associatedTypes + /// Classes implemented through `@objc @implementation`. They have no + /// `__swift5_*` presence; they are recognized from `__objc_classlist` + /// joined with the symbol table. + case objcImplementationClasses +} + +/// Which stored-property offset comments `dump` and `interface` print, +/// computed statically through SwiftLayout. +public enum FieldOffsetComments: Sendable, Hashable { + case none + /// One comment per stored property. + case flat + /// Nested struct fields expanded with their absolute offsets. + case expanded +} + +/// `swift-section dump`: print the Swift declarations a binary's metadata +/// describes, section by section, as they are read. +public struct DumpRequest: Sendable, Equatable { + public enum SectionSelection: Sendable, Hashable { + /// Every section. One the binary does not carry is skipped silently — + /// most binaries lack one or two. + case all + /// These sections, in this order. One that fails to read is reported. + case only([DumpSection]) + } + + public enum Ordering: Sendable, Hashable { + /// Section by section, in the order of the selection. + case bySection + /// Types, protocols and `@objc @implementation` classes interleaved by + /// their offset in the binary, then conformances, then associated + /// types. + case binaryOrder + } + + public var source: MachOSource + /// Where the images a standalone binary links are looked for: by the + /// accessor-thunk reader, the static layout engine and the ObjC ancestor + /// chain. Named paths are consulted first; empty infers them from where + /// the binary sits, then uses the running system's shared cache. + public var dependencySearchPaths: [DependencySearchPath] + public var sections: SectionSelection + public var ordering: Ordering + public var demangleOptions: DemangleOptions + /// Computed statically through SwiftLayout. + public var fieldOffsetComments: FieldOffsetComments + public var emitsMemberAddresses: Bool + public var emitsVTableOffsets: Bool + public var emitsProtocolWitnessTableAddresses: Bool + /// Size, stride and alignment, computed statically through SwiftLayout. + public var emitsTypeLayout: Bool + /// Strategy, per-case and spare-bit layout, computed statically through + /// SwiftLayout. + public var emitsEnumLayout: Bool + /// A `not exported` comment on member lines whose symbol has no + /// export-trie entry. + public var emitsExportStatus: Bool + /// A leading header comment: generator, image path, UUID, architecture, + /// library-evolution detection, unrecoverable-facts notes. + public var emitsHeader: Bool + /// The comment templates. `nil` keeps the built-in rendering; a module the + /// configuration enables also turns its comment kind on. + public var commentTransformers: Transformer.SwiftConfiguration? + public var destination: ProductDestination + + public init( + source: MachOSource, + dependencySearchPaths: [DependencySearchPath] = [], + sections: SectionSelection = .all, + ordering: Ordering = .bySection, + demangleOptions: DemangleOptions = .default, + fieldOffsetComments: FieldOffsetComments = .none, + emitsMemberAddresses: Bool = false, + emitsVTableOffsets: Bool = false, + emitsProtocolWitnessTableAddresses: Bool = false, + emitsTypeLayout: Bool = false, + emitsEnumLayout: Bool = false, + emitsExportStatus: Bool = false, + emitsHeader: Bool = false, + commentTransformers: Transformer.SwiftConfiguration? = nil, + destination: ProductDestination = .output + ) { + self.source = source + self.dependencySearchPaths = dependencySearchPaths + self.sections = sections + self.ordering = ordering + self.demangleOptions = demangleOptions + self.fieldOffsetComments = fieldOffsetComments + self.emitsMemberAddresses = emitsMemberAddresses + self.emitsVTableOffsets = emitsVTableOffsets + self.emitsProtocolWitnessTableAddresses = emitsProtocolWitnessTableAddresses + self.emitsTypeLayout = emitsTypeLayout + self.emitsEnumLayout = emitsEnumLayout + self.emitsExportStatus = emitsExportStatus + self.emitsHeader = emitsHeader + self.commentTransformers = commentTransformers + self.destination = destination + } + + /// Prints every declaration as it is read. A declaration that fails is + /// reported as an ``SwiftSectionDiagnostic/Severity/error`` diagnostic in + /// its place and the dump goes on. + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws { + try await withAccessorThunkResolver(searchPaths: dependencySearchPaths) { + let machOFile = try source.load() + let session = DumpSession(output: output, destination: destination) + try await dump(machOFile, into: session, environment: environment) + try session.finish() + } + } + + private func dump(_ machOFile: MachOFile, into session: DumpSession, environment: SwiftSectionEnvironment) async throws { + // The ObjC ancestor chain behind the `overrides` / `explicit selector` + // comments follows a standalone file's binds into the same images the + // interface's indexer would use; `dump` has no indexer, so it installs + // the resolver itself. + ObjCAncestorResolverStore.shared.register( + ObjCAncestorResolver(root: machOFile, searchPaths: dependencySearchPaths.indexingSearchPaths), + for: machOFile + ) + var configuration: DumperConfiguration = .demangleOptions(demangleOptions) + configuration.printMemberAddress = emitsMemberAddresses + configuration.printVTableOffset = emitsVTableOffsets + configuration.printExportStatus = emitsExportStatus + configuration.printConformancePWTAddress = emitsProtocolWitnessTableAddresses + configuration.printFieldOffset = fieldOffsetComments != .none + configuration.printTypeLayout = emitsTypeLayout + configuration.printEnumLayout = emitsEnumLayout + configuration.printExpandedFieldOffsets = fieldOffsetComments == .expanded + // Without a configuration the transformer slots stay empty, keeping + // the built-in rendering byte-for-byte identical. + if let commentTransformers { + configuration.applyTransformersEnablingCommentKinds(commentTransformers) + } + + // The static (offline) field-layout path needs a SwiftLayout-backed + // provider, built once when any layout comment is requested. Without + // it the offline dumpers emit no layout comments, since offline + // metadata is unavailable. + configuration.staticLayoutDependencyResolution = dependencySearchPaths.staticLayoutDependencyResolution + if configuration.printFieldOffset || configuration.printTypeLayout || configuration.printEnumLayout || configuration.printExpandedFieldOffsets { + configuration.staticFieldLayoutProvider = MachOFileStaticFieldLayoutProvider( + machOFile: machOFile, + resolution: configuration.staticLayoutDependencyResolution + ) + } + + if emitsHeader { + let headerInfo = InterfaceHeaderInfo( + machO: machOFile, + generatorName: environment.generator.name, + generatorVersion: environment.generator.version + ) + await session.perform { InterfaceHeaderBlock(headerInfo) } + } + + let isDefaultSelection: Bool + let selectedSections: [DumpSection] + switch sections { + case .all: + isDefaultSelection = true + selectedSections = DumpSection.allCases + case .only(let explicitSections): + isDefaultSelection = false + selectedSections = explicitSections + } + + switch ordering { + case .binaryOrder: + try await dumpInBinaryOrder(selectedSections, isDefaultSelection: isDefaultSelection, using: configuration, in: machOFile, into: session) + case .bySection: + try await dumpBySection(selectedSections, isDefaultSelection: isDefaultSelection, using: configuration, in: machOFile, into: session) + } + } + + private func dumpBySection( + _ selectedSections: [DumpSection], + isDefaultSelection: Bool, + using configuration: DumperConfiguration, + in machOFile: MachOFile, + into session: DumpSession + ) async throws { + for section in selectedSections { + switch section { + case .types: + do { + for type in try machOFile.swift.types { + try await session.dump(.type(type), using: configuration, in: machOFile) + } + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + case .protocols: + do { + for `protocol` in try machOFile.swift.protocols { + try await session.dump(.protocol(`protocol`), using: configuration, in: machOFile) + } + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + case .protocolConformances: + do { + for protocolConformance in try machOFile.swift.protocolConformances { + try await session.dump(.protocolConformance(protocolConformance), using: configuration, in: machOFile) + } + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + case .associatedTypes: + do { + for associatedType in try machOFile.swift.associatedTypes { + try await session.dump(.associatedType(associatedType), using: configuration, in: machOFile) + } + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + case .objcImplementationClasses: + let objcImplementationClasses = ObjCImplementationClass.all(in: machOFile) + if objcImplementationClasses.isEmpty, !isDefaultSelection { + // Asked for explicitly and nothing there: say so, as the + // section-backed cases do, rather than print nothing. + session.write(SemanticString { Comment("No @objc @implementation classes recognized in this image.") }) + } + for objcImplementationClass in objcImplementationClasses { + try await session.dump(.objcImplementationClass(objcImplementationClass), using: configuration, in: machOFile) + } + } + } + } + + private func dumpInBinaryOrder( + _ selectedSections: [DumpSection], + isDefaultSelection: Bool, + using configuration: DumperConfiguration, + in machOFile: MachOFile, + into session: DumpSession + ) async throws { + var topLevelContexts: [DumpTopLevelContext] = [] + if selectedSections.contains(.types) { + do { + topLevelContexts.append(contentsOf: try machOFile.swift.types.map { .type($0) }) + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + } + + if selectedSections.contains(.protocols) { + do { + topLevelContexts.append(contentsOf: try machOFile.swift.protocols.map { .protocol($0) }) + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + } + + if selectedSections.contains(.objcImplementationClasses) { + topLevelContexts.append(contentsOf: ObjCImplementationClass.all(in: machOFile).map { .objcImplementationClass($0) }) + } + + topLevelContexts.sort(by: { $0.offset < $1.offset }) + + if selectedSections.contains(.protocolConformances) { + do { + topLevelContexts.append(contentsOf: try machOFile.swift.protocolConformances.map { .protocolConformance($0) }) + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + } + + if selectedSections.contains(.associatedTypes) { + do { + topLevelContexts.append(contentsOf: try machOFile.swift.associatedTypes.map { .associatedType($0) }) + } catch { + if !isDefaultSelection { + session.reportError(error) + } + } + } + + for topLevelContext in topLevelContexts { + try? await session.dump(topLevelContext, using: configuration, in: machOFile) + } + } +} + +/// One top-level declaration of a dump, from whichever section it came. +private enum DumpTopLevelContext { + case type(TypeContextWrapper) + case `protocol`(MachOSwiftSection.`Protocol`) + case protocolConformance(ProtocolConformance) + case associatedType(AssociatedType) + case objcImplementationClass(ObjCImplementationClass) + + var offset: Int { + switch self { + case .objcImplementationClass(let objcImplementationClass): + return objcImplementationClass.offset + case .type(let type): + switch type { + case .enum(let `enum`): + return `enum`.offset + case .struct(let `struct`): + return `struct`.offset + case .class(let `class`): + return `class`.offset + } + case .protocol(let `protocol`): + return `protocol`.offset + case .associatedType(let associatedType): + return associatedType.offset + case .protocolConformance(let protocolConformance): + return protocolConformance.offset + } + } + + var section: DumpSection { + switch self { + case .type: + .types + case .protocol: + .protocols + case .protocolConformance: + .protocolConformances + case .associatedType: + .associatedTypes + case .objcImplementationClass: + .objcImplementationClasses + } + } + + func dump(using configuration: DumperConfiguration, in machOFile: MachOFile) async throws -> SemanticString { + switch self { + case .type(.enum(let `enum`)): + try await `enum`.dump(using: configuration, in: machOFile) + case .type(.struct(let `struct`)): + try await `struct`.dump(using: configuration, in: machOFile) + case .type(.class(let `class`)): + try await `class`.dump(using: configuration, in: machOFile) + case .protocol(let `protocol`): + try await `protocol`.dump(using: configuration, in: machOFile) + case .protocolConformance(let protocolConformance): + try await protocolConformance.dump(using: configuration, in: machOFile) + case .associatedType(let associatedType): + try await associatedType.dump(using: configuration, in: machOFile) + case .objcImplementationClass(let objcImplementationClass): + try await objcImplementationClass.dump(using: configuration, in: machOFile) + } + } + + /// The name the dump prints for this declaration: a conformance's and an + /// associated type's is the extended type's, as their `extension` line + /// spells it, which for a type of this image is that type's own name. + /// `nil` when it cannot be rendered. + /// + /// A conformance's line spells the type in full. The public `dumpTypeName` + /// prints with the interface-type options instead, which drop a private + /// type's discriminator that the type's own name keeps. + func declaredName(using configuration: DumperConfiguration, in machOFile: MachOFile) async -> String? { + let context = machOFile.context + do { + let name: SemanticString + switch self { + case .type(.enum(let `enum`)): + name = try await `enum`.dumpName(using: configuration, in: context) + case .type(.struct(let `struct`)): + name = try await `struct`.dumpName(using: configuration, in: context) + case .type(.class(let `class`)): + name = try await `class`.dumpName(using: configuration, in: context) + case .protocol(let `protocol`): + name = try await `protocol`.dumpName(using: configuration, in: context) + case .protocolConformance(let protocolConformance): + name = try await protocolConformance.dumpedTypeName(isFull: true, resolver: configuration.demangleResolver, in: context) + case .associatedType(let associatedType): + name = try await associatedType.dumpTypeName(using: configuration, in: context) + case .objcImplementationClass(let objcImplementationClass): + name = try await objcImplementationClass.dumpName(using: configuration, in: context) + } + return name.string + } catch { + return nil + } + } +} + +/// One dump in progress: where its pieces go, and — for a file destination — +/// the text collected so far. +private final class DumpSession { + let output: Output + let destination: ProductDestination + private var dumpedText = "" + + init(output: Output, destination: ProductDestination) { + self.output = output + self.destination = destination + } + + /// Dumps one top-level declaration and hands it to the output with what it + /// declares. Its failure is reported in its place; what throws out of here + /// is only a failure to deliver. + func dump(_ topLevelContext: DumpTopLevelContext, using configuration: DumperConfiguration, in machOFile: MachOFile) async throws { + let dumpedDeclaration: SemanticString + do { + dumpedDeclaration = try await topLevelContext.dump(using: configuration, in: machOFile) + } catch { + reportError(error) + return + } + switch destination { + case .output: + // Named only once the declaration itself rendered, and only here: + // a file destination never hands a piece over. + let name = await topLevelContext.declaredName(using: configuration, in: machOFile) + output.write(.declarations(dumpedDeclaration), declaring: .swift(topLevelContext.section, name: name)) + case .file: + write(dumpedDeclaration) + } + } + + func perform(@SemanticStringBuilder _ action: @Sendable () async throws -> SemanticString) async { + do { + write(try await action()) + } catch { + reportError(error) + } + } + + func write(_ semanticString: SemanticString) { + switch destination { + case .output: + output.write(.declarations(semanticString)) + case .file: + dumpedText.append(semanticString.string) + dumpedText.append("\n") + } + } + + /// A per-declaration (or per-section) failure. It reaches the output even + /// when the dump goes to a file. + func reportError(_ error: any Swift.Error) { + output.reportError(error.localizedDescription) + } + + /// Writes the collected text when the destination is a file. + func finish() throws { + if case .file(let path) = destination { + try dumpedText.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + } + } +} diff --git a/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift new file mode 100644 index 000000000..cfdd53164 --- /dev/null +++ b/Sources/Commands/SwiftSectionKit/Swift/InterfaceRequest.swift @@ -0,0 +1,244 @@ +import Foundation +import MachOKit +import MachOFoundation +import MachOSwiftSection +import SwiftDeclaration +import SwiftIndexing +import SwiftPrinting +import SwiftInterface +import SwiftDeclarationRendering +import OutputTransformer +import SwiftOutputTransformer +#if os(macOS) +import TypeIndexing +#endif + +/// `swift-section interface`: generate a `.swiftinterface` from a binary. +public struct InterfaceRequest: Sendable, Equatable { + /// Whether `__C` / `__ObjC` type module names are resolved to their real + /// modules (`__C.NSString` → `Foundation.NSString`). + public enum CModuleNameResolution: Sendable, Hashable { + case disabled + /// Index the SDK modules the binary links, their APINotes and the + /// dependencies' ObjC metadata. Needs Xcode; the first run per SDK + /// generates module interfaces through sourcekitd and caches the + /// extraction. `supplementaryAPINotesPaths` adds `.apinotes` files (or + /// directories of them) for frameworks with no SDK module, loaded on + /// top of the SDK's own; later paths override earlier ones. + case enabled(supplementaryAPINotesPaths: [String]) + } + + public var source: MachOSource + /// Where the images a standalone binary links are looked for: by the + /// accessor-thunk reader, the static layout engine and the indexer's + /// cross-image facts. Named paths are consulted first. + public var dependencySearchPaths: [DependencySearchPath] + public var showsCImportedTypes: Bool + /// Experimental: may fail to parse complex return types. + public var parsesOpaqueReturnTypes: Bool + public var cModuleNameResolution: CModuleNameResolution + public var fieldOffsetComments: FieldOffsetComments + public var emitsMemberAddresses: Bool + /// For class methods, computed properties and non-final stored + /// properties' accessors. + public var emitsVTableOffsets: Bool + public var emitsTypeLayout: Bool + public var emitsEnumLayout: Bool + /// A `not exported` comment on members none of whose symbols has an + /// export-trie entry. + public var emitsExportStatus: 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. + public var printsExportedDeclarationsOnly: Bool + public var memberSortOrder: SwiftDeclarationMemberSortOrder + /// Whether an ObjC method tied to its Swift member by the member's name + /// alone (no symbol behind it) prints as `override`. The tie is recorded + /// either way. + public var infersObjCOverridesFromSelectorNames: Bool + /// A leading header comment: generator, image path, UUID, architecture, + /// library-evolution detection, unrecoverable-facts notes. + public var emitsHeader: Bool + public var commentTransformers: Transformer.SwiftConfiguration? + public var destination: ProductDestination + + public init( + source: MachOSource, + dependencySearchPaths: [DependencySearchPath] = [], + showsCImportedTypes: Bool = false, + parsesOpaqueReturnTypes: Bool = false, + cModuleNameResolution: CModuleNameResolution = .disabled, + fieldOffsetComments: FieldOffsetComments = .none, + emitsMemberAddresses: Bool = false, + emitsVTableOffsets: Bool = false, + emitsTypeLayout: Bool = false, + emitsEnumLayout: Bool = false, + emitsExportStatus: Bool = false, + printsExportedDeclarationsOnly: Bool = false, + memberSortOrder: SwiftDeclarationMemberSortOrder = .byCategory, + infersObjCOverridesFromSelectorNames: Bool = false, + emitsHeader: Bool = false, + commentTransformers: Transformer.SwiftConfiguration? = nil, + destination: ProductDestination = .output + ) { + self.source = source + self.dependencySearchPaths = dependencySearchPaths + self.showsCImportedTypes = showsCImportedTypes + self.parsesOpaqueReturnTypes = parsesOpaqueReturnTypes + self.cModuleNameResolution = cModuleNameResolution + self.fieldOffsetComments = fieldOffsetComments + self.emitsMemberAddresses = emitsMemberAddresses + self.emitsVTableOffsets = emitsVTableOffsets + self.emitsTypeLayout = emitsTypeLayout + self.emitsEnumLayout = emitsEnumLayout + self.emitsExportStatus = emitsExportStatus + self.printsExportedDeclarationsOnly = printsExportedDeclarationsOnly + self.memberSortOrder = memberSortOrder + self.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames + self.emitsHeader = emitsHeader + self.commentTransformers = commentTransformers + self.destination = destination + } + + public func run(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws { + try await withAccessorThunkResolver(searchPaths: dependencySearchPaths) { + try await buildInterface(output: output, environment: environment) + } + } + + private func buildInterface(output: some SwiftSectionOutput, environment: SwiftSectionEnvironment) async throws { + let machOFile = try source.load() + + var printConfiguration = SwiftDeclarationPrintConfiguration( + printStrippedSymbolicItem: true, + printFieldOffset: fieldOffsetComments != .none, + printExpandedFieldOffsets: fieldOffsetComments == .expanded, + printMemberAddress: emitsMemberAddresses, + printVTableOffset: emitsVTableOffsets, + printExportStatus: emitsExportStatus, + printExportedDeclarationsOnly: printsExportedDeclarationsOnly, + memberSortOrder: memberSortOrder, + printTypeLayout: emitsTypeLayout, + printEnumLayout: emitsEnumLayout + ) + // Without a configuration the transformer slots stay empty, keeping + // the built-in rendering byte-for-byte identical. + if let commentTransformers { + printConfiguration.applyTransformersEnablingCommentKinds(commentTransformers) + } + printConfiguration.staticLayoutDependencyResolution = dependencySearchPaths.staticLayoutDependencyResolution + // The index records the name-only ObjC tie either way; this decides + // whether it prints as `@objc override`. + printConfiguration.infersObjCOverridesFromSelectorNames = infersObjCOverridesFromSelectorNames + + var configuration = SwiftInterfaceBuilderConfiguration( + indexConfiguration: .init( + showCImportedTypes: showsCImportedTypes, + dependencySearchPaths: dependencySearchPaths.indexingSearchPaths + ), + printConfiguration: printConfiguration + ) + + if emitsHeader { + // The header's dispatch-thunk count triggers the symbol-index + // build (which `prepare()` below then reuses), so progress is + // announced BEFORE it — otherwise nothing is heard for the whole + // index build. + output.reportProgress("Preparing to build Swift interface...") + configuration.interfaceHeaderInfo = InterfaceHeaderInfo( + machO: machOFile, + generatorName: environment.generator.name, + generatorVersion: environment.generator.version + ) + } + + let builder = try SwiftInterfaceBuilder( + configuration: configuration, + eventHandlers: output.indexEventHandlers(forInputLabeled: nil), + in: machOFile + ) + + if parsesOpaqueReturnTypes { + builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) + } + + if case .enabled(let supplementaryAPINotesPaths) = cModuleNameResolution { + addTypeNameProvider(to: builder, machOFile: machOFile, supplementaryAPINotesPaths: supplementaryAPINotesPaths, output: output) + } + + if !emitsHeader { + output.reportProgress("Preparing to build Swift interface...") + } + + try await builder.prepare() + + output.reportProgress("Building Swift interface...") + + let interfaceString = try await builder.printRoot() + + output.reportProgress("Swift interface built successfully.") + + switch destination { + case .file(let path): + output.reportProgress("Writing Swift interface to \(path)...") + try interfaceString.string.write(to: URL(fileURLWithPath: path), atomically: true, encoding: .utf8) + case .output: + output.write(.declarations(interfaceString)) + } + } + + private func addTypeNameProvider( + to builder: SwiftInterfaceBuilder, + machOFile: MachOFile, + supplementaryAPINotesPaths: [String], + output: some SwiftSectionOutput + ) { + #if os(macOS) + guard #available(macOS 13.0, *) else { + output.reportWarning("warning: --resolve-c-module-names requires macOS 13 or later") + return + } + let providerDependencies = SwiftInterfaceBuilderDependencies( + machO: machOFile, + searchPaths: [.systemDyldSharedCache], + eventHandlers: output.indexEventHandlers(forInputLabeled: nil) + ) + // Dependency resolution against the HOST dyld cache matches install + // names exactly, then bare names; a non-macOS binary's paths mostly + // miss both, which silently guts the SDK-interface source. Said + // aloud, misses named, instead of degrading quietly. + if providerDependencies.dependencies.isEmpty { + output.reportWarning("warning: --resolve-c-module-names resolved no dependency images against this host (non-macOS binary?); attribution will be limited to SDK APINotes and supplementary files") + } else if !providerDependencies.unresolvedLoadNames.isEmpty { + output.reportWarning("warning: --resolve-c-module-names could not resolve \(providerDependencies.unresolvedLoadNames.count) dependency image(s) against this host; their types will not be attributed: \(providerDependencies.unresolvedLoadNames.joined(separator: ", "))") + } + // A bad supplementary path is otherwise only os_log'd by the library + // floor; a mistyped path or a broken YAML deserves the same warning + // the other degradations get. (Files inside a directory argument stay + // on the library's skip-and-log contract.) + for supplementaryAPINotesPath in supplementaryAPINotesPaths { + var pathIsDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: supplementaryAPINotesPath, isDirectory: &pathIsDirectory) else { + output.reportWarning("warning: --supplementary-apinotes path does not exist: \(supplementaryAPINotesPath)") + continue + } + if !pathIsDirectory.boolValue { + do { + _ = try APINotesFile(path: supplementaryAPINotesPath) + } catch { + output.reportWarning("warning: --supplementary-apinotes file failed to parse and will be skipped: \(supplementaryAPINotesPath): \(error)") + } + } + } + let supplementaryAPINotesURLs = supplementaryAPINotesPaths.map { URL(fileURLWithPath: $0) } + if let typeNameProvider = SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: providerDependencies, supplementaryAPINotesURLs: supplementaryAPINotesURLs) { + builder.addExtraDataProvider(typeNameProvider) + } else { + output.reportWarning("warning: --resolve-c-module-names ignored: the binary carries no build-version command mapping to a known SDK platform") + } + #else + output.reportWarning("warning: --resolve-c-module-names is only available on macOS") + #endif + } +} diff --git a/Sources/swift-section/Commands/TransformerCommand.swift b/Sources/Commands/SwiftSectionKit/Swift/TransformerRequests.swift similarity index 52% rename from Sources/swift-section/Commands/TransformerCommand.swift rename to Sources/Commands/SwiftSectionKit/Swift/TransformerRequests.swift index fba4f3383..990a58fa9 100644 --- a/Sources/swift-section/Commands/TransformerCommand.swift +++ b/Sources/Commands/SwiftSectionKit/Swift/TransformerRequests.swift @@ -1,19 +1,122 @@ -import ArgumentParser import Foundation import OutputTransformer import SwiftOutputTransformer -// MARK: - Module Selector - -/// The comment transformer modules addressable from the command line. -enum TransformerModuleSelector: String, ExpressibleByArgument, CaseIterable { +/// The comment transformer modules whose tokens and templates can be listed. +/// +/// The raw values are the names the command line spells them by. +public enum TransformerModule: String, CaseIterable, Sendable, Hashable { case fieldOffset = "field-offset" case vtableOffset = "vtable-offset" case memberAddress = "member-address" case typeLayout = "type-layout" case enumLayout = "enum-layout" +} + +/// `swift-section transformer tokens`: list the `${token}` placeholders each +/// comment template accepts. +public struct TransformerTokensRequest: Sendable, Equatable { + /// One module, or `nil` for all of them. + public var module: TransformerModule? + + public init(module: TransformerModule? = nil) { + self.module = module + } + + public func run(output: some SwiftSectionOutput) { + for (moduleIndex, module) in (module.map { [$0] } ?? TransformerModule.allCases).enumerated() { + if moduleIndex > 0 { + output.write(.text("")) + } + let description = module.listingDescription + output.write(.text("\(description.displayName) (\(module.rawValue))")) + for section in description.tokenSections { + output.write(.text(" \(section.title) — \(section.optionName)")) + let widestPlaceholder = section.tokens.map(\.placeholder.count).max() ?? 0 + for token in section.tokens { + let padding = String(repeating: " ", count: widestPlaceholder - token.placeholder.count) + output.write(.text(" \(token.placeholder)\(padding) \(token.displayName)")) + } + } + } + } +} + +/// `swift-section transformer templates`: list the built-in comment templates, +/// whose names the template options accept. +public struct TransformerTemplatesRequest: Sendable, Equatable { + /// One module, or `nil` for all of them. + public var module: TransformerModule? - var description: TransformerModuleDescription { + public init(module: TransformerModule? = nil) { + self.module = module + } + + public func run(output: some SwiftSectionOutput) { + for (moduleIndex, module) in (module.map { [$0] } ?? TransformerModule.allCases).enumerated() { + if moduleIndex > 0 { + output.write(.text("")) + } + let description = module.listingDescription + output.write(.text("\(description.displayName) (\(module.rawValue))")) + for section in description.templateSections { + output.write(.text(" \(section.title) — \(section.optionName)")) + for template in section.templates { + output.write(.text(" \(template.name)")) + for line in template.template.components(separatedBy: "\n") { + output.write(.text(" \(line)")) + } + } + } + } + } +} + +/// `swift-section transformer config`: a comment transformer configuration as +/// pretty-printed JSON, the shape `--transformer-config` reads back. +public struct TransformerConfigurationRequest: Sendable, Equatable { + public var configuration: Transformer.SwiftConfiguration + public var destination: ProductDestination + + public init(configuration: Transformer.SwiftConfiguration = .init(), destination: ProductDestination = .output) { + self.configuration = configuration + self.destination = destination + } + + public func run(output: some SwiftSectionOutput) throws { + let encoder = JSONEncoder() + encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + // JSONEncoder only ever produces UTF-8. + let encodedString = String(decoding: try encoder.encode(configuration), as: UTF8.self) + try destination.deliver(encodedString, to: output) + } +} + +// MARK: - Listing + +/// One module's listing: which tokens its templates accept, and which built-in +/// templates can be named. The option names are the command line's, since the +/// listing exists to say what to pass to them. +struct TransformerModuleListing { + struct TokenSection { + let title: String + let optionName: String + let tokens: [(placeholder: String, displayName: String)] + } + + struct TemplateSection { + let title: String + let optionName: String + let templates: [(name: String, template: String)] + } + + let displayName: String + let tokenSections: [TokenSection] + let templateSections: [TemplateSection] +} + +extension TransformerModule { + var listingDescription: TransformerModuleListing { switch self { case .fieldOffset: .init( @@ -133,144 +236,3 @@ enum TransformerModuleSelector: String, ExpressibleByArgument, CaseIterable { } } } - -/// One module's command-line-facing surface: which tokens its templates accept -/// and which built-in templates can be named. -struct TransformerModuleDescription { - struct TokenSection { - let title: String - let optionName: String - let tokens: [(placeholder: String, displayName: String)] - } - - struct TemplateSection { - let title: String - let optionName: String - let templates: [(name: String, template: String)] - } - - let displayName: String - let tokenSections: [TokenSection] - let templateSections: [TemplateSection] -} - -// MARK: - Command - -struct TransformerCommand: ParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "transformer", - abstract: "Inspect and build the comment transformer configuration used by `dump` and `interface`.", - discussion: """ - Comment templates substitute ${token} placeholders. Use `tokens` to see what each \ - module's templates accept, `templates` to see the built-in templates (their names can \ - be passed to the template options directly), and `config` to produce a JSON \ - configuration for --transformer-config. - """, - subcommands: [ - TokensCommand.self, - TemplatesCommand.self, - ConfigCommand.self, - ], - defaultSubcommand: TokensCommand.self - ) -} - -// MARK: - Tokens - -extension TransformerCommand { - struct TokensCommand: ParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "tokens", - abstract: "List the ${token} placeholders each comment template accepts." - ) - - @Option(name: .shortAndLong, help: "Restrict the listing to one module. If not specified, all modules are listed.") - var module: TransformerModuleSelector? - - func run() throws { - let selectors = module.map { [$0] } ?? TransformerModuleSelector.allCases - for (index, selector) in selectors.enumerated() { - if index > 0 { print("") } - let description = selector.description - print("\(description.displayName) (\(selector.rawValue))") - for section in description.tokenSections { - print(" \(section.title) — \(section.optionName)") - let widestPlaceholder = section.tokens.map(\.placeholder.count).max() ?? 0 - for token in section.tokens { - let padding = String(repeating: " ", count: widestPlaceholder - token.placeholder.count) - print(" \(token.placeholder)\(padding) \(token.displayName)") - } - } - } - } - } -} - -// MARK: - Templates - -extension TransformerCommand { - struct TemplatesCommand: ParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "templates", - abstract: "List the built-in comment templates. Their names are accepted by the template options." - ) - - @Option(name: .shortAndLong, help: "Restrict the listing to one module. If not specified, all modules are listed.") - var module: TransformerModuleSelector? - - func run() throws { - let selectors = module.map { [$0] } ?? TransformerModuleSelector.allCases - for (index, selector) in selectors.enumerated() { - if index > 0 { print("") } - let description = selector.description - print("\(description.displayName) (\(selector.rawValue))") - for section in description.templateSections { - print(" \(section.title) — \(section.optionName)") - for template in section.templates { - print(" \(template.name)") - for line in template.template.components(separatedBy: "\n") { - print(" \(line)") - } - } - } - } - } - } -} - -// MARK: - Config - -extension TransformerCommand { - struct ConfigCommand: ParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "config", - abstract: "Print the transformer configuration described by the given options as JSON.", - discussion: """ - Without any option this prints the all-defaults skeleton, a starting point to edit \ - and feed back through --transformer-config. With options it prints what those \ - options resolve to, so a command line can be frozen into a reusable file. - """ - ) - - @OptionGroup - var transformerOptions: TransformerOptionGroup - - @Option(name: .shortAndLong, help: "The output path for the configuration. If not specified, it is printed to the console.", completion: .file()) - var outputPath: String? - - func run() throws { - let configuration = try transformerOptions.buildTransformerConfiguration() ?? .init() - let encoder = JSONEncoder() - encoder.outputFormatting = [.prettyPrinted, .sortedKeys] - let encodedData = try encoder.encode(configuration) - guard let encodedString = String(data: encodedData, encoding: .utf8) else { - throw ValidationError("The transformer configuration could not be encoded as UTF-8 text.") - } - if let outputPath { - try encodedString.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - } else { - print(encodedString) - } - } - } -} diff --git a/Sources/SwiftAttributeInference/MemberAttributeInferrer.swift b/Sources/Declaration/SwiftAttributeInference/MemberAttributeInferrer.swift similarity index 100% rename from Sources/SwiftAttributeInference/MemberAttributeInferrer.swift rename to Sources/Declaration/SwiftAttributeInference/MemberAttributeInferrer.swift diff --git a/Sources/SwiftAttributeInference/TypeAttributeInferrer.swift b/Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift similarity index 100% rename from Sources/SwiftAttributeInference/TypeAttributeInferrer.swift rename to Sources/Declaration/SwiftAttributeInference/TypeAttributeInferrer.swift diff --git a/Sources/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift b/Sources/Declaration/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift rename to Sources/Declaration/SwiftDeclaration/Components/AssociatedTypeWitnessProjection.swift diff --git a/Sources/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/AnnotatedSymbol.swift diff --git a/Sources/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/ClassDispatchLookups.swift diff --git a/Sources/SwiftDeclaration/Components/Building/DefinitionBuilder.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/DefinitionBuilder.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/DefinitionBuilder.swift diff --git a/Sources/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/MemberAttributeApplication.swift diff --git a/Sources/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/MemberSymbolBucketing.swift diff --git a/Sources/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/ObjCMemberApplication.swift diff --git a/Sources/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift similarity index 96% rename from Sources/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift index 59e83cfd1..a19e4b51f 100644 --- a/Sources/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Building/OverrideSymbolMatcher.swift @@ -36,11 +36,11 @@ import OrderedCollections /// member form; every other tree keys as-is. package func memberJoinKey( for node: NodeReference, - in machO: some MachOSwiftSectionRepresentableWithCache + 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: machO)) + return StructuralNodeReferenceKey(InternedNodeReferenceCache.shared.reference(interning: strippedTree, in: context)) } return StructuralNodeReferenceKey(node) } diff --git a/Sources/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift b/Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift rename to Sources/Declaration/SwiftDeclaration/Components/Building/WrappedPropertyRecovery.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/Definition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/Definition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/Definition.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift similarity index 98% rename from Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift index 6453f9709..ff3b4e92e 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+Indexing.swift @@ -20,7 +20,7 @@ extension ExtensionDefinition { isIndexed = true return } - guard let protocolConformance = try materializedProtocolConformance(in: machO), !protocolConformance.resilientWitnesses.isEmpty else { + guard let protocolConformance = try materializedProtocolConformance(in: machO.context), !protocolConformance.resilientWitnesses.isEmpty else { isIndexed = true return } @@ -44,7 +44,7 @@ extension ExtensionDefinition { if let symbols = resilientWitness.implementationSymbols(in: machO), let symbol = try _symbol(for: symbols, typeName: extensionName.name, visitedNodes: visitedNodes) { _ = visitedNodes.append(StructuralNodeReferenceKey(symbol.demangledNode)) addSymbol(.init(symbol), memberSymbolsByKind: &memberSymbolsByKind, inExtension: true) - } else if let requirement = try resilientWitness.requirement(in: machO) { + } else if let requirement = try resilientWitness.requirement(in: machO.context) { switch requirement { case .symbol(let symbol): if let demangledNode = SymbolicDemangler.demangleSymbolReference(for: symbol, in: machO) { diff --git a/Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ObjCMembers.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition+ThunkAttributes.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift similarity index 85% rename from Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift index 48ba8cf1c..5b4c1d780 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ExtensionDefinition.swift @@ -113,7 +113,7 @@ public final class ExtensionDefinition: Definition, MutableDefinition { /// 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] = [], in machO: some MachOSwiftSectionRepresentableWithCache) throws { + public init(extensionName: ExtensionName, genericSignature: NodeReference?, protocolConformance: ProtocolConformance?, conformingProtocolName: ProtocolName? = nil, associatedTypes: [AssociatedType] = [], resolvedAssociatedTypeWitnesses: [AssociatedTypeWitnessProjection] = []) { self.extensionName = extensionName self.genericSignature = genericSignature self.protocolConformanceDescriptor = protocolConformance?.descriptor @@ -122,6 +122,12 @@ public final class ExtensionDefinition: Definition, MutableDefinition { self.resolvedAssociatedTypeWitnesses = resolvedAssociatedTypeWitnesses } + /// 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 { + 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] = []) { @@ -151,8 +157,13 @@ public final class ExtensionDefinition: Definition, MutableDefinition { /// extensions. Materialization discipline (evolution proposal 0002): /// call at most once per operation and thread the result through as a /// local variable — the result is deliberately not cached. + public func materializedProtocolConformance(in context: some ReadingContext) throws -> ProtocolConformance? { + 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 protocolConformanceDescriptor.map { try ProtocolConformance(descriptor: $0, in: machO) } + try materializedProtocolConformance(in: machO.context) } /// Folds another definition's associated types (and their frozen witness @@ -197,11 +208,13 @@ public final class ExtensionDefinition: Definition, MutableDefinition { /// Records the recognition and joins the variables built from accessor /// symbols with the stored properties the ObjC ivar list carries, by the - /// Swift property name the field-offset symbol supplies. + /// Swift property name the field-offset symbol supplies — a `lazy var` + /// with the storage its name prefixes, which the ObjC ivar name still + /// spells once that symbol is stripped. package func attachObjCImplementation(_ facts: ObjCImplementationClassFacts) { objcImplementation = facts for index in variables.indices { - variables[index].objcImplementationStorage = facts.instanceVariable(forSwiftPropertyNamed: variables[index].name) + variables[index].objcImplementationStorage = facts.storageInstanceVariable(forPropertyNamed: variables[index].name) } } @@ -211,8 +224,13 @@ public final class ExtensionDefinition: Definition, MutableDefinition { /// else would show them. public var unrepresentedObjCImplementationInstanceVariables: [ObjCImplementationClassFacts.InstanceVariable] { guard let objcImplementation else { return [] } - let representedNames = Set(variables.compactMap { $0.objcImplementationStorage?.swiftPropertyName }) + let representedStorages = variables.compactMap(\.objcImplementationStorage) + let representedNames = Set(representedStorages.compactMap(\.swiftPropertyName)) + // A `lazy var`'s storage joins through the ObjC ivar name alone once + // its field-offset symbol is stripped, so it has no Swift name to match. + let representedIdentities = Set(representedStorages.map(ObjectIdentifier.init)) return objcImplementation.instanceVariables.filter { instanceVariable in + if representedIdentities.contains(ObjectIdentifier(instanceVariable)) { return false } guard let swiftPropertyName = instanceVariable.swiftPropertyName else { return true } return !representedNames.contains(swiftPropertyName) } diff --git a/Sources/SwiftDeclaration/Components/Definitions/FieldDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/FieldDefinition.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/FieldDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/FieldDefinition.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/FunctionDefinition.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift similarity index 94% rename from Sources/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift index a2d317a4a..7335532f8 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition+Indexing.swift @@ -8,7 +8,7 @@ import SwiftStdlibToolbox extension ProtocolDefinition { package func index(in machO: some MachOSwiftSectionRepresentableWithCache) async throws { guard !isIndexed else { return } - let dumpedProtocol = try materializedProtocol(in: machO) + let dumpedProtocol = try materializedProtocol(in: machO.context) let name = protocolName.name // Structurally keyed: `demangleSymbolReference` returns references from // different stores, and store-identity equality would let the same @@ -21,7 +21,7 @@ extension ProtocolDefinition { } return nil } - associatedTypes = try protocolDescriptor.associatedTypes(in: machO) + associatedTypes = try protocolDescriptor.associatedTypes(in: machO.context) var requirementMemberSymbolsByKind: OrderedDictionary = [:] var defaultImplementationMemberSymbolsByKind: OrderedDictionary = [:] @@ -63,7 +63,7 @@ extension ProtocolDefinition { // `ProtocolDefinition` (SPI use, no module indexer) still needs the // synthesis. if defaultImplementationExtensions.isEmpty { - let extensionDefinition = try ExtensionDefinition(extensionName: protocolName.extensionName, genericSignature: nil, protocolConformance: nil, in: machO) + let extensionDefinition = ExtensionDefinition(extensionName: protocolName.extensionName, genericSignature: nil, protocolConformance: nil) extensionDefinition.setDefinitions(for: defaultImplementationMemberSymbolsByKind, inExtension: true) extensionDefinition.orderedMembers = OrderedMember.offsetOrdered(OrderedMember.allMembers(from: extensionDefinition)) diff --git a/Sources/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift similarity index 94% rename from Sources/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift index 4fa890e43..1848221de 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ProtocolDefinition.swift @@ -82,7 +82,7 @@ public final class ProtocolDefinition: Definition, MutableDefinition { /// is retained. public init(`protocol`: MachOSwiftSection.`Protocol`, in machO: some MachOSwiftSectionRepresentableWithCache) throws { self.protocolDescriptor = `protocol`.descriptor - let node = try SymbolicDemangler.demangleContext(for: .protocol(`protocol`.descriptor), in: machO) + let node = try SymbolicDemangler.demangleContext(for: .protocol(`protocol`.descriptor), in: machO.context) let protocolName = ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: machO)) self.protocolName = protocolName self.exportStatus = ExportStatus.resolve( @@ -114,7 +114,12 @@ public final class ProtocolDefinition: Definition, MutableDefinition { /// (evolution proposal 0002): call at most once per operation and thread /// the result through as a local variable — the result is deliberately /// not cached. + 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 MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: machO) + try materializedProtocol(in: machO.context) } } diff --git a/Sources/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/ResolvedObjCMemberFacts.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/SubscriptDefinition.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift similarity index 96% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift index cac408b99..ecbcf1b56 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ClassDispatch.swift @@ -16,9 +16,9 @@ extension TypeDefinition { func classDispatchLookups(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDispatchLookups { var lookups = ClassDispatchLookups() guard case .class(let classDescriptor) = typeContextDescriptorWrapper else { return lookups } - let classWrapper = try Class(descriptor: classDescriptor, in: machO) + let classWrapper = try Class(descriptor: classDescriptor, in: machO.context) var visitedNodes: OrderedSet = [] - let typeNode = try SymbolicDemangler.demangleContext(for: .type(.class(classWrapper.descriptor)), in: machO) + let typeNode = try SymbolicDemangler.demangleContext(for: .type(.class(classWrapper.descriptor)), in: machO.context) let vtableBaseOffset = classWrapper.vTableDescriptorHeader.map { Int($0.layout.vTableOffset) } lookups.canRecoverFinalMembers = classWrapper.vTableDescriptorHeader != nil && !classDescriptor.isActor @@ -75,7 +75,7 @@ extension TypeDefinition { continue } visitedNodes.append(StructuralNodeReferenceKey(node)) - let joinKey = memberJoinKey(for: node, in: machO) + let joinKey = memberJoinKey(for: node, in: machO.context) lookups.methodDescriptorLookup[joinKey] = .method(descriptor) if let vtableBaseOffset { lookups.vtableOffsetLookup[joinKey] = vtableBaseOffset + index @@ -93,10 +93,10 @@ extension TypeDefinition { guard let overrideSymbol = 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) + let joinKey = memberJoinKey(for: node, in: machO.context) lookups.methodDescriptorLookup[joinKey] = .methodOverride(descriptor) - if let vtableSlot = try? parentVTableCache.slotIndex(for: descriptor, in: machO) { + if let vtableSlot = try? parentVTableCache.slotIndex(for: descriptor, in: machO.context) { lookups.vtableOffsetLookup[joinKey] = vtableSlot } } @@ -110,7 +110,7 @@ extension TypeDefinition { guard let overrideSymbol = 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)] = .methodDefaultOverride(descriptor) + lookups.methodDescriptorLookup[memberJoinKey(for: node, in: machO.context)] = .methodDefaultOverride(descriptor) } return lookups } @@ -158,7 +158,7 @@ extension TypeDefinition { private func asyncFunctionEntryOffset(ofAsyncFunctionPointerAt offset: Int, in machO: some MachOSwiftSectionRepresentableWithCache) -> Int? { do { // Annotated: the optional-returning overload reads another shape. - let asyncFunctionPointer: AsyncFunctionPointer = try AsyncFunctionPointer.resolve(from: offset, in: machO) + let asyncFunctionPointer: AsyncFunctionPointer = try AsyncFunctionPointer.resolve(at: offset, in: machO.context) return asyncFunctionPointer.resolvedDirectOffset(from: \.function) } catch { return nil diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+FinalRecovery.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift similarity index 96% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift index 84f3316c9..48f857a87 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+Indexing.swift @@ -95,8 +95,8 @@ extension TypeDefinition { /// once the members are built. func indexedFieldDefinitions(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> [FieldDefinition] { let typeContextDescriptor = typeContextDescriptorWrapper.typeContextDescriptor - let fieldDescriptor = try typeContextDescriptor.fieldDescriptor(in: machO) - let records = try fieldDescriptor.records(in: machO) + let fieldDescriptor = try typeContextDescriptor.fieldDescriptor(in: machO.context) + let records = try fieldDescriptor.records(in: machO.context) // Field type trees intern into the image's shared store // (`InternedNodeReferenceCache`), so common subtrees (module // references, stdlib types) deduplicate across the whole image — @@ -107,12 +107,12 @@ extension TypeDefinition { // generic, say) is read offline through the same thunk reader the // opaque-type path uses; the thunk's arguments are this type's own // generic arguments. - let accessorThunkOwnerLayout = AccessorThunkOwnerLayout(genericContext: try typeContextDescriptor.genericContext(in: machO)) + let accessorThunkOwnerLayout = AccessorThunkOwnerLayout(genericContext: try typeContextDescriptor.genericContext(in: machO.context)) var indexedFields: [FieldDefinition] = [] for record in records { - let typeNode = try record.demangledTypeNode(in: machO) + let typeNode = try record.demangledTypeNode(in: machO.context) .resolvingAccessorFunctionReferences(in: machO, ownerLayout: accessorThunkOwnerLayout) - let name = try record.fieldName(in: machO) + let name = try record.fieldName(in: machO.context) var fieldFlags = FieldFlags() if name.hasLazyPrefix { fieldFlags.insert(.isLazy) @@ -134,7 +134,7 @@ extension TypeDefinition { if record.flags.contains(.isArtificial) { fieldFlags.insert(.isArtificial) } - if try !record.mangledTypeName(in: machO).isEmpty { + if try !record.mangledTypeName(in: machO.context).isEmpty { fieldFlags.insert(.hasMangledTypeName) } indexedFields.append(FieldDefinition(name: name.stripLazyPrefix, typeNode: InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machO), flags: fieldFlags)) diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+MemberIndexing.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ObjCMembers.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+SynthesizedMembers.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+ThunkAttributes.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition+WrappedProperties.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift similarity index 96% rename from Sources/SwiftDeclaration/Components/Definitions/TypeDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift index 109cca5d9..041268f24 100644 --- a/Sources/SwiftDeclaration/Components/Definitions/TypeDefinition.swift +++ b/Sources/Declaration/SwiftDeclaration/Components/Definitions/TypeDefinition.swift @@ -193,7 +193,7 @@ public final class TypeDefinition: Definition { } public convenience init(type: TypeContextWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) async throws { - let typeName = try type.typeName(in: machO) + let typeName = try type.typeName(in: machO.context) let exportStatus = ExportStatus.resolve( forNominalTypeDescriptorAt: type.typeContextDescriptorWrapper.typeContextDescriptor.offset, typeNameNode: typeName.node, @@ -210,8 +210,13 @@ public final class TypeDefinition: Definition { /// the result through as a local variable. The result is deliberately /// not cached — retaining it on the definition would re-accumulate, in /// browse order, the memory the descriptor slimming reclaimed. + public func materializedTypeContext(in context: some ReadingContext) throws -> TypeContextWrapper { + 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 TypeContextWrapper.forTypeContextDescriptorWrapper(typeContextDescriptorWrapper, in: machO) + try materializedTypeContext(in: machO.context) } /// What a type-level attribute prints in parentheses, or `nil` when it diff --git a/Sources/SwiftDeclaration/Components/Definitions/VariableDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/VariableDefinition.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/VariableDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/VariableDefinition.swift diff --git a/Sources/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift b/Sources/Declaration/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift rename to Sources/Declaration/SwiftDeclaration/Components/Definitions/WrappedPropertyDefinition.swift diff --git a/Sources/SwiftDeclaration/Components/ExportStatus.swift b/Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/ExportStatus.swift rename to Sources/Declaration/SwiftDeclaration/Components/ExportStatus.swift diff --git a/Sources/SwiftDeclaration/Components/Kinds/AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Kinds/AccessorKind.swift rename to Sources/Declaration/SwiftDeclaration/Components/Kinds/AccessorKind.swift diff --git a/Sources/SwiftDeclaration/Components/Kinds/ExtensionKind.swift b/Sources/Declaration/SwiftDeclaration/Components/Kinds/ExtensionKind.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Kinds/ExtensionKind.swift rename to Sources/Declaration/SwiftDeclaration/Components/Kinds/ExtensionKind.swift diff --git a/Sources/SwiftDeclaration/Components/Kinds/FunctionKind.swift b/Sources/Declaration/SwiftDeclaration/Components/Kinds/FunctionKind.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Kinds/FunctionKind.swift rename to Sources/Declaration/SwiftDeclaration/Components/Kinds/FunctionKind.swift diff --git a/Sources/SwiftDeclaration/Components/Kinds/TypeKind.swift b/Sources/Declaration/SwiftDeclaration/Components/Kinds/TypeKind.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Kinds/TypeKind.swift rename to Sources/Declaration/SwiftDeclaration/Components/Kinds/TypeKind.swift diff --git a/Sources/SwiftDeclaration/Components/Members/Accessor.swift b/Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Members/Accessor.swift rename to Sources/Declaration/SwiftDeclaration/Components/Members/Accessor.swift diff --git a/Sources/SwiftDeclaration/Components/Members/MemberCategory.swift b/Sources/Declaration/SwiftDeclaration/Components/Members/MemberCategory.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Members/MemberCategory.swift rename to Sources/Declaration/SwiftDeclaration/Components/Members/MemberCategory.swift diff --git a/Sources/SwiftDeclaration/Components/Members/OrderedMember.swift b/Sources/Declaration/SwiftDeclaration/Components/Members/OrderedMember.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Members/OrderedMember.swift rename to Sources/Declaration/SwiftDeclaration/Components/Members/OrderedMember.swift diff --git a/Sources/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift b/Sources/Declaration/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift rename to Sources/Declaration/SwiftDeclaration/Components/Members/StrippedSymbolicRequirement.swift diff --git a/Sources/SwiftDeclaration/Components/Names/DefinitionName.swift b/Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Names/DefinitionName.swift rename to Sources/Declaration/SwiftDeclaration/Components/Names/DefinitionName.swift diff --git a/Sources/SwiftDeclaration/Components/Names/ExtensionName.swift b/Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Names/ExtensionName.swift rename to Sources/Declaration/SwiftDeclaration/Components/Names/ExtensionName.swift diff --git a/Sources/SwiftDeclaration/Components/Names/ProtocolName.swift b/Sources/Declaration/SwiftDeclaration/Components/Names/ProtocolName.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Names/ProtocolName.swift rename to Sources/Declaration/SwiftDeclaration/Components/Names/ProtocolName.swift diff --git a/Sources/SwiftDeclaration/Components/Names/TypeName.swift b/Sources/Declaration/SwiftDeclaration/Components/Names/TypeName.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/Names/TypeName.swift rename to Sources/Declaration/SwiftDeclaration/Components/Names/TypeName.swift diff --git a/Sources/SwiftDeclaration/Components/SwiftAttribute.swift b/Sources/Declaration/SwiftDeclaration/Components/SwiftAttribute.swift similarity index 100% rename from Sources/SwiftDeclaration/Components/SwiftAttribute.swift rename to Sources/Declaration/SwiftDeclaration/Components/SwiftAttribute.swift diff --git a/Sources/SwiftDeclaration/Events/SwiftIndexEvents.swift b/Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift similarity index 100% rename from Sources/SwiftDeclaration/Events/SwiftIndexEvents.swift rename to Sources/Declaration/SwiftDeclaration/Events/SwiftIndexEvents.swift diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift new file mode 100644 index 000000000..070dc0f21 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/AssociatedType+Names.swift @@ -0,0 +1,16 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection + +extension AssociatedType { + package func typeName(in context: some ReadingContext) throws -> TypeName? { + let node = try SymbolicDemangler.demangleType(for: conformingTypeName, in: context) + guard let kind = node.typeKind else { return nil } + return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: context), kind: kind) + } + + package func protocolName(in context: some ReadingContext) throws -> ProtocolName { + ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleType(for: protocolTypeName, in: context), in: context)) + } +} diff --git a/Sources/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift b/Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift similarity index 100% rename from Sources/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift rename to Sources/Declaration/SwiftDeclaration/Extensions/DemanglingNode+AccessorKind.swift diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift new file mode 100644 index 000000000..5840e3acc --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift @@ -0,0 +1,14 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection +import Semantic +extension FieldRecord { + package func demangledTypeNode(in context: some ReadingContext) throws -> Node { + try SymbolicDemangler.demangleType(for: mangledTypeName(in: context), in: context) + } + + package func demangledTypeName(in context: some ReadingContext) throws -> SemanticString { + try demangledTypeNode(in: context).printSemantic(using: .interfaceTypeBuilderOnly) + } +} diff --git a/Sources/SwiftDeclaration/Extensions/Node+TypeKind.swift b/Sources/Declaration/SwiftDeclaration/Extensions/Node+TypeKind.swift similarity index 100% rename from Sources/SwiftDeclaration/Extensions/Node+TypeKind.swift rename to Sources/Declaration/SwiftDeclaration/Extensions/Node+TypeKind.swift diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift new file mode 100644 index 000000000..f32dbcb11 --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/Protocol+Names.swift @@ -0,0 +1,16 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection + +extension MachOSwiftSection.`Protocol` { + package func protocolName(in context: some ReadingContext) throws -> ProtocolName { + try descriptor.protocolName(in: context) + } +} + +extension ProtocolDescriptor { + package func protocolName(in context: some ReadingContext) throws -> ProtocolName { + ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleContext(for: .protocol(self), in: context), in: context)) + } +} diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift new file mode 100644 index 000000000..7119559ac --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift @@ -0,0 +1,40 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering + +extension ProtocolConformance { + /// The conforming type's name. A type bound from another image — an + /// indirect reference that resolved to a symbol — takes its kind from the + /// demangled symbol; one that names only a type alias (a C typedef) reads + /// as a struct, as `Node.typeKind` decides. + package func typeName(in context: some ReadingContext) throws -> TypeName? { + switch typeReference { + case .directTypeDescriptor(let descriptor): + return try descriptor?.typeContextDescriptorWrapper?.typeName(in: context) + case .indirectTypeDescriptor(let descriptorOrSymbol): + switch descriptorOrSymbol { + case .symbol(let symbol): + guard let node = try SymbolicDemangler.demangleType(for: symbol, in: context)?.first(of: .type) else { return nil } + guard let kind = node.typeKind else { return nil } + return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: context), kind: kind) + + case .element(let element): + return try element.typeContextDescriptorWrapper?.typeName(in: context) + + case nil: + return nil + } + case .directObjCClassName, + .indirectObjCClass: + guard let node = try typeNode(in: context) else { return nil } + return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: context), kind: .class) + } + } + + package func protocolName(in context: some ReadingContext) throws -> ProtocolName? { + guard let node = try protocolNode(in: context) else { return nil } + return ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: context)) + } +} diff --git a/Sources/SwiftDeclaration/Extensions/Sequence+NonNil.swift b/Sources/Declaration/SwiftDeclaration/Extensions/Sequence+NonNil.swift similarity index 100% rename from Sources/SwiftDeclaration/Extensions/Sequence+NonNil.swift rename to Sources/Declaration/SwiftDeclaration/Extensions/Sequence+NonNil.swift diff --git a/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift b/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift new file mode 100644 index 000000000..8414b1ebb --- /dev/null +++ b/Sources/Declaration/SwiftDeclaration/Extensions/TypeContext+Names.swift @@ -0,0 +1,27 @@ +import Demangling +import MachOSwiftSection +@_spi(Internals) import MachOSymbols +@_spi(Internals) import SwiftInspection + +extension TypeContextWrapper { + package func typeName(in context: some ReadingContext) throws -> TypeName { + try typeContextDescriptorWrapper.typeName(in: context) + } +} + +extension TypeContextDescriptorWrapper { + package var kind: TypeKind { + switch self { + case .enum: + .enum + case .struct: + .struct + case .class: + .class + } + } + + package func typeName(in context: some ReadingContext) throws -> TypeName { + return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleContext(for: .type(self), in: context), in: context), kind: kind) + } +} diff --git a/Sources/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift b/Sources/Declaration/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift similarity index 100% rename from Sources/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift rename to Sources/Declaration/SwiftIndexing/ObjCInterfaceIndexerClassHierarchyProvider.swift diff --git a/Sources/SwiftIndexing/SwiftDeclarationIndexConfiguration.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexConfiguration.swift similarity index 100% rename from Sources/SwiftIndexing/SwiftDeclarationIndexConfiguration.swift rename to Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexConfiguration.swift diff --git a/Sources/SwiftIndexing/SwiftDeclarationIndexer.swift b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift similarity index 95% rename from Sources/SwiftIndexing/SwiftDeclarationIndexer.swift rename to Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift index 609fa02ea..fda686668 100644 --- a/Sources/SwiftIndexing/SwiftDeclarationIndexer.swift +++ b/Sources/Declaration/SwiftIndexing/SwiftDeclarationIndexer.swift @@ -492,7 +492,7 @@ public final class SwiftDeclarationIndexer TypeKind? { if node.children.first?.kind == .typeAlias, - let descriptor = try SymbolicDemangler.extendedTypeContextDescriptor(forExtendedContext: mangledName, in: machO) { + let descriptor = try SymbolicDemangler.extendedTypeContextDescriptor(forExtendedContext: mangledName, in: machO.context) { return descriptor.kind } return node.typeKind @@ -635,12 +635,12 @@ public final class SwiftDeclarationIndexer, genericSignature: NodeReference?) throws -> ExtensionDefinition { - let extensionDefinition = try ExtensionDefinition(extensionName: .init(node: node, kind: kind), genericSignature: genericSignature, protocolConformance: nil, in: machO) + let extensionDefinition = ExtensionDefinition(extensionName: .init(node: node, kind: kind), genericSignature: genericSignature, protocolConformance: nil) var memberCount = 0 for (kind, memberSymbols) in memberSymbolsByKind { @@ -1063,16 +1063,11 @@ public final class SwiftDeclarationIndexer GenericContext { - guard let genericContext = try type.genericContext(in: machO) else { + guard let genericContext = try type.genericContext(in: machO.context) else { throw SpecializerError.notGenericType(type: type) } return genericContext @@ -296,8 +296,8 @@ extension GenericSpecializer { for genericRequirement in genericRequirements { // Get the mangled param name and demangle it - let mangledParamName = try genericRequirement.paramMangledName(in: machO) - let paramNode = try SymbolicDemangler.demangleType(for: mangledParamName, in: machO) + let mangledParamName = try genericRequirement.paramMangledName(in: machO.context) + let paramNode = try SymbolicDemangler.demangleType(for: mangledParamName, in: machO.context) // The requirement applies to this parameter only if its LHS is the // generic parameter directly (not an associated-type reference like A.Element). @@ -409,7 +409,7 @@ extension GenericSpecializer { switch flags.kind { case .protocol: - let resolvedContent = try genericRequirement.resolvedContent(in: machO) + let resolvedContent = try genericRequirement.resolvedContent(in: machO.context) guard case .protocol(let protocolRef) = resolvedContent, let resolved = protocolRef.resolved else { return nil @@ -418,8 +418,8 @@ extension GenericSpecializer { // Try to get protocol name let protocolName: ProtocolName if let swiftProto = resolved.swift { - let proto = try MachOSwiftSection.`Protocol`(descriptor: swiftProto, in: machO) - protocolName = try proto.protocolName(in: machO) + let proto = try MachOSwiftSection.`Protocol`(descriptor: swiftProto, in: machO.context) + protocolName = try proto.protocolName(in: machO.context) } else { return nil } @@ -430,17 +430,17 @@ extension GenericSpecializer { )) case .sameType: - let mangledTypeName = try genericRequirement.type(in: machO) - let demangledTypeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO) + let mangledTypeName = try genericRequirement.type(in: machO.context) + let demangledTypeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context) return .sameType(demangledTypeNode: demangledTypeNode, mangledName: mangledTypeName) case .baseClass: - let mangledTypeName = try genericRequirement.type(in: machO) - let demangledTypeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO) + let mangledTypeName = try genericRequirement.type(in: machO.context) + let demangledTypeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context) return .baseClass(demangledTypeNode: demangledTypeNode, mangledName: mangledTypeName) case .layout: - let resolvedContent = try genericRequirement.resolvedContent(in: machO) + let resolvedContent = try genericRequirement.resolvedContent(in: machO.context) guard case .layout(let layoutKind) = resolvedContent else { return nil } @@ -484,8 +484,8 @@ extension GenericSpecializer { let genericRequirements = Self.mergedRequirements(from: genericContext) for genericRequirement in genericRequirements { - let mangledParamName = try genericRequirement.paramMangledName(in: machO) - let paramNode = try SymbolicDemangler.demangleType(for: mangledParamName, in: machO) + let mangledParamName = try genericRequirement.paramMangledName(in: machO.context) + let paramNode = try SymbolicDemangler.demangleType(for: mangledParamName, in: machO.context) // Only handle dependent-member chains here; direct GP requirements // are collected per parameter in `collectRequirements`. @@ -950,7 +950,8 @@ extension GenericSpecializer where MachO == MachOImage { let descriptor: MachOSwiftSection.`Protocol` do { descriptor = try MachOSwiftSection.`Protocol`( - descriptor: protocolDef.value.protocolDescriptor.asPointerWrapper(in: protocolDef.machO) + descriptor: protocolDef.value.protocolDescriptor.asPointerWrapper(in: protocolDef.machO), + in: .inProcess ) } catch { // Indexer found the entry but materializing the @@ -1089,7 +1090,7 @@ extension GenericSpecializer where MachO == MachOImage { return } - guard let genericContext = (try? request.typeDescriptor.genericContext(in: machO)) ?? nil else { + guard let genericContext = (try? request.typeDescriptor.genericContext(in: machO.context)) ?? nil else { return } @@ -1128,8 +1129,8 @@ extension GenericSpecializer where MachO == MachOImage { let lhsMangled: MangledName let rhsMangled: MangledName do { - lhsMangled = try descriptor.paramMangledName(in: machO) - rhsMangled = try descriptor.type(in: machO) + lhsMangled = try descriptor.paramMangledName(in: machO.context) + rhsMangled = try descriptor.type(in: machO.context) } catch { return } @@ -1208,7 +1209,7 @@ extension GenericSpecializer where MachO == MachOImage { /// placeholder when demangling fails (rare; should never block the /// rest of the validation pipeline). private func constraintDisplayName(for mangledName: MangledName) -> String { - if let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machO) { + if let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machO.context) { return node.print(using: .interfaceTypeBuilderOnly) } return "" @@ -1276,7 +1277,7 @@ extension GenericSpecializer where MachO == MachOImage { /// Subclass-or-self test mirroring Swift runtime's `isSubclass` /// (`swift/stdlib/public/runtime/ProtocolConformance.cpp:1702`): /// pointer-equality short-circuit, then walk the superclass chain via - /// the universal `AnyClassMetadataObjCInterop.superclass()` accessor + /// the universal `AnyClassMetadataObjCInterop.superclass(in:)` accessor /// (works for pure Swift classes, ObjC class wrappers, and foreign /// classes alike). private func isClassDescendantOrSelf( @@ -1300,8 +1301,8 @@ extension GenericSpecializer where MachO == MachOImage { guard isClassLike else { return false } do { - var current = try AnyClassMetadataObjCInterop.resolve(from: selectedPointer) - while let parent = try current.superclass() { + var current = try AnyClassMetadataObjCInterop.resolve(at: selectedPointer, in: .inProcess) + while let parent = try current.superclass(in: .inProcess) { let parentPointer = try parent.asPointer if parentPointer == expectedPointer { return true } current = parent @@ -1492,7 +1493,7 @@ extension GenericSpecializer where MachO == MachOImage { let buffer = try buildKeyArgumentsBuffer(for: request, with: selection, depth: depth) // Get metadata accessor function - let accessorFunction = try typeDescriptor.typeContextDescriptor.metadataAccessorFunction() + let accessorFunction = try typeDescriptor.typeContextDescriptor.metadataAccessorFunction(in: .inProcess) guard let accessorFunction else { throw SpecializerError.metadataCreationFailed( typeName: "unknown", @@ -1791,7 +1792,7 @@ extension GenericSpecializer where MachO == MachOImage { // Generic candidates need nested specialization; surface a typed error // rather than letting the no-argument accessor call below fail with // a generic message. - if let genericContext = try typeContext.genericContext(in: machO) { + if let genericContext = try typeContext.genericContext(in: machO.context) { throw SpecializerError.candidateRequiresNestedSpecialization( candidate: candidate, parameterCount: Int(genericContext.header.numParams) @@ -1799,7 +1800,7 @@ extension GenericSpecializer where MachO == MachOImage { } // Get accessor function from type definition's type context - let accessorFunction = try typeContext.metadataAccessorFunction(in: machO) + let accessorFunction = try typeContext.metadataAccessorFunction(in: machO.context) guard let accessorFunction else { throw SpecializerError.candidateResolutionFailed( candidate: candidate, @@ -1809,8 +1810,8 @@ extension GenericSpecializer where MachO == MachOImage { // Non-generic: call accessor with no arguments let response = try accessorFunction(request: .completeAndBlocking) - let wrapper = try response.value.resolve() - return try wrapper.metadata + let wrapper = try response.value.resolve(in: .inProcess) + return try wrapper.anyMetadata.asMetadata(in: .inProcess) } /// Resolve witness table for a type conforming to a protocol using runtime conformance check @@ -1836,7 +1837,8 @@ extension GenericSpecializer where MachO == MachOImage { // Create in-process protocol descriptor and use runtime conformance check let protocolDescriptor = try MachOSwiftSection.`Protocol`( - descriptor: protocolDef.value.protocolDescriptor.asPointerWrapper(in: protocolDef.machO) + descriptor: protocolDef.value.protocolDescriptor.asPointerWrapper(in: protocolDef.machO), + in: .inProcess ) guard let witnessTable = try RuntimeFunctions.conformsToProtocol( @@ -1886,7 +1888,7 @@ extension GenericSpecializer where MachO == MachOImage { var results: [ProtocolWitnessTable] = [] - guard let genericContextInProcess = try type.genericContext() else { + guard let genericContextInProcess = try type.genericContext(in: .inProcess) else { throw AssociatedTypeResolutionError.missingGenericContext(typeDescriptor: type) } @@ -1895,7 +1897,7 @@ extension GenericSpecializer where MachO == MachOImage { } let requirements = try Self.mergedRequirements(from: genericContextInProcess) - .map { try GenericRequirement(descriptor: $0) } + .map { try GenericRequirement(descriptor: $0, in: .inProcess) } let allProtocolDefinitions = indexer.allAllProtocolDefinitions for requirement in requirements { @@ -1906,8 +1908,8 @@ extension GenericSpecializer where MachO == MachOImage { let requirementProtocolDescriptor = requirement.content.protocol?.resolved, let protocolDescriptor = requirementProtocolDescriptor.swift else { continue } - let requirementProtocol = try MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor) - let paramNode = try SymbolicDemangler.demangleType(for: requirement.paramManagledName) + let requirementProtocol = try MachOSwiftSection.`Protocol`(descriptor: protocolDescriptor, in: .inProcess) + let paramNode = try SymbolicDemangler.demangleType(for: requirement.paramManagledName, in: .inProcess) guard let pathInfo = Self.extractAssociatedPath(of: paramNode) else { throw AssociatedTypeResolutionError.unknownParamNodeStructure(paramNode: paramNode) @@ -1935,7 +1937,7 @@ extension GenericSpecializer where MachO == MachOImage { // The leaf metadata must conform to the requirement protocol; that // conformance PWT is the value the runtime expects in the slot. - let currentProtocolName = try requirementProtocol.protocolName() + let currentProtocolName = try requirementProtocol.protocolName(in: .inProcess) guard let associatedTypePWT = try? RuntimeFunctions.conformsToProtocol( metadata: currentMetadata, protocolDescriptor: requirementProtocol.descriptor @@ -1982,14 +1984,15 @@ extension GenericSpecializer where MachO == MachOImage { let stepProtocol: MachOSwiftSection.`Protocol` do { stepProtocol = try MachOSwiftSection.`Protocol`( - descriptor: entry.value.protocolDescriptor.asPointerWrapper(in: entry.machO) + descriptor: entry.value.protocolDescriptor.asPointerWrapper(in: entry.machO), + in: .inProcess ) } catch { throw AssociatedTypeResolutionError.failedToCreateAssociatedTypeRefProtocol(underlyingError: error) } - let stepProtocolFullName = try stepProtocol.protocolName() - let availableAssociatedTypes = try stepProtocol.descriptor.associatedTypes() + let stepProtocolFullName = try stepProtocol.protocolName(in: .inProcess) + let availableAssociatedTypes = try stepProtocol.descriptor.associatedTypes(in: .inProcess) guard let associatedTypeIndex = availableAssociatedTypes.firstIndex(of: step.name) else { throw AssociatedTypeResolutionError.missingAssociatedTypeIndex( @@ -2031,7 +2034,7 @@ extension GenericSpecializer where MachO == MachOImage { conformingTypeMetadata: currentMetadata, baseRequirement: baseRequirement, associatedTypeRequirement: accessFunctionRequirement - ).value.resolve().metadata else { + ).value.resolve(in: .inProcess).anyMetadata.asMetadata(in: .inProcess) else { throw AssociatedTypeResolutionError.failedToGetAssociatedTypeWitness( conformingType: currentMetadata, protocolName: stepProtocolFullName, diff --git a/Sources/SwiftSpecialization/SpecializationRequest.swift b/Sources/Declaration/SwiftSpecialization/SpecializationRequest.swift similarity index 100% rename from Sources/SwiftSpecialization/SpecializationRequest.swift rename to Sources/Declaration/SwiftSpecialization/SpecializationRequest.swift diff --git a/Sources/SwiftSpecialization/SpecializationResult.swift b/Sources/Declaration/SwiftSpecialization/SpecializationResult.swift similarity index 95% rename from Sources/SwiftSpecialization/SpecializationResult.swift rename to Sources/Declaration/SwiftSpecialization/SpecializationResult.swift index 20d4d6555..a0f42d6f9 100644 --- a/Sources/SwiftSpecialization/SpecializationResult.swift +++ b/Sources/Declaration/SwiftSpecialization/SpecializationResult.swift @@ -30,12 +30,12 @@ public struct SpecializationResult: @unchecked Sendable { /// Get resolved metadata wrapper public func resolveMetadata() throws -> MetadataWrapper { - try metadataPointer.resolve() + try metadataPointer.resolve(in: .inProcess) } /// Get resolved metadata public func metadata() throws -> Metadata { - try resolveMetadata().metadata + try resolveMetadata().anyMetadata.asMetadata(in: .inProcess) } } @@ -93,6 +93,6 @@ extension SpecializationResult { /// would crash with SIGBUS and is intentionally not exposed here. public func valueWitnessTable() throws -> ValueWitnessTable { let wrapper = try resolveMetadata() - return try wrapper.valueWitnessTable() + return try wrapper.valueWitnessTable(in: .inProcess) } } diff --git a/Sources/SwiftSpecialization/SpecializationSelection.swift b/Sources/Declaration/SwiftSpecialization/SpecializationSelection.swift similarity index 100% rename from Sources/SwiftSpecialization/SpecializationSelection.swift rename to Sources/Declaration/SwiftSpecialization/SpecializationSelection.swift diff --git a/Sources/SwiftSpecialization/SpecializationValidation.swift b/Sources/Declaration/SwiftSpecialization/SpecializationValidation.swift similarity index 100% rename from Sources/SwiftSpecialization/SpecializationValidation.swift rename to Sources/Declaration/SwiftSpecialization/SpecializationValidation.swift diff --git a/Sources/SwiftSpecialization/TypeDefinition+Specialization.swift b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift similarity index 98% rename from Sources/SwiftSpecialization/TypeDefinition+Specialization.swift rename to Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift index 86743c45b..01e88ed8e 100644 --- a/Sources/SwiftSpecialization/TypeDefinition+Specialization.swift +++ b/Sources/Declaration/SwiftSpecialization/TypeDefinition+Specialization.swift @@ -203,7 +203,7 @@ extension TypeDefinition { // This specialize operation's single wrapper materialization // (proposal 0002): feeds the typeName derivation and the designated // init below, released when this function returns. - let materializedTypeContext = try materializedTypeContext(in: machO) + let materializedTypeContext = try materializedTypeContext(in: machO.context) // Compute the final typeName up-front so it can flow through the // designated init: either the unbound form (`Box`) when no type @@ -212,7 +212,7 @@ extension TypeDefinition { // definition print as `Box` rather than the placeholder // `Box`, and gives it a unique mangled name per specialization // (via `mangleAsString(typeName.node)`). - let unboundTypeName = try materializedTypeContext.typeName(in: machO) + let unboundTypeName = try materializedTypeContext.typeName(in: machO.context) let finalTypeName: TypeName if let typeArgumentNodes, !typeArgumentNodes.isEmpty { finalTypeName = Self.boundGenericTypeName( @@ -409,11 +409,11 @@ extension TypeDefinition { private func descriptorOffset(of metadata: MetadataWrapper) throws -> Int { switch metadata { case .struct(let structMetadata): - return try structMetadata.descriptor().contextDescriptor.offset + return try structMetadata.descriptor(in: .inProcess).contextDescriptor.offset case .class(let classMetadata): - return try required(classMetadata.descriptor()).offset + return try required(classMetadata.descriptor(in: .inProcess)).offset case .enum(let enumMetadata), .optional(let enumMetadata), .errorObject(let enumMetadata): - return try enumMetadata.descriptor().contextDescriptor.offset + return try enumMetadata.descriptor(in: .inProcess).contextDescriptor.offset default: // Other metadata kinds don't carry a nominal-type descriptor in // the form we compare against here. Treating this as a hard diff --git a/Sources/TypeIndexing/APINotesIndex.swift b/Sources/Declaration/TypeIndexing/APINotesIndex.swift similarity index 100% rename from Sources/TypeIndexing/APINotesIndex.swift rename to Sources/Declaration/TypeIndexing/APINotesIndex.swift diff --git a/Sources/TypeIndexing/InterfaceDeclarationNode.swift b/Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift similarity index 100% rename from Sources/TypeIndexing/InterfaceDeclarationNode.swift rename to Sources/Declaration/TypeIndexing/InterfaceDeclarationNode.swift diff --git a/Sources/TypeIndexing/InterfaceTypeNameExtractor.swift b/Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift similarity index 100% rename from Sources/TypeIndexing/InterfaceTypeNameExtractor.swift rename to Sources/Declaration/TypeIndexing/InterfaceTypeNameExtractor.swift diff --git a/Sources/TypeIndexing/ModuleIndexCache.swift b/Sources/Declaration/TypeIndexing/ModuleIndexCache.swift similarity index 100% rename from Sources/TypeIndexing/ModuleIndexCache.swift rename to Sources/Declaration/TypeIndexing/ModuleIndexCache.swift diff --git a/Sources/TypeIndexing/ModuleInterfaceIndexer.swift b/Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift similarity index 100% rename from Sources/TypeIndexing/ModuleInterfaceIndexer.swift rename to Sources/Declaration/TypeIndexing/ModuleInterfaceIndexer.swift diff --git a/Sources/TypeIndexing/SDKIndexer.swift b/Sources/Declaration/TypeIndexing/SDKIndexer.swift similarity index 100% rename from Sources/TypeIndexing/SDKIndexer.swift rename to Sources/Declaration/TypeIndexing/SDKIndexer.swift diff --git a/Sources/TypeIndexing/SDKPlatform.swift b/Sources/Declaration/TypeIndexing/SDKPlatform.swift similarity index 100% rename from Sources/TypeIndexing/SDKPlatform.swift rename to Sources/Declaration/TypeIndexing/SDKPlatform.swift diff --git a/Sources/TypeIndexing/SourceKitManager.swift b/Sources/Declaration/TypeIndexing/SourceKitManager.swift similarity index 100% rename from Sources/TypeIndexing/SourceKitManager.swift rename to Sources/Declaration/TypeIndexing/SourceKitManager.swift diff --git a/Sources/TypeIndexing/Subprocess.swift b/Sources/Declaration/TypeIndexing/Subprocess.swift similarity index 100% rename from Sources/TypeIndexing/Subprocess.swift rename to Sources/Declaration/TypeIndexing/Subprocess.swift diff --git a/Sources/TypeIndexing/SupplementaryAPINotes.swift b/Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift similarity index 100% rename from Sources/TypeIndexing/SupplementaryAPINotes.swift rename to Sources/Declaration/TypeIndexing/SupplementaryAPINotes.swift diff --git a/Sources/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift b/Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift similarity index 100% rename from Sources/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift rename to Sources/Declaration/TypeIndexing/SwiftInterfaceBuilderTypeNameProvider.swift diff --git a/Sources/TypeIndexing/TypeDatabase.swift b/Sources/Declaration/TypeIndexing/TypeDatabase.swift similarity index 94% rename from Sources/TypeIndexing/TypeDatabase.swift rename to Sources/Declaration/TypeIndexing/TypeDatabase.swift index a65265f70..2bcde721c 100644 --- a/Sources/TypeIndexing/TypeDatabase.swift +++ b/Sources/Declaration/TypeIndexing/TypeDatabase.swift @@ -136,10 +136,16 @@ package actor TypeDatabase { for (cName, moduleName) in attributionIndex.moduleNamesByCName { moduleNamesByTypeName[cName] = moduleName } - // The renamed Swift spelling reaches manglings too: a foreign - // descriptor the consuming binary emits records the *imported* name - // (`__C.Graph` for an `AG_SWIFT_NAME(Graph)` type), so it needs - // attribution alongside the C spellings. Nested renames + // Swift spellings too, after the C spellings. A printed `__C` name no + // longer carries one: a foreign descriptor records the imported + // spelling (`Graph` for an `AG_SWIFT_NAME(Graph)` type), but the + // demangler names it by the ABI name in its import info (evolution + // proposal `type-import-info-identity`). What this pass still decides + // is a C name several modules' APINotes list. Foundation's and + // AppKit's list `NSObject` only to annotate category methods, and the + // pass above lets whichever file came last win; ObjectiveC's entry + // renames `NSObject` to itself, so registering that spelling last + // gives the class back to ObjectiveC. Nested renames // (`ProcessInfo.ActivityOptions`) never appear as one identifier and // are skipped. for (swiftName, originalCName) in attributionIndex.cNamesBySwiftName where !swiftName.contains(".") { diff --git a/Sources/baseline-generator/BaselineGeneratorMain.swift b/Sources/Executables/baseline-generator/BaselineGeneratorMain.swift similarity index 100% rename from Sources/baseline-generator/BaselineGeneratorMain.swift rename to Sources/Executables/baseline-generator/BaselineGeneratorMain.swift diff --git a/Sources/Executables/swift-section/Commands/DiffCommand.swift b/Sources/Executables/swift-section/Commands/DiffCommand.swift new file mode 100644 index 000000000..89fd6b691 --- /dev/null +++ b/Sources/Executables/swift-section/Commands/DiffCommand.swift @@ -0,0 +1,147 @@ +import Foundation +import ArgumentParser +import SwiftSectionKit + +/// The output format for the annotated interface (`--interface`). +enum DiffOutputFormat: String, CaseIterable, ExpressibleByArgument { + /// git-diff-style `+`/`-`/` ` line prefixes (the default). + case inline + /// A real unified diff (`--- old`/`+++ new` + `@@` hunks), consumable by + /// `git apply` / `patch` / `delta`. + case unified + /// The inline body wrapped in a Markdown ```` ```diff ```` fence. + case markdown + + var annotatedDiffFormat: AnnotatedDiffFormat { + switch self { + case .inline: + .inline + case .unified: + .unified + case .markdown: + .markdownFenced + } + } +} + +struct DiffCommand: AsyncParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "diff", + abstract: "Diff the Swift ABI of two Mach-O binaries (or persisted baseline snapshots)." + ) + + @Argument(help: "The old (baseline) side: a Mach-O file path or a snapshot JSON produced by `swift-section snapshot`.", completion: .file()) + var oldPath: String + + @Argument(help: "The new side: a Mach-O file path or a snapshot JSON.", completion: .file()) + var newPath: String + + @Option(name: .shortAndLong, help: "The architecture slice to use for fat binaries. Required when either path is a fat (universal) binary.") + var architecture: Architecture? + + @Flag(name: [.customLong("dyld-shared-cache")], help: "Treat both paths as dyld shared caches and extract the same image (--cache-image-name) from each.") + var isDyldSharedCache: Bool = false + + @Option(name: [.long, .customShort("n")], help: "Image name to extract from each dyld shared cache (e.g. SwiftUICore).") + var cacheImageName: String? + + @Option(name: [.long, .customShort("p")], help: "Image path to extract from each dyld shared cache.") + var cacheImagePath: String? + + @Flag(help: "Print only the breaking/backward-compatible verdict, not the full report.") + var summaryOnly: Bool = false + + @Flag(help: "Emit the ABI diff as JSON (with provenance) instead of the text report.") + var json: Bool = false + + @Flag(help: "Emit the full Swift interface annotated with diff markers instead of the change-list.") + var interface: Bool = false + + @Option(name: .long, help: "Annotated-interface format: inline (git-diff style), unified (real unified diff), or markdown (```diff fence). Requires --interface; defaults to inline.") + var format: DiffOutputFormat? + + @Flag(help: "Exit with a nonzero status when the diff contains an ABI-breaking change, for CI gating. Honored with --interface too.") + var failOnBreaking: Bool = false + + @Option(name: .shortAndLong, help: "Write the report to this path instead of stdout.", completion: .file()) + var outputPath: String? + + @Option(name: .long, help: "How many inputs to index at once (default: the processor count). Pass 1 to index the old side, then the new side.") + var jobs: Int? + + /// The library request these flags describe. + func makeRequest() -> ABIDiffRequest { + let report: ABIDiffRequest.Report + if interface { + report = .annotatedInterface( + format: (format ?? .inline).annotatedDiffFormat, + // Only the `--fail-on-breaking` CI gate needs the change-list + // diff on the annotated-interface path. + includesBreakingChangeVerdict: failOnBreaking + ) + } else if json { + report = .json + } else if summaryOnly { + report = .summary + } else { + report = .changeList + } + // validate() has already required exactly one of -n / -p with + // --dyld-shared-cache. + let cacheImage: DyldSharedCacheImage? = cacheImageName.map { .name($0) } ?? cacheImagePath.map { .path($0) } + return ABIDiffRequest( + old: .path(oldPath), + new: .path(newPath), + binaryLoading: BinaryLoadingOptions( + architecture: architecture, + dyldSharedCacheImage: isDyldSharedCache ? cacheImage : nil + ), + report: report, + destination: outputPath.map { .file(path: $0) } ?? .output, + maximumConcurrentPreparations: jobs + ) + } + + func run() async throws { + let outcome: ABIDiffOutcome + do { + outcome = try await makeRequest().run(output: StandardStreamOutput(), environment: .commandLine) + } catch { + throw CommandLineErrorTranslation.translated(error, annotatedInterfaceRequiresBinaries: { _ in + "--interface needs two binaries; snapshot JSON inputs only support the change-list report." + }) + } + if failOnBreaking, outcome.hasBreakingChange == true { + throw ExitCode.failure + } + } + + /// 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, summaryOnly { + throw ValidationError("--interface and --summary-only are mutually exclusive.") + } + if json, interface { + throw ValidationError("--json and --interface are mutually exclusive.") + } + if json, summaryOnly { + throw ValidationError("--json and --summary-only are mutually exclusive.") + } + if format != nil, !interface { + throw ValidationError("--format only applies to the annotated interface; pass --interface.") + } + if let jobs, jobs < 1 { + throw ValidationError("--jobs must be at least 1.") + } + if cacheImageName != nil, cacheImagePath != nil { + throw ValidationError("--cache-image-name and --cache-image-path are mutually exclusive; pass only one.") + } + if cacheImageName != nil || cacheImagePath != nil, !isDyldSharedCache { + throw ValidationError("--cache-image-name / --cache-image-path require --dyld-shared-cache.") + } + if isDyldSharedCache, cacheImageName == nil, cacheImagePath == nil { + throw ValidationError("--dyld-shared-cache requires --cache-image-name or --cache-image-path.") + } + } +} diff --git a/Sources/Executables/swift-section/Commands/DumpCommand.swift b/Sources/Executables/swift-section/Commands/DumpCommand.swift new file mode 100644 index 000000000..ef12e0d5c --- /dev/null +++ b/Sources/Executables/swift-section/Commands/DumpCommand.swift @@ -0,0 +1,91 @@ +import Foundation +import ArgumentParser +import SwiftSectionKit + +struct DumpCommand: AsyncParsableCommand, Sendable { + static let configuration: CommandConfiguration = .init( + commandName: "dump", + abstract: "Dump Swift information from a Mach-O file or dyld shared cache." + ) + + @OptionGroup + var machOOptions: MachOOptionGroup + + @OptionGroup + var demangleOptions: DemangleOptionGroup + + @OptionGroup(title: "Comment Templates") + var transformerOptions: TransformerOptionGroup + + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) + var outputPath: String? + + @Option(name: .shortAndLong, parsing: .upToNextOption, help: "The sections to dump. If not specified, all sections will be dumped.") + var sections: [DumpSection] = [] + + @Option(name: .shortAndLong, help: "The color scheme for the output.") + var colorScheme: SemanticColorScheme = .none + + @Flag(help: "Generate member address comments for each member symbol") + var emitMemberAddresses: Bool = false + + @Flag(help: "Generate vtable offset comments for class methods") + var emitVtableOffsets: Bool = false + + @Flag(help: "Generate PWT (Protocol Witness Table) address comments for protocol conformances") + var emitPWTAddresses: Bool = false + + @Flag(help: "Generate field offset comments for struct/class stored properties, computed statically via SwiftLayout") + var emitFieldOffsets: Bool = false + + @Flag(help: "Generate type layout (size/stride/alignment) comments, computed statically via SwiftLayout") + var emitTypeLayout: Bool = false + + @Flag(help: "Generate enum layout (strategy/per-case/spare-bit) comments, computed statically via SwiftLayout") + var emitEnumLayout: Bool = false + + @Flag(help: "Expand nested struct fields with their absolute offsets (implies --emit-field-offsets)") + var emitExpandedFieldOffsets: Bool = false + + @Flag(help: "The definitions of types and protocols will be output in the order they are stored in the binary.") + var preferredBinaryOrder: Bool = false + + @Flag(help: "Emit a leading header comment block (generator, image path, UUID, architecture, library-evolution detection, unrecoverable-facts notes)") + var emitHeader: Bool = false + + @Flag(help: "Annotate member-symbol lines whose symbol has no export-trie entry with a `not exported` comment") + var emitExportStatus: Bool = false + + /// The library request these flags describe. + func makeRequest() throws -> DumpRequest { + DumpRequest( + source: try machOOptions.machOSource(), + dependencySearchPaths: machOOptions.dependencySearchPathValues, + sections: sections.isEmpty ? .all : .only(sections), + ordering: preferredBinaryOrder ? .binaryOrder : .bySection, + demangleOptions: demangleOptions.buildSwiftDumpDemangleOptions(), + fieldOffsetComments: emitExpandedFieldOffsets ? .expanded : (emitFieldOffsets ? .flat : .none), + emitsMemberAddresses: emitMemberAddresses, + emitsVTableOffsets: emitVtableOffsets, + emitsProtocolWitnessTableAddresses: emitPWTAddresses, + emitsTypeLayout: emitTypeLayout, + emitsEnumLayout: emitEnumLayout, + emitsExportStatus: emitExportStatus, + emitsHeader: emitHeader, + commentTransformers: try transformerOptions.buildTransformerConfiguration(), + destination: outputPath.map { .file(path: $0) } ?? .output + ) + } + + func run() async throws { + let request = try makeRequest() + do { + try await request.run( + output: StandardStreamOutput(colorScheme: colorScheme, standardOutputSeverities: [.error]), + environment: .commandLine + ) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + } +} diff --git a/Sources/Executables/swift-section/Commands/EvolutionCommand.swift b/Sources/Executables/swift-section/Commands/EvolutionCommand.swift new file mode 100644 index 000000000..cce05761a --- /dev/null +++ b/Sources/Executables/swift-section/Commands/EvolutionCommand.swift @@ -0,0 +1,155 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +struct EvolutionCommand: AsyncParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "evolution", + abstract: "Track the Swift ABI of one module across an ordered series of binary versions.", + discussion: """ + Pass two or more inputs in version order (oldest first). Each input is either a \ + Mach-O / fat binary, a dyld shared cache (with --dyld-shared-cache, extracting the \ + same image from every cache), or a baseline snapshot produced by `swift-section snapshot`. + """ + ) + + @Argument(help: "The input paths in version order (oldest first); Mach-O binaries, dyld shared caches, or snapshot JSON files.", completion: .file()) + var inputPaths: [String] + + @Option(name: .long, help: "Comma-separated version labels for the axis (e.g. 17.0,18.0,26.0); one per input. Defaults to each snapshot's stored label or the input's file name.") + var labels: String? + + @Option(name: .shortAndLong, help: "The architecture slice to use for fat binaries. Required when any input is a fat (universal) binary.") + var architecture: Architecture? + + @Flag(name: [.customLong("dyld-shared-cache")], help: "Treat every binary input as a dyld shared cache and extract the same image (--cache-image-name) from each.") + var isDyldSharedCache: Bool = false + + @Option(name: [.long, .customShort("n")], help: "Image name to extract from each dyld shared cache (e.g. SwiftUICore).") + var cacheImageName: String? + + @Option(name: [.long, .customShort("p")], help: "Image path to extract from each dyld shared cache.") + var cacheImagePath: String? + + @Flag(help: "Print only the header and per-transition summary, not the full lineage report.") + var summaryOnly: Bool = false + + @Flag(help: "Emit the evolution as JSON instead of the text report.") + var json: Bool = false + + @Flag(help: "Emit the union Swift interface annotated with per-declaration lifecycle comments instead of the lineage report. 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 is fully expressible as one @available attribute (introduced:/obsoleted: resolved from the version axis) with that genuine attribute. 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 @available platform spelling (e.g. iOS, macOS, macCatalyst) for --emit-available, overriding LC_BUILD_VERSION inference.") + var platform: String? + + @Flag(help: "Exit with a nonzero status when any transition contains an ABI-breaking change, for CI gating.") + var failOnBreaking: Bool = false + + @Option(name: .shortAndLong, help: "Write the report to this path instead of stdout.", completion: .file()) + var outputPath: String? + + @Option(name: .long, help: "How many inputs to index at once (default: the processor count). Pass 1 to index the versions one after the other, oldest first.") + var jobs: Int? + + /// The library request these flags describe. + func makeRequest() -> ABIEvolutionRequest { + let report: ABIEvolutionRequest.Report = if interface { + .annotatedInterface(availabilityAttributes: availabilityAttributes) + } else if json { + .json + } else if summaryOnly { + .summary + } else { + .lineage + } + // validate() has already required exactly one of -n / -p with + // --dyld-shared-cache. + let cacheImage: DyldSharedCacheImage? = cacheImageName.map { .name($0) } ?? cacheImagePath.map { .path($0) } + return ABIEvolutionRequest( + inputs: inputPaths.map { .path($0) }, + labels: labels.map(Self.splitLabels), + binaryLoading: BinaryLoadingOptions( + architecture: architecture, + dyldSharedCacheImage: isDyldSharedCache ? cacheImage : nil + ), + report: report, + destination: outputPath.map { .file(path: $0) } ?? .output, + maximumConcurrentPreparations: jobs + ) + } + + /// `--emit-available`, with `--platform` naming the platform instead of + /// leaving it to inference. validate() has already required + /// `--emit-available` for `--platform`. + private var availabilityAttributes: ABIEvolutionRequest.AvailabilityAttributes { + if !emitAvailable { + .none + } else if let platform { + .platform(platform) + } else { + .inferredPlatform + } + } + + /// `--labels a,b,c`, each label trimmed. Empty labels are kept, so that a + /// stray comma fails the one-label-per-input check instead of shifting + /// every label after it. + static func splitLabels(_ commaSeparatedLabels: String) -> [String] { + commaSeparatedLabels + .split(separator: ",", omittingEmptySubsequences: false) + .map { $0.trimmingCharacters(in: .whitespaces) } + } + + func run() async throws { + let outcome: ABIEvolutionOutcome + do { + outcome = try await makeRequest().run(output: StandardStreamOutput(), environment: .commandLine) + } catch { + 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 + } + } + + /// 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).") + } + if json, summaryOnly { + throw ValidationError("--json and --summary-only are mutually exclusive.") + } + if let jobs, jobs < 1 { + throw ValidationError("--jobs must be at least 1.") + } + if cacheImageName != nil, cacheImagePath != nil { + throw ValidationError("--cache-image-name and --cache-image-path are mutually exclusive; pass only one.") + } + if cacheImageName != nil || cacheImagePath != nil, !isDyldSharedCache { + throw ValidationError("--cache-image-name / --cache-image-path require --dyld-shared-cache.") + } + if isDyldSharedCache, cacheImageName == nil, cacheImagePath == nil { + throw ValidationError("--dyld-shared-cache requires --cache-image-name or --cache-image-path.") + } + } +} diff --git a/Sources/Executables/swift-section/Commands/InterfaceCommand.swift b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift new file mode 100644 index 000000000..7d9c0c0e6 --- /dev/null +++ b/Sources/Executables/swift-section/Commands/InterfaceCommand.swift @@ -0,0 +1,105 @@ +import Foundation +import ArgumentParser +import SwiftSectionKit + +struct InterfaceCommand: AsyncParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "interface", + abstract: "Generate Swift interface from a Mach-O file." + ) + + @OptionGroup + var machOOptions: MachOOptionGroup + + @OptionGroup + var objcMemberOptions: ObjCMemberOptionGroup + + @OptionGroup(title: "Comment Templates") + var transformerOptions: TransformerOptionGroup + + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) + var outputPath: String? + + @Flag(help: "Show imported C types in the generated Swift interface.") + var showCImportedTypes: Bool = false + + @Flag(help: "Parse opaque return value, this option is an experimental feature and may result in parsing errors for complex return types.") + var parseOpaqueReturnType: Bool = false + + @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, and its dependencies' ObjC metadata. Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") + var resolveCModuleNames: Bool = false + + @Option(name: .customLong("supplementary-apinotes"), help: "A supplementary .apinotes file (or a directory of them) of user-provided type mappings for frameworks with no SDK module (e.g. AttributeGraph), loaded on top of the SDK's own APINotes. Repeatable; later paths override earlier ones. Only used with --resolve-c-module-names.", completion: .file()) + var supplementaryAPINotesPaths: [String] = [] + + @Flag(help: "Generate field offset and PWT offset comments, if possible") + var emitOffsetComments: Bool = false + + @Flag(help: "Generate member address comments for each member symbol") + var emitMemberAddresses: Bool = false + + @Flag(help: "Generate vtable offset comments for class methods, computed properties, and non-final stored properties' accessors") + var emitVtableOffsets: Bool = false + + @Flag(help: "Expand nested struct fields with their absolute offsets (implies --emit-offset-comments)") + var emitExpandedFieldOffsets: Bool = false + + @Flag(help: "Generate type layout (size/stride/alignment) comments, computed statically via SwiftLayout") + var emitTypeLayout: Bool = false + + @Flag(help: "Generate enum layout (strategy/per-case/spare-bit) comments, computed statically via SwiftLayout") + var emitEnumLayout: Bool = false + + @Flag(help: "Sort members by binary layout offset instead of grouping by category") + var sortMembersByOffset: Bool = false + + @Flag(help: "Emit a leading header comment block (generator, image path, UUID, architecture, library-evolution detection, unrecoverable-facts notes)") + var emitHeader: Bool = false + + @Flag(help: "Annotate members none of whose symbols have an export-trie entry with a `not exported` comment") + var emitExportStatus: Bool = false + + @Flag(name: .customLong("exported-only"), help: "Print only the declarations the image exports: types and protocols whose descriptor symbol has an export-trie entry, extensions targeting them, and members with at least one exported symbol (dispatch-thunk and other derived forms included). `override` / `@objc` members and anything without export evidence are kept.") + var exportedOnly: Bool = false + + @Option(name: .shortAndLong, help: "The color scheme for the output.") + var colorScheme: SemanticColorScheme = .none + + /// The library request these flags describe. + func makeRequest() throws -> InterfaceRequest { + InterfaceRequest( + source: try machOOptions.machOSource(), + dependencySearchPaths: machOOptions.dependencySearchPathValues, + showsCImportedTypes: showCImportedTypes, + parsesOpaqueReturnTypes: parseOpaqueReturnType, + cModuleNameResolution: resolveCModuleNames ? .enabled(supplementaryAPINotesPaths: supplementaryAPINotesPaths) : .disabled, + fieldOffsetComments: emitExpandedFieldOffsets ? .expanded : (emitOffsetComments ? .flat : .none), + emitsMemberAddresses: emitMemberAddresses, + emitsVTableOffsets: emitVtableOffsets, + emitsTypeLayout: emitTypeLayout, + emitsEnumLayout: emitEnumLayout, + emitsExportStatus: emitExportStatus, + printsExportedDeclarationsOnly: exportedOnly, + memberSortOrder: sortMembersByOffset ? .byOffset : .byCategory, + infersObjCOverridesFromSelectorNames: objcMemberOptions.infersOverridesFromSelectorNames, + emitsHeader: emitHeader, + commentTransformers: try transformerOptions.buildTransformerConfiguration(), + destination: outputPath.map { .file(path: $0) } ?? .output + ) + } + + func run() async throws { + let request = try makeRequest() + // Progress lines have always gone to stdout here, mixed into the + // product unless `-o` is given. + let output = StandardStreamOutput(colorScheme: colorScheme, standardOutputSeverities: [.progress]) + if !resolveCModuleNames, !supplementaryAPINotesPaths.isEmpty { + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: --supplementary-apinotes has no effect without --resolve-c-module-names")) + } + do { + try await request.run(output: output, environment: .commandLine) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + } +} diff --git a/Sources/Executables/swift-section/Commands/SnapshotCommand.swift b/Sources/Executables/swift-section/Commands/SnapshotCommand.swift new file mode 100644 index 000000000..7040f77ca --- /dev/null +++ b/Sources/Executables/swift-section/Commands/SnapshotCommand.swift @@ -0,0 +1,54 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +struct SnapshotCommand: AsyncParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "snapshot", + abstract: "Index a Mach-O binary's Swift ABI and persist it as a baseline snapshot (JSON)." + ) + + @OptionGroup var machOOptions: MachOOptionGroup + + @Option(name: .long, help: "A human-readable version label stored in the snapshot's provenance (e.g. 17.0).") + var label: String? + + @Option(name: .shortAndLong, help: "Write the snapshot JSON to this path instead of stdout.", completion: .file()) + var outputPath: String? + + /// The library request these flags describe. + func makeRequest() throws -> ABISnapshotRequest { + guard let filePath = machOOptions.filePath else { + throw ValidationError("A Mach-O file path is required.") + } + return ABISnapshotRequest( + source: .path(filePath), + binaryLoading: try makeBinaryLoadingOptions( + isDyldSharedCache: machOOptions.isDyldSharedCache, + cacheImageName: machOOptions.cacheImageName, + cacheImagePath: machOOptions.cacheImagePath, + architecture: machOOptions.architecture + ), + dependencySearchPaths: machOOptions.dependencySearchPathValues, + label: label, + destination: outputPath.map { .file(path: $0) } ?? .output + ) + } + + func run() async throws { + let request = try makeRequest() + do { + try await request.run(output: StandardStreamOutput(), environment: .commandLine) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + } + + func validate() throws { + if machOOptions.usesSystemDyldSharedCache { + // A snapshot of "the current system cache" would have no stable + // path to record; require an explicit cache file for baselines. + throw ValidationError("snapshot requires an explicit file path; --uses-system-dyld-shared-cache is not supported here.") + } + } +} diff --git a/Sources/Executables/swift-section/Commands/TransformerCommand.swift b/Sources/Executables/swift-section/Commands/TransformerCommand.swift new file mode 100644 index 000000000..7252000b2 --- /dev/null +++ b/Sources/Executables/swift-section/Commands/TransformerCommand.swift @@ -0,0 +1,89 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +// MARK: - Command + +struct TransformerCommand: ParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "transformer", + abstract: "Inspect and build the comment transformer configuration used by `dump` and `interface`.", + discussion: """ + Comment templates substitute ${token} placeholders. Use `tokens` to see what each \ + module's templates accept, `templates` to see the built-in templates (their names can \ + be passed to the template options directly), and `config` to produce a JSON \ + configuration for --transformer-config. + """, + subcommands: [ + TokensCommand.self, + TemplatesCommand.self, + ConfigCommand.self, + ], + defaultSubcommand: TokensCommand.self + ) +} + +// MARK: - Tokens + +extension TransformerCommand { + struct TokensCommand: ParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "tokens", + abstract: "List the ${token} placeholders each comment template accepts." + ) + + @Option(name: .shortAndLong, help: "Restrict the listing to one module. If not specified, all modules are listed.") + var module: TransformerModule? + + func run() throws { + TransformerTokensRequest(module: module).run(output: StandardStreamOutput()) + } + } +} + +// MARK: - Templates + +extension TransformerCommand { + struct TemplatesCommand: ParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "templates", + abstract: "List the built-in comment templates. Their names are accepted by the template options." + ) + + @Option(name: .shortAndLong, help: "Restrict the listing to one module. If not specified, all modules are listed.") + var module: TransformerModule? + + func run() throws { + TransformerTemplatesRequest(module: module).run(output: StandardStreamOutput()) + } + } +} + +// MARK: - Config + +extension TransformerCommand { + struct ConfigCommand: ParsableCommand { + static let configuration: CommandConfiguration = .init( + commandName: "config", + abstract: "Print the transformer configuration described by the given options as JSON.", + discussion: """ + Without any option this prints the all-defaults skeleton, a starting point to edit \ + and feed back through --transformer-config. With options it prints what those \ + options resolve to, so a command line can be frozen into a reusable file. + """ + ) + + @OptionGroup + var transformerOptions: TransformerOptionGroup + + @Option(name: .shortAndLong, help: "The output path for the configuration. If not specified, it is printed to the console.", completion: .file()) + var outputPath: String? + + func run() throws { + try TransformerConfigurationRequest( + configuration: transformerOptions.buildTransformerConfiguration() ?? .init(), + destination: outputPath.map { .file(path: $0) } ?? .output + ).run(output: StandardStreamOutput()) + } + } +} diff --git a/Sources/Executables/swift-section/Models/CommandLineSupport.swift b/Sources/Executables/swift-section/Models/CommandLineSupport.swift new file mode 100644 index 000000000..95b537300 --- /dev/null +++ b/Sources/Executables/swift-section/Models/CommandLineSupport.swift @@ -0,0 +1,112 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +// The library's enums, spelled on the command line by their raw values. The +// library is in this package, so the conformances are not retroactive. +extension Architecture: ExpressibleByArgument {} +extension DumpSection: ExpressibleByArgument {} +extension TransformerModule: ExpressibleByArgument {} +extension ObjCDeclarationKind: ExpressibleByArgument {} + +extension SwiftSectionEnvironment { + /// What the command line stamps into headers and provenance. + static var commandLine: SwiftSectionEnvironment { + SwiftSectionEnvironment(generator: GeneratorIdentity(name: "swift-section", version: BundledVersion.value)) + } +} + +/// The image the input options name, rejecting the combinations a +/// `MachOSource` cannot express with the messages the command line has always +/// printed for them. Shared by the Swift and the ObjC option groups. +func makeMachOSource( + filePath: String?, + isDyldSharedCache: Bool, + usesSystemDyldSharedCache: Bool, + cacheImageName: String?, + cacheImagePath: String?, + architecture: Architecture? +) throws -> MachOSource { + guard isDyldSharedCache || usesSystemDyldSharedCache else { + guard let filePath else { throw SwiftSectionCommandError.missingFilePath } + return .file(path: filePath, architecture: architecture) + } + guard usesSystemDyldSharedCache || filePath != nil else { + throw SwiftSectionCommandError.missingFilePath + } + let image = try makeDyldSharedCacheImage(cacheImageName: cacheImageName, cacheImagePath: cacheImagePath) + if usesSystemDyldSharedCache { + return .systemDyldSharedCache(image: image) + } else { + // Checked above. + return .dyldSharedCache(cachePath: filePath!, image: image) + } +} + +/// The binary-loading options of `snapshot`: `--dyld-shared-cache` turns every +/// binary input into a cache to extract the named image from. +func makeBinaryLoadingOptions( + isDyldSharedCache: Bool, + cacheImageName: String?, + cacheImagePath: String?, + architecture: Architecture? +) throws -> BinaryLoadingOptions { + BinaryLoadingOptions( + architecture: architecture, + dyldSharedCacheImage: isDyldSharedCache + ? try makeDyldSharedCacheImage(cacheImageName: cacheImageName, cacheImagePath: cacheImagePath) + : nil + ) +} + +private func makeDyldSharedCacheImage(cacheImageName: String?, cacheImagePath: String?) throws -> DyldSharedCacheImage { + if cacheImagePath != nil, cacheImageName != nil { + throw SwiftSectionCommandError.ambiguousCacheImageNameAndCacheImagePath + } else if let cacheImageName { + return .name(cacheImageName) + } else if let cacheImagePath { + return .path(cacheImagePath) + } else { + throw SwiftSectionCommandError.missingCacheImageNameOrCacheImagePath + } +} + +enum CommandLineErrorTranslation { + /// `error` as the command line has always reported it. + /// + /// The library words its errors without naming options; the command line + /// names them, and a usage mistake is a `ValidationError` (usage text, + /// exit code 64) rather than a plain failure (exit code 1). Anything not + /// listed passes through unchanged. + /// + /// `annotatedInterfaceRequiresBinaries` words the `--interface` mistake of + /// handing a snapshot document to `diff` or `evolution`; the two have + /// always worded it differently. + static func translated( + _ error: any Swift.Error, + annotatedInterfaceRequiresBinaries: ((_ snapshotPath: String) -> String)? = nil + ) -> any Swift.Error { + switch error { + case let machOSourceError as MachOSourceError: + switch machOSourceError { + case .fatBinaryRequiresArchitecture(let availableArchitectures): + return SwiftSectionCommandError.fatBinaryRequiresArchitecture(availableArchitectures: availableArchitectures) + case .architectureNotFound: + return SwiftSectionCommandError.invalidArchitecture + case .dyldSharedCacheImageNotFound: + return SwiftSectionCommandError.imageNotFound + case .systemDyldSharedCacheUnavailable: + return SwiftSectionCommandError.unsupportedSystemVersionForDyldSharedCache + } + case SnapshotSourceError.binaryRequired(let snapshotPath): + guard let annotatedInterfaceRequiresBinaries else { return error } + return ValidationError(annotatedInterfaceRequiresBinaries(snapshotPath)) + case AvailabilityPlatformInferenceError.noPlatform(let path): + 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.") + default: + return error + } + } +} diff --git a/Sources/swift-section/Models/DemangleOptionGroup.swift b/Sources/Executables/swift-section/Models/DemangleOptionGroup.swift similarity index 100% rename from Sources/swift-section/Models/DemangleOptionGroup.swift rename to Sources/Executables/swift-section/Models/DemangleOptionGroup.swift diff --git a/Sources/swift-section/Models/MachOOptionGroup.swift b/Sources/Executables/swift-section/Models/MachOOptionGroup.swift similarity index 50% rename from Sources/swift-section/Models/MachOOptionGroup.swift rename to Sources/Executables/swift-section/Models/MachOOptionGroup.swift index 30149b2d6..cd7d2f4b7 100644 --- a/Sources/swift-section/Models/MachOOptionGroup.swift +++ b/Sources/Executables/swift-section/Models/MachOOptionGroup.swift @@ -1,7 +1,7 @@ import ArgumentParser import Foundation import MachOFoundation -import SwiftDeclarationRendering +import SwiftSectionKit struct MachOOptionGroup: ParsableArguments, Sendable { @Argument(help: "The path to the Mach-O file or dyld shared cache to dump.", completion: .file()) @@ -22,7 +22,7 @@ struct MachOOptionGroup: ParsableArguments, Sendable { @Option(name: .shortAndLong, help: "The architecture of the Mach-O file. If not specified, the current architecture will be used.") var architecture: Architecture? - @Option(name: .customLong("dependency-search-path"), help: "Where the images a standalone binary links are looked for — when a type must be read out of another image's metadata accessor (an availability-conditional opaque type, a noncopyable field type), when the static field-offset / type-layout comments need a cross-module type's descriptor, and when a class's ObjC ancestor chain (the `override` keyword, the explicit-selector verdict) crosses into another image: a Mach-O file, a dyld shared cache file (dyld_shared_cache_* / dyld_sim_shared_cache_*), or a directory used as a system root under which absolute install names resolve (an iOS 26 or earlier simulator runtime's RuntimeRoot). Repeatable; named paths are consulted before the running system's shared cache. Without it the paths are inferred from where the binary sits on disk, and the running system's shared cache is used.", completion: .file()) + @Option(name: .customLong("dependency-search-path"), help: "Where the images a standalone binary links are looked for — when a type must be read out of another image's metadata accessor (an availability-conditional opaque type, a noncopyable field type), when the static field-offset / type-layout comments need a cross-module type's descriptor, and when a class's ObjC ancestor chain (the `override` keyword, the explicit-selector verdict) crosses into another image: a Mach-O file, a dyld shared cache file (dyld_shared_cache_* / dyld_sim_shared_cache_*), or a directory used as a system root under which absolute install names resolve (an iOS 26 or earlier simulator runtime's RuntimeRoot). Repeatable; named paths are consulted before the running system's shared cache. An image read out of a dyld shared cache resolves in that same cache before either, so a cache needs no path named. Without it the paths are inferred from where the binary sits on disk, and the running system's shared cache is used.", completion: .file()) var dependencySearchPaths: [String] = [] /// A mistyped search path is a usage error, not a silent miss: the @@ -34,40 +34,21 @@ struct MachOOptionGroup: ParsableArguments, Sendable { } } - /// The resolver the accessor-thunk rewrites should use when the user - /// named search paths, else `nil` for the inferring default. - var accessorThunkResolver: DisassemblingAccessorThunkResolver? { - guard !dependencySearchPaths.isEmpty else { return nil } - return DisassemblingAccessorThunkResolver(searchPaths: dependencySearchPaths.map { DependencySearchPath(classifyingPath: $0) }) + /// The image these options name. + func machOSource() throws -> MachOSource { + try makeMachOSource( + filePath: filePath, + isDyldSharedCache: isDyldSharedCache, + usesSystemDyldSharedCache: usesSystemDyldSharedCache, + cacheImageName: cacheImageName, + cacheImagePath: cacheImagePath, + architecture: architecture + ) } - /// How the static (offline) layout engine resolves cross-module types: - /// the user-named search paths first, the running system's shared cache - /// as the fallback — so a binary can be laid out against the OS version - /// whose cache was named rather than the host's. Without any path this is - /// the library default. - var staticLayoutDependencyResolution: StaticLayoutDependencyResolution { - guard !dependencySearchPaths.isEmpty else { return .default } - return .dependencyClosure(searchPaths: dependencySearchPaths.map { DependencySearchPath(classifyingPath: $0) } + [.systemDyldSharedCache]) - } - - /// The same paths for the indexer's cross-image facts (a stored field - /// whose type is a property wrapper defined in another image; a class's - /// ObjC ancestors behind a bind): the user-named ones first, the running - /// system's cache as the fallback. `dump` hands the same list to the - /// ObjC ancestor resolver it registers itself. - var indexDependencySearchPaths: [DependencySearchPath] { - dependencySearchPaths.map { DependencySearchPath(classifyingPath: $0) } + [.systemDyldSharedCache] - } -} - -extension AccessorThunkResolution { - /// Runs `operation` with the user-named search paths in force for every - /// kind-9 accessor-thunk rewrite it performs, or unchanged when none - /// were named. The task-local is the one injection point the rendering - /// layer offers; the CLI is a host like any other. - nonisolated(nonsending) static func withResolver(from options: MachOOptionGroup, _ operation: nonisolated(nonsending) () async throws -> Result) async rethrows -> Result { - guard let resolver = options.accessorThunkResolver else { return try await operation() } - return try await $taskResolver.withValue(resolver, operation: operation) + /// `--dependency-search-path`, each path classified as a Mach-O file, a + /// dyld shared cache or a system root. + var dependencySearchPathValues: [DependencySearchPath] { + dependencySearchPaths.map { DependencySearchPath(classifyingPath: $0) } } } diff --git a/Sources/swift-section/Models/ObjCMemberOptionGroup.swift b/Sources/Executables/swift-section/Models/ObjCMemberOptionGroup.swift similarity index 100% rename from Sources/swift-section/Models/ObjCMemberOptionGroup.swift rename to Sources/Executables/swift-section/Models/ObjCMemberOptionGroup.swift diff --git a/Sources/swift-section/Models/SemanticColorScheme.swift b/Sources/Executables/swift-section/Models/SemanticColorScheme.swift similarity index 100% rename from Sources/swift-section/Models/SemanticColorScheme.swift rename to Sources/Executables/swift-section/Models/SemanticColorScheme.swift diff --git a/Sources/swift-section/Models/SwiftSectionCommandError.swift b/Sources/Executables/swift-section/Models/SwiftSectionCommandError.swift similarity index 87% rename from Sources/swift-section/Models/SwiftSectionCommandError.swift rename to Sources/Executables/swift-section/Models/SwiftSectionCommandError.swift index 76a4f66cb..1a7a27909 100644 --- a/Sources/swift-section/Models/SwiftSectionCommandError.swift +++ b/Sources/Executables/swift-section/Models/SwiftSectionCommandError.swift @@ -1,5 +1,8 @@ import Foundation +/// The loading failures as the command line has always worded them. The first +/// three are combinations of options a `MachOSource` cannot express; the rest +/// translate `MachOSourceError` (see `CommandLineErrorTranslation`). enum SwiftSectionCommandError: LocalizedError { case missingFilePath case ambiguousCacheImageNameAndCacheImagePath @@ -7,7 +10,6 @@ enum SwiftSectionCommandError: LocalizedError { case imageNotFound case invalidArchitecture case fatBinaryRequiresArchitecture(availableArchitectures: [String]) - case failedFetchFromSystemDyldSharedCache case unsupportedSystemVersionForDyldSharedCache var errorDescription: String? { @@ -24,8 +26,6 @@ enum SwiftSectionCommandError: LocalizedError { "The specified architecture is not found or supported." case .fatBinaryRequiresArchitecture(let availableArchitectures): "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). Available architectures: \(availableArchitectures.joined(separator: ", "))" - case .failedFetchFromSystemDyldSharedCache: - "Failed to fetch the Mach-O file from the current system dyld shared cache. Please ensure the cache is accessible." case .unsupportedSystemVersionForDyldSharedCache: "The minimum system version that supports the --uses-system-dyld-shared-cache flag is macOS 11.0. Current system version: \(ProcessInfo.processInfo.operatingSystemVersionString)." } diff --git a/Sources/swift-section/Models/TransformerOptionGroup.swift b/Sources/Executables/swift-section/Models/TransformerOptionGroup.swift similarity index 81% rename from Sources/swift-section/Models/TransformerOptionGroup.swift rename to Sources/Executables/swift-section/Models/TransformerOptionGroup.swift index f1e775fd5..a3b0b736f 100644 --- a/Sources/swift-section/Models/TransformerOptionGroup.swift +++ b/Sources/Executables/swift-section/Models/TransformerOptionGroup.swift @@ -2,8 +2,6 @@ import ArgumentParser import Foundation import OutputTransformer import SwiftOutputTransformer -import SwiftDeclarationRendering -import SwiftPrinting extension Transformer.SwiftEnumLayout.Preset: ExpressibleByArgument {} @@ -20,8 +18,8 @@ extension Transformer.SwiftEnumLayout.Preset: ExpressibleByArgument {} /// 2. `--enum-layout-style` — a whole-module preset for the enum-layout module. /// 3. The per-module template / formatting options — one field each. /// -/// A module that ends up enabled also turns on the comment kind it renders (see -/// ``commentFlagsForEnabledModules(of:)``), so passing a template is enough to +/// A module that ends up enabled also turns on the comment kind it renders (the +/// requests in `SwiftSectionKit` do that), so passing a template is enough to /// see its output — no separate `--emit-…` flag to remember. struct TransformerOptionGroup: ParsableArguments, Sendable { private static let templateValueHelp = "Pass a built-in template name (list them with `swift-section transformer templates`) or a literal template containing ${token} placeholders (list them with `swift-section transformer tokens`)." @@ -260,55 +258,3 @@ enum TransformerTemplateResolver { name.lowercased().filter { !$0.isWhitespace && $0 != "-" && $0 != "_" } } } - -// MARK: - Comment Flags - -extension Transformer.SwiftConfiguration { - /// The comment kinds the enabled modules render. A module is only reached - /// once its comment kind is emitted, so enabling one implies emitting it. - struct CommentFlags { - var printFieldOffset = false - var printVTableOffset = false - var printMemberAddress = false - var printTypeLayout = false - var printEnumLayout = false - } - - var commentFlagsForEnabledModules: CommentFlags { - .init( - printFieldOffset: swiftFieldOffset.isEnabled, - printVTableOffset: swiftVTableOffset.isEnabled, - printMemberAddress: swiftMemberAddress.isEnabled, - printTypeLayout: swiftTypeLayout.isEnabled, - printEnumLayout: swiftEnumLayout.isEnabled - ) - } -} - -extension DeclarationRenderConfiguration { - /// Applies `transformers` and turns on the comment kinds its enabled - /// modules render, leaving every already-requested comment kind on. - mutating func applyTransformersEnablingCommentKinds(_ transformers: Transformer.SwiftConfiguration) { - let commentFlags = transformers.commentFlagsForEnabledModules - printFieldOffset = printFieldOffset || commentFlags.printFieldOffset - printVTableOffset = printVTableOffset || commentFlags.printVTableOffset - printMemberAddress = printMemberAddress || commentFlags.printMemberAddress - printTypeLayout = printTypeLayout || commentFlags.printTypeLayout - printEnumLayout = printEnumLayout || commentFlags.printEnumLayout - applyTransformers(transformers) - } -} - -extension SwiftDeclarationPrintConfiguration { - /// Applies `transformers` and turns on the comment kinds its enabled - /// modules render, leaving every already-requested comment kind on. - mutating func applyTransformersEnablingCommentKinds(_ transformers: Transformer.SwiftConfiguration) { - let commentFlags = transformers.commentFlagsForEnabledModules - printFieldOffset = printFieldOffset || commentFlags.printFieldOffset - printVTableOffset = printVTableOffset || commentFlags.printVTableOffset - printMemberAddress = printMemberAddress || commentFlags.printMemberAddress - printTypeLayout = printTypeLayout || commentFlags.printTypeLayout - printEnumLayout = printEnumLayout || commentFlags.printEnumLayout - applyTransformers(transformers) - } -} diff --git a/Sources/swift-section/ObjC/Commands/ObjCDiffCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCDiffCommand.swift similarity index 64% rename from Sources/swift-section/ObjC/Commands/ObjCDiffCommand.swift rename to Sources/Executables/swift-section/ObjC/Commands/ObjCDiffCommand.swift index fdc33f88b..57536fa36 100644 --- a/Sources/swift-section/ObjC/Commands/ObjCDiffCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCDiffCommand.swift @@ -1,6 +1,6 @@ import ArgumentParser import Foundation -import ObjCDiffing +import SwiftSectionKit struct ObjCDiffCommand: AsyncParsableCommand { static let configuration: CommandConfiguration = .init( @@ -38,24 +38,38 @@ struct ObjCDiffCommand: AsyncParsableCommand { @Option(name: .shortAndLong, help: "Write the report to this path instead of stdout.", completion: .file()) var outputPath: String? - func run() async throws { - let oldDocument = try await loadDocument(at: oldPath) - let newDocument = try await loadDocument(at: newPath) - - log("Diffing…") - let diff = ObjCAPIDiffer().diff(old: oldDocument, new: newDocument) - - let verdict = "API-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" - if json { - let encoded = String(decoding: try ObjCAPIJSON.encoder().encode(diff), as: UTF8.self) - try emit(encoded) + /// The library request these flags describe. + func makeRequest() -> ObjCAPIDiffRequest { + let report: ObjCAPIDiffRequest.Report = if json { + .json } else if summaryOnly { - print(verdict) + .summary } else { - try emit(ObjCAPIDiffReporter().report(diff) + "\n\n" + verdict) + .changeList } + // validate() has already required exactly one of -n / -p with + // --dyld-shared-cache. + let cacheImage: DyldSharedCacheImage? = cacheImageName.map { .name($0) } ?? cacheImagePath.map { .path($0) } + return ObjCAPIDiffRequest( + old: .path(oldPath), + new: .path(newPath), + binaryLoading: BinaryLoadingOptions( + architecture: architecture, + dyldSharedCacheImage: isDyldSharedCache ? cacheImage : nil + ), + report: report, + destination: outputPath.map { .file(path: $0) } ?? .output + ) + } - if failOnBreaking, diff.hasBreakingChange { + func run() async throws { + let outcome: ObjCAPIDiffOutcome + do { + outcome = try await makeRequest().run(output: StandardStreamOutput(), environment: .commandLine) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + if failOnBreaking, outcome.hasBreakingChange { throw ExitCode.failure } } @@ -76,32 +90,4 @@ struct ObjCDiffCommand: AsyncParsableCommand { throw ValidationError("--dyld-shared-cache requires --cache-image-name or --cache-image-path.") } } - - /// Loads one input: a snapshot JSON is decoded, a binary is indexed and - /// frozen (with provenance stamped). - private func loadDocument(at path: String) async throws -> ObjCAPISnapshotDocument { - try await ObjCSnapshotInputLoader.loadDocument( - path: path, - architecture: architecture, - isDyldSharedCache: isDyldSharedCache, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - label: nil, - log: log - ) - } - - /// Writes a report to `--output` or stdout. - private func emit(_ text: String) throws { - if let outputPath { - try text.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - log("Report written to \(outputPath)") - } else { - print(text) - } - } - - private func log(_ message: String) { - writeStandardErrorLine(message) - } } diff --git a/Sources/Executables/swift-section/ObjC/Commands/ObjCDumpCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCDumpCommand.swift new file mode 100644 index 000000000..340a202ea --- /dev/null +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCDumpCommand.swift @@ -0,0 +1,88 @@ +import ArgumentParser +import Foundation +import SwiftSectionKit + +struct ObjCDumpCommand: AsyncParsableCommand, Sendable { + static let configuration: CommandConfiguration = .init( + commandName: "dump", + abstract: "Dump every Objective-C declaration in a Mach-O file or dyld shared cache image." + ) + + @OptionGroup + var machOOptions: ObjCMachOOptionGroup + + @OptionGroup(title: "Generation") + var generationOptions: ObjCGenerationOptionGroup + + @OptionGroup(title: "Comment Templates") + var transformerOptions: ObjCTransformerOptionGroup + + @Option( + name: .shortAndLong, + help: ArgumentHelp( + "The kinds of declaration to dump, comma-separated (e.g. classes,protocols). If not specified, all of them are dumped.", + valueName: "kinds" + ) + ) + var sections: ObjCSectionKindList? + + @Option(name: .shortAndLong, help: "Only dump declarations whose name contains this text, case-insensitively.") + var filter: String? + + @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output is printed to stdout.", completion: .file()) + var outputPath: String? + + @Option(name: .shortAndLong, help: "The color scheme for the output.") + var colorScheme: SemanticColorScheme = .none + + @Flag(name: .shortAndLong, help: "Report indexing progress on stderr.") + var verbose: Bool = false + + /// The library request these flags describe. + func makeRequest() throws -> ObjCDumpRequest { + ObjCDumpRequest( + source: try machOOptions.machOSource(), + kinds: sections?.kinds, + nameFilter: filter, + generation: generationOptions.build(), + cTypeReplacements: try transformerOptions.buildCTypeReplacements(), + ivarOffsetComment: transformerOptions.buildIvarOffsetComment(), + reportsIndexingProgress: verbose, + imageDescription: machOOptions.imageDescription, + destination: outputPath.map { .file(path: $0) } ?? .output + ) + } + + func run() async throws { + let request = try makeRequest() + do { + try await request.run(output: StandardStreamOutput(colorScheme: colorScheme)) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + } + + /// Catches the spelling this option used to accept. `--sections classes protocols` + /// leaves `protocols` sitting in the positional slot, so the binary would be + /// looked for under a declaration kind's name — a confusing "no such file" + /// far from the real mistake. + /// + /// Only the two-token shape is recoverable here: with a path as well + /// (`--sections classes protocols /bin/ls`) the parser rejects the extra + /// positional argument before `validate()` ever runs. + func validate() throws { + guard let sections, + let filePath = machOOptions.filePath, + ObjCDeclarationKind(rawValue: filePath) != nil + else { return } + + let combinedKinds = (sections.kinds.map(\.rawValue) + [filePath]).joined(separator: ",") + throw ValidationError( + """ + '\(filePath)' was read as the input path, but it is also a declaration kind. \ + --sections takes one comma-separated value: write '--sections \(combinedKinds)' \ + and put the input path after it. + """ + ) + } +} diff --git a/Sources/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift similarity index 66% rename from Sources/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift rename to Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift index b90500154..3f568712e 100644 --- a/Sources/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCEvolutionCommand.swift @@ -1,6 +1,6 @@ import ArgumentParser import Foundation -import ObjCDiffing +import SwiftSectionKit struct ObjCEvolutionCommand: AsyncParsableCommand { static let configuration: CommandConfiguration = .init( @@ -43,48 +43,38 @@ struct ObjCEvolutionCommand: AsyncParsableCommand { @Option(name: .shortAndLong, help: "Write the report to this path instead of stdout.", completion: .file()) var outputPath: String? - func run() async throws { - let explicitLabels = try ObjCSnapshotInputLoader.parseLabels(labels, inputCount: inputPaths.count) - - var documents: [ObjCAPISnapshotDocument] = [] - for (index, inputPath) in inputPaths.enumerated() { - let document = try await ObjCSnapshotInputLoader.loadDocument( - path: inputPath, - architecture: architecture, - isDyldSharedCache: isDyldSharedCache, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - label: explicitLabels[index], - log: log - ) - documents.append(document) - } - - // Snapshot inputs may already carry a provenance label; binaries fall - // back to their file name so the axis is always readable. - let resolvedLabels = documents.enumerated().map { index, document in - document.provenance?.label ?? ObjCSnapshotInputLoader.defaultLabel(forPath: inputPaths[index]) - } - - log("Tracking evolution…") - let evolution = try ObjCAPIEvolutionBuilder().evolution(of: documents, labels: resolvedLabels) - - let output: String - if json { - output = String(decoding: try ObjCAPIJSON.encoder().encode(evolution), as: UTF8.self) + /// The library request these flags describe. + func makeRequest() -> ObjCAPIEvolutionRequest { + let report: ObjCAPIEvolutionRequest.Report = if json { + .json } else if summaryOnly { - output = ObjCAPIEvolutionReporter().summary(evolution) + .summary } else { - output = ObjCAPIEvolutionReporter().report(evolution) - } - if let outputPath { - try (output + "\n").write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - log("Report written to \(outputPath)") - } else { - print(output) + .lineage } + // validate() has already required exactly one of -n / -p with + // --dyld-shared-cache. + let cacheImage: DyldSharedCacheImage? = cacheImageName.map { .name($0) } ?? cacheImagePath.map { .path($0) } + return ObjCAPIEvolutionRequest( + inputs: inputPaths.map { .path($0) }, + labels: labels.map(EvolutionCommand.splitLabels), + binaryLoading: BinaryLoadingOptions( + architecture: architecture, + dyldSharedCacheImage: isDyldSharedCache ? cacheImage : nil + ), + report: report, + destination: outputPath.map { .file(path: $0) } ?? .output + ) + } - if failOnBreaking, evolution.hasBreakingChange { + func run() async throws { + let outcome: ObjCAPIEvolutionOutcome + do { + outcome = try await makeRequest().run(output: StandardStreamOutput(), environment: .commandLine) + } catch { + throw CommandLineErrorTranslation.translated(error) + } + if failOnBreaking, outcome.hasBreakingChange { throw ExitCode.failure } } @@ -108,8 +98,4 @@ struct ObjCEvolutionCommand: AsyncParsableCommand { throw ValidationError("--dyld-shared-cache requires --cache-image-name or --cache-image-path.") } } - - private func log(_ message: String) { - writeStandardErrorLine(message) - } } diff --git a/Sources/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift similarity index 56% rename from Sources/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift rename to Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift index 1b0a5b7f5..da6d5e5d2 100644 --- a/Sources/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCInterfaceCommand.swift @@ -1,7 +1,6 @@ import ArgumentParser import Foundation -import MachOKit -import Semantic +import SwiftSectionKit struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { static let configuration: CommandConfiguration = .init( @@ -15,7 +14,7 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { ) // Fully qualified: `Semantic` exports an `Argument` of its own, so the - // bare spelling is ambiguous here. + // bare spelling is ambiguous wherever both are imported. @ArgumentParser.Argument(help: "The name of the declaration to print.") var declarationName: String @@ -29,7 +28,7 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { var transformerOptions: ObjCTransformerOptionGroup @Option(help: "Only look for the name among declarations of this kind. If not specified, every kind is searched.") - var kind: ObjCSectionKind? + var kind: ObjCDeclarationKind? @Option(name: .shortAndLong, help: "The output path. If not specified, the output is printed to stdout.", completion: .file()) var outputPath: String? @@ -40,30 +39,26 @@ struct ObjCInterfaceCommand: AsyncParsableCommand, Sendable { @Flag(name: .shortAndLong, help: "Report indexing progress on stderr.") var verbose: Bool = false - func run() async throws { - let session = try await ObjCInterfaceSession.make( - machOOptions: machOOptions, - generationOptions: generationOptions, - transformerOptions: transformerOptions, - isVerbose: verbose + /// The library request these flags describe. + func makeRequest() throws -> ObjCInterfaceRequest { + ObjCInterfaceRequest( + declarationName: declarationName, + kind: kind, + source: try machOOptions.machOSource(), + generation: generationOptions.build(), + cTypeReplacements: try transformerOptions.buildCTypeReplacements(), + ivarOffsetComment: transformerOptions.buildIvarOffsetComment(), + reportsIndexingProgress: verbose, + destination: outputPath.map { .file(path: $0) } ?? .output ) + } - // Searched in declaration-kind order rather than by guessing from the - // spelling: `Foo(Bar)` is unambiguous, but a bare name could be a - // class, a protocol or a struct, and binaries do reuse a name across - // those. `--kind` is how a caller settles it. - let kinds = kind.map { [$0] } ?? ObjCSectionKind.allCases - - for candidateKind in kinds { - guard let interface = session.interface(of: candidateKind, named: declarationName) else { continue } - if let outputPath { - try interface.string.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - } else { - interface.printColorfully(using: colorScheme) - } - return + func run() async throws { + let request = try makeRequest() + do { + try await request.run(output: StandardStreamOutput(colorScheme: colorScheme)) + } catch { + throw CommandLineErrorTranslation.translated(error) } - - throw ObjCSectionCommandError.declarationNotFound(declarationName) } } diff --git a/Sources/swift-section/ObjC/Commands/ObjCSnapshotCommand.swift b/Sources/Executables/swift-section/ObjC/Commands/ObjCSnapshotCommand.swift similarity index 60% rename from Sources/swift-section/ObjC/Commands/ObjCSnapshotCommand.swift rename to Sources/Executables/swift-section/ObjC/Commands/ObjCSnapshotCommand.swift index 6fa9b2008..139cf8ebb 100644 --- a/Sources/swift-section/ObjC/Commands/ObjCSnapshotCommand.swift +++ b/Sources/Executables/swift-section/ObjC/Commands/ObjCSnapshotCommand.swift @@ -1,6 +1,6 @@ import ArgumentParser import Foundation -import ObjCDiffing +import SwiftSectionKit struct ObjCSnapshotCommand: AsyncParsableCommand { static let configuration: CommandConfiguration = .init( @@ -16,26 +16,30 @@ struct ObjCSnapshotCommand: AsyncParsableCommand { @Option(name: .shortAndLong, help: "Write the snapshot JSON to this path instead of stdout.", completion: .file()) var outputPath: String? - func run() async throws { + /// The library request these flags describe. + func makeRequest() throws -> ObjCAPISnapshotRequest { guard let filePath = machOOptions.filePath else { throw ValidationError("A Mach-O file path is required.") } - let document = try await ObjCSnapshotInputLoader.loadDocument( - path: filePath, - architecture: machOOptions.architecture, - isDyldSharedCache: machOOptions.isDyldSharedCache, - cacheImageName: machOOptions.cacheImageName, - cacheImagePath: machOOptions.cacheImagePath, + return ObjCAPISnapshotRequest( + source: .path(filePath), + binaryLoading: try makeBinaryLoadingOptions( + isDyldSharedCache: machOOptions.isDyldSharedCache, + cacheImageName: machOOptions.cacheImageName, + cacheImagePath: machOOptions.cacheImagePath, + architecture: machOOptions.architecture + ), label: label, - log: log + destination: outputPath.map { .file(path: $0) } ?? .output ) - let encoded = try document.encoded() - if let outputPath { - try encoded.write(to: URL(fileURLWithPath: outputPath), options: .atomic) - log("Snapshot written to \(outputPath)") - } else { - FileHandle.standardOutput.write(encoded) - FileHandle.standardOutput.write(Data("\n".utf8)) + } + + func run() async throws { + let request = try makeRequest() + do { + try await request.run(output: StandardStreamOutput(), environment: .commandLine) + } catch { + throw CommandLineErrorTranslation.translated(error) } } @@ -46,8 +50,4 @@ struct ObjCSnapshotCommand: AsyncParsableCommand { throw ValidationError("snapshot requires an explicit file path; --uses-system-dyld-shared-cache is not supported here.") } } - - private func log(_ message: String) { - writeStandardErrorLine(message) - } } diff --git a/Sources/swift-section/ObjC/Models/ObjCGenerationOptionGroup.swift b/Sources/Executables/swift-section/ObjC/Models/ObjCGenerationOptionGroup.swift similarity index 91% rename from Sources/swift-section/ObjC/Models/ObjCGenerationOptionGroup.swift rename to Sources/Executables/swift-section/ObjC/Models/ObjCGenerationOptionGroup.swift index f66ce37ee..575b16120 100644 --- a/Sources/swift-section/ObjC/Models/ObjCGenerationOptionGroup.swift +++ b/Sources/Executables/swift-section/ObjC/Models/ObjCGenerationOptionGroup.swift @@ -8,7 +8,7 @@ import ObjCDeclarationRendering /// nothing annotated. That matches the library's ``ObjCGenerationOptions`` /// default and keeps "what the binary says" the baseline you opt away from. struct ObjCGenerationOptionGroup: ParsableArguments, Sendable { - @Flag(help: "Drop the conformance list, and the members those protocols already declare.") + @Flag(help: "Drop every property and method the adopted protocols declare, required and optional, along the whole protocol chain — as a hand-written header leaves them out. The list stays.") var stripProtocolConformance: Bool = false @Flag(help: "Drop members that merely override a superclass member. In file mode the superclass chain can be shorter, so this strips less — see the CLI guide.") diff --git a/Sources/swift-section/ObjC/Models/ObjCMachOOptionGroup.swift b/Sources/Executables/swift-section/ObjC/Models/ObjCMachOOptionGroup.swift similarity index 82% rename from Sources/swift-section/ObjC/Models/ObjCMachOOptionGroup.swift rename to Sources/Executables/swift-section/ObjC/Models/ObjCMachOOptionGroup.swift index b3e8cf5bd..3d5cbe81d 100644 --- a/Sources/swift-section/ObjC/Models/ObjCMachOOptionGroup.swift +++ b/Sources/Executables/swift-section/ObjC/Models/ObjCMachOOptionGroup.swift @@ -1,5 +1,5 @@ import ArgumentParser -import MachOKit +import SwiftSectionKit /// How the `objc` subcommands get at the binary: a path on disk, or an image /// inside a dyld shared cache (the running system's, or a cache file given by @@ -36,17 +36,16 @@ struct ObjCMachOOptionGroup: ParsableArguments, Sendable { var imageDescription: String { cacheImageName ?? cacheImagePath ?? filePath ?? "the system dyld shared cache" } -} -extension MachOFile { - static func load(options: ObjCMachOOptionGroup) throws -> MachOFile { - try load( - filePath: options.filePath, - isDyldSharedCache: options.isDyldSharedCache, - usesSystemDyldSharedCache: options.usesSystemDyldSharedCache, - cacheImageName: options.cacheImageName, - cacheImagePath: options.cacheImagePath, - architecture: options.architecture + /// The image these options name. + func machOSource() throws -> MachOSource { + try makeMachOSource( + filePath: filePath, + isDyldSharedCache: isDyldSharedCache, + usesSystemDyldSharedCache: usesSystemDyldSharedCache, + cacheImageName: cacheImageName, + cacheImagePath: cacheImagePath, + architecture: architecture ) } } diff --git a/Sources/swift-section/ObjC/Models/ObjCSectionCommandError.swift b/Sources/Executables/swift-section/ObjC/Models/ObjCSectionCommandError.swift similarity index 55% rename from Sources/swift-section/ObjC/Models/ObjCSectionCommandError.swift rename to Sources/Executables/swift-section/ObjC/Models/ObjCSectionCommandError.swift index d4c07adbc..df95a31bb 100644 --- a/Sources/swift-section/ObjC/Models/ObjCSectionCommandError.swift +++ b/Sources/Executables/swift-section/ObjC/Models/ObjCSectionCommandError.swift @@ -1,13 +1,12 @@ import Foundation -/// The failures only the `objc` subcommands can hit. Loading the binary is -/// shared with the Swift commands, so its failures are -/// ``SwiftSectionCommandError`` cases — with the same wording `objc-section` -/// printed before it moved here. +/// The command-line spellings only the `objc` subcommands parse. Loading the +/// binary is shared with the Swift commands, so its failures are +/// ``SwiftSectionCommandError`` cases; a declaration that is not found is the +/// library's `ObjCDeclarationLookupError`. enum ObjCSectionCommandError: LocalizedError { case malformedCTypeReplacement(String) case unknownCType(String) - case declarationNotFound(String) var errorDescription: String? { switch self { @@ -15,8 +14,6 @@ enum ObjCSectionCommandError: LocalizedError { "Malformed --c-type-replacement '\(argument)'. Expected =, e.g. double=CGFloat." case .unknownCType(let name): "Unknown C type '\(name)'. Supported: \(CTypeName.allSpellings.joined(separator: ", "))." - case .declarationNotFound(let name): - "No class, protocol, category, struct or union named '\(name)' in this binary." } } } diff --git a/Sources/swift-section/ObjC/Models/ObjCSectionKindList.swift b/Sources/Executables/swift-section/ObjC/Models/ObjCSectionKindList.swift similarity index 81% rename from Sources/swift-section/ObjC/Models/ObjCSectionKindList.swift rename to Sources/Executables/swift-section/ObjC/Models/ObjCSectionKindList.swift index 5847ccc07..ea749e9a0 100644 --- a/Sources/swift-section/ObjC/Models/ObjCSectionKindList.swift +++ b/Sources/Executables/swift-section/ObjC/Models/ObjCSectionKindList.swift @@ -1,7 +1,8 @@ import ArgumentParser import Foundation +import SwiftSectionKit -/// A comma-separated list of ``ObjCSectionKind``, as in `--sections classes,protocols`. +/// A comma-separated list of ``ObjCDeclarationKind``, as in `--sections classes,protocols`. /// /// Deliberately a single value rather than an array option. `dump` also takes /// the binary as a positional argument, and an array option — `.upToNextOption` @@ -12,7 +13,7 @@ import Foundation /// The comma form also matches `evolution --labels 17.0,18.0,26.0`, the CLI's /// other multi-value option. struct ObjCSectionKindList: ExpressibleByArgument, Equatable, Sendable { - let kinds: [ObjCSectionKind] + let kinds: [ObjCDeclarationKind] init?(argument: String) { // Empty subsequences are kept so that a stray comma (`classes,`) fails @@ -21,9 +22,9 @@ struct ObjCSectionKindList: ExpressibleByArgument, Equatable, Sendable { .split(separator: ",", omittingEmptySubsequences: false) .map { $0.trimmingCharacters(in: .whitespaces) } - var resolvedKinds: [ObjCSectionKind] = [] + var resolvedKinds: [ObjCDeclarationKind] = [] for spelledKind in spelledKinds { - guard let kind = ObjCSectionKind(rawValue: spelledKind) else { return nil } + guard let kind = ObjCDeclarationKind(rawValue: spelledKind) else { return nil } // A repeated kind would dump the same declarations twice. if !resolvedKinds.contains(kind) { resolvedKinds.append(kind) @@ -37,6 +38,6 @@ struct ObjCSectionKindList: ExpressibleByArgument, Equatable, Sendable { /// the parse error. A single kind is itself a valid value, so listing the /// kinds is accurate as far as it goes. static var allValueStrings: [String] { - ObjCSectionKind.allCases.map(\.rawValue) + ObjCDeclarationKind.allCases.map(\.rawValue) } } diff --git a/Sources/swift-section/ObjC/Models/ObjCTransformerOptionGroup.swift b/Sources/Executables/swift-section/ObjC/Models/ObjCTransformerOptionGroup.swift similarity index 90% rename from Sources/swift-section/ObjC/Models/ObjCTransformerOptionGroup.swift rename to Sources/Executables/swift-section/ObjC/Models/ObjCTransformerOptionGroup.swift index 4f6332b8d..7c8a1d72a 100644 --- a/Sources/swift-section/ObjC/Models/ObjCTransformerOptionGroup.swift +++ b/Sources/Executables/swift-section/ObjC/Models/ObjCTransformerOptionGroup.swift @@ -69,24 +69,18 @@ struct ObjCTransformerOptionGroup: ParsableArguments, Sendable { } } - /// The ivar-offset comment builder, or `nil` to keep the renderer's - /// built-in wording. - func buildIvarOffsetCommentBuilder() -> (@Sendable (Int) -> String)? { + /// The ivar-offset comment module, or `nil` to keep the renderer's + /// built-in wording. A module also switches ivar offset comments on — a + /// template option on its own would otherwise be silently inert. + func buildIvarOffsetComment() -> Transformer.ObjCIvarOffset? { // Hexadecimal is the module's own default, so asking for decimal is a // customization even without a template. guard ivarOffsetTemplate != nil || ivarOffsetDecimal else { return nil } - let module = Transformer.ObjCIvarOffset( + return Transformer.ObjCIvarOffset( isEnabled: true, template: ivarOffsetTemplate ?? Transformer.ObjCIvarOffset.Templates.standard, useHexadecimal: !ivarOffsetDecimal ) - return { offset in module.transform(.init(offset: offset)) } - } - - /// Whether a template option was given that only has an effect once ivar - /// offset comments are switched on. - var impliesIvarOffsetComments: Bool { - ivarOffsetTemplate != nil || ivarOffsetDecimal } } diff --git a/Sources/swift-section/ObjC/ObjCCommand.swift b/Sources/Executables/swift-section/ObjC/ObjCCommand.swift similarity index 100% rename from Sources/swift-section/ObjC/ObjCCommand.swift rename to Sources/Executables/swift-section/ObjC/ObjCCommand.swift diff --git a/Sources/Executables/swift-section/Output/StandardStreamOutput.swift b/Sources/Executables/swift-section/Output/StandardStreamOutput.swift new file mode 100644 index 000000000..4cfb5213c --- /dev/null +++ b/Sources/Executables/swift-section/Output/StandardStreamOutput.swift @@ -0,0 +1,154 @@ +import Foundation +import Rainbow +import Semantic +import SwiftDeclaration +import SwiftIndexing +import SwiftSectionKit + +/// Writes a request's output where `swift-section` has always written it: the +/// product to stdout, diagnostics to stderr — except the severities a command +/// lists in `standardOutputSeverities`. +/// +/// Every write goes through `fwrite`, never `FileHandle.write(_:)`: that +/// overload is the Objective-C bridge and raises an exception Swift cannot +/// catch when the stream is closed, which aborted the process instead of +/// dropping the line. +/// +/// `@unchecked Sendable`: the two `FILE` pointers are only ever passed to +/// stdio, whose calls lock the stream themselves. +struct StandardStreamOutput: SwiftSectionOutput, @unchecked Sendable { + var colorScheme: SemanticColorScheme = .none + /// `interface` prints its progress lines on stdout and `dump` its + /// per-declaration errors. Both are historical, kept so that the output + /// stays byte-identical (evolution proposal `swift-section-kit`, follow-up + /// work). + var standardOutputSeverities: Set = [] + var standardOutput: UnsafeMutablePointer = stdout + var standardError: UnsafeMutablePointer = stderr + + func write(_ product: SwiftSectionProduct) { + switch product { + case .declarations(let semanticString): + writeLine(semanticString.colorized(using: colorScheme), to: standardOutput) + case .text(let text): + writeLine(text, to: standardOutput) + case .annotatedInterface(let text, let style): + let lines = text.split(separator: "\n", omittingEmptySubsequences: false) + for (line, lineKind) in zip(lines, style.lineKinds(of: text)) { + writeLine(String(line).colorized(as: lineKind), to: standardOutput) + } + case .data(let data): + data.withUnsafeBytes { buffer in + _ = fwrite(buffer.baseAddress, 1, buffer.count, standardOutput) + } + writeLine("", to: standardOutput) + } + } + + func report(_ diagnostic: SwiftSectionDiagnostic) { + if standardOutputSeverities.contains(diagnostic.severity) { + // `dump`'s error lines have always been red, whatever the color + // scheme. + writeLine(diagnostic.severity == .error ? diagnostic.message.red : diagnostic.message, to: standardOutput) + } else { + writeLine(diagnostic.message, to: standardError) + } + } + + func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] { + [ConsoleEventHandler(label: label)] + } + + /// `text` and a newline, byte for byte — `fputs` would stop at an + /// embedded NUL where `print` does not. + private func writeLine(_ text: String, to stream: UnsafeMutablePointer) { + var bytes = Array(text.utf8) + bytes.append(UInt8(ascii: "\n")) + bytes.withUnsafeBufferPointer { buffer in + _ = fwrite(buffer.baseAddress, 1, buffer.count, stream) + } + } +} + +extension SemanticString { + func colorized(using colorScheme: SemanticColorScheme) -> String { + components.map { $0.string.withColor(for: $0.type, colorScheme: colorScheme) }.joined() + } +} + +extension String { + func colorized(as lineKind: AnnotatedLineKind) -> String { + switch lineKind { + case .header: + cyan + case .added: + green + case .removed: + red + case .modified: + yellow + case .plain: + self + } + } + + func withColorHex(for type: SemanticType, colorScheme: SemanticColorScheme) -> String? { + switch colorScheme { + case .none: + return nil + case .light: + switch type { + case .comment: + return "#56606B" + case .keyword: + return "#C33381" + case .type(_, .name): + return "#2E0D6E" + case .type(_, .declaration): + return "#004975" + case .function(.name), + .member(.name): + return "#5C2699" + case .function(.declaration), + .member(.declaration), + .variable: + return "#0F68A0" + case .numeric: + return "#000BFF" + default: + return nil + } + case .dark: + switch type { + case .comment: + return "#6C7987" + case .keyword: + return "#F2248C" + case .type(_, .name): + return "#D0A8FF" + case .type(_, .declaration): + return "#5DD8FF" + case .function(.name), + .member(.name): + return "#A167E6" + case .function(.declaration), + .member(.declaration): + return "#41A1C0" + case .numeric: + return "#D0BF69" + default: + return nil + } + } + } + + func withColor(for type: SemanticType, colorScheme: SemanticColorScheme) -> String { + if let colorHex = withColorHex(for: type, colorScheme: colorScheme) { + hex(colorHex, to: .bit24) + } else if type == .error { + red + } else { + self + } + } +} diff --git a/Sources/swift-section/SwiftSectionCommand.swift b/Sources/Executables/swift-section/SwiftSectionCommand.swift similarity index 100% rename from Sources/swift-section/SwiftSectionCommand.swift rename to Sources/Executables/swift-section/SwiftSectionCommand.swift diff --git a/Sources/swift-section/Version.swift b/Sources/Executables/swift-section/Version.swift similarity index 91% rename from Sources/swift-section/Version.swift rename to Sources/Executables/swift-section/Version.swift index 67ed9f89a..cef965f52 100644 --- a/Sources/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.21.0" + static let value = "0.22.0" } diff --git a/Sources/MachOBase/Exported.swift b/Sources/MachO/MachOBase/Exported.swift similarity index 100% rename from Sources/MachOBase/Exported.swift rename to Sources/MachO/MachOBase/Exported.swift diff --git a/Sources/MachOCaches/SharedCache.swift b/Sources/MachO/MachOCaches/SharedCache.swift similarity index 100% rename from Sources/MachOCaches/SharedCache.swift rename to Sources/MachO/MachOCaches/SharedCache.swift diff --git a/Sources/MachOCaches/SharedCacheBuildPromise.swift b/Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift similarity index 100% rename from Sources/MachOCaches/SharedCacheBuildPromise.swift rename to Sources/MachO/MachOCaches/SharedCacheBuildPromise.swift diff --git a/Sources/MachOCaches/SharedCacheEvictionGroup.swift b/Sources/MachO/MachOCaches/SharedCacheEvictionGroup.swift similarity index 100% rename from Sources/MachOCaches/SharedCacheEvictionGroup.swift rename to Sources/MachO/MachOCaches/SharedCacheEvictionGroup.swift diff --git a/Sources/MachOCaches/SharedCacheKey.swift b/Sources/MachO/MachOCaches/SharedCacheKey.swift similarity index 82% rename from Sources/MachOCaches/SharedCacheKey.swift rename to Sources/MachO/MachOCaches/SharedCacheKey.swift index bf79b9eb3..55e0552f6 100644 --- a/Sources/MachOCaches/SharedCacheKey.swift +++ b/Sources/MachO/MachOCaches/SharedCacheKey.swift @@ -11,10 +11,12 @@ import MachOKitExtensions /// 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) 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`. +/// 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. @@ -53,6 +55,10 @@ public struct SharedCacheKey: Hashable, CustomStringConvertible, @unchecked Send 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) diff --git a/Sources/MachOCaches/SharedCacheRegistry.swift b/Sources/MachO/MachOCaches/SharedCacheRegistry.swift similarity index 100% rename from Sources/MachOCaches/SharedCacheRegistry.swift rename to Sources/MachO/MachOCaches/SharedCacheRegistry.swift diff --git a/Sources/MachODependencies/DependencyClosure.swift b/Sources/MachO/MachODependencies/DependencyClosure.swift similarity index 71% rename from Sources/MachODependencies/DependencyClosure.swift rename to Sources/MachO/MachODependencies/DependencyClosure.swift index b47bea831..f165df9a2 100644 --- a/Sources/MachODependencies/DependencyClosure.swift +++ b/Sources/MachO/MachODependencies/DependencyClosure.swift @@ -1,4 +1,5 @@ -import MachOKit +import Foundation +@_spi(Support) import MachOKit import MachOKitExtensions /// How far a `DependencyClosure` follows the load commands. @@ -101,8 +102,45 @@ extension DependencyClosure where MachO == MachOFile { /// (`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) { - let locator = FileDependencyLocator(searchPaths: searchPaths, preferredCPU: root.header.cpu, platforms: DependencyPlatforms.platforms(of: root)) + // 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/MachODependencies/DependencyLoadName.swift b/Sources/MachO/MachODependencies/DependencyLoadName.swift similarity index 100% rename from Sources/MachODependencies/DependencyLoadName.swift rename to Sources/MachO/MachODependencies/DependencyLoadName.swift diff --git a/Sources/MachODependencies/DependencyLocating.swift b/Sources/MachO/MachODependencies/DependencyLocating.swift similarity index 100% rename from Sources/MachODependencies/DependencyLocating.swift rename to Sources/MachO/MachODependencies/DependencyLocating.swift diff --git a/Sources/MachODependencies/DependencyPlatforms.swift b/Sources/MachO/MachODependencies/DependencyPlatforms.swift similarity index 100% rename from Sources/MachODependencies/DependencyPlatforms.swift rename to Sources/MachO/MachODependencies/DependencyPlatforms.swift diff --git a/Sources/MachODependencies/DependencySearchPath.swift b/Sources/MachO/MachODependencies/DependencySearchPath.swift similarity index 98% rename from Sources/MachODependencies/DependencySearchPath.swift rename to Sources/MachO/MachODependencies/DependencySearchPath.swift index c57ff4cc9..6ded87fc0 100644 --- a/Sources/MachODependencies/DependencySearchPath.swift +++ b/Sources/MachO/MachODependencies/DependencySearchPath.swift @@ -146,7 +146,7 @@ extension DependencySearchPath { public enum DependencySearchPathError: Error, Sendable, Equatable { /// The file loaded but yielded no Mach-O slice. case noMachOSlice(path: String) - /// `FullDyldCache.host` returned `nil` — the platform exposes no shared + /// `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. diff --git a/Sources/MachODependencies/FileDependencyLocator.swift b/Sources/MachO/MachODependencies/FileDependencyLocator.swift similarity index 88% rename from Sources/MachODependencies/FileDependencyLocator.swift rename to Sources/MachO/MachODependencies/FileDependencyLocator.swift index c1d896016..002f42d2c 100644 --- a/Sources/MachODependencies/FileDependencyLocator.swift +++ b/Sources/MachO/MachODependencies/FileDependencyLocator.swift @@ -20,6 +20,10 @@ import MachOKitExtensions /// 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 @@ -66,11 +70,15 @@ public final class FileDependencyLocator: DependencyLocating, @unchecked Sendabl /// - 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. - public init(searchPaths: [DependencySearchPath], preferredCPU: CPU? = nil, platforms: Set = []) { + /// - 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] = [] + var caches: [FullDyldCache] = rootDyldCache.map { [$0] } ?? [] var loadFailures: [DependencySearchPathLoadFailure] = [] for searchPath in searchPaths { @@ -103,14 +111,22 @@ public final class FileDependencyLocator: DependencyLocating, @unchecked Sendabl 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: - if let hostCache = FullDyldCache.host { - caches.append(hostCache) + // 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)) } @@ -164,6 +180,12 @@ public final class FileDependencyLocator: DependencyLocating, @unchecked Sendabl 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 diff --git a/Sources/MachODependencies/SharedDependencyClosure.swift b/Sources/MachO/MachODependencies/SharedDependencyClosure.swift similarity index 100% rename from Sources/MachODependencies/SharedDependencyClosure.swift rename to Sources/MachO/MachODependencies/SharedDependencyClosure.swift diff --git a/Sources/MachOFoundation/Exported.swift b/Sources/MachO/MachOFoundation/Exported.swift similarity index 100% rename from Sources/MachOFoundation/Exported.swift rename to Sources/MachO/MachOFoundation/Exported.swift diff --git a/Sources/MachOPointers/Bit.swift b/Sources/MachO/MachOPointers/Bit.swift similarity index 100% rename from Sources/MachOPointers/Bit.swift rename to Sources/MachO/MachOPointers/Bit.swift diff --git a/Sources/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift b/Sources/MachO/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift similarity index 100% rename from Sources/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift rename to Sources/MachO/MachOPointers/LocatableLayoutWrapper+RelativePointer.swift diff --git a/Sources/MachOPointers/Pointer.swift b/Sources/MachO/MachOPointers/Pointer.swift similarity index 59% rename from Sources/MachOPointers/Pointer.swift rename to Sources/MachO/MachOPointers/Pointer.swift index 8c78954cd..1d9b7fe53 100644 --- a/Sources/MachOPointers/Pointer.swift +++ b/Sources/MachO/MachOPointers/Pointer.swift @@ -12,20 +12,24 @@ public struct Pointer: RelativeIndirectType, PointerProtoco self.address = address } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - if let machOFile = machO as? MachOFile, let rebase = machOFile.resolveRebase(fileOffset: offset.cast()) { + /// 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) - } else { - return try machO.readElement(offset: offset) } + return try context.readElement(at: address) } - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - .init(address: ptr.assumingMemoryBound(to: UInt64.self).pointee) + @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) } - public static func resolve(at address: Context.Address, in context: Context) throws -> Pointer where Context : ReadingContext { - return try context.readElement(at: address) + @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) } } diff --git a/Sources/MachO/MachOPointers/Protocol/PointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/PointerProtocol.swift new file mode 100644 index 000000000..9f4acb388 --- /dev/null +++ b/Sources/MachO/MachOPointers/Protocol/PointerProtocol.swift @@ -0,0 +1,99 @@ +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/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift similarity index 100% rename from Sources/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift rename to Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerIntPairProtocol.swift diff --git a/Sources/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift similarity index 51% rename from Sources/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift rename to Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift index de284d6c1..c163bd80e 100644 --- a/Sources/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift +++ b/Sources/MachO/MachOPointers/Protocol/RelativeDirectPointerProtocol.swift @@ -6,38 +6,6 @@ import MachOResolving public protocol RelativeDirectPointerProtocol: RelativePointerProtocol {} extension RelativeDirectPointerProtocol { - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - return try resolveDirect(from: offset, in: machO) - } - - func resolveDirect(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - return try Pointee.resolve(from: resolveDirectOffset(from: offset), in: machO) - } - - public func resolveAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - return try resolveDirectAny(from: offset, in: machO) - } - - func resolveDirectAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - return try T.resolve(from: resolveDirectOffset(from: offset), in: machO) - } - - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - return try resolveDirect(from: ptr) - } - - func resolveDirect(from ptr: UnsafeRawPointer) throws -> Pointee { - return try Pointee.resolve(from: resolveDirectOffset(from: ptr)) - } - - public func resolveAny(from ptr: UnsafeRawPointer) throws -> T { - return try resolveDirectAny(from: ptr) - } - - func resolveDirectAny(from ptr: UnsafeRawPointer) throws -> T { - return try T.resolve(from: resolveDirectOffset(from: ptr)) - } - public func resolve( at address: Context.Address, in context: Context @@ -51,14 +19,14 @@ extension RelativeDirectPointerProtocol { ) 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 @@ -68,17 +36,26 @@ extension RelativeDirectPointerProtocol { } 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 { - guard isValid else { return nil } - return try resolve(from: offset, in: machO) + 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 { - guard isValid else { return nil } - return try resolve(from: ptr) + try resolveUnlessNull(at: ptr, in: InProcessContext.shared) } - - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { + + /// 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/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift similarity index 55% rename from Sources/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift rename to Sources/MachO/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift index 30d041461..557b5236c 100644 --- a/Sources/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift +++ b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectPointerProtocol.swift @@ -5,58 +5,9 @@ import MachOKitExtensions public protocol RelativeIndirectPointerProtocol: RelativePointerProtocol { associatedtype IndirectType: RelativeIndirectType where IndirectType.Resolved == Pointee - - func resolveIndirectOffset(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Int } extension RelativeIndirectPointerProtocol { - // MARK: - MachO - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - return try resolveIndirect(from: offset, in: machO) - } - - func resolveIndirect(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - return try resolveIndirectType(from: offset, in: machO).resolve(in: machO) - } - - public func resolveAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - return try resolveIndirectAny(from: offset, in: machO) - } - - func resolveIndirectAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - return try resolveIndirectType(from: offset, in: machO).resolveAny(in: machO) - } - - public func resolveIndirectType(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> IndirectType { - return try .resolve(from: resolveDirectOffset(from: offset), in: machO) - } - - public func resolveIndirectOffset(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Int { - return try resolveIndirectType(from: offset, in: machO).resolveOffset(in: machO) - } - - // MARK: - InProcess - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - return try resolveIndirect(from: ptr) - } - - func resolveIndirect(from ptr: UnsafeRawPointer) throws -> Pointee { - return try resolveIndirectType(from: ptr).resolve() - } - - public func resolveAny(from ptr: UnsafeRawPointer) throws -> T { - return try resolveIndirectAny(from: ptr) - } - - func resolveIndirectAny(from ptr: UnsafeRawPointer) throws -> T { - return try resolveIndirectType(from: ptr).resolveAny() - } - - public func resolveIndirectType(from ptr: UnsafeRawPointer) throws -> IndirectType { - return try .resolve(from: resolveDirectOffset(from: ptr)) - } - - // MARK: - Context public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { return try resolveIndirect(at: address, in: context) } @@ -82,18 +33,44 @@ extension RelativeIndirectPointerProtocol { } } +// 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 { - guard isValid else { return nil } - return try resolve(from: offset, in: machO) + 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 { - guard isValid else { return nil } - return try resolve(from: ptr) + try resolveUnlessNull(at: ptr, in: InProcessContext.shared) } - - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { + + /// 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/MachOPointers/Protocol/RelativeIndirectType.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectType.swift similarity index 56% rename from Sources/MachOPointers/Protocol/RelativeIndirectType.swift rename to Sources/MachO/MachOPointers/Protocol/RelativeIndirectType.swift index f8169142a..896f09824 100644 --- a/Sources/MachOPointers/Protocol/RelativeIndirectType.swift +++ b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectType.swift @@ -6,14 +6,21 @@ 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 - - func resolve(in context: some ReadingContext) throws -> Resolved - func resolveAny(in context: some ReadingContext) throws -> T - func resolveAddress(in context: Context) throws -> Context.Address } diff --git a/Sources/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift similarity index 68% rename from Sources/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift rename to Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift index 87336758a..1f5cf3428 100644 --- a/Sources/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift +++ b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerIntPairProtocol.swift @@ -36,17 +36,24 @@ extension RelativeIndirectablePointerIntPairProtocol { } 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 { - guard isValid else { return nil } - return try resolve(from: offset, in: machO) + 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 { - guard isValid else { return nil } - return try resolve(from: ptr) + try resolveUnlessNull(at: ptr, in: InProcessContext.shared) } - - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { + + /// 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/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift similarity index 55% rename from Sources/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift rename to Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift index 3f72838b3..9aac6de21 100644 --- a/Sources/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift +++ b/Sources/MachO/MachOPointers/Protocol/RelativeIndirectablePointerProtocol.swift @@ -6,7 +6,6 @@ import MachOKitExtensions public protocol RelativeIndirectablePointerProtocol: RelativeDirectPointerProtocol, RelativeIndirectPointerProtocol { var relativeOffsetPlusIndirect: Offset { get } var isIndirect: Bool { get } - func resolveIndirectableOffset(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Int } extension RelativeIndirectablePointerProtocol { @@ -20,75 +19,6 @@ extension RelativeIndirectablePointerProtocol { } extension RelativeIndirectablePointerProtocol { - public func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - return try resolveIndirectable(from: offset, in: machO) - } - - public func resolveAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - return try resolveIndirectableAny(from: offset, in: machO) - } - - func resolveIndirectable(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - if isIndirect { - return try resolveIndirect(from: offset, in: machO) - } else { - return try resolveDirect(from: offset, in: machO) - } - } - - public func resolveIndirectableType(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> IndirectType? { - guard isIndirect else { return nil } - return try resolveIndirectType(from: offset, in: machO) - } - - func resolveIndirectableAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T { - if isIndirect { - return try resolveIndirectAny(from: offset, in: machO) - } else { - return try resolveDirectAny(from: offset, in: machO) - } - } - - public func resolveIndirectableOffset(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Int { - guard let indirectType = try resolveIndirectableType(from: offset, in: machO) else { - return resolveDirectOffset(from: offset) - } - return indirectType.resolveOffset(in: machO) - } - - // MARK: - InProcess - - public func resolve(from ptr: UnsafeRawPointer) throws -> Pointee { - return try resolveIndirectable(from: ptr) - } - - public func resolveAny(from ptr: UnsafeRawPointer) throws -> T { - return try resolveIndirectableAny(from: ptr) - } - - func resolveIndirectable(from ptr: UnsafeRawPointer) throws -> Pointee { - if isIndirect { - return try resolveIndirect(from: ptr) - } else { - return try resolveDirect(from: ptr) - } - } - - public func resolveIndirectableType(from ptr: UnsafeRawPointer) throws -> IndirectType? { - guard isIndirect else { return nil } - return try resolveIndirectType(from: ptr) - } - - func resolveIndirectableAny(from ptr: UnsafeRawPointer) throws -> T { - if isIndirect { - return try resolveIndirectAny(from: ptr) - } else { - return try resolveDirectAny(from: ptr) - } - } - - // MARK: - Context - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { return try resolveIndirectable(at: address, in: context) } @@ -126,18 +56,44 @@ extension RelativeIndirectablePointerProtocol { } } +// 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 { - guard isValid else { return nil } - return try resolve(from: offset, in: machO) + 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 { - guard isValid else { return nil } - return try resolve(from: ptr) + try resolveUnlessNull(at: ptr, in: InProcessContext.shared) } - public func resolve(at address: Context.Address, in context: Context) throws -> Pointee { + /// 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 new file mode 100644 index 000000000..f9ac42847 --- /dev/null +++ b/Sources/MachO/MachOPointers/Protocol/RelativePointerProtocol.swift @@ -0,0 +1,66 @@ +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/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift b/Sources/MachO/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift similarity index 100% rename from Sources/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift rename to Sources/MachO/MachOPointers/RelativeDirectPointer+LayoutProtocol.swift diff --git a/Sources/MachOPointers/RelativePointers.swift b/Sources/MachO/MachOPointers/RelativePointers.swift similarity index 100% rename from Sources/MachOPointers/RelativePointers.swift rename to Sources/MachO/MachOPointers/RelativePointers.swift diff --git a/Sources/MachOPointers/SymbolOrElementPointer.swift b/Sources/MachO/MachOPointers/SymbolOrElementPointer.swift similarity index 61% rename from Sources/MachOPointers/SymbolOrElementPointer.swift rename to Sources/MachO/MachOPointers/SymbolOrElementPointer.swift index 4d8762673..1ee2619d5 100644 --- a/Sources/MachOPointers/SymbolOrElementPointer.swift +++ b/Sources/MachO/MachOPointers/SymbolOrElementPointer.swift @@ -15,24 +15,6 @@ public enum SymbolOrElementPointer: RelativeIndirectType { case symbol(Symbol) case address(UInt64) - public func resolve() throws -> Resolved { - switch self { - case .symbol: - fatalError() - case .address(let address): - return try .element(Element.resolve(from: .init(bitPattern: stripPointerTags(of: address).uint))) - } - } - - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Resolved { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .address: - return try .element(Element.resolve(from: resolveOffset(in: machO), in: machO)) - } - } - public func resolve(in context: some ReadingContext) throws -> Resolved { switch self { case .symbol(let unsolvedSymbol): @@ -42,15 +24,6 @@ public enum SymbolOrElementPointer: RelativeIndirectType { } } - public func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int { - switch self { - case .symbol(let unsolvedSymbol): - return unsolvedSymbol.offset - case .address(let address): - return numericCast(machO.resolveOffset(at: machO.stripPointerTags(of: address))) - } - } - public func resolveAddress(in context: Context) throws -> Context.Address { switch self { case .symbol(let symbol): @@ -60,34 +33,13 @@ public enum SymbolOrElementPointer: RelativeIndirectType { } } - public func resolveAny() throws -> T where T: Resolvable { - fatalError() - } - - public func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T { - fatalError() - } - public func resolveAny(in context: some ReadingContext) throws -> T { fatalError("resolveAny is not supported for SymbolOrElementPointer with ReadingContext") } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - if let resolver = machO as? any MachOBindRebaseResolving { - 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(machO.readElement(offset: offset)) - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - return try .address(ptr.stripPointerTags().assumingMemoryBound(to: UInt64.self).pointee) - } - + /// 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) @@ -102,34 +54,59 @@ public enum SymbolOrElementPointer: RelativeIndirectType { } } -extension SymbolOrElementPointer where Element: OptionalProtocol { +// MARK: - Deprecated Mach-O and pointer forms + +extension SymbolOrElementPointer { + @available(*, deprecated, message: "Pass a ReadingContext: resolve(in: .inProcess).") public func resolve() throws -> Resolved { - switch self { - case .symbol: - fatalError() - case .address(let address) where stripPointerTags(of: address).uint == 0: - return .element(.none) - case .address(let address): - return try .element(Element.resolve(from: .init(bitPattern: stripPointerTags(of: address).uint))) - } + 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 { - switch self { - case .symbol(let unsolvedSymbol): - return .symbol(unsolvedSymbol) - case .address(let address) where machO.stripPointerTags(of: address) == 0: - return .element(.none) - case .address: - return try .element(Element.resolve(from: resolveOffset(in: machO), in: machO)) - } + 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 address == 0: + 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/MachOPointers/TargetRelativeDirectPointer.swift b/Sources/MachO/MachOPointers/TargetRelativeDirectPointer.swift similarity index 100% rename from Sources/MachOPointers/TargetRelativeDirectPointer.swift rename to Sources/MachO/MachOPointers/TargetRelativeDirectPointer.swift diff --git a/Sources/MachOPointers/TargetRelativeDirectPointerIntPair.swift b/Sources/MachO/MachOPointers/TargetRelativeDirectPointerIntPair.swift similarity index 100% rename from Sources/MachOPointers/TargetRelativeDirectPointerIntPair.swift rename to Sources/MachO/MachOPointers/TargetRelativeDirectPointerIntPair.swift diff --git a/Sources/MachOPointers/TargetRelativeIndirectPointer.swift b/Sources/MachO/MachOPointers/TargetRelativeIndirectPointer.swift similarity index 100% rename from Sources/MachOPointers/TargetRelativeIndirectPointer.swift rename to Sources/MachO/MachOPointers/TargetRelativeIndirectPointer.swift diff --git a/Sources/MachOPointers/TargetRelativeIndirectablePointer.swift b/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointer.swift similarity index 100% rename from Sources/MachOPointers/TargetRelativeIndirectablePointer.swift rename to Sources/MachO/MachOPointers/TargetRelativeIndirectablePointer.swift diff --git a/Sources/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift b/Sources/MachO/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift similarity index 100% rename from Sources/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift rename to Sources/MachO/MachOPointers/TargetRelativeIndirectablePointerIntPair.swift diff --git a/Sources/MachOReading/Extensions/DyldCache+.swift b/Sources/MachO/MachOReading/Extensions/DyldCache+.swift similarity index 100% rename from Sources/MachOReading/Extensions/DyldCache+.swift rename to Sources/MachO/MachOReading/Extensions/DyldCache+.swift diff --git a/Sources/MachOReading/Extensions/FileHandle+.swift b/Sources/MachO/MachOReading/Extensions/FileHandle+.swift similarity index 100% rename from Sources/MachOReading/Extensions/FileHandle+.swift rename to Sources/MachO/MachOReading/Extensions/FileHandle+.swift diff --git a/Sources/MachOReading/Extensions/FileIO+.swift b/Sources/MachO/MachOReading/Extensions/FileIO+.swift similarity index 100% rename from Sources/MachOReading/Extensions/FileIO+.swift rename to Sources/MachO/MachOReading/Extensions/FileIO+.swift diff --git a/Sources/MachOReading/Extensions/MachOFile+.swift b/Sources/MachO/MachOReading/Extensions/MachOFile+.swift similarity index 100% rename from Sources/MachOReading/Extensions/MachOFile+.swift rename to Sources/MachO/MachOReading/Extensions/MachOFile+.swift diff --git a/Sources/MachOReading/Extensions/ReadingError.swift b/Sources/MachO/MachOReading/Extensions/ReadingError.swift similarity index 100% rename from Sources/MachOReading/Extensions/ReadingError.swift rename to Sources/MachO/MachOReading/Extensions/ReadingError.swift diff --git a/Sources/MachOReading/Models/DataSequence.swift b/Sources/MachO/MachOReading/Models/DataSequence.swift similarity index 100% rename from Sources/MachOReading/Models/DataSequence.swift rename to Sources/MachO/MachOReading/Models/DataSequence.swift diff --git a/Sources/MachOReading/Models/MemorySequence.swift b/Sources/MachO/MachOReading/Models/MemorySequence.swift similarity index 100% rename from Sources/MachOReading/Models/MemorySequence.swift rename to Sources/MachO/MachOReading/Models/MemorySequence.swift diff --git a/Sources/MachOReading/Readable/MachOFile+Readable.swift b/Sources/MachO/MachOReading/Readable/MachOFile+Readable.swift similarity index 100% rename from Sources/MachOReading/Readable/MachOFile+Readable.swift rename to Sources/MachO/MachOReading/Readable/MachOFile+Readable.swift diff --git a/Sources/MachOReading/Readable/MachOImage+Readable.swift b/Sources/MachO/MachOReading/Readable/MachOImage+Readable.swift similarity index 100% rename from Sources/MachOReading/Readable/MachOImage+Readable.swift rename to Sources/MachO/MachOReading/Readable/MachOImage+Readable.swift diff --git a/Sources/MachOReading/Readable/Readable.swift b/Sources/MachO/MachOReading/Readable/Readable.swift similarity index 100% rename from Sources/MachOReading/Readable/Readable.swift rename to Sources/MachO/MachOReading/Readable/Readable.swift diff --git a/Sources/MachOReading/Readable/UnsafeRawPointer+Readable.swift b/Sources/MachO/MachOReading/Readable/UnsafeRawPointer+Readable.swift similarity index 100% rename from Sources/MachOReading/Readable/UnsafeRawPointer+Readable.swift rename to Sources/MachO/MachOReading/Readable/UnsafeRawPointer+Readable.swift diff --git a/Sources/MachOReading/ReadingContext/InProcessContext.swift b/Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift similarity index 64% rename from Sources/MachOReading/ReadingContext/InProcessContext.swift rename to Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift index 1aa152462..289d894b4 100644 --- a/Sources/MachOReading/ReadingContext/InProcessContext.swift +++ b/Sources/MachO/MachOReading/ReadingContext/InProcessContext.swift @@ -1,5 +1,6 @@ import MachOKit import MachOKitExtensions +import Utilities /// A reading context for direct in-process memory access. /// @@ -46,32 +47,49 @@ public struct InProcessContext: ReadingContext, Sendable { /// 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 ptr.stripPointerTags().readElement() + try strippingTags(from: ptr).readElement() } public func readElements(at ptr: Address, numberOfElements: Int) throws -> [T] { - try ptr.stripPointerTags().readElements(numberOfElements: numberOfElements) + try strippingTags(from: ptr).readElements(numberOfElements: numberOfElements) } - + public func readWrapperElement(at ptr: Address) throws -> T { - try ptr.stripPointerTags().readWrapperElement() + try strippingTags(from: ptr).readWrapperElement() } - + public func readWrapperElements(at ptr: Address, numberOfElements: Int) throws -> [T] where T : LocatableLayoutWrapper { - try ptr.stripPointerTags().readWrapperElements(numberOfElements: numberOfElements) + try strippingTags(from: ptr).readWrapperElements(numberOfElements: numberOfElements) } public func readString(at ptr: Address) throws -> String { - try ptr.stripPointerTags().readString() + 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 { - address.advanced(by: delta) + ((try? strippingTags(from: address)) ?? address).advanced(by: delta) } - + public func advanceAddress(_ address: Address, of type: T.Type) -> Address { - address.advanced(by: MemoryLayout.size) + advanceAddress(address, by: MemoryLayout.size) } public func addressFromOffset(_ offset: Int) throws -> Address { @@ -80,11 +98,10 @@ public struct InProcessContext: ReadingContext, Sendable { } public func addressFromVirtualAddress(_ virtualAddress: UInt64) throws -> Address { - // For InProcess context, the virtual address is a pointer bit pattern - // Use UInt for the intermediate conversion to handle large addresses correctly - try UnsafeRawPointer(bitPattern: UInt(virtualAddress)).stripPointerTags() + // 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) } @@ -98,6 +115,12 @@ extension InProcessContext { 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 { diff --git a/Sources/MachOReading/ReadingContext/MachOContext.swift b/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift similarity index 80% rename from Sources/MachOReading/ReadingContext/MachOContext.swift rename to Sources/MachO/MachOReading/ReadingContext/MachOContext.swift index 6e5e4626d..254d0fefd 100644 --- a/Sources/MachOReading/ReadingContext/MachOContext.swift +++ b/Sources/MachO/MachOReading/ReadingContext/MachOContext.swift @@ -70,15 +70,19 @@ public struct MachOContext: Readi address.offseting(of: type) } - public func addressFromOffset(_ offset: Int) throws -> Int { + public func addressFromOffset(_ offset: Int) -> Int { offset } - public func addressFromVirtualAddress(_ virtualAddress: UInt64) throws -> Int { - machO.resolveOffset(at: machO.stripPointerTags(of: virtualAddress)).cast() + /// 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) throws -> Int { + public func offsetFromAddress(_ address: Int) -> Int { address } @@ -90,6 +94,17 @@ public struct MachOContext: Readi public var bindRebaseResolver: (any MachOBindRebaseResolving)? { machO 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 diff --git a/Sources/MachOReading/ReadingContext/ReadingContext.swift b/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift similarity index 86% rename from Sources/MachOReading/ReadingContext/ReadingContext.swift rename to Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift index f542b77ad..b455566c1 100644 --- a/Sources/MachOReading/ReadingContext/ReadingContext.swift +++ b/Sources/MachO/MachOReading/ReadingContext/ReadingContext.swift @@ -263,12 +263,48 @@ public protocol ReadingContext: Sendable { /// 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 { diff --git a/Sources/MachOResolving/AnyResolvable.swift b/Sources/MachO/MachOResolving/AnyResolvable.swift similarity index 100% rename from Sources/MachOResolving/AnyResolvable.swift rename to Sources/MachO/MachOResolving/AnyResolvable.swift diff --git a/Sources/MachO/MachOResolving/AsyncResolvable.swift b/Sources/MachO/MachOResolving/AsyncResolvable.swift new file mode 100644 index 000000000..22174934e --- /dev/null +++ b/Sources/MachO/MachOResolving/AsyncResolvable.swift @@ -0,0 +1,65 @@ +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/MachOResolving/Resolvable.swift b/Sources/MachO/MachOResolving/Resolvable.swift similarity index 62% rename from Sources/MachOResolving/Resolvable.swift rename to Sources/MachO/MachOResolving/Resolvable.swift index 6e3deba50..6fa41fde7 100644 --- a/Sources/MachOResolving/Resolvable.swift +++ b/Sources/MachO/MachOResolving/Resolvable.swift @@ -3,40 +3,18 @@ import MachOReading import MachOKitExtensions public protocol Resolvable: Sendable { - static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self - static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? - static func resolve(from ptr: UnsafeRawPointer) throws -> Self - static func resolve(from ptr: UnsafeRawPointer) throws -> Self? 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(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - return try machO.readElement(offset: offset) - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { - let result: Self = try resolve(from: offset, in: machO) - return .some(result) - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - try ptr.stripPointerTags().readElement() - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self? { - let result: Self = try resolve(from: ptr) - return .some(result) - } - 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 @@ -46,25 +24,36 @@ extension Resolvable { } } -extension Optional: Resolvable where Wrapped: Resolvable { +// 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 { - let result: Wrapped? = try Wrapped.resolve(from: offset, in: machO) - if let result { - return .some(result) - } else { - return .none - } + 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 { - let result: Wrapped? = try Wrapped.resolve(from: ptr) - if let result { - return .some(result) - } else { - return .none - } + 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 { @@ -73,34 +62,48 @@ extension Optional: Resolvable where Wrapped: Resolvable { return .none } } -} -extension String: 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 { - return try machO.readString(offset: offset) + 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 { - return try ptr.stripPointerTags().readString() + 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) } -} -extension Resolvable where Self: LocatableLayoutWrapper { + @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 machO.readWrapperElement(offset: offset) + 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 ptr.stripPointerTags().readWrapperElement() + 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 {} @@ -125,6 +128,6 @@ 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(from: offset, in: machO) + return try .resolve(at: offset, in: machO.context) } } diff --git a/Sources/MachOResolving/Symbol.swift b/Sources/MachO/MachOResolving/Symbol.swift similarity index 100% rename from Sources/MachOResolving/Symbol.swift rename to Sources/MachO/MachOResolving/Symbol.swift diff --git a/Sources/MachOResolving/SymbolOrElement.swift b/Sources/MachO/MachOResolving/SymbolOrElement.swift similarity index 72% rename from Sources/MachOResolving/SymbolOrElement.swift rename to Sources/MachO/MachOResolving/SymbolOrElement.swift index 7dbbe5c28..5fae66c88 100644 --- a/Sources/MachOResolving/SymbolOrElement.swift +++ b/Sources/MachO/MachOResolving/SymbolOrElement.swift @@ -33,41 +33,46 @@ public enum SymbolOrElement: Resolvable { } } - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: offset) { - return .symbol(.init(offset: offset, name: symbol)) - } else { - return try .element(.resolve(from: offset, in: machO)) - } - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self? { - if let machOFile = machO as? MachOFile, let symbol = machOFile.resolveBind(fileOffset: offset) { - return .symbol(.init(offset: offset, name: symbol)) - } else { - return try Element.resolve(from: offset, in: machO).map { .element($0) } - } - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - return try .element(.resolve(from: ptr)) - } - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - if let machOFileContext = context as? MachOContext, let offset = try? context.offsetFromAddress(address), let symbol = machOFileContext.machO.resolveBind(fileOffset: offset) { - return .symbol(.init(offset: offset, name: symbol)) + 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 machOFileContext = context as? MachOContext, let offset = try? context.offsetFromAddress(address), let symbol = machOFileContext.machO.resolveBind(fileOffset: offset) { - return .symbol(.init(offset: offset, name: symbol)) + 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 { diff --git a/Sources/MachOResolving/Symbols.swift b/Sources/MachO/MachOResolving/Symbols.swift similarity index 100% rename from Sources/MachOResolving/Symbols.swift rename to Sources/MachO/MachOResolving/Symbols.swift diff --git a/Sources/MachOSymbols/DemangledSymbol.swift b/Sources/MachO/MachOSymbols/DemangledSymbol.swift similarity index 100% rename from Sources/MachOSymbols/DemangledSymbol.swift rename to Sources/MachO/MachOSymbols/DemangledSymbol.swift diff --git a/Sources/MachOSymbols/InternedNodeReferenceCache.swift b/Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift similarity index 84% rename from Sources/MachOSymbols/InternedNodeReferenceCache.swift rename to Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift index 29c3475d2..74fc2b79a 100644 --- a/Sources/MachOSymbols/InternedNodeReferenceCache.swift +++ b/Sources/MachO/MachOSymbols/InternedNodeReferenceCache.swift @@ -2,6 +2,7 @@ import Foundation @_spi(Internals) import Demangling import MachOKit import MachOKitExtensions +import MachOReading @_spi(Internals) import MachOCaches import SwiftStdlibToolbox @@ -79,6 +80,23 @@ public final class InternedNodeReferenceCache: @unchecked Sendable { Self.processScopedStorage.reference(interning: node) } + /// The shared reference for `node` in the scope `context` declares: the + /// image's store, the process-wide store, or — for a context with no + /// identity — a store of its own, as when an image store cannot be built. + public func reference(interning node: Node, in context: some ReadingContext) -> NodeReference { + switch context.cacheScope { + case .image(let identifier): + guard let storage = cache.resolve(key: SharedCacheKey(identifier: identifier), build: { Storage() }) else { + return NodeReference(interning: node) + } + return storage.reference(interning: node) + case .process: + return reference(interning: node) + case .uncached: + return NodeReference(interning: node) + } + } + public func contains(in machO: some MachORepresentableWithCache) -> Bool { cache.contains(in: machO) } diff --git a/Sources/MachOSymbols/LargeStackTaskExecution.swift b/Sources/MachO/MachOSymbols/LargeStackTaskExecution.swift similarity index 100% rename from Sources/MachOSymbols/LargeStackTaskExecution.swift rename to Sources/MachO/MachOSymbols/LargeStackTaskExecution.swift diff --git a/Sources/MachOSymbols/MachO+Symbol.swift b/Sources/MachO/MachOSymbols/MachO+Symbol.swift similarity index 51% rename from Sources/MachOSymbols/MachO+Symbol.swift rename to Sources/MachO/MachOSymbols/MachO+Symbol.swift index 2b527460d..42c189e5a 100644 --- a/Sources/MachOSymbols/MachO+Symbol.swift +++ b/Sources/MachO/MachOSymbols/MachO+Symbol.swift @@ -12,7 +12,13 @@ extension MachORepresentableWithCache { } extension MachORepresentable { + /// The image's Swift symbols, each at the offset the symbol index files + /// it under (see `SymbolValueOffsetConverter`). Debug-map entries are + /// left out. public var swiftSymbols: [MachOResolving.Symbol] { - symbols.filter { $0.name.isSwiftSymbol }.map { .init(offset: $0.offset, name: $0.name) } + let symbolValueOffsetConverter = (self as? MachOFile).map { SymbolValueOffsetConverter(for: $0) } + return symbols.filter { $0.name.isSwiftSymbol && !$0.nlist.isDebuggingEntry }.map { + .init(offset: symbolValueOffsetConverter?.offset(forSymbolValue: $0.offset) ?? $0.offset, name: $0.name) + } } } diff --git a/Sources/MachOSymbols/SharedCacheEvictionGroup+MachOSymbols.swift b/Sources/MachO/MachOSymbols/SharedCacheEvictionGroup+MachOSymbols.swift similarity index 100% rename from Sources/MachOSymbols/SharedCacheEvictionGroup+MachOSymbols.swift rename to Sources/MachO/MachOSymbols/SharedCacheEvictionGroup+MachOSymbols.swift diff --git a/Sources/MachOSymbols/StructuralNodeReferenceKey.swift b/Sources/MachO/MachOSymbols/StructuralNodeReferenceKey.swift similarity index 100% rename from Sources/MachOSymbols/StructuralNodeReferenceKey.swift rename to Sources/MachO/MachOSymbols/StructuralNodeReferenceKey.swift diff --git a/Sources/MachOSymbols/Symbol.swift b/Sources/MachO/MachOSymbols/Symbol.swift similarity index 100% rename from Sources/MachOSymbols/Symbol.swift rename to Sources/MachO/MachOSymbols/Symbol.swift diff --git a/Sources/MachOSymbols/SymbolIndexStore.swift b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift similarity index 97% rename from Sources/MachOSymbols/SymbolIndexStore.swift rename to Sources/MachO/MachOSymbols/SymbolIndexStore.swift index 26ca94b70..7d5a4f384 100644 --- a/Sources/MachOSymbols/SymbolIndexStore.swift +++ b/Sources/MachO/MachOSymbols/SymbolIndexStore.swift @@ -585,11 +585,21 @@ public final class SymbolIndexStore: @unchecked Sendable { /// that pointer; a `String` is materialized only for the symbols /// that pass it, and only as the build-time dedup key. An image's /// offsets need no cache adjustment (that path is `MachOFile`-only), - /// so canonical == raw here. + /// so canonical == raw here. A debug-map entry only reserves its + /// name's row (see `SymbolTableBuilder.reserveRow`), on both legs. func collectMappedSymbolRows(_ mappedSymbols: some Sequence, stringBase: UnsafeRawPointer) { for symbol in mappedSymbols { if nameBytesHaveSwiftManglingPrefix(symbol.nameC) { guard !symbol.nlist.isExternal else { continue } + if symbol.nlist.isDebuggingEntry { + tableBuilder.reserveRow( + forName: String(cString: symbol.nameC), + mappedNameByteOffset: UnsafeRawPointer(symbol.nameC) - stringBase, + nameByteLength: strlen(symbol.nameC), + canonicalOffset: symbol.offset + ) + continue + } // A `nil` row means the name's binary-supplied geometry // exceeds the packed budgets (malformed/hostile string // table) — skip the symbol instead of trapping (M3). @@ -602,6 +612,15 @@ public final class SymbolIndexStore: @unchecked Sendable { ) else { continue } registerRow(row, rawOffset: symbol.offset, canonicalOffset: symbol.offset, isNewRow: isNewRow) } else if nameBytesHaveSymbolicManglingSymbolPrefix(symbol.nameC), !symbol.nlist.isExternal { + if symbol.nlist.isDebuggingEntry { + symbolicManglingTableBuilder.reserveRow( + forName: String(cString: symbol.nameC), + mappedNameByteOffset: UnsafeRawPointer(symbol.nameC) - stringBase, + nameByteLength: strlen(symbol.nameC), + canonicalOffset: symbol.offset + ) + continue + } // Same refusal rule for a name whose geometry cannot pack. _ = symbolicManglingTableBuilder.canonicalRow( forName: String(cString: symbol.nameC), @@ -619,14 +638,20 @@ public final class SymbolIndexStore: @unchecked Sendable { } else if let mappedSymbols32, let mappedStringTableBase { collectMappedSymbolRows(mappedSymbols32, stringBase: mappedStringTableBase) } else { + let symbolValueOffsetConverter = SymbolValueOffsetConverter(for: machO) for symbol in machO.symbols where !symbol.nlist.isExternal { let name = symbol.name let isSwiftSymbol = name.isSwiftSymbol guard isSwiftSymbol || SymbolicManglingSymbolName.hasPrefix(name) else { continue } let rawOffset = symbol.offset - var canonicalOffset = rawOffset - if let cache = machO.cache, rawOffset >= 0, machO is MachOFile { - canonicalOffset = rawOffset - cache.mainCacheHeader.sharedRegionStart.cast() + let canonicalOffset = symbolValueOffsetConverter.offset(forSymbolValue: rawOffset) + if symbol.nlist.isDebuggingEntry { + if isSwiftSymbol { + tableBuilder.reserveRow(forName: name, canonicalOffset: canonicalOffset) + } else { + symbolicManglingTableBuilder.reserveRow(forName: name, canonicalOffset: canonicalOffset) + } + continue } if isSwiftSymbol { guard let (row, isNewRow) = tableBuilder.canonicalRow(forName: name, canonicalOffset: canonicalOffset, isExternal: symbol.nlist.isExternal) else { continue } @@ -1418,4 +1443,14 @@ extension NlistProtocol { guard let flags = flags, let type = flags.type else { return false } return flags.contains(.ext) && type == .undf } + + /// A debug-map (STABS) entry: it describes a symbol for the debugger and + /// is not one. An `N_GSYM` entry carries the value 0 under the very name + /// of the symbol it describes; indexed like a symbol, it was filed at the + /// mach header and, listed after a local symbol, overwrote that symbol's + /// offset with 0. The index lets one only reserve a row + /// (`SymbolTableBuilder.reserveRow`). + package var isDebuggingEntry: Bool { + flags?.stab != nil + } } diff --git a/Sources/MachOSymbols/SymbolRowBucket.swift b/Sources/MachO/MachOSymbols/SymbolRowBucket.swift similarity index 100% rename from Sources/MachOSymbols/SymbolRowBucket.swift rename to Sources/MachO/MachOSymbols/SymbolRowBucket.swift diff --git a/Sources/MachOSymbols/SymbolTable.swift b/Sources/MachO/MachOSymbols/SymbolTable.swift similarity index 93% rename from Sources/MachOSymbols/SymbolTable.swift rename to Sources/MachO/MachOSymbols/SymbolTable.swift index 59b6ba32e..fedf4c745 100644 --- a/Sources/MachOSymbols/SymbolTable.swift +++ b/Sources/MachO/MachOSymbols/SymbolTable.swift @@ -290,6 +290,25 @@ struct SymbolTableBuilder { 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) diff --git a/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift b/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift new file mode 100644 index 000000000..b320f358b --- /dev/null +++ b/Sources/MachO/MachOSymbols/SymbolValueOffsetConverter.swift @@ -0,0 +1,73 @@ +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 as? MachOFile 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/MachOSymbols/SymbolicManglingSymbols.swift b/Sources/MachO/MachOSymbols/SymbolicManglingSymbols.swift similarity index 100% rename from Sources/MachOSymbols/SymbolicManglingSymbols.swift rename to Sources/MachO/MachOSymbols/SymbolicManglingSymbols.swift diff --git a/Sources/MachOFixtureSupport/DyldSharedCachePath.swift b/Sources/MachOFixtureSupport/DyldSharedCachePath.swift deleted file mode 100644 index 8199f4071..000000000 --- a/Sources/MachOFixtureSupport/DyldSharedCachePath.swift +++ /dev/null @@ -1,12 +0,0 @@ -package enum DyldSharedCachePath: String { - case current = "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e" - case iOS_18_5 = "/Volumes/Generic/iOS Systems/22F76__iPhone17,5/dyld_shared_cache_arm64e" - case iOS_26_1 = "/Volumes/Generic/iOS Systems/23B85__iPhone17,5/dyld_shared_cache_arm64e" - case macOS_15_5 = "/Volumes/DyldSharedCaches/macOS/15.5/dyld_shared_cache_arm64e" - case macOS_26_5_1 = "/Volumes/DyldSharedCaches/macOS/26.5.1/dyld_shared_cache_arm64e" - case macOS_26_5_2 = "/Volumes/DyldSharedCaches/macOS/26.5.2/dyld_shared_cache_arm64e" - case macOS_27_0 = "/Volumes/DyldSharedCaches/macOS/27.0/dyld_shared_cache_arm64e" - /// From iOS 27 beta 3 on a simulator runtime ships its frameworks in a - /// cache of its own instead of as files under `RuntimeRoot`. - case iOS_27_0_Simulator = "/Library/Developer/CoreSimulator/Volumes/iOS_24A434/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 27.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Caches/com.apple.dyld/dyld_sim_shared_cache_arm64" -} diff --git a/Sources/MachOPointers/Protocol/PointerProtocol.swift b/Sources/MachOPointers/Protocol/PointerProtocol.swift deleted file mode 100644 index 9382090fe..000000000 --- a/Sources/MachOPointers/Protocol/PointerProtocol.swift +++ /dev/null @@ -1,72 +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() throws -> Pointee - func resolveAny() throws -> T - - func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Pointee - func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T - func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int - - func resolve(in context: some ReadingContext) throws -> Pointee - func resolveAny(in context: some ReadingContext) throws -> T - func resolveAddress(in context: Context) throws -> Context.Address -} - -extension PointerProtocol { - public func resolve() throws -> Pointee { - return try Pointee.resolve(from: .init(bitPattern: UInt(stripPointerTags(of: address)))) - } - - public func resolveAny() throws -> T { - return try T.resolve(from: .init(bitPattern: UInt(stripPointerTags(of: address)))) - } - - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - return try Pointee.resolve(from: resolveOffset(in: machO), in: machO) - } - - public func resolveAny(in machO: some MachORepresentableWithCache & Readable) throws -> T { - return try T.resolve(from: resolveOffset(in: machO), in: machO) - } - - public func resolveOffset(in machO: some MachORepresentableWithCache & Readable) -> Int { - machO.resolveOffset(at: address) - } - - 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) - } -} - -extension PointerProtocol where Pointee: OptionalProtocol { - public func resolve(in machO: some MachORepresentableWithCache & Readable) throws -> Pointee { - guard address != 0 else { return nil } - return try Pointee.resolve(from: resolveOffset(in: machO), in: machO) - } - - public func resolve() throws -> Pointee { - guard address != 0 else { return nil } - return try Pointee.resolve(from: .init(bitPattern: UInt(stripPointerTags(of: address)))) - } - - public func resolve(in context: some ReadingContext) throws -> Pointee { - guard address != 0 else { return nil } - return try Pointee.resolve(at: resolveAddress(in: context), in: context) - } -} diff --git a/Sources/MachOPointers/Protocol/RelativePointerProtocol.swift b/Sources/MachOPointers/Protocol/RelativePointerProtocol.swift deleted file mode 100644 index faa5ee2c9..000000000 --- a/Sources/MachOPointers/Protocol/RelativePointerProtocol.swift +++ /dev/null @@ -1,46 +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(from ptr: UnsafeRawPointer) throws -> Pointee - func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Pointee - func resolve(at address: Context.Address, in context: Context) throws -> Pointee - - func resolveAny(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> T - func resolveAny(from ptr: UnsafeRawPointer) throws -> T - func resolveAny(at address: Context.Address, in context: Context) throws -> T - - func resolveDirectOffset(from offset: Int) -> Int - func resolveDirectOffset(from ptr: UnsafeRawPointer) throws -> UnsafeRawPointer - func resolveDirectAddress(at address: Context.Address, in context: Context) throws -> Context.Address - -} - -extension RelativePointerProtocol { - public func resolveDirectOffset(from ptr: UnsafeRawPointer) throws -> UnsafeRawPointer { - try ptr.stripPointerTags().advanced(by: .init(relativeOffset)) - } - - 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 - } -} diff --git a/Sources/MachOResolving/AsyncResolvable.swift b/Sources/MachOResolving/AsyncResolvable.swift deleted file mode 100644 index 5754d80f2..000000000 --- a/Sources/MachOResolving/AsyncResolvable.swift +++ /dev/null @@ -1,60 +0,0 @@ -import MachOKit -import MachOReading -import MachOKitExtensions - -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? -} - -extension AsyncResolvable { - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self { - return try machO.readElement(offset: offset) - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self? { - let result: Self = try await resolve(from: offset, in: machO) - return .some(result) - } -} - -extension Optional: AsyncResolvable where Wrapped: AsyncResolvable { - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self { - let result: Wrapped? = try await Wrapped.resolve(from: offset, in: machO) - if let result { - return .some(result) - } else { - return .none - } - } -} - -extension String: AsyncResolvable { - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self { - return try machO.readString(offset: offset) - } -} - -extension AsyncResolvable where Self: LocatableLayoutWrapper { - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) async throws -> Self { - try machO.readWrapperElement(offset: offset) - } -} - -extension Int: AsyncResolvable {} -extension UInt: AsyncResolvable {} - -extension Int8: AsyncResolvable {} -extension UInt8: AsyncResolvable {} - -extension Int16: AsyncResolvable {} -extension UInt16: AsyncResolvable {} - -extension Int32: AsyncResolvable {} -extension UInt32: AsyncResolvable {} - -extension Int64: AsyncResolvable {} -extension UInt64: AsyncResolvable {} - -extension Float: AsyncResolvable {} -extension Double: AsyncResolvable {} diff --git a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift b/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift deleted file mode 100644 index a8fcd90b1..000000000 --- a/Sources/MachOSwiftSection/Models/Anonymous/AnonymousContext.swift +++ /dev/null @@ -1,75 +0,0 @@ -import Foundation -import MachOKit -import MachOBase - -public struct AnonymousContext: TopLevelType, ContextProtocol { - public let descriptor: AnonymousContextDescriptor - public let genericContext: GenericContext? - public let mangledName: MangledName? - - public init(descriptor: AnonymousContextDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - var currentOffset = descriptor.offset + descriptor.layoutSize - - let genericContext = try descriptor.genericContext(in: machO) - - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - - if descriptor.hasMangledName { - let mangledNamePointer: RelativeDirectPointer = try machO.readElement(offset: currentOffset) - self.mangledName = try mangledNamePointer.resolve(from: currentOffset, in: machO) - currentOffset += MemoryLayout>.size - } else { - self.mangledName = nil - } - } - - public init(descriptor: AnonymousContextDescriptor) throws { - self.descriptor = descriptor - var currentOffset = descriptor.layoutSize - - let genericContext = try descriptor.genericContext() - - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - - let pointer = try descriptor.asPointer - - if descriptor.hasMangledName { - let mangledNamePointer: RelativeDirectPointer = try pointer.readElement(offset: currentOffset) - self.mangledName = try mangledNamePointer.resolve(from: pointer.advanced(by: currentOffset)) - currentOffset += MemoryLayout>.size - } else { - self.mangledName = nil - } - } -} - -// MARK: - ReadingContext Support - -extension AnonymousContext { - public init(descriptor: AnonymousContextDescriptor, in context: some ReadingContext) throws { - self.descriptor = descriptor - var currentOffset = descriptor.offset + descriptor.layoutSize - - let genericContext = try descriptor.genericContext(in: context) - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - - if descriptor.hasMangledName { - let mangledNamePointerAddress = try context.addressFromOffset(currentOffset) - let mangledNamePointer: RelativeDirectPointer = try context.readElement(at: mangledNamePointerAddress) - self.mangledName = try mangledNamePointer.resolve(at: mangledNamePointerAddress, in: context) - currentOffset += MemoryLayout>.size - } else { - self.mangledName = nil - } - } -} diff --git a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextWrapper.swift b/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextWrapper.swift deleted file mode 100644 index 4427dfc1b..000000000 --- a/Sources/MachOSwiftSection/Models/ContextDescriptor/ContextWrapper.swift +++ /dev/null @@ -1,187 +0,0 @@ -import Foundation -import MachOKit -import FoundationToolbox -import MachOBase - -@CaseCheckable(.public) -@AssociatedValue(.public) -public enum ContextWrapper: Resolvable { - case type(TypeContextWrapper) - case `protocol`(`Protocol`) - case anonymous(AnonymousContext) - case `extension`(ExtensionContext) - case module(ModuleContext) - case opaqueType(OpaqueType) - - public var context: any ContextProtocol { - switch self { - case .type(let typeWrapper): - switch typeWrapper { - case .enum(let `enum`): - return `enum` - case .struct(let `struct`): - return `struct` - case .class(let `class`): - return `class` - } - case .protocol(let protocolWrapper): - return protocolWrapper - case .anonymous(let anonymousContext): - return anonymousContext - case .extension(let extensionContext): - return extensionContext - case .module(let moduleContext): - return moduleContext - case .opaqueType(let opaqueType): - return opaqueType - } - } - - public static func forContextDescriptorWrapper(_ contextDescriptorWrapper: ContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Self { - switch contextDescriptorWrapper { - case .type(let typeContextDescriptorWrapper): - switch typeContextDescriptorWrapper { - case .enum(let enumDescriptor): - return try .type(.enum(.init(descriptor: enumDescriptor, in: machO))) - case .struct(let structDescriptor): - return try .type(.struct(.init(descriptor: structDescriptor, in: machO))) - case .class(let classDescriptor): - return try .type(.class(.init(descriptor: classDescriptor, in: machO))) - } - case .protocol(let protocolDescriptor): - return try .protocol(.init(descriptor: protocolDescriptor, in: machO)) - case .anonymous(let anonymousContextDescriptor): - return try .anonymous(.init(descriptor: anonymousContextDescriptor, in: machO)) - case .extension(let extensionContextDescriptor): - return try .extension(.init(descriptor: extensionContextDescriptor, in: machO)) - case .module(let moduleContextDescriptor): - return try .module(.init(descriptor: moduleContextDescriptor, in: machO)) - case .opaqueType(let opaqueTypeDescriptor): - return try .opaqueType(.init(descriptor: opaqueTypeDescriptor, in: machO)) - } - } - - public func parent(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SymbolOrElement? { - switch self { - case .type(let typeWrapper): - switch typeWrapper { - case .enum(let `enum`): - return try `enum`.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - case .struct(let `struct`): - return try `struct`.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - case .class(let `class`): - return try `class`.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - } - case .protocol(let `protocol`): - return try `protocol`.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - case .anonymous(let anonymousContext): - return try anonymousContext.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - case .extension(let extensionContext): - return try extensionContext.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - case .module(let moduleContext): - return try moduleContext.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - case .opaqueType(let opaqueType): - return try opaqueType.descriptor.parent(in: machO)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: machO) } - } - } - - public static func forContextDescriptorWrapper(_ contextDescriptorWrapper: ContextDescriptorWrapper) throws -> Self { - switch contextDescriptorWrapper { - case .type(let typeContextDescriptorWrapper): - switch typeContextDescriptorWrapper { - case .enum(let enumDescriptor): - return try .type(.enum(.init(descriptor: enumDescriptor))) - case .struct(let structDescriptor): - return try .type(.struct(.init(descriptor: structDescriptor))) - case .class(let classDescriptor): - return try .type(.class(.init(descriptor: classDescriptor))) - } - case .protocol(let protocolDescriptor): - return try .protocol(.init(descriptor: protocolDescriptor)) - case .anonymous(let anonymousContextDescriptor): - return try .anonymous(.init(descriptor: anonymousContextDescriptor)) - case .extension(let extensionContextDescriptor): - return try .extension(.init(descriptor: extensionContextDescriptor)) - case .module(let moduleContextDescriptor): - return try .module(.init(descriptor: moduleContextDescriptor)) - case .opaqueType(let opaqueTypeDescriptor): - return try .opaqueType(.init(descriptor: opaqueTypeDescriptor)) - } - } - - public func parent() throws -> SymbolOrElement? { - switch self { - case .type(let typeWrapper): - switch typeWrapper { - case .enum(let `enum`): - return try `enum`.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - case .struct(let `struct`): - return try `struct`.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - case .class(let `class`): - return try `class`.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - } - case .protocol(let `protocol`): - return try `protocol`.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - case .anonymous(let anonymousContext): - return try anonymousContext.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - case .extension(let extensionContext): - return try extensionContext.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - case .module(let moduleContext): - return try moduleContext.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - case .opaqueType(let opaqueType): - return try opaqueType.descriptor.parent()?.map { try ContextWrapper.forContextDescriptorWrapper($0) } - } - } -} - -// MARK: - ReadingContext Support - -extension ContextWrapper { - public static func forContextDescriptorWrapper(_ contextDescriptorWrapper: ContextDescriptorWrapper, in context: some ReadingContext) throws -> Self { - switch contextDescriptorWrapper { - case .type(let typeContextDescriptorWrapper): - switch typeContextDescriptorWrapper { - case .enum(let enumDescriptor): - return try .type(.enum(.init(descriptor: enumDescriptor, in: context))) - case .struct(let structDescriptor): - return try .type(.struct(.init(descriptor: structDescriptor, in: context))) - case .class(let classDescriptor): - return try .type(.class(.init(descriptor: classDescriptor, in: context))) - } - case .protocol(let protocolDescriptor): - return try .protocol(.init(descriptor: protocolDescriptor, in: context)) - case .anonymous(let anonymousContextDescriptor): - return try .anonymous(.init(descriptor: anonymousContextDescriptor, in: context)) - case .extension(let extensionContextDescriptor): - return try .extension(.init(descriptor: extensionContextDescriptor, in: context)) - case .module(let moduleContextDescriptor): - return try .module(.init(descriptor: moduleContextDescriptor, in: context)) - case .opaqueType(let opaqueTypeDescriptor): - return try .opaqueType(.init(descriptor: opaqueTypeDescriptor, in: context)) - } - } - - public func parent(in context: some ReadingContext) throws -> SymbolOrElement? { - switch self { - case .type(let typeWrapper): - switch typeWrapper { - case .enum(let `enum`): - return try `enum`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - case .struct(let `struct`): - return try `struct`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - case .class(let `class`): - return try `class`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - } - case .protocol(let `protocol`): - return try `protocol`.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - case .anonymous(let anonymousContext): - return try anonymousContext.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - case .extension(let extensionContext): - return try extensionContext.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - case .module(let moduleContext): - return try moduleContext.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - case .opaqueType(let opaqueType): - return try opaqueType.descriptor.parent(in: context)?.map { try ContextWrapper.forContextDescriptorWrapper($0, in: context) } - } - } -} diff --git a/Sources/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift b/Sources/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift deleted file mode 100644 index f36fa0d89..000000000 --- a/Sources/MachOSwiftSection/Models/Metadata/MetadataWrapper.swift +++ /dev/null @@ -1,426 +0,0 @@ -import Foundation -import MachOBase -import SwiftStdlibToolbox - -@CaseCheckable(.public) -@AssociatedValue(.public) -public enum MetadataWrapper: Resolvable { - case `class`(ClassMetadataObjCInterop) - case `struct`(StructMetadata) - case `enum`(EnumMetadata) - case optional(EnumMetadata) - case foreignClass(ForeignClassMetadata) - case foreignReferenceType(ForeignReferenceTypeMetadata) - case opaque(OpaqueMetadata) - case tuple(TupleTypeMetadata) - case function(FunctionTypeMetadata) - case existential(ExistentialTypeMetadata) - case metatype(MetatypeMetadata) - case objcClassWrapper(ObjCClassWrapperMetadata) - case existentialMetatype(ExistentialMetatypeMetadata) - case extendedExistential(ExtendedExistentialTypeMetadata) - case fixedArray(FixedArrayTypeMetadata) - case borrow(BorrowTypeMetadata) - case heapLocalVariable(HeapLocalVariableMetadata) - case heapGenericLocalVariable(GenericBoxHeapMetadata) - case errorObject(EnumMetadata) - case task(DispatchClassMetadata) - case job(DispatchClassMetadata) - - public var anyMetadata: any MetadataProtocol { - switch self { - case .class(let classMetadataObjCInterop): - return classMetadataObjCInterop - case .struct(let structMetadata): - return structMetadata - case .enum(let enumMetadata): - return enumMetadata - case .optional(let enumMetadata): - return enumMetadata - case .foreignClass(let foreignClassMetadata): - return foreignClassMetadata - case .foreignReferenceType(let foreignReferenceTypeMetadata): - return foreignReferenceTypeMetadata - case .opaque(let opaqueMetadata): - return opaqueMetadata - case .tuple(let tupleTypeMetadata): - return tupleTypeMetadata - case .function(let functionTypeMetadata): - return functionTypeMetadata - case .existential(let existentialTypeMetadata): - return existentialTypeMetadata - case .metatype(let metatypeMetadata): - return metatypeMetadata - case .objcClassWrapper(let objCClassWrapperMetadata): - return objCClassWrapperMetadata - case .existentialMetatype(let existentialMetatypeMetadata): - return existentialMetatypeMetadata - case .extendedExistential(let extendedExistentialTypeMetadata): - return extendedExistentialTypeMetadata - case .fixedArray(let fixedArrayTypeMetadata): - return fixedArrayTypeMetadata - case .borrow(let borrowTypeMetadata): - return borrowTypeMetadata - case .heapLocalVariable(let heapLocalVariableMetadata): - return heapLocalVariableMetadata - case .heapGenericLocalVariable(let genericBoxHeapMetadata): - return genericBoxHeapMetadata - case .errorObject(let enumMetadata): - return enumMetadata - case .task(let dispatchClassMetadata): - return dispatchClassMetadata - case .job(let dispatchClassMetadata): - return dispatchClassMetadata - } - } - - public var metadata: Metadata { - get throws { - switch self { - case .class(let classMetadataObjCInterop): - return try classMetadataObjCInterop.asMetadata() - case .struct(let structMetadata): - return try structMetadata.asMetadata() - case .enum(let enumMetadata): - return try enumMetadata.asMetadata() - case .optional(let enumMetadata): - return try enumMetadata.asMetadata() - case .foreignClass(let foreignClassMetadata): - return try foreignClassMetadata.asMetadata() - case .foreignReferenceType(let foreignReferenceTypeMetadata): - return try foreignReferenceTypeMetadata.asMetadata() - case .opaque(let opaqueMetadata): - return try opaqueMetadata.asMetadata() - case .tuple(let tupleTypeMetadata): - return try tupleTypeMetadata.asMetadata() - case .function(let functionTypeMetadata): - return try functionTypeMetadata.asMetadata() - case .existential(let existentialTypeMetadata): - return try existentialTypeMetadata.asMetadata() - case .metatype(let metatypeMetadata): - return try metatypeMetadata.asMetadata() - case .objcClassWrapper(let objCClassWrapperMetadata): - return try objCClassWrapperMetadata.asMetadata() - case .existentialMetatype(let existentialMetatypeMetadata): - return try existentialMetatypeMetadata.asMetadata() - case .extendedExistential(let extendedExistentialTypeMetadata): - return try extendedExistentialTypeMetadata.asMetadata() - case .fixedArray(let fixedArrayTypeMetadata): - return try fixedArrayTypeMetadata.asMetadata() - case .borrow(let borrowTypeMetadata): - return try borrowTypeMetadata.asMetadata() - case .heapLocalVariable(let heapLocalVariableMetadata): - return try heapLocalVariableMetadata.asMetadata() - case .heapGenericLocalVariable(let genericBoxHeapMetadata): - return try genericBoxHeapMetadata.asMetadata() - case .errorObject(let enumMetadata): - return try enumMetadata.asMetadata() - case .task(let dispatchClassMetadata): - return try dispatchClassMetadata.asMetadata() - case .job(let dispatchClassMetadata): - return try dispatchClassMetadata.asMetadata() - } - } - } - - // On arm64e the value-witness-table slot in a live `TargetFullMetadata` - // header is PAC-signed (`__ptrauth_swift_value_witness_table`). Every leg - // below is safe as long as it dereferences through `Pointer.resolve` — - // `PointerProtocol.resolve()` / `InProcessContext` strip pointer tags on - // every in-process read (evolution proposal 0004). Do not replace these - // with raw pointer arithmetic. - public func valueWitnessTable(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ValueWitnessTable { - switch self { - case .class(let classMetadataObjCInterop): - return try classMetadataObjCInterop.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .struct(let structMetadata): - return try structMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .enum(let enumMetadata): - return try enumMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .optional(let enumMetadata): - return try enumMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .foreignClass(let foreignClassMetadata): - return try foreignClassMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .foreignReferenceType(let foreignReferenceTypeMetadata): - return try foreignReferenceTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .opaque(let opaqueMetadata): - return try opaqueMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .tuple(let tupleTypeMetadata): - return try tupleTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .function(let functionTypeMetadata): - return try functionTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .existential(let existentialTypeMetadata): - return try existentialTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .metatype(let metatypeMetadata): - return try metatypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .objcClassWrapper(let objCClassWrapperMetadata): - return try objCClassWrapperMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .existentialMetatype(let existentialMetatypeMetadata): - return try existentialMetatypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .extendedExistential(let extendedExistentialTypeMetadata): - return try extendedExistentialTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .fixedArray(let fixedArrayTypeMetadata): - return try fixedArrayTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .borrow(let borrowTypeMetadata): - return try borrowTypeMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .heapLocalVariable(let heapLocalVariableMetadata): - return try heapLocalVariableMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .heapGenericLocalVariable(let genericBoxHeapMetadata): - return try genericBoxHeapMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .errorObject(let enumMetadata): - return try enumMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .task(let dispatchClassMetadata): - return try dispatchClassMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - case .job(let dispatchClassMetadata): - return try dispatchClassMetadata.asFullMetadata(in: machO).valueWitnesses.resolve(in: machO) - } - } - - public func valueWitnessTable() throws -> ValueWitnessTable { - switch self { - case .class(let classMetadataObjCInterop): - return try classMetadataObjCInterop.asFullMetadata().valueWitnesses.resolve() - case .struct(let structMetadata): - return try structMetadata.asFullMetadata().valueWitnesses.resolve() - case .enum(let enumMetadata): - return try enumMetadata.asFullMetadata().valueWitnesses.resolve() - case .optional(let enumMetadata): - return try enumMetadata.asFullMetadata().valueWitnesses.resolve() - case .foreignClass(let foreignClassMetadata): - return try foreignClassMetadata.asFullMetadata().valueWitnesses.resolve() - case .foreignReferenceType(let foreignReferenceTypeMetadata): - return try foreignReferenceTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .opaque(let opaqueMetadata): - return try opaqueMetadata.asFullMetadata().valueWitnesses.resolve() - case .tuple(let tupleTypeMetadata): - return try tupleTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .function(let functionTypeMetadata): - return try functionTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .existential(let existentialTypeMetadata): - return try existentialTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .metatype(let metatypeMetadata): - return try metatypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .objcClassWrapper(let objCClassWrapperMetadata): - return try objCClassWrapperMetadata.asFullMetadata().valueWitnesses.resolve() - case .existentialMetatype(let existentialMetatypeMetadata): - return try existentialMetatypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .extendedExistential(let extendedExistentialTypeMetadata): - return try extendedExistentialTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .fixedArray(let fixedArrayTypeMetadata): - return try fixedArrayTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .borrow(let borrowTypeMetadata): - return try borrowTypeMetadata.asFullMetadata().valueWitnesses.resolve() - case .heapLocalVariable(let heapLocalVariableMetadata): - return try heapLocalVariableMetadata.asFullMetadata().valueWitnesses.resolve() - case .heapGenericLocalVariable(let genericBoxHeapMetadata): - return try genericBoxHeapMetadata.asFullMetadata().valueWitnesses.resolve() - case .errorObject(let enumMetadata): - return try enumMetadata.asFullMetadata().valueWitnesses.resolve() - case .task(let dispatchClassMetadata): - return try dispatchClassMetadata.asFullMetadata().valueWitnesses.resolve() - case .job(let dispatchClassMetadata): - return try dispatchClassMetadata.asFullMetadata().valueWitnesses.resolve() - } - } - - public static func resolve(from offset: Int, in machO: some MachORepresentableWithCache & Readable) throws -> Self { - let metadata = try machO.readWrapperElement(offset: offset) as Metadata - switch metadata.kind { - case .class: - return try .class(machO.readWrapperElement(offset: offset)) - case .struct: - return try .struct(machO.readWrapperElement(offset: offset)) - case .enum: - return try .enum(machO.readWrapperElement(offset: offset)) - case .optional: - return try .optional(machO.readWrapperElement(offset: offset)) - case .foreignClass: - return try .foreignClass(machO.readWrapperElement(offset: offset)) - case .foreignReferenceType: - return try .foreignReferenceType(machO.readWrapperElement(offset: offset)) - case .opaque: - return try .opaque(machO.readWrapperElement(offset: offset)) - case .tuple: - return try .tuple(machO.readWrapperElement(offset: offset)) - case .function: - return try .function(machO.readWrapperElement(offset: offset)) - case .existential: - return try .existential(machO.readWrapperElement(offset: offset)) - case .metatype: - return try .metatype(machO.readWrapperElement(offset: offset)) - case .objcClassWrapper: - return try .objcClassWrapper(machO.readWrapperElement(offset: offset)) - case .existentialMetatype: - return try .existentialMetatype(machO.readWrapperElement(offset: offset)) - case .extendedExistential: - return try .extendedExistential(machO.readWrapperElement(offset: offset)) - case .fixedArray: - return try .fixedArray(machO.readWrapperElement(offset: offset)) - case .borrow: - return try .borrow(machO.readWrapperElement(offset: offset)) - case .heapLocalVariable: - return try .heapLocalVariable(machO.readWrapperElement(offset: offset)) - case .heapGenericLocalVariable: - return try .heapGenericLocalVariable(machO.readWrapperElement(offset: offset)) - case .errorObject: - return try .errorObject(machO.readWrapperElement(offset: offset)) - case .task: - return try .task(machO.readWrapperElement(offset: offset)) - case .job: - return try .job(machO.readWrapperElement(offset: offset)) - case .lastEnumerated: - throw MachOSwiftSectionError.unknownMetadataKind(rawValue: UInt(metadata.kind.rawValue)) - } - } - - public static func resolve(from ptr: UnsafeRawPointer) throws -> Self { - let metadata = try Metadata.resolve(from: ptr) - switch metadata.kind { - case .class: - return try .class(.resolve(from: ptr)) - case .struct: - return try .struct(.resolve(from: ptr)) - case .enum: - return try .enum(.resolve(from: ptr)) - case .optional: - return try .optional(.resolve(from: ptr)) - case .foreignClass: - return try .foreignClass(.resolve(from: ptr)) - case .foreignReferenceType: - return try .foreignReferenceType(.resolve(from: ptr)) - case .opaque: - return try .opaque(.resolve(from: ptr)) - case .tuple: - return try .tuple(.resolve(from: ptr)) - case .function: - return try .function(.resolve(from: ptr)) - case .existential: - return try .existential(.resolve(from: ptr)) - case .metatype: - return try .metatype(.resolve(from: ptr)) - case .objcClassWrapper: - return try .objcClassWrapper(.resolve(from: ptr)) - case .existentialMetatype: - return try .existentialMetatype(.resolve(from: ptr)) - case .extendedExistential: - return try .extendedExistential(.resolve(from: ptr)) - case .fixedArray: - return try .fixedArray(.resolve(from: ptr)) - case .borrow: - return try .borrow(.resolve(from: ptr)) - case .heapLocalVariable: - return try .heapLocalVariable(.resolve(from: ptr)) - case .heapGenericLocalVariable: - return try .heapGenericLocalVariable(.resolve(from: ptr)) - case .errorObject: - return try .errorObject(.resolve(from: ptr)) - case .task: - return try .task(.resolve(from: ptr)) - case .job: - return try .job(.resolve(from: ptr)) - case .lastEnumerated: - throw MachOSwiftSectionError.unknownMetadataKind(rawValue: UInt(metadata.kind.rawValue)) - } - } -} - -// MARK: - ReadingContext Support - -extension MetadataWrapper { - public func valueWitnessTable(in context: some ReadingContext) throws -> ValueWitnessTable { - switch self { - case .class(let classMetadataObjCInterop): - return try classMetadataObjCInterop.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .struct(let structMetadata): - return try structMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .enum(let enumMetadata): - return try enumMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .optional(let enumMetadata): - return try enumMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .foreignClass(let foreignClassMetadata): - return try foreignClassMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .foreignReferenceType(let foreignReferenceTypeMetadata): - return try foreignReferenceTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .opaque(let opaqueMetadata): - return try opaqueMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .tuple(let tupleTypeMetadata): - return try tupleTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .function(let functionTypeMetadata): - return try functionTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .existential(let existentialTypeMetadata): - return try existentialTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .metatype(let metatypeMetadata): - return try metatypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .objcClassWrapper(let objCClassWrapperMetadata): - return try objCClassWrapperMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .existentialMetatype(let existentialMetatypeMetadata): - return try existentialMetatypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .extendedExistential(let extendedExistentialTypeMetadata): - return try extendedExistentialTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .fixedArray(let fixedArrayTypeMetadata): - return try fixedArrayTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .borrow(let borrowTypeMetadata): - return try borrowTypeMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .heapLocalVariable(let heapLocalVariableMetadata): - return try heapLocalVariableMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .heapGenericLocalVariable(let genericBoxHeapMetadata): - return try genericBoxHeapMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .errorObject(let enumMetadata): - return try enumMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .task(let dispatchClassMetadata): - return try dispatchClassMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - case .job(let dispatchClassMetadata): - return try dispatchClassMetadata.asFullMetadata(in: context).valueWitnesses.resolve(in: context) - } - } - - public static func resolve(at address: Context.Address, in context: Context) throws -> Self { - let metadata = try context.readWrapperElement(at: address) as Metadata - switch metadata.kind { - case .class: - return try .class(context.readWrapperElement(at: address)) - case .struct: - return try .struct(context.readWrapperElement(at: address)) - case .enum: - return try .enum(context.readWrapperElement(at: address)) - case .optional: - return try .optional(context.readWrapperElement(at: address)) - case .foreignClass: - return try .foreignClass(context.readWrapperElement(at: address)) - case .foreignReferenceType: - return try .foreignReferenceType(context.readWrapperElement(at: address)) - case .opaque: - return try .opaque(context.readWrapperElement(at: address)) - case .tuple: - return try .tuple(context.readWrapperElement(at: address)) - case .function: - return try .function(context.readWrapperElement(at: address)) - case .existential: - return try .existential(context.readWrapperElement(at: address)) - case .metatype: - return try .metatype(context.readWrapperElement(at: address)) - case .objcClassWrapper: - return try .objcClassWrapper(context.readWrapperElement(at: address)) - case .existentialMetatype: - return try .existentialMetatype(context.readWrapperElement(at: address)) - case .extendedExistential: - return try .extendedExistential(context.readWrapperElement(at: address)) - case .fixedArray: - return try .fixedArray(context.readWrapperElement(at: address)) - case .borrow: - return try .borrow(context.readWrapperElement(at: address)) - case .heapLocalVariable: - return try .heapLocalVariable(context.readWrapperElement(at: address)) - case .heapGenericLocalVariable: - return try .heapGenericLocalVariable(context.readWrapperElement(at: address)) - case .errorObject: - return try .errorObject(context.readWrapperElement(at: address)) - case .task: - return try .task(context.readWrapperElement(at: address)) - case .job: - return try .job(context.readWrapperElement(at: address)) - case .lastEnumerated: - throw MachOSwiftSectionError.unknownMetadataKind(rawValue: UInt(metadata.kind.rawValue)) - } - } -} diff --git a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift b/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift deleted file mode 100644 index bba237e63..000000000 --- a/Sources/MachOSwiftSection/Models/OpaqueType/OpaqueType.swift +++ /dev/null @@ -1,113 +0,0 @@ -import Foundation -import MachOKit -import MachOBase - -public struct OpaqueType: TopLevelType, ContextProtocol { - public let descriptor: OpaqueTypeDescriptor - - public let genericContext: GenericContext? - - public let underlyingTypeArgumentMangledNames: [MangledName] - - public let invertedProtocols: InvertibleProtocolSet? - - public init(descriptor: OpaqueTypeDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache) throws { - self.descriptor = descriptor - var currentOffset = descriptor.offset + descriptor.layoutSize - - let genericContext = try descriptor.genericContext(in: machO) - - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - - if descriptor.numUnderlyingTypeArguments > 0 { - let underlyingTypeArgumentMangledNamePointers: [RelativeDirectPointer] = try machO.readElements(offset: currentOffset, numberOfElements: descriptor.numUnderlyingTypeArguments) - var underlyingTypeArgumentMangledNames: [MangledName] = [] - for underlyingTypeArgumentMangledNamePointer in underlyingTypeArgumentMangledNamePointers { - try underlyingTypeArgumentMangledNames.append(underlyingTypeArgumentMangledNamePointer.resolve(from: currentOffset, in: machO)) - currentOffset += MemoryLayout>.size - } - self.underlyingTypeArgumentMangledNames = underlyingTypeArgumentMangledNames - } else { - self.underlyingTypeArgumentMangledNames = [] - } - - if descriptor.flags.contains(.hasInvertibleProtocols) { - self.invertedProtocols = try machO.readElement(offset: currentOffset) as InvertibleProtocolSet - currentOffset.offset(of: InvertibleProtocolSet.self) - } else { - self.invertedProtocols = nil - } - } - - public init(descriptor: OpaqueTypeDescriptor) throws { - self.descriptor = descriptor - - var currentOffset = descriptor.layoutSize - - let pointer = try descriptor.asPointer - - let genericContext = try descriptor.genericContext() - - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - - if descriptor.numUnderlyingTypeArguments > 0 { - let underlyingTypeArgumentMangledNamePointers: [RelativeDirectPointer] = try pointer.readElements(offset: currentOffset, numberOfElements: descriptor.numUnderlyingTypeArguments) - var underlyingTypeArgumentMangledNames: [MangledName] = [] - for underlyingTypeArgumentMangledNamePointer in underlyingTypeArgumentMangledNamePointers { - try underlyingTypeArgumentMangledNames.append(underlyingTypeArgumentMangledNamePointer.resolve(from: pointer.advanced(by: currentOffset))) - currentOffset += MemoryLayout>.size - } - self.underlyingTypeArgumentMangledNames = underlyingTypeArgumentMangledNames - } else { - self.underlyingTypeArgumentMangledNames = [] - } - - if descriptor.flags.contains(.hasInvertibleProtocols) { - self.invertedProtocols = try pointer.readElement(offset: currentOffset) as InvertibleProtocolSet - currentOffset.offset(of: InvertibleProtocolSet.self) - } else { - self.invertedProtocols = nil - } - } -} - -// MARK: - ReadingContext Support - -extension OpaqueType { - public init(descriptor: OpaqueTypeDescriptor, in context: some ReadingContext) throws { - self.descriptor = descriptor - var currentOffset = descriptor.offset + descriptor.layoutSize - - let genericContext = try descriptor.genericContext(in: context) - - if let genericContext { - currentOffset += genericContext.size - } - self.genericContext = genericContext - - if descriptor.numUnderlyingTypeArguments > 0 { - let underlyingTypeArgumentMangledNamePointers: [RelativeDirectPointer] = try context.readElements(at: try context.addressFromOffset(currentOffset), numberOfElements: descriptor.numUnderlyingTypeArguments) - var underlyingTypeArgumentMangledNames: [MangledName] = [] - for underlyingTypeArgumentMangledNamePointer in underlyingTypeArgumentMangledNamePointers { - try underlyingTypeArgumentMangledNames.append(underlyingTypeArgumentMangledNamePointer.resolve(at: try context.addressFromOffset(currentOffset), in: context)) - currentOffset += MemoryLayout>.size - } - self.underlyingTypeArgumentMangledNames = underlyingTypeArgumentMangledNames - } else { - self.underlyingTypeArgumentMangledNames = [] - } - - if descriptor.flags.contains(.hasInvertibleProtocols) { - self.invertedProtocols = try context.readElement(at: try context.addressFromOffset(currentOffset)) as InvertibleProtocolSet - currentOffset.offset(of: InvertibleProtocolSet.self) - } else { - self.invertedProtocols = nil - } - } -} diff --git a/Sources/SwiftDeclarationRendering/AccessorThunkResolution.swift b/Sources/Output/SwiftDeclarationRendering/AccessorThunkResolution.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/AccessorThunkResolution.swift rename to Sources/Output/SwiftDeclarationRendering/AccessorThunkResolution.swift diff --git a/Sources/SwiftDeclarationRendering/BoundDumpedTypeNameRenderer.swift b/Sources/Output/SwiftDeclarationRendering/BoundDumpedTypeNameRenderer.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/BoundDumpedTypeNameRenderer.swift rename to Sources/Output/SwiftDeclarationRendering/BoundDumpedTypeNameRenderer.swift diff --git a/Sources/SwiftDeclarationRendering/ConditionalWitnessComment.swift b/Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/ConditionalWitnessComment.swift rename to Sources/Output/SwiftDeclarationRendering/ConditionalWitnessComment.swift diff --git a/Sources/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift similarity index 85% rename from Sources/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift rename to Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift index 69a702d9c..4037fe35c 100644 --- a/Sources/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift +++ b/Sources/Output/SwiftDeclarationRendering/DeclarationRenderConfiguration.swift @@ -90,6 +90,12 @@ public struct DeclarationRenderConfiguration: Sendable { /// transitive dependency closure over the system dyld shared cache. public var staticLayoutDependencyResolution: StaticLayoutDependencyResolution = .default + /// Set by a printer that marks optional content + /// (`SwiftDeclarationPrintConfiguration.marksOptionalContent`): every + /// layout comment is worked out and printed, each conditioned on its + /// option with a `VisibilityRegion`, whatever the `print…` flags say. + public var marksOptionalContent: Bool = false + public static func demangleOptions(_ demangleOptions: DemangleOptions) -> Self { .init(demangleResolver: .options(demangleOptions)) } @@ -100,6 +106,47 @@ extension DeclarationRenderConfiguration { .init(level: indentation) } + /// Whether the flag for `option` is on. Options this configuration does + /// not carry read as off. + package func isEnabled(_ option: SwiftVisibilityOption) -> Bool { + switch option { + case .printFieldOffset: printFieldOffset + case .printExpandedFieldOffsets: printExpandedFieldOffsets + case .printMemberAddress: printMemberAddress + case .printVTableOffset: printVTableOffset + case .printTypeLayout: printTypeLayout + case .printEnumLayout: printEnumLayout + case .printStrippedSymbolicItem, .printPWTOffset, .infersObjCOverridesFromSelectorNames, .opaqueTypeResolution: false + } + } + + /// Whether the content `option` controls is worked out at all: when its + /// flag is on, and always when marking. + package func producesContent(for option: SwiftVisibilityOption) -> Bool { + marksOptionalContent || isEnabled(option) + } + + /// `content` when `option`'s flag is on; when marking, always, in a + /// region conditioned on `option`. + @SemanticStringBuilder + package func optionalContent(_ option: SwiftVisibilityOption, @SemanticStringBuilder content: () -> SemanticString) -> SemanticString { + if marksOptionalContent { + VisibilityRegion(.enabled(option.rawValue), content: content()) + } else if isEnabled(option) { + content() + } + } + + /// The async form of `optionalContent(_:content:)`. + @SemanticStringBuilder + package func optionalContent(_ option: SwiftVisibilityOption, @SemanticStringBuilder content: () async throws -> SemanticString) async rethrows -> SemanticString { + if marksOptionalContent { + try await VisibilityRegion(.enabled(option.rawValue), content: content) + } else if isEnabled(option) { + try await content() + } + } + /// Builds a member address comment line for the given symbol offset. /// /// The returned ``SemanticString`` includes indentation and a trailing line break. diff --git a/Sources/SwiftDeclarationRendering/DemangleResolver.swift b/Sources/Output/SwiftDeclarationRendering/DemangleResolver.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/DemangleResolver.swift rename to Sources/Output/SwiftDeclarationRendering/DemangleResolver.swift diff --git a/Sources/SwiftDeclarationRendering/DependentMemberProjection.swift b/Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/DependentMemberProjection.swift rename to Sources/Output/SwiftDeclarationRendering/DependentMemberProjection.swift diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/ContextDescriptorWrapper+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/ContextDescriptorWrapper+Dump.swift new file mode 100644 index 000000000..44980bdcd --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/ContextDescriptorWrapper+Dump.swift @@ -0,0 +1,15 @@ +import MachOKit +import MachOSwiftSection +import Semantic +import Demangling +@_spi(Internals) import SwiftInspection + +extension ContextDescriptorWrapper { + package func dumpName(using options: DemangleOptions, in context: some ReadingContext) throws -> SemanticString { + try dumpNameNode(in: context).printSemantic(using: options) + } + + package func dumpNameNode(in context: some ReadingContext) throws -> Node { + try SymbolicDemangler.demangleContext(for: self, in: context) + } +} diff --git a/Sources/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/CustomObjCClassName+Keyword.swift diff --git a/Sources/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift similarity index 72% rename from Sources/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift index 668424fdc..ecb1a76f8 100644 --- a/Sources/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericContext+Dump.swift @@ -33,27 +33,27 @@ package func genericValueName(depth: Int, index: Int) throws -> String { extension TargetGenericContext { @SemanticStringBuilder - package func dumpGenericSignature(resolver: DemangleResolver, in machO: some MachOSwiftSectionRepresentableWithCache, isDumpCurrentLevelParams: Bool = true, isDumpCurrentLevelRequirements: Bool = true, @SemanticStringBuilder conformancesBuilder: () async throws -> SemanticString = { "" }) async throws -> SemanticString { + package func dumpGenericSignature(resolver: DemangleResolver, in context: some ReadingContext, isDumpCurrentLevelParams: Bool = true, isDumpCurrentLevelRequirements: Bool = true, @SemanticStringBuilder conformancesBuilder: () async throws -> SemanticString = { "" }) async throws -> SemanticString { if (isDumpCurrentLevelParams ? currentParameters : parameters).count > 0 { Standard("<") - try await dumpGenericParameters(in: machO, isDumpCurrentLevel: isDumpCurrentLevelParams) + try await dumpGenericParameters(in: context, isDumpCurrentLevel: isDumpCurrentLevelParams) Standard(">") } try await conformancesBuilder() - if (isDumpCurrentLevelRequirements ? uniqueCurrentRequirements(in: machO) : requirements).count > 0 { + if (isDumpCurrentLevelRequirements ? uniqueCurrentRequirements(in: context) : requirements).count > 0 { Space() Keyword(.where) Space() - try await dumpGenericRequirements(resolver: resolver, in: machO, isDumpCurrentLevel: isDumpCurrentLevelRequirements) + try await dumpGenericRequirements(resolver: resolver, in: context, isDumpCurrentLevel: isDumpCurrentLevelRequirements) } } } extension TargetGenericContext { @SemanticStringBuilder - package func dumpGenericParameters(in machO: some MachOSwiftSectionRepresentableWithCache, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { + package func dumpGenericParameters(in context: some ReadingContext, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { if isDumpCurrentLevel { var currentValueIndex = 0 for (offset, parameter) in currentParameters.offsetEnumerated() { @@ -181,24 +181,24 @@ extension TargetGenericContext { } @SemanticStringBuilder - package func dumpGenericRequirements(resolver: DemangleResolver, in machO: some MachOSwiftSectionRepresentableWithCache, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { + package func dumpGenericRequirements(resolver: DemangleResolver, in context: some ReadingContext, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { switch resolver { case .options(let demangleOptions): - try await dumpGenericRequirements(using: demangleOptions, in: machO, isDumpCurrentLevel: isDumpCurrentLevel) + try await dumpGenericRequirements(using: demangleOptions, in: context, isDumpCurrentLevel: isDumpCurrentLevel) case .builder(let builder): - try await dumpGenericRequirements(in: machO, isDumpCurrentLevel: isDumpCurrentLevel, builder: builder) + try await dumpGenericRequirements(in: context, isDumpCurrentLevel: isDumpCurrentLevel, builder: builder) } } @SemanticStringBuilder - package func dumpGenericRequirements(using options: DemangleOptions, in machO: some MachOSwiftSectionRepresentableWithCache, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { - try await dumpGenericRequirements(in: machO, isDumpCurrentLevel: isDumpCurrentLevel) { $0.printSemantic(using: options) } + package func dumpGenericRequirements(using options: DemangleOptions, in context: some ReadingContext, isDumpCurrentLevel: Bool = true) async throws -> SemanticString { + try await dumpGenericRequirements(in: context, isDumpCurrentLevel: isDumpCurrentLevel) { $0.printSemantic(using: options) } } @SemanticStringBuilder - package func dumpGenericRequirements(in machO: some MachOSwiftSectionRepresentableWithCache, isDumpCurrentLevel: Bool = true, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - for (offset, requirement) in (isDumpCurrentLevel ? uniqueCurrentRequirements(in: machO) : requirements).offsetEnumerated() { - try await requirement.dump(in: machO, builder: builder) + package func dumpGenericRequirements(in context: some ReadingContext, isDumpCurrentLevel: Bool = true, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + for (offset, requirement) in (isDumpCurrentLevel ? uniqueCurrentRequirements(in: context) : requirements).offsetEnumerated() { + try await requirement.dump(in: context, builder: builder) if !offset.isEnd { Standard(",") Space() @@ -218,23 +218,23 @@ extension Node { extension GenericRequirementDescriptor { @SemanticStringBuilder - package func dump(resolver: DemangleResolver, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { + package func dump(resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { switch resolver { case .options(let demangleOptions): - try await dump(using: demangleOptions, in: machO) + try await dump(using: demangleOptions, in: context) case .builder(let builder): - try await dump(in: machO, builder: builder) + try await dump(in: context, builder: builder) } } @SemanticStringBuilder - package func dump(using options: DemangleOptions, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { - try await dump(in: machO) { $0.printSemantic(using: options) } + package func dump(using options: DemangleOptions, in context: some ReadingContext) async throws -> SemanticString { + try await dump(in: context) { $0.printSemantic(using: options) } } @SemanticStringBuilder - package func dump(in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - try await dumpParameterName(in: machO, builder: builder) + package func dump(in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + try await dumpParameterName(in: context, builder: builder) if layout.flags.kind == .sameType { Space() @@ -245,26 +245,26 @@ extension GenericRequirementDescriptor { Space() } - try await dumpContent(in: machO, builder: builder) + try await dumpContent(in: context, builder: builder) } @SemanticStringBuilder - package func dumpParameterName(using options: DemangleOptions, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { - try await dumpParameterName(in: machO) { $0.printSemantic(using: options) } + package func dumpParameterName(using options: DemangleOptions, in context: some ReadingContext) async throws -> SemanticString { + try await dumpParameterName(in: context) { $0.printSemantic(using: options) } } @SemanticStringBuilder - package func dumpParameterName(resolver: DemangleResolver, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { + package func dumpParameterName(resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { switch resolver { case .options(let demangleOptions): - try await dumpParameterName(using: demangleOptions, in: machO) + try await dumpParameterName(using: demangleOptions, in: context) case .builder(let builder): - try await dumpParameterName(in: machO, builder: builder) + try await dumpParameterName(in: context, builder: builder) } } @SemanticStringBuilder - package func dumpParameterName(in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + package func dumpParameterName(in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { if layout.flags.contains(.isPackRequirement) { Keyword(.repeat) Space() @@ -272,41 +272,41 @@ extension GenericRequirementDescriptor { Space() } - try await builder(dumpParameterName(in: machO)) + try await builder(dumpParameterName(in: context)) } - package func dumpParameterName(in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> Node { - try SymbolicDemangler.demangleType(for: paramMangledName(in: machO), in: machO) + package func dumpParameterName(in context: some ReadingContext) async throws -> Node { + try SymbolicDemangler.demangleType(for: paramMangledName(in: context), in: context) } @SemanticStringBuilder - package func dumpContent(resolver: DemangleResolver, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { + package func dumpContent(resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { switch resolver { case .options(let demangleOptions): - try await dumpContent(using: demangleOptions, in: machO) + try await dumpContent(using: demangleOptions, in: context) case .builder(let builder): - try await dumpContent(in: machO, builder: builder) + try await dumpContent(in: context, builder: builder) } } @SemanticStringBuilder - package func dumpContent(using options: DemangleOptions, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { - try await dumpContent(in: machO) { $0.printSemantic(using: options) } + package func dumpContent(using options: DemangleOptions, in context: some ReadingContext) async throws -> SemanticString { + try await dumpContent(in: context) { $0.printSemantic(using: options) } } @SemanticStringBuilder - package func dumpContent(in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - switch try resolvedContent(in: machO) { + package func dumpContent(in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + switch try resolvedContent(in: context) { case .type(let mangledName): - try await builder(SymbolicDemangler.demangleType(for: mangledName, in: machO)) + try await builder(SymbolicDemangler.demangleType(for: mangledName, in: context)) case .protocol(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - try await SymbolicDemangler.demangleType(for: unsolvedSymbol, in: machO).asyncMap { try await builder($0) } + try await SymbolicDemangler.demangleType(for: unsolvedSymbol, in: context).asyncMap { try await builder($0) } case .element(let element): switch element { case .objc(let objc): - let objcName = try objc.mangledName(in: machO).rawString + let objcName = try objc.mangledName(in: context).rawString let node = Node.createTransient(kind: .global, children: [ Node.createTransient(kind: .type, children: [ Node.createTransient(kind: .protocol, children: [ @@ -317,7 +317,7 @@ extension GenericRequirementDescriptor { ]) try await builder(node) case .swift(let protocolDescriptor): - try await builder(SymbolicDemangler.demangleContext(for: .protocol(protocolDescriptor), in: machO)) + try await builder(SymbolicDemangler.demangleContext(for: .protocol(protocolDescriptor), in: context)) } } case .layout(let genericRequirementLayoutKind): @@ -335,23 +335,23 @@ extension GenericRequirementDescriptor { extension GenericRequirementDescriptor { @SemanticStringBuilder - package func dumpProtocolRequirement(resolver: DemangleResolver, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { + package func dumpProtocolRequirement(resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { switch resolver { case .options(let demangleOptions): - try await dumpProtocolRequirement(using: demangleOptions, in: machO) + try await dumpProtocolRequirement(using: demangleOptions, in: context) case .builder(let builder): - try await dumpProtocolRequirement(in: machO, builder: builder) + try await dumpProtocolRequirement(in: context, builder: builder) } } @SemanticStringBuilder - package func dumpProtocolRequirement(using options: DemangleOptions, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString { - try await dumpProtocolRequirement(in: machO) { $0.printSemantic(using: options) } + package func dumpProtocolRequirement(using options: DemangleOptions, in context: some ReadingContext) async throws -> SemanticString { + try await dumpProtocolRequirement(in: context) { $0.printSemantic(using: options) } } @SemanticStringBuilder - package func dumpProtocolRequirement(in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - try await dumpProtocolParameterName(in: machO, builder: builder) + package func dumpProtocolRequirement(in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + try await dumpProtocolParameterName(in: context, builder: builder) if layout.flags.kind == .sameType { Space() @@ -362,17 +362,17 @@ extension GenericRequirementDescriptor { Space() } - try await dumpProtocolContent(in: machO, builder: builder) + try await dumpProtocolContent(in: context, builder: builder) } @SemanticStringBuilder - package func dumpProtocolParameterName(in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - try await dumpProtocolMangledName(paramMangledName(in: machO), in: machO, builder: builder) + package func dumpProtocolParameterName(in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + try await dumpProtocolMangledName(paramMangledName(in: context), in: context, builder: builder) } @SemanticStringBuilder - private func dumpProtocolMangledName(_ mangledName: MangledName, in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - let node = try SymbolicDemangler.demangleType(for: mangledName, in: machO) + private func dumpProtocolMangledName(_ mangledName: MangledName, in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + let node = try SymbolicDemangler.demangleType(for: mangledName, in: context) let params = node.filter(of: .dependentAssociatedTypeRef).compactMap { $0.first(of: .identifier)?.text } @@ -397,19 +397,19 @@ extension GenericRequirementDescriptor { } @SemanticStringBuilder - package func dumpProtocolContent(in machO: some MachOSwiftSectionRepresentableWithCache, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { - switch try resolvedContent(in: machO) { + package func dumpProtocolContent(in context: some ReadingContext, @SemanticStringBuilder builder: (Node) async throws -> SemanticString) async throws -> SemanticString { + switch try resolvedContent(in: context) { case .type(let mangledName): -// try builder(SymbolicDemangler.demangleType(for: mangledName, in: machO)) - try await dumpProtocolMangledName(mangledName, in: machO, builder: builder) +// try builder(SymbolicDemangler.demangleType(for: mangledName, in: context)) + try await dumpProtocolMangledName(mangledName, in: context, builder: builder) case .protocol(let resolvableElement): switch resolvableElement { case .symbol(let unsolvedSymbol): - try await SymbolicDemangler.demangleType(for: unsolvedSymbol, in: machO).asyncMap { try await builder($0) } + try await SymbolicDemangler.demangleType(for: unsolvedSymbol, in: context).asyncMap { try await builder($0) } case .element(let element): switch element { case .objc(let objc): - let objcName = try objc.mangledName(in: machO).rawString + let objcName = try objc.mangledName(in: context).rawString let node = Node.createTransient(kind: .global, children: [ Node.createTransient(kind: .type, children: [ Node.createTransient(kind: .protocol, children: [ @@ -420,7 +420,7 @@ extension GenericRequirementDescriptor { ]) try await builder(node) case .swift(let protocolDescriptor): - try await builder(SymbolicDemangler.demangleContext(for: .protocol(protocolDescriptor), in: machO)) + try await builder(SymbolicDemangler.demangleContext(for: .protocol(protocolDescriptor), in: context)) } } case .layout(let genericRequirementLayoutKind): diff --git a/Sources/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/GenericRequirement+Inherited.swift diff --git a/Sources/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/Keyword+Swift.swift diff --git a/Sources/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift similarity index 86% rename from Sources/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift index 887e37a37..09065e8dd 100644 --- a/Sources/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/MetadataWrapper+Dump.swift @@ -12,14 +12,14 @@ extension MetadataWrapper { configuration.indentString InlineComment("Type Layout") BreakLine() - for (_, element) in try tupleMetadata.elements().enumerated() { - let tupleElementMetadata = try element.type.resolve() - if let descriptor = try tupleElementMetadata.typeContextDescriptorWrapper()?.asContextDescriptorWrapper { + 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)).string) + try await Comment("Type: " + configuration.demangleResolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptor, in: .inProcess)).string) BreakLine() configuration.indentString - let elementLayout = try tupleElementMetadata.asFullMetadata().valueWitnesses.resolve().typeLayout + let elementLayout = try tupleElementMetadata.asFullMetadata(in: .inProcess).valueWitnesses.resolve(in: .inProcess).typeLayout if let transformer = configuration.typeLayoutTransformer { transformer(elementLayout) } else { @@ -33,7 +33,7 @@ extension MetadataWrapper { BreakLine() isTuple = true } - let typeLayout = try valueWitnessTable().typeLayout + let typeLayout = try valueWitnessTable(in: .inProcess).typeLayout configuration.indentString if let transformer = configuration.typeLayoutTransformer { transformer(typeLayout) diff --git a/Sources/SwiftDeclarationRendering/Extensions/Node+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/Node+.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/Node+.swift diff --git a/Sources/SwiftDeclarationRendering/Extensions/Node+AssociatedTypeQualifier.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+AssociatedTypeQualifier.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/Node+AssociatedTypeQualifier.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/Node+AssociatedTypeQualifier.swift diff --git a/Sources/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift similarity index 99% rename from Sources/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift index 8e73c3cc6..a5ec321bc 100644 --- a/Sources/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/Node+OpaqueType.swift @@ -339,13 +339,13 @@ extension Node { if reference.isKind(of: .opaqueTypeDescriptorSymbolicReference), let offset: Int = reference.index?.cast() { if machO is MachOImage, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { let opaqueTypeDescriptor: OpaqueTypeDescriptor = try absolutePointer.readWrapperElement() - return try OpaqueType(descriptor: opaqueTypeDescriptor) + return try OpaqueType(descriptor: opaqueTypeDescriptor, in: .inProcess) } - return try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(from: offset, in: machO), in: machO) + return try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: offset, in: machO.context), in: machO.context) } if reference.isKind(of: .opaqueReturnTypeOf), let memberNode = reference.firstChild, let descriptorSymbol = SymbolIndexStore.shared.opaqueTypeDescriptorSymbol(for: memberNode, in: machO) { - return try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(from: descriptorSymbol.offset, in: machO), in: machO) + return try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: descriptorSymbol.offset, in: machO.context), in: machO.context) } return nil } @@ -384,7 +384,7 @@ extension Node { guard let descriptorAddress = imageAddressSpace.address(forExportedSymbolOffset: location.exportedSymbolOffset), let descriptorOffset = imageAddressSpace.offset(forAddress: descriptorAddress) else { return nil } - let opaqueType = try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(from: descriptorOffset, in: location.image), in: location.image) + let opaqueType = try OpaqueType(descriptor: OpaqueTypeDescriptor.resolve(at: descriptorOffset, in: location.image.context), in: location.image.context) return (image: location.image, opaqueType: opaqueType) } @@ -415,9 +415,9 @@ extension Node { guard let underlyingTypeArgumentMangledName = opaqueType.underlyingTypeArgumentMangledNames[safe: ordinal] else { return nil } let underlyingTypeArgumentNode: Node? if machO is MachOImage { - underlyingTypeArgumentNode = try? SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName) + underlyingTypeArgumentNode = try? SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: .inProcess) } else { - underlyingTypeArgumentNode = try? SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO) + underlyingTypeArgumentNode = try? SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO.context) } // The thunk's argument buffer is the opaque // descriptor's generic arguments, so its generic diff --git a/Sources/SwiftDeclarationRendering/Extensions/OpaqueType+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift similarity index 90% rename from Sources/SwiftDeclarationRendering/Extensions/OpaqueType+.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift index fc6ad21df..d2e90e927 100644 --- a/Sources/SwiftDeclarationRendering/Extensions/OpaqueType+.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/OpaqueType+.swift @@ -13,11 +13,11 @@ extension OpaqueType { usedRequirements = .init(dependentGenericType.all(of: .dependentGenericSameTypeRequirement, .dependentGenericConformanceRequirement)) } - let currentRequirements = genericContext.uniqueCurrentRequirements(in: machO) + let currentRequirements = genericContext.uniqueCurrentRequirements(in: machO.context) var results: [GenericRequirementDescriptor] = [] for currentRequirement in currentRequirements { if currentRequirement.content.isType { - guard let node = try SymbolicDemangler.buildGenericSignature(for: currentRequirement, in: machO) else { continue } + guard let node = try SymbolicDemangler.buildGenericSignature(for: currentRequirement, in: machO.context) else { continue } if let sameTypeRequirementNode = node.first(of: .dependentGenericSameTypeRequirement) { let sameTypeRequirementCopy: Node if let associatedTypeRefNode = sameTypeRequirementNode.first(of: .dependentAssociatedTypeRef) { @@ -40,7 +40,7 @@ extension OpaqueType { results.append(currentRequirement) } } else if currentRequirement.content.isProtocol { - if let node = try SymbolicDemangler.buildGenericSignature(for: currentRequirement, in: machO), let conformanceRequirementNode = node.first(of: .dependentGenericConformanceRequirement), !usedRequirements.contains(conformanceRequirementNode) { + if let node = try SymbolicDemangler.buildGenericSignature(for: currentRequirement, in: machO.context), let conformanceRequirementNode = node.first(of: .dependentGenericConformanceRequirement), !usedRequirements.contains(conformanceRequirementNode) { results.append(currentRequirement) } } diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/ProtocolConformance+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/ProtocolConformance+.swift new file mode 100644 index 000000000..eea9b6c5b --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/ProtocolConformance+.swift @@ -0,0 +1,21 @@ +import MachOKit +import MachOSwiftSection +import Demangling +@_spi(Internals) import SwiftInspection + +extension ProtocolConformance { + package func typeNode(in context: some ReadingContext) throws -> Node? { + return try typeReference.node(in: context) + } + + package func protocolNode(in context: some ReadingContext) throws -> Node? { + switch `protocol` { + case .symbol(let symbol): + return try SymbolicDemangler.demangleType(for: symbol, in: context) + case .element(let element): + return try SymbolicDemangler.demangleContext(for: .protocol(element), in: context) + case .none: + return nil + } + } +} diff --git a/Sources/SwiftDeclarationRendering/Extensions/ResilientSuperclass+Dump.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/ResilientSuperclass+Dump.swift similarity index 58% rename from Sources/SwiftDeclarationRendering/Extensions/ResilientSuperclass+Dump.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/ResilientSuperclass+Dump.swift index 7666e9f3b..71680220d 100644 --- a/Sources/SwiftDeclarationRendering/Extensions/ResilientSuperclass+Dump.swift +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/ResilientSuperclass+Dump.swift @@ -5,37 +5,37 @@ import Demangling @_spi(Internals) import SwiftInspection extension ResilientSuperclass { - package func dumpSuperclass(resolver: DemangleResolver, for kind: TypeReferenceKind, in machO: some MachOSwiftSectionRepresentableWithCache) async throws -> SemanticString? { + package func dumpSuperclass(resolver: DemangleResolver, for kind: TypeReferenceKind, in context: some ReadingContext) async throws -> SemanticString? { switch resolver { case .options(let demangleOptions): - return try dumpSuperclass(using: demangleOptions, for: kind, in: machO) + return try dumpSuperclass(using: demangleOptions, for: kind, in: context) case .builder(let builder): - return try await dumpSuperclassNode(for: kind, in: machO).asyncMap { try await builder($0) } + return try await dumpSuperclassNode(for: kind, in: context).asyncMap { try await builder($0) } } } - package func dumpSuperclass(using options: DemangleOptions, for kind: TypeReferenceKind, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SemanticString? { - try dumpSuperclassNode(for: kind, in: machO)?.printSemantic(using: options) + package func dumpSuperclass(using options: DemangleOptions, for kind: TypeReferenceKind, in context: some ReadingContext) throws -> SemanticString? { + try dumpSuperclassNode(for: kind, in: context)?.printSemantic(using: options) } - package func dumpSuperclassNode(for kind: TypeReferenceKind, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { + package func dumpSuperclassNode(for kind: TypeReferenceKind, in context: some ReadingContext) throws -> Node? { let typeReference = TypeReference.forKind(kind, at: layout.superclass.relativeOffset) - let resolvedTypeReference = try typeReference.resolve(at: offset(of: \.superclass), in: machO) - return try resolvedTypeReference.node(in: machO) + let resolvedTypeReference = try typeReference.resolve(at: offset(of: \.superclass), in: context) + return try resolvedTypeReference.node(in: context) } - package func superclassResolvedTypeReference(for kind: TypeReferenceKind, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ResolvedTypeReference { + package func superclassResolvedTypeReference(for kind: TypeReferenceKind, in context: some ReadingContext) throws -> ResolvedTypeReference { let typeReference = TypeReference.forKind(kind, at: layout.superclass.relativeOffset) - return try typeReference.resolve(at: offset(of: \.superclass), in: machO) + return try typeReference.resolve(at: offset(of: \.superclass), in: context) } } extension Class { - package func superclassNode(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - if let superclassTypeMangledName = try descriptor.superclassTypeMangledName(in: machO) { - return try SymbolicDemangler.demangleType(for: superclassTypeMangledName, in: machO) + package func superclassNode(in context: some ReadingContext) throws -> Node? { + if let superclassTypeMangledName = try descriptor.superclassTypeMangledName(in: context) { + return try SymbolicDemangler.demangleType(for: superclassTypeMangledName, in: context) } else if let resilientSuperclassReferenceKind = descriptor.resilientSuperclassReferenceKind, let resilientSuperclass { - return try resilientSuperclass.dumpSuperclassNode(for: resilientSuperclassReferenceKind, in: machO) + return try resilientSuperclass.dumpSuperclassNode(for: resilientSuperclassReferenceKind, in: context) } else { return nil } diff --git a/Sources/Output/SwiftDeclarationRendering/Extensions/ResolvedTypeReference+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/ResolvedTypeReference+.swift new file mode 100644 index 000000000..4c5e2ab1e --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/Extensions/ResolvedTypeReference+.swift @@ -0,0 +1,40 @@ +import MachOKit +import MachOSwiftSection +@_spi(Internals) import Demangling +@_spi(Internals) import SwiftInspection + +extension ResolvedTypeReference { + package func node(in context: some ReadingContext) throws -> Node? { + switch self { + case .directTypeDescriptor(let descriptor): + return try descriptor.map { try SymbolicDemangler.demangleContext(for: $0, in: context) } + case .indirectTypeDescriptor(let descriptor): + switch descriptor { + case .symbol(let symbol): + return try SymbolicDemangler.demangleType(for: symbol, in: context) + case .element(let element): + return try SymbolicDemangler.demangleContext(for: element, in: context) + case nil: + return nil + } + case .directObjCClassName(let objcClassName): + guard let objcClassName, !objcClassName.isEmpty else { return nil } + return Node.createTransient(kind: .type, children: [ + Node.createTransient(kind: .class, children: [ + .createTransient(kind: .module, text: objcModule), + .createTransient(kind: .identifier, text: objcClassName), + ]) + ]) + case .indirectObjCClass(let objcClass): + switch objcClass { + case .symbol(let symbol): + return try SymbolicDemangler.demangleType(for: symbol, in: context) + case .element(let element): + guard let classDescriptor = try element.descriptor.resolve(in: context) else { return nil } + return try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: context) + case nil: + return nil + } + } + } +} diff --git a/Sources/SwiftDeclarationRendering/Extensions/SemanticString+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/SemanticString+.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/SemanticString+.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/SemanticString+.swift diff --git a/Sources/SwiftDeclarationRendering/Extensions/String+.swift b/Sources/Output/SwiftDeclarationRendering/Extensions/String+.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/Extensions/String+.swift rename to Sources/Output/SwiftDeclarationRendering/Extensions/String+.swift diff --git a/Sources/SwiftDeclarationRendering/FieldLayoutRenderer.swift b/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift similarity index 98% rename from Sources/SwiftDeclarationRendering/FieldLayoutRenderer.swift rename to Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift index 6be624552..b7accd704 100644 --- a/Sources/SwiftDeclarationRendering/FieldLayoutRenderer.swift +++ b/Sources/Output/SwiftDeclarationRendering/FieldLayoutRenderer.swift @@ -166,11 +166,11 @@ package struct FieldLayoutRenderer { private static func resolveAccessorMetadata(for type: TypeContextWrapper, in machO: MachO) throws -> MetadataWrapper? { switch type { case .struct(let structType): - return try structType.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO) + return try structType.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context) case .enum(let enumType): - return try enumType.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO) + return try enumType.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context) case .class(let classType): - return try classType.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO) + return try classType.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context) } } diff --git a/Sources/SwiftDeclarationRendering/FieldRecordRendering.swift b/Sources/Output/SwiftDeclarationRendering/FieldRecordRendering.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/FieldRecordRendering.swift rename to Sources/Output/SwiftDeclarationRendering/FieldRecordRendering.swift diff --git a/Sources/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift b/Sources/Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift rename to Sources/Output/SwiftDeclarationRendering/InProcessAccessorFunctionResolution.swift diff --git a/Sources/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift b/Sources/Output/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift similarity index 98% rename from Sources/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift rename to Sources/Output/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift index 13aa2cb6c..2db1a021b 100644 --- a/Sources/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift +++ b/Sources/Output/SwiftDeclarationRendering/MultiPayloadEnumDescriptorCache.swift @@ -87,9 +87,9 @@ final class MultiPayloadEnumDescriptorCache: @unchecked Sendable { // and memoized for the image's lifetime by the enclosing // `SharedCache`. do { - let mangledTypeName = try multiPayloadEnumDescriptor.mangledTypeName(in: machO) + let mangledTypeName = try multiPayloadEnumDescriptor.mangledTypeName(in: machO.context) - let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO) + let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context) multiPayloadEnumDescriptorByNode[node] = multiPayloadEnumDescriptor } catch { diff --git a/Sources/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift similarity index 98% rename from Sources/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift rename to Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift index c1eda1348..377ed69c9 100644 --- a/Sources/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift +++ b/Sources/Output/SwiftDeclarationRendering/OpaqueReferenceSpelling.swift @@ -73,10 +73,10 @@ extension Node { var contextNode: Node? if machO is MachOImage, let absolutePointer = UnsafeRawPointer(bitPattern: offset) { if let descriptor: OpaqueTypeDescriptor = try? absolutePointer.readWrapperElement() { - contextNode = try? SymbolicDemangler.demangleContext(for: .opaqueType(descriptor)) + contextNode = try? SymbolicDemangler.demangleContext(for: .opaqueType(descriptor), in: .inProcess) } - } else if let descriptor = try? OpaqueTypeDescriptor.resolve(from: offset, in: machO) { - contextNode = try? SymbolicDemangler.demangleContext(for: .opaqueType(descriptor), in: machO) + } else if let descriptor = try? OpaqueTypeDescriptor.resolve(at: offset, in: machO.context) { + contextNode = try? SymbolicDemangler.demangleContext(for: .opaqueType(descriptor), in: machO.context) if contextNode == nil, let symbol = try? Symbol.resolve(from: offset, in: machO) { contextNode = try? symbol.demangledNode } diff --git a/Sources/SwiftDeclarationRendering/ParentClassVTableCache.swift b/Sources/Output/SwiftDeclarationRendering/ParentClassVTableCache.swift similarity index 94% rename from Sources/SwiftDeclarationRendering/ParentClassVTableCache.swift rename to Sources/Output/SwiftDeclarationRendering/ParentClassVTableCache.swift index 4de87287c..3d4a1420f 100644 --- a/Sources/SwiftDeclarationRendering/ParentClassVTableCache.swift +++ b/Sources/Output/SwiftDeclarationRendering/ParentClassVTableCache.swift @@ -19,14 +19,14 @@ package struct ParentClassVTableCache { /// the parent's vtable). package mutating func slotIndex( for descriptor: MethodOverrideDescriptor, - in machO: some MachOSwiftSectionRepresentableWithCache + in context: some ReadingContext ) throws -> Int? { - guard let methodResult = try descriptor.methodDescriptor(in: machO), + guard let methodResult = try descriptor.methodDescriptor(in: context), case .element(let originalMethod) = methodResult else { return nil } - guard let classResult = try descriptor.classDescriptor(in: machO), + guard let classResult = try descriptor.classDescriptor(in: context), case .element(let parentContext) = classResult, case .type(.class(let parentClassDescriptor)) = parentContext else { return nil @@ -35,7 +35,7 @@ package struct ParentClassVTableCache { let parentOffset = parentClassDescriptor.offset if entriesByParentOffset[parentOffset] == nil { - let parentClass = try Class(descriptor: parentClassDescriptor, in: machO) + let parentClass = try Class(descriptor: parentClassDescriptor, in: context) if let header = parentClass.vTableDescriptorHeader { entriesByParentOffset[parentOffset] = Entry( baseOffset: Int(header.layout.vTableOffset), diff --git a/Sources/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift b/Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift rename to Sources/Output/SwiftDeclarationRendering/PropertyWrapperTypeCatalog.swift diff --git a/Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift similarity index 91% rename from Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift rename to Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift index 56af075bd..8c6d8491f 100644 --- a/Sources/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/RuntimeFieldLayoutBackend.swift @@ -83,7 +83,7 @@ struct RuntimeFieldLayoutBackend { /// offsets are disabled, no metadata is available, or the type is not a /// stored-field aggregate. var fieldOffsets: [Int]? { - guard configuration.printFieldOffset, let metadata else { return nil } + guard configuration.producesContent(for: .printFieldOffset), let metadata else { return nil } switch type { case .struct(let structType): guard let structMetadata = metadata.struct else { return nil } @@ -107,22 +107,27 @@ struct RuntimeFieldLayoutBackend { if let nextFieldOffset = fieldOffsets[safe: index + 1] { endOffset = nextFieldOffset } else if let metatype = resolveFieldMetatype(for: mangledTypeName, in: machO), - let typeLayout = try? StructMetadata.createInProcess(metatype).asMetadataWrapper().valueWitnessTable().typeLayout { + let typeLayout = try? StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout { endOffset = startOffset + Int(typeLayout.size) } else { endOffset = nil } - configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) - - if configuration.printExpandedFieldOffsets { - expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset, baseIndentation: configuration.indentation, ancestors: [], in: machO) + 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, baseIndentation: configuration.indentation, ancestors: [], in: machO) + } } } - if configuration.printTypeLayout, + if configuration.producesContent(for: .printTypeLayout), let resolvedMetatype = resolveFieldMetatype(for: mangledTypeName, in: machO), let resolvedMetadata = try? StructMetadata.createInProcess(resolvedMetatype) { - try await resolvedMetadata.asMetadataWrapper().dumpTypeLayout(using: configuration) + try await configuration.optionalContent(.printTypeLayout) { + try await resolvedMetadata.asMetadataWrapper(in: .inProcess).dumpTypeLayout(using: configuration) + } } } @@ -137,21 +142,28 @@ struct RuntimeFieldLayoutBackend { var isTypeLayoutPrinted = false if !mangledTypeName.isEmpty, - configuration.printTypeLayout, + configuration.producesContent(for: .printTypeLayout), let resolvedMetatype = resolveFieldMetatype(for: mangledTypeName, in: machO), let resolvedMetadata = try? StructMetadata.createInProcess(resolvedMetatype) { - try await resolvedMetadata.asMetadataWrapper().dumpTypeLayout(using: configuration) + try await configuration.optionalContent(.printTypeLayout) { + try await resolvedMetadata.asMetadataWrapper(in: .inProcess).dumpTypeLayout(using: configuration) + } isTypeLayoutPrinted = true } if let caseProjection = enumLayout?.cases[safe: index] { - if isTypeLayoutPrinted { + configuration.optionalContent(.printEnumLayout) { + // The line between the two blocks exists only when both do. + if isTypeLayoutPrinted { + configuration.optionalContent(.printTypeLayout) { + BreakLine() + } + } + configuration.indentString + InlineComment("Enum Layout") BreakLine() + configuration.enumLayoutCaseComment(caseProjection: caseProjection) } - configuration.indentString - InlineComment("Enum Layout") - BreakLine() - configuration.enumLayoutCaseComment(caseProjection: caseProjection) } } @@ -182,7 +194,7 @@ struct RuntimeFieldLayoutBackend { // // Lifted verbatim from `SwiftDump.TypedDumper`; behaviour-preserving. The // only changes: `Metadata.createInProcess` → `StructMetadata.createInProcess` - // (the static metadata type is incidental — `asMetadataWrapper()` re-dispatches + // (the static metadata type is incidental — `asMetadataWrapper(in: .inProcess)` re-dispatches // on the actual kind), and the top-hop substitution goes through this type's // `resolveFieldMetatype`. See the original for the extensive rationale on the // PAC-fault-avoiding static substitution. @@ -224,7 +236,7 @@ struct RuntimeFieldLayoutBackend { emitNestedFieldOffsetCycleWarning(for: metatype) } else if depth >= nestedFieldOffsetExpansionDepthLimit { emitNestedFieldOffsetDepthLimitWarning(for: metatype) - } else if let wrapper = try? StructMetadata.createInProcess(metatype).asMetadataWrapper() { + } else if let wrapper = try? StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess) { let nestedEnclosingMetatypes = enclosingMetatypes.union([ObjectIdentifier(metatype)]) switch wrapper { case .struct(let metadata): @@ -257,15 +269,15 @@ struct RuntimeFieldLayoutBackend { @SemanticStringBuilder private func walkNestedStructFieldOffsets(of metadata: StructMetadata, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int, enclosingMetatypes: Set) -> SemanticString { - if let descriptor = try? metadata.structDescriptor(), - let nestedFieldOffsets = try? metadata.fieldOffsets(for: descriptor), - let nestedFieldRecords = try? descriptor.fieldDescriptor().records() { + if let descriptor = try? metadata.structDescriptor(in: .inProcess), + let nestedFieldOffsets = try? metadata.fieldOffsets(for: descriptor, in: .inProcess), + let nestedFieldRecords = try? descriptor.fieldDescriptor(in: .inProcess).records(in: .inProcess) { let fieldEntries = Array(zip(nestedFieldRecords, nestedFieldOffsets)) for (fieldIndex, (nestedFieldRecord, nestedRelativeOffset)) in fieldEntries.enumerated() { - if let fieldName = try? nestedFieldRecord.fieldName() { + if let fieldName = try? nestedFieldRecord.fieldName(in: .inProcess) { let absoluteOffset = baseOffset + Int(nestedRelativeOffset) let isLastField = fieldIndex == fieldEntries.count - 1 - let nestedMangledTypeName = try? nestedFieldRecord.mangledTypeName() + let nestedMangledTypeName = try? nestedFieldRecord.mangledTypeName(in: .inProcess) let typeName = nestedTypeName(for: nestedMangledTypeName, parentMetadata: metadata) configuration.expandedFieldOffsetComment(fieldName: fieldName, typeName: typeName, offset: absoluteOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: isLastField) @@ -280,15 +292,15 @@ struct RuntimeFieldLayoutBackend { @SemanticStringBuilder private func walkNestedEnumPayloadFieldOffsets(of metadata: EnumMetadata, baseOffset: Int, baseIndentation: Int, ancestors: [Bool], depth: Int, enclosingMetatypes: Set) -> SemanticString { - if let descriptor = try? metadata.enumDescriptor(), + if let descriptor = try? metadata.enumDescriptor(in: .inProcess), descriptor.hasPayloadCases, - let records = try? descriptor.fieldDescriptor().records() { + let records = try? descriptor.fieldDescriptor(in: .inProcess).records(in: .inProcess) { let payloadRecords = Array(records.prefix(descriptor.numberOfPayloadCases)) for (payloadIndex, payloadRecord) in payloadRecords.enumerated() { - if let mangledTypeName = try? payloadRecord.mangledTypeName(), + if let mangledTypeName = try? payloadRecord.mangledTypeName(in: .inProcess), !mangledTypeName.isEmpty, let resolvedMetatype = resolveNestedMetatype(for: mangledTypeName, parentMetadata: metadata) { - let fieldName = (try? payloadRecord.fieldName()) ?? "payload" + let fieldName = (try? payloadRecord.fieldName(in: .inProcess)) ?? "payload" let typeName = nestedTypeName(for: mangledTypeName, parentMetadata: metadata) let isLastPayload = payloadIndex == payloadRecords.count - 1 configuration.expandedFieldOffsetComment(fieldName: fieldName, typeName: typeName, offset: baseOffset, baseIndentation: baseIndentation, ancestors: ancestors, isLast: isLastPayload) @@ -316,7 +328,7 @@ struct RuntimeFieldLayoutBackend { if let boundType = staticallyBoundMetatype(for: mangledTypeName, parentMetadata: parentMetadata) { return boundType } - guard let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName), + guard let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName, in: .inProcess), !nodeContainsDependentReference(node) else { return nil } return try? RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName) @@ -327,7 +339,7 @@ struct RuntimeFieldLayoutBackend { if let substitutedNode = substitutedNestedTypeNode(for: mangledTypeName, parentMetadata: parentMetadata) { return substitutedNode.printSemantic(using: .default).string } - return (try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName).printSemantic(using: .default).string) ?? "" + return (try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName, in: .inProcess).printSemantic(using: .default).string) ?? "" } // MARK: - Static generic-argument substitution (PAC-fault-avoiding) @@ -365,13 +377,13 @@ struct RuntimeFieldLayoutBackend { } private func substitutedNestedTypeNode(for mangledTypeName: MangledName, parentMetadata: some ValueMetadataProtocol) -> Node? { - guard let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName) else { return nil } + guard let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName, in: .inProcess) else { return nil } guard let layout = topLevelGenericLayout(of: parentMetadata) else { return node } return substitutingGenericParameters(in: node, parentMetadata: parentMetadata, layout: layout) } private func staticallyBoundMetatype(for mangledTypeName: MangledName, parentMetadata: some ValueMetadataProtocol) -> Any.Type? { - guard let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName) else { return nil } + guard let node = try? SymbolicDemangler.demangleTypeUncached(for: mangledTypeName, in: .inProcess) else { return nil } let typeNode = innerTypeNode(of: node) guard typeNode.kind == .dependentGenericParamType, let (depthValue, indexValue) = genericParameterDepthAndIndex(of: typeNode), @@ -534,8 +546,8 @@ struct RuntimeFieldLayoutBackend { } private func topLevelGenericLayout(of parentMetadata: some ValueMetadataProtocol) -> TopLevelGenericLayout? { - guard let descriptor = try? parentMetadata.descriptor(), - let genericContext = try? descriptor.genericContext(), + guard let descriptor = try? parentMetadata.descriptor(in: .inProcess), + let genericContext = try? descriptor.genericContext(in: .inProcess), let topLevelParameters = genericContext.allParameters.first else { return nil } return TopLevelGenericLayout( @@ -581,16 +593,16 @@ struct RuntimeFieldLayoutBackend { /// The enum's own value-witness type layout. Resolved with the `machO` /// context (matching the former `EnumDumper.typeLayout`): the enum metadata - /// came from `…resolve(in: machO)`, so its value-witness table must be read - /// back through the same reader — the no-argument `valueWitnessTable()` + /// came from `…resolve(in: machO.context)`, so its value-witness table must be read + /// back through the same reader — the in-process `valueWitnessTable(in: .inProcess)` /// misinterprets that offset and segfaults. Used by single-payload layout. private var enumTypeLayout: TypeLayout? { - try? metadata?.valueWitnessTable(in: machO).typeLayout + try? metadata?.valueWitnessTable(in: machO.context).typeLayout } var enumLayout: EnumLayoutCalculator.LayoutResult? { get async { - guard configuration.printEnumLayout, + guard configuration.producesContent(for: .printEnumLayout), let enumValue, !enumValue.descriptor.isGeneric else { return nil } return try? await computeEnumLayout(enumValue, in: machO) @@ -603,10 +615,10 @@ struct RuntimeFieldLayoutBackend { let numberOfEmptyCases = enumValue.numberOfEmptyCases var layoutResult: EnumLayoutCalculator.LayoutResult if enumValue.isMultiPayload { - let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machOImage) + let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machOImage.context) if let multiPayloadEnumDescriptor = MultiPayloadEnumDescriptorCache.shared.multiPayloadEnumDescriptor(for: node, in: machOImage), multiPayloadEnumDescriptor.usesPayloadSpareBits { - let spareBytes = try multiPayloadEnumDescriptor.payloadSpareBits(in: machOImage) - let spareBytesOffset = try multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: machOImage) + let spareBytes = try multiPayloadEnumDescriptor.payloadSpareBits(in: machOImage.context) + let spareBytesOffset = try multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: machOImage.context) layoutResult = EnumLayoutCalculator.calculateMultiPayload(payloadSize: payloadSize.cast(), spareBytes: spareBytes, spareBytesOffset: spareBytesOffset.cast(), numPayloadCases: numberOfPayloadCases.cast(), numEmptyCases: numberOfEmptyCases.cast()) } else { layoutResult = EnumLayoutCalculator.calculateTaggedMultiPayload(payloadSize: payloadSize.cast(), numPayloadCases: numberOfPayloadCases.cast(), numEmptyCases: numberOfEmptyCases.cast()) @@ -706,15 +718,17 @@ struct RuntimeFieldLayoutBackend { /// cases first, then empty cases — the same order the layout's projections /// use). private func declaredEnumCaseNames(of descriptor: EnumDescriptor, in machOImage: MachOImage) -> [String]? { - guard let records = try? descriptor.fieldDescriptor(in: machOImage).records(in: machOImage) else { return nil } - return try? records.map { try $0.fieldName(in: machOImage) } + guard let records = try? descriptor.fieldDescriptor(in: machOImage.context).records(in: machOImage.context) else { return nil } + return try? records.map { try $0.fieldName(in: machOImage.context) } } @SemanticStringBuilder func enumPrefixComments(enumLayout: EnumLayoutCalculator.LayoutResult?) async -> SemanticString { - if configuration.printEnumLayout, let enumLayout { - BreakLine() - configuration.enumLayoutComment(layoutResult: enumLayout) + if let enumLayout { + configuration.optionalContent(.printEnumLayout) { + BreakLine() + configuration.enumLayoutComment(layoutResult: enumLayout) + } } if configuration.printSpareBitAnalysis, @@ -727,18 +741,18 @@ struct RuntimeFieldLayoutBackend { private func spareBitAnalysis(for enumValue: Enum, in machOImage: MachOImage) -> SpareBitAnalyzer.Analysis? { try? { - let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machOImage) + let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machOImage.context) guard let multiPayloadEnumDescriptor = MultiPayloadEnumDescriptorCache.shared.multiPayloadEnumDescriptor(for: node, in: machOImage), multiPayloadEnumDescriptor.usesPayloadSpareBits else { return nil } - let spareBytes = try multiPayloadEnumDescriptor.payloadSpareBits(in: machOImage) - let spareBytesOffset = try multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: machOImage) + let spareBytes = try multiPayloadEnumDescriptor.payloadSpareBits(in: machOImage.context) + let spareBytesOffset = try multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: machOImage.context) return SpareBitAnalyzer.analyze(bytes: spareBytes, startOffset: spareBytesOffset.cast()) }() } private func enumPayloadSize(_ descriptor: EnumDescriptor, in machOImage: MachOImage) throws -> Int { guard descriptor.hasPayloadCases else { return .zero } - let records = try descriptor.fieldDescriptor(in: machOImage).records(in: machOImage) + let records = try descriptor.fieldDescriptor(in: machOImage.context).records(in: machOImage.context) guard !records.isEmpty else { return .zero } var payloadSize = 0 let indirectPayloadSize = MemoryLayout.size @@ -747,10 +761,10 @@ struct RuntimeFieldLayoutBackend { payloadSize = max(payloadSize, indirectPayloadSize) continue } - let mangledTypeName = try record.mangledTypeName(in: machOImage) + let mangledTypeName = try record.mangledTypeName(in: machOImage.context) guard !mangledTypeName.isEmpty else { continue } guard let metatype = try RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, genericContext: nil, genericArguments: nil, in: machOImage) else { continue } - let typeLayout = try StructMetadata.createInProcess(metatype).asMetadataWrapper().valueWitnessTable().typeLayout + let typeLayout = try StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout payloadSize = max(payloadSize, typeLayout.size.cast()) } return payloadSize @@ -758,7 +772,7 @@ struct RuntimeFieldLayoutBackend { private func enumPayloadExtraInhabitantCount(_ descriptor: EnumDescriptor, in machOImage: MachOImage) throws -> Int? { guard descriptor.hasPayloadCases else { return nil } - let records = try descriptor.fieldDescriptor(in: machOImage).records(in: machOImage) + let records = try descriptor.fieldDescriptor(in: machOImage.context).records(in: machOImage.context) guard !records.isEmpty else { return nil } for record in records { if record.flags.contains(.isIndirectCase) { @@ -769,10 +783,10 @@ struct RuntimeFieldLayoutBackend { // payload-sized with no extra tag bytes). return EnumLayoutCalculator.heapObjectExtraInhabitantCount } - let mangledTypeName = try record.mangledTypeName(in: machOImage) + let mangledTypeName = try record.mangledTypeName(in: machOImage.context) guard !mangledTypeName.isEmpty else { continue } guard let metatype = try RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, genericContext: nil, genericArguments: nil, in: machOImage) else { continue } - let typeLayout = try StructMetadata.createInProcess(metatype).asMetadataWrapper().valueWitnessTable().typeLayout + let typeLayout = try StructMetadata.createInProcess(metatype).asMetadataWrapper(in: .inProcess).valueWitnessTable(in: .inProcess).typeLayout return typeLayout.extraInhabitantCount.cast() } return nil diff --git a/Sources/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift b/Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift rename to Sources/Output/SwiftDeclarationRendering/RuntimeTypeNameDemangling.swift diff --git a/Sources/SwiftDeclarationRendering/SharedCacheEvictionGroup+SwiftDeclarationRendering.swift b/Sources/Output/SwiftDeclarationRendering/SharedCacheEvictionGroup+SwiftDeclarationRendering.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/SharedCacheEvictionGroup+SwiftDeclarationRendering.swift rename to Sources/Output/SwiftDeclarationRendering/SharedCacheEvictionGroup+SwiftDeclarationRendering.swift diff --git a/Sources/SwiftDeclarationRendering/SpecializedMetadataNodeSubstitution.swift b/Sources/Output/SwiftDeclarationRendering/SpecializedMetadataNodeSubstitution.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/SpecializedMetadataNodeSubstitution.swift rename to Sources/Output/SwiftDeclarationRendering/SpecializedMetadataNodeSubstitution.swift diff --git a/Sources/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift similarity index 82% rename from Sources/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift rename to Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift index 0098d1bd7..67e899882 100644 --- a/Sources/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutBackend.swift @@ -17,7 +17,7 @@ extension MachOFile: FieldLayoutRenderable { public static func precomputedStaticAggregateFieldLayout(for type: TypeContextWrapper, machO: MachOFile, configuration: DeclarationRenderConfiguration) -> AggregateFieldLayout? { // Only when a layout-bearing flag is on and a provider was injected; // enums (no field-offset vector) compute their layout lazily instead. - guard configuration.printFieldOffset || configuration.printTypeLayout || configuration.printExpandedFieldOffsets, + guard configuration.producesContent(for: .printFieldOffset) || configuration.producesContent(for: .printTypeLayout) || configuration.producesContent(for: .printExpandedFieldOffsets), let provider = configuration.staticFieldLayoutProvider else { return nil } @@ -82,7 +82,7 @@ struct StaticFieldLayoutBackend { /// SwiftLayout could not resolve (so a degraded field and everything after it /// emit no offset comment rather than a wrong one). var fieldOffsets: [Int]? { - guard configuration.printFieldOffset else { return nil } + guard configuration.producesContent(for: .printFieldOffset) else { return nil } return staticAggregateFieldLayout?.computedFieldOffsets } @@ -103,24 +103,31 @@ struct StaticFieldLayoutBackend { } else { endOffset = nil } - configuration.fieldOffsetComment(startOffset: startOffset, endOffset: endOffset) - - if configuration.printExpandedFieldOffsets { - expandedFieldOffsets(for: mangledTypeName, baseOffset: startOffset) + 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) + } } } else if - configuration.printFieldOffset, + configuration.producesContent(for: .printFieldOffset), case .unknown(let reason)? = staticAggregateFieldLayout?.fields[safe: index]?.resolution { // The offset could not be computed: say why, instead of silently // omitting the comment (an unresolved generic parameter reads very // differently from a disabled flag). The field's own type layout — // often still resolvable — renders below as usual. - configuration.unknownFieldOffsetComment(reasonDescription: Self.shortDescription(of: reason)) + configuration.optionalContent(.printFieldOffset) { + configuration.unknownFieldOffsetComment(reasonDescription: Self.shortDescription(of: reason)) + } } - if configuration.printTypeLayout, let fieldLayout = staticAggregateFieldLayout?.fields[safe: index]?.layout { - configuration.staticTypeLayoutComment(fieldLayout) + if configuration.producesContent(for: .printTypeLayout), let fieldLayout = staticAggregateFieldLayout?.fields[safe: index]?.layout { + configuration.optionalContent(.printTypeLayout) { + configuration.staticTypeLayoutComment(fieldLayout) + } } } @@ -185,21 +192,28 @@ struct StaticFieldLayoutBackend { var isTypeLayoutPrinted = false if !mangledTypeName.isEmpty, - configuration.printTypeLayout, + configuration.producesContent(for: .printTypeLayout), let provider = configuration.staticFieldLayoutProvider, let payloadTypeLayout = payloadTypeLayout(for: mangledTypeName, provider: provider) { - configuration.staticTypeLayoutComment(payloadTypeLayout) + configuration.optionalContent(.printTypeLayout) { + configuration.staticTypeLayoutComment(payloadTypeLayout) + } isTypeLayoutPrinted = true } if let caseProjection = enumLayout?.cases[safe: index] { - if isTypeLayoutPrinted { + configuration.optionalContent(.printEnumLayout) { + // The line between the two blocks exists only when both do. + if isTypeLayoutPrinted { + configuration.optionalContent(.printTypeLayout) { + BreakLine() + } + } + configuration.indentString + InlineComment("Enum Layout") BreakLine() + configuration.enumLayoutCaseComment(caseProjection: caseProjection) } - configuration.indentString - InlineComment("Enum Layout") - BreakLine() - configuration.enumLayoutCaseComment(caseProjection: caseProjection) } } @@ -213,7 +227,7 @@ struct StaticFieldLayoutBackend { /// before. var enumLayout: EnumLayoutCalculator.LayoutResult? { get async { - guard configuration.printEnumLayout, + guard configuration.producesContent(for: .printEnumLayout), let enumValue, let provider = configuration.staticFieldLayoutProvider else { return nil } return provider.enumCaseLayoutResult(forDescriptor: .enum(enumValue.descriptor)) @@ -232,9 +246,11 @@ struct StaticFieldLayoutBackend { @SemanticStringBuilder func enumPrefixComments(enumLayout: EnumLayoutCalculator.LayoutResult?) async -> SemanticString { - if configuration.printEnumLayout, let enumLayout { - BreakLine() - configuration.enumLayoutComment(layoutResult: enumLayout) + if let enumLayout { + configuration.optionalContent(.printEnumLayout) { + BreakLine() + configuration.enumLayoutComment(layoutResult: enumLayout) + } } if configuration.printSpareBitAnalysis, @@ -247,11 +263,11 @@ struct StaticFieldLayoutBackend { private func staticSpareBitAnalysis(for enumValue: Enum) -> SpareBitAnalyzer.Analysis? { try? { - let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machO) + let node = try SymbolicDemangler.demangleContext(for: .type(.enum(enumValue.descriptor)), in: machO.context) guard let multiPayloadEnumDescriptor = try staticMultiPayloadEnumDescriptor(for: node), multiPayloadEnumDescriptor.usesPayloadSpareBits else { return nil } - let spareBytes = try multiPayloadEnumDescriptor.payloadSpareBits(in: machO) - let spareBytesOffset = try multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: machO) + let spareBytes = try multiPayloadEnumDescriptor.payloadSpareBits(in: machO.context) + let spareBytesOffset = try multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: machO.context) return SpareBitAnalyzer.analyze(bytes: spareBytes, startOffset: spareBytesOffset.cast()) }() } @@ -261,8 +277,8 @@ struct StaticFieldLayoutBackend { /// `MachOFile` (no in-process realization needed). private func staticMultiPayloadEnumDescriptor(for node: Node) throws -> MultiPayloadEnumDescriptor? { for multiPayloadEnumDescriptor in try machO.swift.multiPayloadEnumDescriptors { - let mangledTypeName = try multiPayloadEnumDescriptor.mangledTypeName(in: machO) - let descriptorNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO) + let mangledTypeName = try multiPayloadEnumDescriptor.mangledTypeName(in: machO.context) + let descriptorNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context) if descriptorNode == node { return multiPayloadEnumDescriptor } diff --git a/Sources/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift similarity index 97% rename from Sources/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift rename to Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift index a58adbf80..7409d44e7 100644 --- a/Sources/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift +++ b/Sources/Output/SwiftDeclarationRendering/StaticFieldLayoutProvider.swift @@ -15,7 +15,8 @@ public enum StaticLayoutDependencyResolution: Sendable, Equatable, Hashable { case singleImage /// Resolve across the binary's transitive dependency closure, located /// through the given search paths (the system dyld shared cache covers the - /// stdlib / Foundation / the rest of the OS). Cross-module field / + /// stdlib / Foundation / the rest of the OS); a binary read out of a dyld + /// cache resolves in that cache first. Cross-module field / /// superclass / protocol types resolve, and resilient classes are laid out /// against their dependencies' actual binaries ("this specific deployment"). case dependencyClosure(searchPaths: [DependencySearchPath]) diff --git a/Sources/Output/SwiftDeclarationRendering/SwiftVisibilityOption.swift b/Sources/Output/SwiftDeclarationRendering/SwiftVisibilityOption.swift new file mode 100644 index 000000000..025583cd1 --- /dev/null +++ b/Sources/Output/SwiftDeclarationRendering/SwiftVisibilityOption.swift @@ -0,0 +1,25 @@ +import Semantic + +/// The printing options whose effect a marked interface records instead of +/// applying — the option names its `VisibilityRegion`s are conditioned on. +/// +/// See `SwiftDeclarationPrintConfiguration.marksOptionalContent`. Projecting +/// a marked interface with a configuration's +/// `isVisibilityOptionEnabled(_:resolvesOpaqueTypes:)` gives what printing +/// with that configuration gives. +public enum SwiftVisibilityOption: String, CaseIterable, Sendable { + case printStrippedSymbolicItem = "swift.printStrippedSymbolicItem" + case printFieldOffset = "swift.printFieldOffset" + case printExpandedFieldOffsets = "swift.printExpandedFieldOffsets" + case printMemberAddress = "swift.printMemberAddress" + case printVTableOffset = "swift.printVTableOffset" + case printPWTOffset = "swift.printPWTOffset" + case printTypeLayout = "swift.printTypeLayout" + case printEnumLayout = "swift.printEnumLayout" + case infersObjCOverridesFromSelectorNames = "swift.infersObjCOverridesFromSelectorNames" + + /// What an opaque type resolver registered with the printer supplies: + /// the constraint after `some`. Off, the interface reads as printed + /// without such a resolver. + case opaqueTypeResolution = "swift.opaqueTypeResolution" +} diff --git a/Sources/SwiftDeclarationRendering/TransformerClosureFactory.swift b/Sources/Output/SwiftDeclarationRendering/TransformerClosureFactory.swift similarity index 100% rename from Sources/SwiftDeclarationRendering/TransformerClosureFactory.swift rename to Sources/Output/SwiftDeclarationRendering/TransformerClosureFactory.swift diff --git a/Sources/SwiftDiffing/ABIDiagnostics.swift b/Sources/Output/SwiftDiffing/ABIDiagnostics.swift similarity index 100% rename from Sources/SwiftDiffing/ABIDiagnostics.swift rename to Sources/Output/SwiftDiffing/ABIDiagnostics.swift diff --git a/Sources/SwiftDiffing/ABIDiff.swift b/Sources/Output/SwiftDiffing/ABIDiff.swift similarity index 100% rename from Sources/SwiftDiffing/ABIDiff.swift rename to Sources/Output/SwiftDiffing/ABIDiff.swift diff --git a/Sources/SwiftDiffing/ABIDiffReporter.swift b/Sources/Output/SwiftDiffing/ABIDiffReporter.swift similarity index 100% rename from Sources/SwiftDiffing/ABIDiffReporter.swift rename to Sources/Output/SwiftDiffing/ABIDiffReporter.swift diff --git a/Sources/SwiftDiffing/ABIDiffer.swift b/Sources/Output/SwiftDiffing/ABIDiffer.swift similarity index 100% rename from Sources/SwiftDiffing/ABIDiffer.swift rename to Sources/Output/SwiftDiffing/ABIDiffer.swift diff --git a/Sources/SwiftDiffing/ABIEvolution.swift b/Sources/Output/SwiftDiffing/ABIEvolution.swift similarity index 100% rename from Sources/SwiftDiffing/ABIEvolution.swift rename to Sources/Output/SwiftDiffing/ABIEvolution.swift diff --git a/Sources/SwiftDiffing/ABIEvolutionBuilder.swift b/Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift similarity index 100% rename from Sources/SwiftDiffing/ABIEvolutionBuilder.swift rename to Sources/Output/SwiftDiffing/ABIEvolutionBuilder.swift diff --git a/Sources/SwiftDiffing/ABIEvolutionReporter.swift b/Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift similarity index 100% rename from Sources/SwiftDiffing/ABIEvolutionReporter.swift rename to Sources/Output/SwiftDiffing/ABIEvolutionReporter.swift diff --git a/Sources/SwiftDiffing/ABIKey.swift b/Sources/Output/SwiftDiffing/ABIKey.swift similarity index 100% rename from Sources/SwiftDiffing/ABIKey.swift rename to Sources/Output/SwiftDiffing/ABIKey.swift diff --git a/Sources/SwiftDiffing/ABIModule.swift b/Sources/Output/SwiftDiffing/ABIModule.swift similarity index 100% rename from Sources/SwiftDiffing/ABIModule.swift rename to Sources/Output/SwiftDiffing/ABIModule.swift diff --git a/Sources/SwiftDiffing/ABIProvenance.swift b/Sources/Output/SwiftDiffing/ABIProvenance.swift similarity index 100% rename from Sources/SwiftDiffing/ABIProvenance.swift rename to Sources/Output/SwiftDiffing/ABIProvenance.swift diff --git a/Sources/SwiftDiffing/ABISnapshot.swift b/Sources/Output/SwiftDiffing/ABISnapshot.swift similarity index 100% rename from Sources/SwiftDiffing/ABISnapshot.swift rename to Sources/Output/SwiftDiffing/ABISnapshot.swift diff --git a/Sources/SwiftDiffing/ABISnapshotDocument.swift b/Sources/Output/SwiftDiffing/ABISnapshotDocument.swift similarity index 100% rename from Sources/SwiftDiffing/ABISnapshotDocument.swift rename to Sources/Output/SwiftDiffing/ABISnapshotDocument.swift diff --git a/Sources/SwiftDiffing/Compatibility.swift b/Sources/Output/SwiftDiffing/Compatibility.swift similarity index 100% rename from Sources/SwiftDiffing/Compatibility.swift rename to Sources/Output/SwiftDiffing/Compatibility.swift diff --git a/Sources/SwiftDiffing/Keying.swift b/Sources/Output/SwiftDiffing/Keying.swift similarity index 100% rename from Sources/SwiftDiffing/Keying.swift rename to Sources/Output/SwiftDiffing/Keying.swift diff --git a/Sources/SwiftDiffing/MemberRecord.swift b/Sources/Output/SwiftDiffing/MemberRecord.swift similarity index 100% rename from Sources/SwiftDiffing/MemberRecord.swift rename to Sources/Output/SwiftDiffing/MemberRecord.swift diff --git a/Sources/Output/SwiftDump/Dumpable/AssociatedType+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/AssociatedType+Dumpable.swift new file mode 100644 index 000000000..d3ba4efcb --- /dev/null +++ b/Sources/Output/SwiftDump/Dumpable/AssociatedType+Dumpable.swift @@ -0,0 +1,36 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import MachOFoundation +import Semantic +import Utilities +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering + +extension AssociatedType: ConformedDumpable { + public func dumpTypeName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedTypeName(using: configuration.demangleResolver, in: context) + } + + public func dumpProtocolName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedProtocolName(using: configuration.demangleResolver, in: context) + } + + /// The conforming type's name as a dump prints it. Behind + /// `dumpTypeName(using:in:)` and `AssociatedTypeDumper` alike. + package func dumpedTypeName(using resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { + try await resolver.resolve(for: SymbolicDemangler.demangleType(for: conformingTypeName, in: context)).replacingTypeNameOrOtherToTypeDeclaration() + } + + /// The protocol's name as a dump prints it. Behind + /// `dumpProtocolName(using:in:)` and `AssociatedTypeDumper` alike. + package func dumpedProtocolName(using resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { + try await resolver.resolve(for: SymbolicDemangler.demangleType(for: protocolTypeName, in: context)) + } + + public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await LargeStackTaskExecution.run { + try await AssociatedTypeDumper(self, using: configuration, in: machO).body + } + } +} diff --git a/Sources/Output/SwiftDump/Dumpable/Class+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/Class+Dumpable.swift new file mode 100644 index 000000000..7ee6d25c0 --- /dev/null +++ b/Sources/Output/SwiftDump/Dumpable/Class+Dumpable.swift @@ -0,0 +1,32 @@ +import Semantic +import Demangling +import MachOKit +import MachOSwiftSection +import MachOFoundation +import Utilities +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering + +extension Class: NamedDumpable { + public func dumpName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedName(using: configuration.demangleResolver, configuration: configuration, in: context) + } + + public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await LargeStackTaskExecution.run { + try await ClassDumper(self, using: configuration, in: machO).body + } + } + + /// The name a dump declares for this class when it has no specialized + /// metadata — behind `dumpName(using:in:)` and `ClassDumper`'s unbound + /// name alike. + @SemanticStringBuilder + package func dumpedName(using resolver: DemangleResolver, configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + if configuration.displayParentName { + try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .type(.class(descriptor)), in: context)).replacingTypeNameOrOtherToTypeDeclaration() + } else { + try TypeDeclaration(kind: .class, descriptor.name(in: context)) + } + } +} diff --git a/Sources/Output/SwiftDump/Dumpable/Enum+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/Enum+Dumpable.swift new file mode 100644 index 000000000..69c495903 --- /dev/null +++ b/Sources/Output/SwiftDump/Dumpable/Enum+Dumpable.swift @@ -0,0 +1,32 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import MachOFoundation +import Semantic +import Utilities +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering + +extension Enum: NamedDumpable { + public func dumpName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedName(using: configuration.demangleResolver, configuration: configuration, in: context) + } + + public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await LargeStackTaskExecution.run { + try await EnumDumper(self, using: configuration, in: machO).body + } + } + + /// The name a dump declares for this enum when it has no specialized + /// metadata — behind `dumpName(using:in:)` and `EnumDumper`'s unbound + /// name alike. + @SemanticStringBuilder + package func dumpedName(using resolver: DemangleResolver, configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + if configuration.displayParentName { + try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .type(.enum(descriptor)), in: context)).replacingTypeNameOrOtherToTypeDeclaration() + } else { + try TypeDeclaration(kind: .enum, descriptor.name(in: context)) + } + } +} diff --git a/Sources/SwiftDump/Dumpable/ObjCImplementationClass+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/ObjCImplementationClass+Dumpable.swift similarity index 76% rename from Sources/SwiftDump/Dumpable/ObjCImplementationClass+Dumpable.swift rename to Sources/Output/SwiftDump/Dumpable/ObjCImplementationClass+Dumpable.swift index 5e11ce400..28a4e6084 100644 --- a/Sources/SwiftDump/Dumpable/ObjCImplementationClass+Dumpable.swift +++ b/Sources/Output/SwiftDump/Dumpable/ObjCImplementationClass+Dumpable.swift @@ -29,8 +29,17 @@ public struct ObjCImplementationClass: Sendable { } extension ObjCImplementationClass: NamedDumpable { - public func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await ObjCImplementationClassDumper(self, using: configuration, in: machO).name + /// The class's ObjC runtime name, which the recognized facts already + /// carry: nothing is read, so the context goes unused. + public func dumpName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + dumpedName + } + + /// The name a dump declares for this class — behind + /// `dumpName(using:in:)` and `ObjCImplementationClassDumper`'s name alike. + @SemanticStringBuilder + package var dumpedName: SemanticString { + TypeDeclaration(kind: .class, facts.className) } public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { diff --git a/Sources/Output/SwiftDump/Dumpable/Protocol+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/Protocol+Dumpable.swift new file mode 100644 index 000000000..c4750aa35 --- /dev/null +++ b/Sources/Output/SwiftDump/Dumpable/Protocol+Dumpable.swift @@ -0,0 +1,33 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import MachOFoundation +import Semantic +import Utilities +import Demangling +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering +import OrderedCollections + +extension MachOSwiftSection.`Protocol`: NamedDumpable { + public func dumpName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedName(using: configuration.demangleResolver, configuration: configuration, in: context) + } + + public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await LargeStackTaskExecution.run { + try await ProtocolDumper(self, using: configuration, in: machO).body + } + } + + /// The name a dump declares for this protocol — behind + /// `dumpName(using:in:)` and `ProtocolDumper`'s name alike. + @SemanticStringBuilder + package func dumpedName(using resolver: DemangleResolver, configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + if configuration.displayParentName { + try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .protocol(descriptor), in: context)).replacingTypeNameOrOtherToTypeDeclaration() + } else { + try TypeDeclaration(kind: .protocol, descriptor.name(in: context)) + } + } +} diff --git a/Sources/Output/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift new file mode 100644 index 000000000..e29f4dcc5 --- /dev/null +++ b/Sources/Output/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift @@ -0,0 +1,40 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import MachOFoundation +import Semantic +import Demangling +import Utilities +import SwiftDeclarationRendering +import OrderedCollections + +extension ProtocolConformance: ConformedDumpable { + public func dumpTypeName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedTypeName(isFull: false, resolver: configuration.demangleResolver, in: context) + } + + public func dumpProtocolName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedProtocolName(using: configuration.demangleResolver, in: context) + } + + public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await LargeStackTaskExecution.run { + try await ProtocolConformanceDumper(self, using: configuration, in: machO).body + } + } + + /// The conforming type's name as a dump prints it, in the interface-type + /// spelling; the full form keeps the resolver's own options. Behind + /// `dumpTypeName(using:in:)` and `ProtocolConformanceDumper` alike. + @SemanticStringBuilder + package func dumpedTypeName(isFull: Bool, resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { + try typeNode(in: context)?.printSemantic(using: isFull ? resolver.options ?? .interfaceType : .interfaceType).replacingTypeNameOrOtherToTypeDeclaration() + } + + /// The conformed protocol's name as a dump prints it. Behind + /// `dumpProtocolName(using:in:)` and `ProtocolConformanceDumper` alike. + @SemanticStringBuilder + package func dumpedProtocolName(using resolver: DemangleResolver, in context: some ReadingContext) async throws -> SemanticString { + try await protocolNode(in: context).asyncMap { try await resolver.resolve(for: $0) } + } +} diff --git a/Sources/Output/SwiftDump/Dumpable/Struct+Dumpable.swift b/Sources/Output/SwiftDump/Dumpable/Struct+Dumpable.swift new file mode 100644 index 000000000..f7d1bbe3f --- /dev/null +++ b/Sources/Output/SwiftDump/Dumpable/Struct+Dumpable.swift @@ -0,0 +1,32 @@ +import Foundation +import MachOKit +import MachOSwiftSection +import MachOFoundation +import Semantic +import Utilities +@_spi(Internals) import SwiftInspection +import SwiftDeclarationRendering + +extension Struct: NamedDumpable { + public func dumpName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + try await dumpedName(using: configuration.demangleResolver, configuration: configuration, in: context) + } + + public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await LargeStackTaskExecution.run { + try await StructDumper(self, using: configuration, in: machO).body + } + } + + /// The name a dump declares for this struct when it has no specialized + /// metadata — behind `dumpName(using:in:)` and `StructDumper`'s unbound + /// name alike. + @SemanticStringBuilder + package func dumpedName(using resolver: DemangleResolver, configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString { + if configuration.displayParentName { + try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .type(.struct(descriptor)), in: context)).replacingTypeNameOrOtherToTypeDeclaration() + } else { + try TypeDeclaration(kind: .struct, descriptor.name(in: context)) + } + } +} diff --git a/Sources/SwiftDump/Dumper/AssociatedTypeDumper.swift b/Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift similarity index 88% rename from Sources/SwiftDump/Dumper/AssociatedTypeDumper.swift rename to Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift index bdea03a82..cae8ed47a 100644 --- a/Sources/SwiftDump/Dumper/AssociatedTypeDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/AssociatedTypeDumper.swift @@ -47,12 +47,12 @@ package struct AssociatedTypeDumper: Conforme package var records: SemanticString { get async throws { for (offset, record) in dumped.records.offsetEnumerated() { - let recordName = try record.name(in: machO) - let witnessMangledName = try record.substitutedTypeName(in: machO) + let recordName = try record.name(in: machO.context) + let witnessMangledName = try record.substitutedTypeName(in: machO.context) // The dump's spelling of a reference that could not be // expanded names the owner declaration in a trailing comment; // the interface's, the indexer's default, does not. - let resolution = try SymbolicDemangler.demangleType(for: witnessMangledName, in: machO) + let resolution = try SymbolicDemangler.demangleType(for: witnessMangledName, in: machO.context) .resolveOpaqueTypeCollectingConditionalCandidates(witnessMangledName: witnessMangledName, conformingTypeName: dumped.conformingTypeName, in: machO, spelling: .annotated) // Every branch of an availability-conditional witness, above @@ -109,13 +109,13 @@ package struct AssociatedTypeDumper: Conforme package var typeName: SemanticString { get async throws { - try await demangleResolver.resolve(for: SymbolicDemangler.demangleType(for: dumped.conformingTypeName, in: machO)).replacingTypeNameOrOtherToTypeDeclaration() + try await dumped.dumpedTypeName(using: demangleResolver, in: machO.context) } } package var protocolName: SemanticString { get async throws { - try await demangleResolver.resolve(for: SymbolicDemangler.demangleType(for: dumped.protocolTypeName, in: machO)) + try await dumped.dumpedProtocolName(using: demangleResolver, in: machO.context) } } } diff --git a/Sources/SwiftDump/Dumper/ClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift similarity index 97% rename from Sources/SwiftDump/Dumper/ClassDumper.swift rename to Sources/Output/SwiftDump/Dumper/ClassDumper.swift index d155ad941..f4c5ae6fa 100644 --- a/Sources/SwiftDump/Dumper/ClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ClassDumper.swift @@ -45,7 +45,7 @@ package struct ClassDumper: TypedDumper { /// the member sections annotate from, looked up once more here because the /// header prints before the member loop computes its context node. private var objcAncestorChainHierarchy: ObjCClassHierarchy? { - guard let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO), + guard let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context), let qualifiedName = NodeTypeNaming.nominalQualifiedName(ofDemangledRoot: contextNode) else { return nil } return ObjCMembers.table(forSwiftClassQualifiedName: qualifiedName, in: machO)?.hierarchy @@ -73,7 +73,7 @@ package struct ClassDumper: TypedDumper { // segment directly in that case. let isBound = boundDumpedMetatype() != nil if !isBound, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO) { + try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO.context) { superclass } } else { @@ -89,7 +89,7 @@ package struct ClassDumper: TypedDumper { get throws { guard dumped.descriptor.isActor else { return [] } - let currentTypeNode = try SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO) + let currentTypeNode = try SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context) let currentTypeName = currentTypeNode.print(using: .interfaceTypeBuilderOnly) var nodes: Set = [] @@ -119,16 +119,16 @@ package struct ClassDumper: TypedDumper { package var superclass: SemanticString { get async throws { let hasInvertedProtocols = dumped.invertibleProtocolSet?.hasInvertedProtocols ?? false - if let superclassMangledName = try dumped.descriptor.superclassTypeMangledName(in: machO) { + if let superclassMangledName = try dumped.descriptor.superclassTypeMangledName(in: machO.context) { Standard(":") Space() - try await demangleResolver.resolve(for: SymbolicDemangler.demangleType(for: superclassMangledName, in: machO)) + try await demangleResolver.resolve(for: SymbolicDemangler.demangleType(for: superclassMangledName, in: machO.context)) if hasInvertedProtocols { Standard(",") Space() dumped.invertibleProtocolSet!.dumpInvertedProtocolNames } - } else if let resilientSuperclass = dumped.resilientSuperclass, let kind = dumped.descriptor.resilientSuperclassReferenceKind, let superclass = try await resilientSuperclass.dumpSuperclass(resolver: demangleResolver, for: kind, in: machO) { + } else if let resilientSuperclass = dumped.resilientSuperclass, let kind = dumped.descriptor.resilientSuperclassReferenceKind, let superclass = try await resilientSuperclass.dumpSuperclass(resolver: demangleResolver, for: kind, in: machO.context) { Standard(":") Space() superclass @@ -170,13 +170,13 @@ package struct ClassDumper: TypedDumper { // be node-matched exactly like the member loops in `members` // (issue #115). A context that cannot be demangled falls back to // the name-only (merged) lookup rather than dropping evidence. - let finalRecoveryContextNode = canRecoverFinalFields ? try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO) : nil + let finalRecoveryContextNode = canRecoverFinalFields ? try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context) : nil let vtableAccessorNames = canRecoverFinalFields ? vtableAccessorFieldNames(interfaceNameString: finalRecoveryInterfaceName, contextNode: finalRecoveryContextNode) : [] let storedAccessorNames = canRecoverFinalFields ? storedAccessorFieldNames(interfaceNameString: finalRecoveryInterfaceName, contextNode: finalRecoveryContextNode) : [] - for (offset, fieldRecord) in try dumped.descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { + for (offset, fieldRecord) in try dumped.descriptor.fieldDescriptor(in: machO.context).records(in: machO.context).offsetEnumerated() { BreakLine() - let mangledTypeName = try fieldRecord.mangledTypeName(in: machO) + let mangledTypeName = try fieldRecord.mangledTypeName(in: machO.context) try await fieldLayoutRenderer.storedFieldComments(forFieldAtIndex: offset.index, mangledTypeName: mangledTypeName, fieldOffsets: fieldOffsets) @@ -184,7 +184,7 @@ package struct ClassDumper: TypedDumper { let demangledTypeNode = try fieldDemangledTypeNode(for: mangledTypeName) - let fieldName = try fieldRecord.fieldName(in: machO) + let fieldName = try fieldRecord.fieldName(in: machO.context) let strippedFieldName = fieldName.stripLazyPrefix let isFinalField = canRecoverFinalFields @@ -305,7 +305,7 @@ package struct ClassDumper: TypedDumper { BreakLine() if configuration.printVTableOffset { - if let vtableSlot = try? parentVTableCache.slotIndex(for: descriptor, in: machO) { + if let vtableSlot = try? parentVTableCache.slotIndex(for: descriptor, in: machO.context) { configuration.vtableOffsetComment(slotOffset: vtableSlot) } } @@ -316,7 +316,7 @@ package struct ClassDumper: TypedDumper { Indent(level: 1) - let methodDescriptor = try descriptor.methodDescriptor(in: machO) + let methodDescriptor = try descriptor.methodDescriptor(in: machO.context) // An override slot keeps the implementation-address route: its // descriptor has no `Tq` symbol, and the parent's descriptor @@ -401,7 +401,7 @@ package struct ClassDumper: TypedDumper { // context node picks this type's own sub-bucket (issue #115). // A context that cannot be demangled falls back to the name-only // (merged) lookup rather than dropping members. - let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO) + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context) // `override` of ObjC-inherited members (evolution proposal // `objc-ancestor-override-recovery`): the class's own ObjC method @@ -556,11 +556,7 @@ package struct ClassDumper: TypedDumper { @SemanticStringBuilder private func _name(using resolver: DemangleResolver) async throws -> SemanticString { - if configuration.displayParentName { - try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO)).replacingTypeNameOrOtherToTypeDeclaration() - } else { - try TypeDeclaration(kind: .class, dumped.descriptor.name(in: machO)) - } + try await dumped.dumpedName(using: resolver, configuration: configuration, in: machO.context) } @SemanticStringBuilder diff --git a/Sources/SwiftDump/Dumper/EnumDumper.swift b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift similarity index 94% rename from Sources/SwiftDump/Dumper/EnumDumper.swift rename to Sources/Output/SwiftDump/Dumper/EnumDumper.swift index da66633ba..547bf11be 100644 --- a/Sources/SwiftDump/Dumper/EnumDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/EnumDumper.swift @@ -54,7 +54,7 @@ package struct EnumDumper: TypedDumper { // matching reasoning). let isBound = boundDumpedMetatype() != nil if !isBound, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO) { + try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO.context) { if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { invertibleProtocolSet.dumpInvertedProtocolsInheritance } @@ -83,16 +83,16 @@ package struct EnumDumper: TypedDumper { await fieldLayoutRenderer.enumPrefixComments(enumLayout: enumLayout) - for (offset, fieldRecord) in try dumped.descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { + for (offset, fieldRecord) in try dumped.descriptor.fieldDescriptor(in: machO.context).records(in: machO.context).offsetEnumerated() { BreakLine() - let mangledTypeName = try fieldRecord.mangledTypeName(in: machO) + let mangledTypeName = try fieldRecord.mangledTypeName(in: machO.context) try await fieldLayoutRenderer.enumCaseComments(forCaseAtIndex: offset.index, mangledTypeName: mangledTypeName, enumLayout: enumLayout) Indent(level: configuration.indentation) - let caseName = try fieldRecord.fieldName(in: machO) + let caseName = try fieldRecord.fieldName(in: machO.context) if caseName.isEmpty { // Swift 6.4: an element unavailable at run time keeps its // tag, but the compiler emits neither its name nor its @@ -154,7 +154,7 @@ package struct EnumDumper: TypedDumper { // context node picks this type's own sub-bucket (issue #115). // A context that cannot be demangled falls back to the name-only // (merged) lookup rather than dropping members. - let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.enum(dumped.descriptor)), in: machO) + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.enum(dumped.descriptor)), in: machO.context) for kind in SymbolIndexStore.MemberKind.allCases { let memberSymbols = if let contextNode { @@ -213,10 +213,6 @@ package struct EnumDumper: TypedDumper { @SemanticStringBuilder private func _name(using resolver: DemangleResolver) async throws -> SemanticString { - if configuration.displayParentName { - try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .type(.enum(dumped.descriptor)), in: machO)).replacingTypeNameOrOtherToTypeDeclaration() - } else { - try TypeDeclaration(kind: .enum, dumped.descriptor.name(in: machO)) - } + try await dumped.dumpedName(using: resolver, configuration: configuration, in: machO.context) } } diff --git a/Sources/SwiftDump/Dumper/ExtensionDumper.swift b/Sources/Output/SwiftDump/Dumper/ExtensionDumper.swift similarity index 100% rename from Sources/SwiftDump/Dumper/ExtensionDumper.swift rename to Sources/Output/SwiftDump/Dumper/ExtensionDumper.swift diff --git a/Sources/SwiftDump/Dumper/ObjCImplementationClassDumper.swift b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift similarity index 95% rename from Sources/SwiftDump/Dumper/ObjCImplementationClassDumper.swift rename to Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift index 0b9c46392..687b22e3f 100644 --- a/Sources/SwiftDump/Dumper/ObjCImplementationClassDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ObjCImplementationClassDumper.swift @@ -57,7 +57,7 @@ package struct ObjCImplementationClassDumper: package var name: SemanticString { get async throws { - TypeDeclaration(kind: .class, facts.className) + dumped.dumpedName } } @@ -139,9 +139,20 @@ package struct ObjCImplementationClassDumper: } Indent(level: 1) if let typeNode = instanceVariable.swiftTypeNode, let propertyName = instanceVariable.swiftPropertyName { - Keyword(.var) - Space() - MemberDeclaration(propertyName) + // A `lazy var`'s storage prints under the property's name with + // its storage type, as `ClassDumper` prints a Swift type's own + // lazy field. + if let lazyPropertyName = instanceVariable.lazyPropertyName { + Keyword(.lazy) + Space() + Keyword(.var) + Space() + MemberDeclaration(lazyPropertyName) + } else { + Keyword(.var) + Space() + MemberDeclaration(propertyName) + } Standard(":") Space() try await demangleResolver.resolve(for: typeNode.materialize()) diff --git a/Sources/SwiftDump/Dumper/ObjCMemberRendering.swift b/Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift similarity index 100% rename from Sources/SwiftDump/Dumper/ObjCMemberRendering.swift rename to Sources/Output/SwiftDump/Dumper/ObjCMemberRendering.swift diff --git a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift b/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift similarity index 95% rename from Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift rename to Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift index 0df207e76..eac0e1680 100644 --- a/Sources/SwiftDump/Dumper/ProtocolConformanceDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ProtocolConformanceDumper.swift @@ -49,7 +49,7 @@ package struct ProtocolConformanceDumper: Con } for (offset, conditionalRequirement) in dumped.conditionalRequirements.offsetEnumerated() { - try await conditionalRequirement.dump(resolver: demangleResolver, in: machO) + try await conditionalRequirement.dump(resolver: demangleResolver, in: machO.context) if !offset.isEnd { Standard(",") Space() @@ -68,7 +68,7 @@ package struct ProtocolConformanceDumper: Con Space() if configuration.printConformancePWTAddress, let proto = dumped.protocol?.resolved { Standard("{") - let protocolModel = try Protocol(descriptor: proto, in: machO) + let protocolModel = try Protocol(descriptor: proto, in: machO.context) if !protocolModel.requirements.isEmpty, let witnessTablePattern = dumped.witnessTablePattern { BreakLine() for (requirementIndex, requirement) in protocolModel.requirements.enumerated() { @@ -102,7 +102,7 @@ package struct ProtocolConformanceDumper: Con for resilientWitness in dumped.resilientWitnesses { BreakLine() - if configuration.printMemberAddress, let implementationOffset = resilientWitness.implementationOffset, let implementationAddressString = resilientWitness.implementationAddress(in: machO) { + if configuration.printMemberAddress, let implementationOffset = resilientWitness.implementationOffset, let implementationAddressString = resilientWitness.implementationAddressString(in: machO) { configuration.memberAddressComment(offset: implementationOffset, addressString: implementationAddressString) } @@ -111,7 +111,7 @@ package struct ProtocolConformanceDumper: Con if let symbols = resilientWitness.implementationSymbols(in: machO), let node = Self.demangledSymbol(for: symbols, typeName: typeNameString, visitedNodes: visitedNodes, in: machO)?.demangledNode { _ = visitedNodes.append(StructuralNodeReferenceKey(node)) try await demangleResolver.resolve(for: node) - } else if let requirement = try resilientWitness.requirement(in: machO) { + } else if let requirement = try resilientWitness.requirement(in: machO.context) { switch requirement { case .symbol(let symbol): @@ -170,13 +170,13 @@ package struct ProtocolConformanceDumper: Con @SemanticStringBuilder private func typeName(isFull: Bool) async throws -> SemanticString { - try dumped.typeNode(in: machO)?.printSemantic(using: isFull ? demangleResolver.options ?? typeNameOptions : typeNameOptions).replacingTypeNameOrOtherToTypeDeclaration() + try await dumped.dumpedTypeName(isFull: isFull, resolver: demangleResolver, in: machO.context) } @SemanticStringBuilder package var protocolName: SemanticString { get async throws { - try await dumped.protocolNode(in: machO).asyncMap { try await demangleResolver.resolve(for: $0) } + try await dumped.dumpedProtocolName(using: demangleResolver, in: machO.context) } } diff --git a/Sources/SwiftDump/Dumper/ProtocolDumper.swift b/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift similarity index 93% rename from Sources/SwiftDump/Dumper/ProtocolDumper.swift rename to Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift index f2bbf755b..67b5cfa1a 100644 --- a/Sources/SwiftDump/Dumper/ProtocolDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/ProtocolDumper.swift @@ -43,7 +43,7 @@ package struct ProtocolDumper: NamedDumper { Standard(",") } Space() - try await requirement.descriptor.dumpContent(resolver: demangleResolver, in: machO) + try await requirement.descriptor.dumpContent(resolver: demangleResolver, in: machO.context) } if !requirementInSignatures.isEmpty { Space() @@ -51,7 +51,7 @@ package struct ProtocolDumper: NamedDumper { Space() for (offset, requirement) in requirementInSignatures.offsetEnumerated() { - try await requirement.descriptor.dumpProtocolRequirement(resolver: demangleResolver, in: machO) + try await requirement.descriptor.dumpProtocolRequirement(resolver: demangleResolver, in: machO.context) if !offset.isEnd { Standard(",") Space() @@ -65,7 +65,7 @@ package struct ProtocolDumper: NamedDumper { @SemanticStringBuilder package var associatedTypes: SemanticString { get async throws { - let associatedTypes = try dumped.descriptor.associatedTypes(in: machO) + let associatedTypes = try dumped.descriptor.associatedTypes(in: machO.context) if !associatedTypes.isEmpty { for (offset, associatedType) in associatedTypes.offsetEnumerated() { @@ -139,11 +139,7 @@ package struct ProtocolDumper: NamedDumper { @SemanticStringBuilder private func _name(using resolver: DemangleResolver) async throws -> SemanticString { - if configuration.displayParentName { - try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .protocol(dumped.descriptor), in: machO)).replacingTypeNameOrOtherToTypeDeclaration() - } else { - try TypeDeclaration(kind: .protocol, dumped.descriptor.name(in: machO)) - } + try await dumped.dumpedName(using: resolver, configuration: configuration, in: machO.context) } /// The first symbol among `symbols` mentioning THIS protocol and not yet diff --git a/Sources/SwiftDump/Dumper/StructDumper.swift b/Sources/Output/SwiftDump/Dumper/StructDumper.swift similarity index 93% rename from Sources/SwiftDump/Dumper/StructDumper.swift rename to Sources/Output/SwiftDump/Dumper/StructDumper.swift index f08a46770..ec305894d 100644 --- a/Sources/SwiftDump/Dumper/StructDumper.swift +++ b/Sources/Output/SwiftDump/Dumper/StructDumper.swift @@ -56,7 +56,7 @@ package struct StructDumper: TypedDumper { // is orthogonal to substitution. let isBound = boundDumpedMetatype() != nil if !isBound, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO) { + try await genericContext.dumpGenericSignature(resolver: demangleResolver, in: machO.context) { if let invertibleProtocolSet = dumped.invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { invertibleProtocolSet.dumpInvertedProtocolsInheritance } @@ -82,17 +82,17 @@ package struct StructDumper: TypedDumper { autoResolveAccessorMetadata: false ) let fieldOffsets = fieldLayoutRenderer.fieldOffsets - for (offset, fieldRecord) in try dumped.descriptor.fieldDescriptor(in: machO).records(in: machO).offsetEnumerated() { + for (offset, fieldRecord) in try dumped.descriptor.fieldDescriptor(in: machO.context).records(in: machO.context).offsetEnumerated() { BreakLine() - let mangledTypeName = try fieldRecord.mangledTypeName(in: machO) + let mangledTypeName = try fieldRecord.mangledTypeName(in: machO.context) try await fieldLayoutRenderer.storedFieldComments(forFieldAtIndex: offset.index, mangledTypeName: mangledTypeName, fieldOffsets: fieldOffsets) // dump shows what the record says, so a `@_rawLayout(like:)` // struct's artificial `_rawLayout` record (Swift 6.4) still // renders — behind a comment saying it is not a stored property. - if FieldRecordRendering.isRawLayoutStorageRecord(name: try fieldRecord.fieldName(in: machO), isArtificial: fieldRecord.flags.contains(.isArtificial)) { + if FieldRecordRendering.isRawLayoutStorageRecord(name: try fieldRecord.fieldName(in: machO.context), isArtificial: fieldRecord.flags.contains(.isArtificial)) { Indent(level: configuration.indentation) Comment(FieldRecordRendering.artificialRawLayoutRecordComment) BreakLine() @@ -102,7 +102,7 @@ package struct StructDumper: TypedDumper { let demangledTypeNode = try fieldDemangledTypeNode(for: mangledTypeName) - let fieldName = try fieldRecord.fieldName(in: machO) + let fieldName = try fieldRecord.fieldName(in: machO.context) fieldDeclarationKeywords(for: fieldRecord, typeNode: demangledTypeNode, fieldName: fieldName) @@ -142,7 +142,7 @@ package struct StructDumper: TypedDumper { // bucket; the context node picks this type's own sub-bucket // (issue #115). A context that cannot be demangled falls back to // the name-only (merged) lookup rather than dropping members. - let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.struct(dumped.descriptor)), in: machO) + let contextNode = try? SymbolicDemangler.demangleContext(for: .type(.struct(dumped.descriptor)), in: machO.context) for kind in SymbolIndexStore.MemberKind.allCases { let memberSymbols = if let contextNode { @@ -209,11 +209,7 @@ package struct StructDumper: TypedDumper { @SemanticStringBuilder private func _name(using resolver: DemangleResolver) async throws -> SemanticString { - if configuration.displayParentName { - try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .type(.struct(dumped.descriptor)), in: machO)).replacingTypeNameOrOtherToTypeDeclaration() - } else { - try TypeDeclaration(kind: .struct, dumped.descriptor.name(in: machO)) - } + try await dumped.dumpedName(using: resolver, configuration: configuration, in: machO.context) } } diff --git a/Sources/SwiftDump/Extensions/TypeWrapper+Dumper.swift b/Sources/Output/SwiftDump/Extensions/TypeWrapper+Dumper.swift similarity index 83% rename from Sources/SwiftDump/Extensions/TypeWrapper+Dumper.swift rename to Sources/Output/SwiftDump/Extensions/TypeWrapper+Dumper.swift index d5d33578f..d40b75ce8 100644 --- a/Sources/SwiftDump/Extensions/TypeWrapper+Dumper.swift +++ b/Sources/Output/SwiftDump/Extensions/TypeWrapper+Dumper.swift @@ -16,7 +16,7 @@ extension TypeContextWrapper { } else if type.descriptor.isGeneric { metadataContext = nil } else { - metadataContext = try? type.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO).enum.map { .init(metadata: $0, readingContext: MachOContext(machO)) } + metadataContext = try? type.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context).enum.map { .init(metadata: $0, readingContext: MachOContext(machO)) } } return EnumDumper(type, metadataContext: metadataContext, using: configuration, in: machO) case .struct(let type): @@ -26,7 +26,7 @@ extension TypeContextWrapper { } else if type.descriptor.isGeneric { metadataContext = nil } else { - metadataContext = try? type.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO).struct.map { .init(metadata: $0, readingContext: MachOContext(machO)) } + metadataContext = try? type.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context).struct.map { .init(metadata: $0, readingContext: MachOContext(machO)) } } return StructDumper(type, metadataContext: metadataContext, using: configuration, in: machO) case .class(let type): @@ -36,7 +36,7 @@ extension TypeContextWrapper { } else if type.descriptor.isGeneric { metadataContext = nil } else { - metadataContext = try? type.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO).class.map { .init(metadata: $0, readingContext: MachOContext(machO)) } + metadataContext = try? type.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context).class.map { .init(metadata: $0, readingContext: MachOContext(machO)) } } return ClassDumper(type, metadataContext: metadataContext, using: configuration, in: machO) } diff --git a/Sources/Output/SwiftDump/Protocols/ConformedDumpable.swift b/Sources/Output/SwiftDump/Protocols/ConformedDumpable.swift new file mode 100644 index 000000000..10e9d2ab6 --- /dev/null +++ b/Sources/Output/SwiftDump/Protocols/ConformedDumpable.swift @@ -0,0 +1,24 @@ +import MachOKit +import Semantic +import MachOSwiftSection +import SwiftDeclarationRendering + +public protocol ConformedDumpable: Dumpable { + /// The conforming type's name as a dump prints it. Naming only reads, so + /// it takes a `ReadingContext`; the full dump still needs the Mach-O. + func dumpTypeName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString + /// The conformed protocol's name as a dump prints it. + func dumpProtocolName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString +} + +extension ConformedDumpable { + @available(*, deprecated, message: "Pass a ReadingContext: dumpTypeName(using:in: machO.context).") + public func dumpTypeName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await dumpTypeName(using: configuration, in: machO.context) + } + + @available(*, deprecated, message: "Pass a ReadingContext: dumpProtocolName(using:in: machO.context).") + public func dumpProtocolName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await dumpProtocolName(using: configuration, in: machO.context) + } +} diff --git a/Sources/SwiftDump/Protocols/ConformedDumper.swift b/Sources/Output/SwiftDump/Protocols/ConformedDumper.swift similarity index 100% rename from Sources/SwiftDump/Protocols/ConformedDumper.swift rename to Sources/Output/SwiftDump/Protocols/ConformedDumper.swift diff --git a/Sources/SwiftDump/Protocols/Dumpable.swift b/Sources/Output/SwiftDump/Protocols/Dumpable.swift similarity index 100% rename from Sources/SwiftDump/Protocols/Dumpable.swift rename to Sources/Output/SwiftDump/Protocols/Dumpable.swift diff --git a/Sources/SwiftDump/Protocols/Dumper.swift b/Sources/Output/SwiftDump/Protocols/Dumper.swift similarity index 100% rename from Sources/SwiftDump/Protocols/Dumper.swift rename to Sources/Output/SwiftDump/Protocols/Dumper.swift diff --git a/Sources/Output/SwiftDump/Protocols/NamedDumpable.swift b/Sources/Output/SwiftDump/Protocols/NamedDumpable.swift new file mode 100644 index 000000000..9ed4219a1 --- /dev/null +++ b/Sources/Output/SwiftDump/Protocols/NamedDumpable.swift @@ -0,0 +1,17 @@ +import MachOKit +import Semantic +import MachOSwiftSection +import SwiftDeclarationRendering + +public protocol NamedDumpable: Dumpable { + /// The declared name a dump prints for this entity. Naming only reads, + /// so it takes a `ReadingContext`; the full dump still needs the Mach-O. + func dumpName(using configuration: DumperConfiguration, in context: some ReadingContext) async throws -> SemanticString +} + +extension NamedDumpable { + @available(*, deprecated, message: "Pass a ReadingContext: dumpName(using:in: machO.context).") + public func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { + try await dumpName(using: configuration, in: machO.context) + } +} diff --git a/Sources/SwiftDump/Protocols/NamedDumper.swift b/Sources/Output/SwiftDump/Protocols/NamedDumper.swift similarity index 100% rename from Sources/SwiftDump/Protocols/NamedDumper.swift rename to Sources/Output/SwiftDump/Protocols/NamedDumper.swift diff --git a/Sources/SwiftDump/Protocols/TypedDumper.swift b/Sources/Output/SwiftDump/Protocols/TypedDumper.swift similarity index 98% rename from Sources/SwiftDump/Protocols/TypedDumper.swift rename to Sources/Output/SwiftDump/Protocols/TypedDumper.swift index d873990f0..7237e4ca4 100644 --- a/Sources/SwiftDump/Protocols/TypedDumper.swift +++ b/Sources/Output/SwiftDump/Protocols/TypedDumper.swift @@ -117,7 +117,7 @@ extension TypedDumper { extension TypedDumper { package var typeLayout: TypeLayout? { get throws { - try dumped.descriptor.metadataAccessorFunction(in: machO)?(request: .init()).value.resolve(in: machO).valueWitnessTable(in: machO).typeLayout + try dumped.descriptor.metadataAccessorFunction(in: machO.context)?(request: .init()).value.resolve(in: machO.context).valueWitnessTable(in: machO.context).typeLayout } } } @@ -197,12 +197,12 @@ extension TypedDumper { if let substituted = substitutedFieldNode(for: mangledTypeName) { return substituted } - let typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO) + let typeNode = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context) guard typeNode.contains(Node.Kind.accessorFunctionReference) else { return typeNode } // A kind-9 field type: read the thunk offline (the registered // resolver, `MachOFile` only), naming its arguments as this type's // generic parameters — the same leg `TypeDefinition.index` takes. - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try dumped.descriptor.genericContext(in: machO)) + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try dumped.descriptor.genericContext(in: machO.context)) return typeNode.resolvingAccessorFunctionReferences(in: machO, ownerLayout: ownerLayout) } diff --git a/Sources/SwiftDump/Utils/DumperMetadataContext.swift b/Sources/Output/SwiftDump/Utils/DumperMetadataContext.swift similarity index 100% rename from Sources/SwiftDump/Utils/DumperMetadataContext.swift rename to Sources/Output/SwiftDump/Utils/DumperMetadataContext.swift diff --git a/Sources/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift b/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift similarity index 87% rename from Sources/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift rename to Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift index db9dcd5eb..c53aad37b 100644 --- a/Sources/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/AnySwiftEvolutionInterfaceBuilder.swift @@ -40,6 +40,16 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { /// The version-axis labels, oldest first (e.g. `["17.0", "18.0", "26.0"]`). public let labels: [String] + /// The `@available` platform spelling (`"iOS"`, `"macOS"`, …) for genuine + /// availability attributes above declarations whose lifecycle is fully + /// expressible as one attribute (evolution proposal + /// draft-evolution-interface-available-annotations); `nil` — the default — + /// disables them and keeps output byte-identical to the pre-attribute + /// builder. Inexpressible lifecycles (disappeared-and-returned shapes, + /// non-version labels, modified-only histories) never emit an attribute; + /// the bitmap comment stays the carrier of the full truth either way. + public let availabilityAnnotationPlatform: String? + @Mutex private var preparedEvolution: ABIEvolution? = nil @@ -60,7 +70,8 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { eventHandlers: [SwiftIndexEvents.Handler] = [], eventHandlersPerVersion: ((_ versionIndex: Int, _ label: String) -> [SwiftIndexEvents.Handler])? = nil, versions: [MachO], - labels: [String] + labels: [String], + availabilityAnnotationPlatform: String? = nil ) throws { try Self.validate(versionCount: versions.count, labelCount: labels.count) self.versionUnits = versions.enumerated().map { versionIndex, machO in @@ -71,6 +82,7 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { ) } self.labels = labels + self.availabilityAnnotationPlatform = availabilityAnnotationPlatform } /// Heterogeneous construction: each version brings its own reader type. @@ -81,7 +93,8 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { configuration: SwiftDeclarationIndexConfiguration = .init(), eventHandlers: [SwiftIndexEvents.Handler] = [], versions: repeat each Reader, - labels: [String] + labels: [String], + availabilityAnnotationPlatform: String? = nil ) throws { var units: [any InterfaceVersionRendering] = [] for machO in repeat each versions { @@ -90,6 +103,7 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { try Self.validate(versionCount: units.count, labelCount: labels.count) self.versionUnits = units self.labels = labels + self.availabilityAnnotationPlatform = availabilityAnnotationPlatform } private static func validate(versionCount: Int, labelCount: Int) throws { @@ -151,7 +165,11 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { let evolution = try requirePrepared() return await LargeStackTaskExecution.run { let blocks = await makeRenderer(for: evolution).annotatedBlocks() - return EvolutionMarking.renderInterface(blocks: blocks, evolution: evolution) + return EvolutionMarking.renderInterface( + blocks: blocks, + evolution: evolution, + availabilityAnnotationPlatform: availabilityAnnotationPlatform + ) } } @@ -172,7 +190,9 @@ public final class AnySwiftEvolutionInterfaceBuilder: Sendable { private func makeRenderer(for evolution: ABIEvolution) -> SwiftEvolutionInterfaceRenderer { SwiftEvolutionInterfaceRenderer( versions: versionUnits, - annotations: EvolutionAnnotationIndex(evolution: evolution) + annotations: EvolutionAnnotationIndex(evolution: evolution), + versionDescriptors: evolution.versions, + availabilityAnnotationPlatform: availabilityAnnotationPlatform ) } diff --git a/Sources/SwiftInterface/BuiltinStandardLibraryProtocolFacts.swift b/Sources/Output/SwiftInterface/BuiltinStandardLibraryProtocolFacts.swift similarity index 100% rename from Sources/SwiftInterface/BuiltinStandardLibraryProtocolFacts.swift rename to Sources/Output/SwiftInterface/BuiltinStandardLibraryProtocolFacts.swift diff --git a/Sources/SwiftInterface/DependencyPath.swift b/Sources/Output/SwiftInterface/DependencyPath.swift similarity index 100% rename from Sources/SwiftInterface/DependencyPath.swift rename to Sources/Output/SwiftInterface/DependencyPath.swift diff --git a/Sources/SwiftInterface/DiffContainerAssembler.swift b/Sources/Output/SwiftInterface/DiffContainerAssembler.swift similarity index 100% rename from Sources/SwiftInterface/DiffContainerAssembler.swift rename to Sources/Output/SwiftInterface/DiffContainerAssembler.swift diff --git a/Sources/SwiftInterface/DiffFormat.swift b/Sources/Output/SwiftInterface/DiffFormat.swift similarity index 100% rename from Sources/SwiftInterface/DiffFormat.swift rename to Sources/Output/SwiftInterface/DiffFormat.swift diff --git a/Sources/SwiftInterface/DiffMarking.swift b/Sources/Output/SwiftInterface/DiffMarking.swift similarity index 100% rename from Sources/SwiftInterface/DiffMarking.swift rename to Sources/Output/SwiftInterface/DiffMarking.swift diff --git a/Sources/SwiftInterface/EvolutionAnnotationIndex.swift b/Sources/Output/SwiftInterface/EvolutionAnnotationIndex.swift similarity index 100% rename from Sources/SwiftInterface/EvolutionAnnotationIndex.swift rename to Sources/Output/SwiftInterface/EvolutionAnnotationIndex.swift diff --git a/Sources/SwiftInterface/EvolutionLine.swift b/Sources/Output/SwiftInterface/EvolutionLine.swift similarity index 100% rename from Sources/SwiftInterface/EvolutionLine.swift rename to Sources/Output/SwiftInterface/EvolutionLine.swift diff --git a/Sources/SwiftInterface/EvolutionMarking.swift b/Sources/Output/SwiftInterface/EvolutionMarking.swift similarity index 66% rename from Sources/SwiftInterface/EvolutionMarking.swift rename to Sources/Output/SwiftInterface/EvolutionMarking.swift index 32028141e..1123e5cb4 100644 --- a/Sources/SwiftInterface/EvolutionMarking.swift +++ b/Sources/Output/SwiftInterface/EvolutionMarking.swift @@ -100,14 +100,105 @@ enum EvolutionMarking { return text } + // MARK: - Availability attributes + + /// The genuine `@available` attribute expressing a lifecycle, or `nil` + /// when the facts are not FULLY expressible as one syntactically valid + /// attribute — the attribute is emitted only when it tells the whole + /// presence story, the bitmap comment stays the carrier of everything + /// else (evolution proposal draft-evolution-interface-available-annotations): + /// + /// - The presence bitmap must be a single interval (`○ᵃ●ᵇ○ᶜ`); a + /// disappeared-and-returned shape (`●○●`) fits no single attribute. + /// - `introduced:` exists only when the declaration is absent at the + /// axis start (present-from-the-first-version means "predates the + /// axis", which is not an introduction fact); `obsoleted:` only when + /// it is absent at the axis end. + /// - Every involved version label must parse as a dotted numeric version + /// (`26.0`, `18.5.1`) — a file-name fallback label cannot become a + /// version literal. + /// - Modified events never participate: `@available` has no vocabulary + /// for them, so a modified-throughout lifecycle yields `nil`. + /// + /// The facts are axis-resolution: `introduced:` names the first axis + /// point carrying the declaration, not necessarily the OS release that + /// really introduced it (the legend states this once per document). + static func availabilityAttributeText( + for annotation: EvolutionAnnotation, + versions: [ABIVersionDescriptor], + platform: String + ) -> String? { + guard annotation.presence.count == versions.count else { return nil } + guard let interval = singlePresenceInterval(annotation.presence) else { return nil } + var clauses: [String] = [] + if interval.firstPresentIndex > 0 { + guard let introducedVersion = availabilityVersion(fromLabel: versions[interval.firstPresentIndex].label) else { return nil } + clauses.append("introduced: \(introducedVersion)") + } + if let firstAbsentIndexAfterPresence = interval.firstAbsentIndexAfterPresence { + guard let obsoletedVersion = availabilityVersion(fromLabel: versions[firstAbsentIndexAfterPresence].label) else { return nil } + clauses.append("obsoleted: \(obsoletedVersion)") + } + guard !clauses.isEmpty else { return nil } + return "@available(\(platform), \(clauses.joined(separator: ", ")))" + } + + /// Prepends the availability attribute as its own line above a unit's + /// lines. An empty unit stays empty — no stray attribute, mirroring + /// `annotatedLines`' empty-source rule. The attribute line carries no + /// annotation of its own (the bitmap comment stays anchored on the + /// declaration line it has always lived on). + static func prependingAvailabilityAttribute( + _ attributeText: String?, + to lines: [EvolutionLine], + indentLevel: Int + ) -> [EvolutionLine] { + guard let attributeText, !lines.isEmpty else { return lines } + var attributeContent = SemanticString() + attributeContent.append(attributeText, type: .keyword) + return [EvolutionLine(content: attributeContent, indentLevel: indentLevel, annotation: nil)] + lines + } + + /// The single presence interval `○ᵃ●ᵇ○ᶜ` (a, c ≥ 0, b ≥ 1), or `nil` + /// when the bitmap holds no presence at all or more than one presence + /// run. `firstAbsentIndexAfterPresence` is the removal transition's + /// version index, `nil` when the declaration is still present at the + /// axis end. + private static func singlePresenceInterval( + _ presence: [Bool] + ) -> (firstPresentIndex: Int, firstAbsentIndexAfterPresence: Int?)? { + guard let firstPresentIndex = presence.firstIndex(of: true) else { return nil } + guard let firstAbsentIndexAfterPresence = presence[firstPresentIndex...].firstIndex(of: false) else { + return (firstPresentIndex, nil) + } + guard !presence[firstAbsentIndexAfterPresence...].contains(true) else { return nil } + return (firstPresentIndex, firstAbsentIndexAfterPresence) + } + + /// A label usable as an `@available` version literal: one to three + /// dot-separated runs of ASCII digits (`26`, `18.5`, `18.5.1`). Returned + /// verbatim on success. + static func availabilityVersion(fromLabel label: String) -> String? { + let components = label.split(separator: ".", omittingEmptySubsequences: false) + guard (1...3).contains(components.count) else { return nil } + for component in components { + guard !component.isEmpty, component.allSatisfy({ $0.isASCII && $0.isNumber }) else { return nil } + } + return label + } + // MARK: - Document rendering /// The final annotated interface: legend header, the blocks separated by /// blank lines, and — when the evolution carries diagnostics — a warnings /// tail mirroring `ABIEvolutionReporter`'s two warnings sections as /// comments (surfaced, not silent). - static func renderInterface(blocks: [[EvolutionLine]], evolution: ABIEvolution) -> SemanticString { - var result = legendLines(for: evolution) + static func renderInterface( + blocks: [[EvolutionLine]], + evolution: ABIEvolution, + availabilityAnnotationPlatform: String? = nil + ) -> SemanticString { + var result = legendLines(for: evolution, availabilityAnnotationPlatform: availabilityAnnotationPlatform) for block in blocks { let renderedBlock = renderBlock(block, versions: evolution.versions) if renderedBlock.string.isEmpty { continue } @@ -122,8 +213,10 @@ enum EvolutionMarking { } /// Two comment lines naming the axis and mapping bitmap positions to - /// version labels — the key to reading every `[●●○]` in the body. - static func legendLines(for evolution: ABIEvolution) -> SemanticString { + /// version labels — the key to reading every `[●●○]` in the body. With + /// availability attributes enabled, a third line states their semantic + /// resolution once, so no attribute in the body overclaims. + static func legendLines(for evolution: ABIEvolution, availabilityAnnotationPlatform: String? = nil) -> SemanticString { let labels = evolution.versions.map(\.label) var result = SemanticString() result.append( @@ -135,6 +228,13 @@ enum EvolutionMarking { "// Bitmap positions: " + labels.enumerated().map { "[\($0 + 1)] \($1)" }.joined(separator: " "), type: .comment ) + if let availabilityAnnotationPlatform { + result.append("\n", type: .standard) + result.append( + "// @available(\(availabilityAnnotationPlatform), …) attributes are axis-resolution facts: introduced: names the first axis point carrying a declaration, obsoleted: the first axis point without it — not necessarily the exact release versions.", + type: .comment + ) + } return result } diff --git a/Sources/SwiftInterface/InterfaceUnionWalker.swift b/Sources/Output/SwiftInterface/InterfaceUnionWalker.swift similarity index 100% rename from Sources/SwiftInterface/InterfaceUnionWalker.swift rename to Sources/Output/SwiftInterface/InterfaceUnionWalker.swift diff --git a/Sources/SwiftInterface/InterfaceVersionRendering.swift b/Sources/Output/SwiftInterface/InterfaceVersionRendering.swift similarity index 100% rename from Sources/SwiftInterface/InterfaceVersionRendering.swift rename to Sources/Output/SwiftInterface/InterfaceVersionRendering.swift diff --git a/Sources/SwiftInterface/OpaqueSameTypeConstraint.swift b/Sources/Output/SwiftInterface/OpaqueSameTypeConstraint.swift similarity index 100% rename from Sources/SwiftInterface/OpaqueSameTypeConstraint.swift rename to Sources/Output/SwiftInterface/OpaqueSameTypeConstraint.swift diff --git a/Sources/SwiftInterface/ProtocolFactsResolver.swift b/Sources/Output/SwiftInterface/ProtocolFactsResolver.swift similarity index 95% rename from Sources/SwiftInterface/ProtocolFactsResolver.swift rename to Sources/Output/SwiftInterface/ProtocolFactsResolver.swift index 42b5c2d3b..726bee990 100644 --- a/Sources/SwiftInterface/ProtocolFactsResolver.swift +++ b/Sources/Output/SwiftInterface/ProtocolFactsResolver.swift @@ -68,14 +68,14 @@ struct ProtocolFactsResolver { func protocolReference(from symbolOrElement: SymbolOrElement) async -> ProtocolReference? { switch symbolOrElement { case .symbol(let symbol): - guard let symbolNode = try? SymbolicDemangler.demangleType(for: symbol, in: machO) else { return nil } + guard let symbolNode = try? SymbolicDemangler.demangleType(for: symbol, in: machO.context) else { return nil } let qualifiedName = await symbolNode.print(using: .opaqueTypeBuilderOnly) guard !qualifiedName.isEmpty else { return nil } return ProtocolReference(qualifiedName: qualifiedName, descriptor: nil) case .element(let descriptorWithObjCInterop): switch descriptorWithObjCInterop { case .swift(let descriptor): - guard let contextNode = try? SymbolicDemangler.demangleContext(for: .protocol(descriptor), in: machO) else { return nil } + guard let contextNode = try? SymbolicDemangler.demangleContext(for: .protocol(descriptor), in: machO.context) else { return nil } let qualifiedName = await contextNode.print(using: .opaqueTypeBuilderOnly) guard !qualifiedName.isEmpty else { return nil } return ProtocolReference(qualifiedName: qualifiedName, descriptor: descriptor) @@ -89,12 +89,12 @@ struct ProtocolFactsResolver { } private func facts(fromDescriptor descriptor: ProtocolDescriptor) async -> ProtocolFacts? { - guard let protocolModel = try? `Protocol`(descriptor: descriptor, in: machO) else { return nil } - guard let contextNode = try? SymbolicDemangler.demangleContext(for: .protocol(descriptor), in: machO) else { return nil } + guard let protocolModel = try? `Protocol`(descriptor: descriptor, in: machO.context) else { return nil } + guard let contextNode = try? SymbolicDemangler.demangleContext(for: .protocol(descriptor), in: machO.context) else { return nil } let qualifiedName = await contextNode.print(using: .opaqueTypeBuilderOnly) guard !qualifiedName.isEmpty else { return nil } - let declaredAssociatedTypeNames = (try? descriptor.associatedTypes(in: machO)) ?? [] + let declaredAssociatedTypeNames = (try? descriptor.associatedTypes(in: machO.context)) ?? [] var refinedProtocols: [ProtocolReference] = [] for requirement in protocolModel.requirementInSignatures { diff --git a/Sources/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift similarity index 99% rename from Sources/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift rename to Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift index 4c478be44..bce08cc0a 100644 --- a/Sources/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift +++ b/Sources/Output/SwiftInterface/SwiftDeclarationPrinter+DiffRendering.swift @@ -49,7 +49,7 @@ package extension SwiftDeclarationPrinter { // This header-print operation's single wrapper materialization // (proposal 0002). try await renderTypeDeclarationHeader( - for: typeDefinition.materializedTypeContext(in: machO), + for: typeDefinition.materializedTypeContext(in: machO.context), displayParentName: displayParentName, level: level, leafNameNode: leafNameNode(of: typeDefinition.typeName.node.materialize()), @@ -69,7 +69,7 @@ package extension SwiftDeclarationPrinter { // This header-print operation's single wrapper materialization // (proposal 0002). try await renderProtocolDeclarationHeader( - for: protocolDefinition.materializedProtocol(in: machO), + for: protocolDefinition.materializedProtocol(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode(of: protocolDefinition.protocolName.node.materialize()) ) diff --git a/Sources/SwiftInterface/SwiftDiffableInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift similarity index 100% rename from Sources/SwiftInterface/SwiftDiffableInterfaceBuilder.swift rename to Sources/Output/SwiftInterface/SwiftDiffableInterfaceBuilder.swift diff --git a/Sources/SwiftInterface/SwiftDiffableInterfaceRenderer.swift b/Sources/Output/SwiftInterface/SwiftDiffableInterfaceRenderer.swift similarity index 100% rename from Sources/SwiftInterface/SwiftDiffableInterfaceRenderer.swift rename to Sources/Output/SwiftInterface/SwiftDiffableInterfaceRenderer.swift diff --git a/Sources/SwiftInterface/SwiftEvolutionInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftEvolutionInterfaceBuilder.swift similarity index 90% rename from Sources/SwiftInterface/SwiftEvolutionInterfaceBuilder.swift rename to Sources/Output/SwiftInterface/SwiftEvolutionInterfaceBuilder.swift index 48901fc1c..38196f4b6 100644 --- a/Sources/SwiftInterface/SwiftEvolutionInterfaceBuilder.swift +++ b/Sources/Output/SwiftInterface/SwiftEvolutionInterfaceBuilder.swift @@ -41,19 +41,24 @@ public final class SwiftEvolutionInterfaceBuilder [EvolutionLine] { - EvolutionContainerAssembler.assemble( + let annotation = annotations.containerAnnotation(forKey: key) + let lines = EvolutionContainerAssembler.assemble( header: header, - annotation: annotations.containerAnnotation(forKey: key), + annotation: annotation, bodyUnits: bodyUnits, level: level ) + // The container header renders at `level - 1` (the assembler's own + // rule); its attribute line sits at the same indentation. + return withAvailabilityAttribute(for: annotation, lines: lines, indentLevel: level - 1) + } + + /// Prepends the unit's `@available` attribute line when attributes are + /// enabled AND the lifecycle is fully expressible as one attribute + /// (`EvolutionMarking.availabilityAttributeText`'s rules); otherwise the + /// unit passes through untouched and the bitmap comment stays the sole + /// carrier of the lifecycle. + private func withAvailabilityAttribute( + for annotation: EvolutionAnnotation?, + lines: [EvolutionLine], + indentLevel: Int + ) -> [EvolutionLine] { + guard let availabilityAnnotationPlatform, let annotation else { return lines } + let attributeText = EvolutionMarking.availabilityAttributeText( + for: annotation, + versions: versionDescriptors, + platform: availabilityAnnotationPlatform + ) + return EvolutionMarking.prependingAvailabilityAttribute(attributeText, to: lines, indentLevel: indentLevel) } // MARK: - Header resolution diff --git a/Sources/SwiftInterface/SwiftInterfaceBuilder.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift similarity index 100% rename from Sources/SwiftInterface/SwiftInterfaceBuilder.swift rename to Sources/Output/SwiftInterface/SwiftInterfaceBuilder.swift diff --git a/Sources/SwiftInterface/SwiftInterfaceBuilderConfiguration.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderConfiguration.swift similarity index 100% rename from Sources/SwiftInterface/SwiftInterfaceBuilderConfiguration.swift rename to Sources/Output/SwiftInterface/SwiftInterfaceBuilderConfiguration.swift diff --git a/Sources/SwiftInterface/SwiftInterfaceBuilderDependencies.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift similarity index 100% rename from Sources/SwiftInterface/SwiftInterfaceBuilderDependencies.swift rename to Sources/Output/SwiftInterface/SwiftInterfaceBuilderDependencies.swift diff --git a/Sources/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift similarity index 100% rename from Sources/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift rename to Sources/Output/SwiftInterface/SwiftInterfaceBuilderExtraDataProvider.swift diff --git a/Sources/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift similarity index 98% rename from Sources/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift rename to Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift index 67019d68d..3378a1ae8 100644 --- a/Sources/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift +++ b/Sources/Output/SwiftInterface/SwiftInterfaceBuilderOpaqueTypeProvider.swift @@ -87,7 +87,7 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider` names the one after the n-th @@ -98,7 +98,7 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider = .init() var constraintsByParamType: [String: [OpaqueSameTypeConstraint]] = [:] for typeRequirementNode in typeRequirementNodes { @@ -127,18 +127,18 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider = [] for protocolRequirement in protocolRequirements { - try await compositionProtocolNames.insert(protocolRequirement.dumpContent(resolver: .using(options: .opaqueTypeBuilderOnly), in: machO).string) + try await compositionProtocolNames.insert(protocolRequirement.dumpContent(resolver: .using(options: .opaqueTypeBuilderOnly), in: machO.context).string) } var results: [String] = [] if let superclassRequirement = parameterConstraints.superclass { // The class leads the composition, as the compiler's own // interface printer spells it (`some Base & P`). - try await results.append(superclassRequirement.dumpContent(resolver: .using(options: Self.typeSpellingOptions), in: machO).string) + try await results.append(superclassRequirement.dumpContent(resolver: .using(options: Self.typeSpellingOptions), in: machO.context).string) } for protocolRequirement in protocolRequirements { var result = "" - let parameterName = try await protocolRequirement.dumpParameterName(resolver: .using(options: .opaqueTypeBuilderOnly), in: machO).string - let protocolName = try await protocolRequirement.dumpContent(resolver: .using(options: .opaqueTypeBuilderOnly), in: machO).string + let parameterName = try await protocolRequirement.dumpParameterName(resolver: .using(options: .opaqueTypeBuilderOnly), in: machO.context).string + let protocolName = try await protocolRequirement.dumpContent(resolver: .using(options: .opaqueTypeBuilderOnly), in: machO.context).string result.write(protocolName) let constraints = constraintsByParamType[parameterName] ?? [] @@ -246,7 +246,7 @@ public struct SwiftInterfaceBuilderOpaqueTypeProvider? - if let resolvedContent = try? requirement.resolvedContent(in: machO), case .protocol(let element) = resolvedContent { + if let resolvedContent = try? requirement.resolvedContent(in: machO.context), case .protocol(let element) = resolvedContent { symbolOrElement = element } if case .element(.objc) = symbolOrElement { diff --git a/Sources/SwiftInterface/UnifiedDiffFormatter.swift b/Sources/Output/SwiftInterface/UnifiedDiffFormatter.swift similarity index 100% rename from Sources/SwiftInterface/UnifiedDiffFormatter.swift rename to Sources/Output/SwiftInterface/UnifiedDiffFormatter.swift diff --git a/Sources/SwiftOutputTransformer/Transformer+SwiftConfiguration.swift b/Sources/Output/SwiftOutputTransformer/Transformer+SwiftConfiguration.swift similarity index 100% rename from Sources/SwiftOutputTransformer/Transformer+SwiftConfiguration.swift rename to Sources/Output/SwiftOutputTransformer/Transformer+SwiftConfiguration.swift diff --git a/Sources/SwiftOutputTransformer/Transformer+SwiftEnumLayout.swift b/Sources/Output/SwiftOutputTransformer/Transformer+SwiftEnumLayout.swift similarity index 100% rename from Sources/SwiftOutputTransformer/Transformer+SwiftEnumLayout.swift rename to Sources/Output/SwiftOutputTransformer/Transformer+SwiftEnumLayout.swift diff --git a/Sources/SwiftOutputTransformer/Transformer+SwiftFieldOffset.swift b/Sources/Output/SwiftOutputTransformer/Transformer+SwiftFieldOffset.swift similarity index 100% rename from Sources/SwiftOutputTransformer/Transformer+SwiftFieldOffset.swift rename to Sources/Output/SwiftOutputTransformer/Transformer+SwiftFieldOffset.swift diff --git a/Sources/SwiftOutputTransformer/Transformer+SwiftMemberAddress.swift b/Sources/Output/SwiftOutputTransformer/Transformer+SwiftMemberAddress.swift similarity index 100% rename from Sources/SwiftOutputTransformer/Transformer+SwiftMemberAddress.swift rename to Sources/Output/SwiftOutputTransformer/Transformer+SwiftMemberAddress.swift diff --git a/Sources/SwiftOutputTransformer/Transformer+SwiftTypeLayout.swift b/Sources/Output/SwiftOutputTransformer/Transformer+SwiftTypeLayout.swift similarity index 100% rename from Sources/SwiftOutputTransformer/Transformer+SwiftTypeLayout.swift rename to Sources/Output/SwiftOutputTransformer/Transformer+SwiftTypeLayout.swift diff --git a/Sources/SwiftOutputTransformer/Transformer+SwiftVTableOffset.swift b/Sources/Output/SwiftOutputTransformer/Transformer+SwiftVTableOffset.swift similarity index 100% rename from Sources/SwiftOutputTransformer/Transformer+SwiftVTableOffset.swift rename to Sources/Output/SwiftOutputTransformer/Transformer+SwiftVTableOffset.swift diff --git a/Sources/SwiftPrinting/InterfaceHeader.swift b/Sources/Output/SwiftPrinting/InterfaceHeader.swift similarity index 100% rename from Sources/SwiftPrinting/InterfaceHeader.swift rename to Sources/Output/SwiftPrinting/InterfaceHeader.swift diff --git a/Sources/SwiftPrinting/NodePrintables/BoundGenericNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/BoundGenericNodePrintable.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/BoundGenericNodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/BoundGenericNodePrintable.swift diff --git a/Sources/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/DependentGenericNodePrintable.swift diff --git a/Sources/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/FunctionTypeNodePrintable.swift diff --git a/Sources/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/InterfaceNodePrintable.swift diff --git a/Sources/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/MemberDeclarationNodePrintable.swift diff --git a/Sources/SwiftPrinting/NodePrintables/NodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/NodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/NodePrintable.swift diff --git a/Sources/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift similarity index 73% rename from Sources/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift rename to Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift index d05840bb8..dca3c771a 100644 --- a/Sources/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/NodePrintableDelegate.swift @@ -10,4 +10,8 @@ protocol NodePrintableDelegate: AnyObject, Sendable { func moduleName(forTypeName typeName: String) async -> String? func swiftName(forCName cName: String, category: CImportedTypeNameCategory) async -> String? func opaqueType(forNode node: Node, index: Int?) async -> String? + /// Whether what `opaqueType(forNode:index:)` supplies is to be marked as + /// visible only with opaque type resolution on (see + /// `SwiftDeclarationPrintConfiguration.marksOptionalContent`). + var marksOptionalContent: Bool { get } } diff --git a/Sources/SwiftPrinting/NodePrintables/TypeNameResolving.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrintables/TypeNameResolving.swift rename to Sources/Output/SwiftPrinting/NodePrintables/TypeNameResolving.swift diff --git a/Sources/SwiftPrinting/NodePrintables/TypeNodePrintable.swift b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift similarity index 94% rename from Sources/SwiftPrinting/NodePrintables/TypeNodePrintable.swift rename to Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift index 0c624ff85..0181b0b1d 100644 --- a/Sources/SwiftPrinting/NodePrintables/TypeNodePrintable.swift +++ b/Sources/Output/SwiftPrinting/NodePrintables/TypeNodePrintable.swift @@ -1,6 +1,7 @@ import SwiftDeclaration import SwiftDeclarationRendering import Demangling +import Semantic /// The slice of printer state the type layer reads. protocol TypeNodePrintableContext: NodePrintableContext { @@ -90,8 +91,22 @@ extension TypeNodePrintable { mutating func printOpaqueReturnType(_ node: Node) async { target.write("some", context: .context(for: node, state: .printKeyword)) if let targetNode = context.targetNode, let opaqueType = await delegate?.opaqueType(forNode: targetNode, index: node.first(of: .opaqueReturnTypeIndex)?.index?.int) { + let constraintStart = target.writtenUnitCount target.writeSpace() target.write(opaqueType) + // What the resolver supplied, marked when marking optional content + // (evolution proposal `visibility-regions`): a projection with + // opaque type resolution off reads `some` alone, as printing + // without the resolver does. Only a `SemanticString` target + // carries marks; `writtenUnitCount` is its atom count. + if delegate?.marksOptionalContent == true, var semanticTarget = target as? SemanticString { + // Drop the target's reference first, so the mark mutates the + // atoms in place instead of copying the whole print so far. + target = Target() + semanticTarget.markAtoms(from: constraintStart, visibleUnder: .enabled(SwiftVisibilityOption.opaqueTypeResolution.rawValue)) + // `Target` is `SemanticString` here — the cast above said so. + target = semanticTarget as! Target + } } } diff --git a/Sources/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift rename to Sources/Output/SwiftPrinting/NodePrinter/FunctionNodePrinter.swift diff --git a/Sources/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift rename to Sources/Output/SwiftPrinting/NodePrinter/SubscriptNodePrinter.swift diff --git a/Sources/SwiftPrinting/NodePrinter/TypeNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrinter/TypeNodePrinter.swift rename to Sources/Output/SwiftPrinting/NodePrinter/TypeNodePrinter.swift diff --git a/Sources/SwiftPrinting/NodePrinter/VariableNodePrinter.swift b/Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift similarity index 100% rename from Sources/SwiftPrinting/NodePrinter/VariableNodePrinter.swift rename to Sources/Output/SwiftPrinting/NodePrinter/VariableNodePrinter.swift diff --git a/Sources/SwiftPrinting/SemanticExtensions/SemanticComponents.swift b/Sources/Output/SwiftPrinting/SemanticExtensions/SemanticComponents.swift similarity index 100% rename from Sources/SwiftPrinting/SemanticExtensions/SemanticComponents.swift rename to Sources/Output/SwiftPrinting/SemanticExtensions/SemanticComponents.swift diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift similarity index 100% rename from Sources/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration+Transformers.swift diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift similarity index 66% rename from Sources/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift index cd17e881d..0a8e30df0 100644 --- a/Sources/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrintConfiguration.swift @@ -60,6 +60,19 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { public var printTypeLayout: Bool = false public var printEnumLayout: Bool = false + /// Print everything the options named by `SwiftVisibilityOption` control, + /// each piece marked with a `VisibilityRegion` conditioned on its option, + /// instead of letting those options decide (evolution proposal + /// `visibility-regions`). A marked interface, frozen, separated and + /// projected with `isVisibilityOptionEnabled(_:resolvesOpaqueTypes:)` of + /// some configuration, reads byte for byte as printing with that + /// configuration. Everything else here — the transformers, the sort + /// order, the export options — applies as usual. + /// + /// For the opaque type constraints to be there to mark, register the + /// opaque type resolver as for a normal print. + public var marksOptionalContent: Bool = false + /// How the static (`MachOFile`) field-layout path resolves cross-module /// types when a layout-bearing flag is on. Defaults to the full transitive /// dependency closure over the system dyld shared cache; set `.singleImage` @@ -74,3 +87,32 @@ public struct SwiftDeclarationPrintConfiguration: Equatable, Sendable { public var enumLayoutTransformer: EnumLayoutTransformer? = nil public var enumLayoutCaseTransformer: EnumLayoutCaseTransformer? = nil } + +// MARK: - Visibility Options + +extension SwiftDeclarationPrintConfiguration { + /// Whether `option` is on in this configuration. `resolvesOpaqueTypes` + /// answers for `.opaqueTypeResolution`, which is not a setting of the + /// configuration but whether an opaque type resolver is registered. + public func isEnabled(_ option: SwiftVisibilityOption, resolvesOpaqueTypes: Bool) -> Bool { + switch option { + case .printStrippedSymbolicItem: printStrippedSymbolicItem + case .printFieldOffset: printFieldOffset + case .printExpandedFieldOffsets: printExpandedFieldOffsets + case .printMemberAddress: printMemberAddress + case .printVTableOffset: printVTableOffset + case .printPWTOffset: printPWTOffset + case .printTypeLayout: printTypeLayout + case .printEnumLayout: printEnumLayout + case .infersObjCOverridesFromSelectorNames: infersObjCOverridesFromSelectorNames + case .opaqueTypeResolution: resolvesOpaqueTypes + } + } + + /// Whether the option named `optionName` is on — the predicate to project + /// a marked interface with. A name that is not a `SwiftVisibilityOption` + /// reads as off. + public func isVisibilityOptionEnabled(_ optionName: String, resolvesOpaqueTypes: Bool) -> Bool { + SwiftVisibilityOption(rawValue: optionName).map { isEnabled($0, resolvesOpaqueTypes: resolvesOpaqueTypes) } ?? false + } +} diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift similarity index 100% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ExportFilter.swift diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift similarity index 93% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift index ba8f47605..c642d8ba7 100644 --- a/Sources/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Headers.swift @@ -44,7 +44,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), name: dumped.descriptor.name(in: machO), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.struct, descriptorWrapper: .type(.struct(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .enum(let dumped): @@ -53,7 +53,7 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), name: dumped.descriptor.name(in: machO), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.enum, descriptorWrapper: .type(.enum(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } try await renderGenericSignatureWithInvertibles(genericContext: boundTypeNode == nil ? dumped.genericContext : nil, invertibleProtocolSet: dumped.invertibleProtocolSet, resolver: resolver) case .class(let dumped): @@ -70,11 +70,11 @@ extension SwiftDeclarationPrinter { if let boundTypeNode { try await BoundDumpedTypeNameRenderer.render(boundTypeNode, using: resolver) } else { - try await renderUnboundTypeName(.class, descriptorWrapper: .type(.class(dumped.descriptor)), name: dumped.descriptor.name(in: machO), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) + try await renderUnboundTypeName(.class, descriptorWrapper: .type(.class(dumped.descriptor)), name: dumped.descriptor.name(in: machO.context), displayParentName: displayParentName, leafNameNode: leafNameNode, resolver: resolver) } let superclass = try await renderClassSuperclass(dumped, resolver: resolver) if boundTypeNode == nil, let genericContext = dumped.genericContext { - try await genericContext.dumpGenericSignature(resolver: resolver, in: machO) { + try await genericContext.dumpGenericSignature(resolver: resolver, in: machO.context) { superclass } } else { @@ -86,7 +86,7 @@ extension SwiftDeclarationPrinter { @SemanticStringBuilder private func renderGenericSignatureWithInvertibles(genericContext: TypeGenericContext?, invertibleProtocolSet: InvertibleProtocolSet?, resolver: DemangleResolver) async throws -> SemanticString { if let genericContext { - try await genericContext.dumpGenericSignature(resolver: resolver, in: machO) { + try await genericContext.dumpGenericSignature(resolver: resolver, in: machO.context) { if let invertibleProtocolSet, invertibleProtocolSet.hasInvertedProtocols { invertibleProtocolSet.dumpInvertedProtocolsInheritance } @@ -99,7 +99,7 @@ extension SwiftDeclarationPrinter { @SemanticStringBuilder private func renderUnboundTypeName(_ kind: SemanticType.TypeKind, descriptorWrapper: ContextDescriptorWrapper, name: String, displayParentName: Bool, leafNameNode: Node?, resolver: DemangleResolver) async throws -> SemanticString { if displayParentName { - try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptorWrapper, in: machO)).replacingTypeNameOrOtherToTypeDeclaration() + try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: descriptorWrapper, in: machO.context)).replacingTypeNameOrOtherToTypeDeclaration() } else { renderLeafName(kind: kind, bareName: name, leafNameNode: leafNameNode) } @@ -127,16 +127,16 @@ extension SwiftDeclarationPrinter { @SemanticStringBuilder private func renderClassSuperclass(_ dumped: Class, resolver: DemangleResolver) async throws -> SemanticString { let hasInvertedProtocols = dumped.invertibleProtocolSet?.hasInvertedProtocols ?? false - if let superclassMangledName = try dumped.descriptor.superclassTypeMangledName(in: machO) { + if let superclassMangledName = try dumped.descriptor.superclassTypeMangledName(in: machO.context) { Standard(":") Space() - try await resolver.resolve(for: SymbolicDemangler.demangleType(for: superclassMangledName, in: machO)) + try await resolver.resolve(for: SymbolicDemangler.demangleType(for: superclassMangledName, in: machO.context)) if hasInvertedProtocols { Standard(",") Space() dumped.invertibleProtocolSet!.dumpInvertedProtocolNames } - } else if let resilientSuperclass = dumped.resilientSuperclass, let kind = dumped.descriptor.resilientSuperclassReferenceKind, let superclass = try await resilientSuperclass.dumpSuperclass(resolver: resolver, for: kind, in: machO) { + } else if let resilientSuperclass = dumped.resilientSuperclass, let kind = dumped.descriptor.resilientSuperclassReferenceKind, let superclass = try await resilientSuperclass.dumpSuperclass(resolver: resolver, for: kind, in: machO.context) { Standard(":") Space() superclass @@ -156,7 +156,7 @@ extension SwiftDeclarationPrinter { guard dumped.descriptor.isActor else { return false } @Dependency(\.symbolIndexStore) var symbolIndexStore - guard let currentTypeNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO) else { return false } + guard let currentTypeNode = try? SymbolicDemangler.demangleContext(for: .type(.class(dumped.descriptor)), in: machO.context) else { return false } let currentTypeName = currentTypeNode.print(using: .interfaceTypeBuilderOnly) for thunkSymbol in symbolIndexStore.symbols(of: .distributedThunk, in: machO) { @@ -181,9 +181,9 @@ extension SwiftDeclarationPrinter { Keyword(.protocol) Space() if displayParentName { - try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .protocol(dumped.descriptor), in: machO)).replacingTypeNameOrOtherToTypeDeclaration() + try await resolver.resolve(for: SymbolicDemangler.demangleContext(for: .protocol(dumped.descriptor), in: machO.context)).replacingTypeNameOrOtherToTypeDeclaration() } else { - renderLeafName(kind: .protocol, bareName: try dumped.descriptor.name(in: machO), leafNameNode: leafNameNode) + renderLeafName(kind: .protocol, bareName: try dumped.descriptor.name(in: machO.context), leafNameNode: leafNameNode) } if dumped.numberOfRequirementsInSignature > 0 { @@ -195,7 +195,7 @@ extension SwiftDeclarationPrinter { Standard(",") } Space() - try await requirement.descriptor.dumpContent(resolver: resolver, in: machO) + try await requirement.descriptor.dumpContent(resolver: resolver, in: machO.context) } if !requirementInSignatures.isEmpty { Space() @@ -203,7 +203,7 @@ extension SwiftDeclarationPrinter { Space() for (offset, requirement) in requirementInSignatures.offsetEnumerated() { - try await requirement.descriptor.dumpProtocolRequirement(resolver: resolver, in: machO) + try await requirement.descriptor.dumpProtocolRequirement(resolver: resolver, in: machO.context) if !offset.isEnd { Standard(",") Space() @@ -217,7 +217,7 @@ extension SwiftDeclarationPrinter { /// `ProtocolDumper.associatedTypes`. @SemanticStringBuilder func renderProtocolAssociatedTypes(for dumped: MachOSwiftSection.`Protocol`, level: Int) async throws -> SemanticString { - let associatedTypes = try dumped.descriptor.associatedTypes(in: machO) + let associatedTypes = try dumped.descriptor.associatedTypes(in: machO.context) if !associatedTypes.isEmpty { for (offset, associatedType) in associatedTypes.offsetEnumerated() { BreakLine() @@ -246,7 +246,7 @@ extension SwiftDeclarationPrinter { let resolver = typeDemangleResolver let orderedRecords = collectUniqueAssociatedTypeRecords(of: associatedTypes) for (offset, record) in orderedRecords.offsetEnumerated() { - let resolution = try SymbolicDemangler.demangleType(for: record.mangledTypeName, in: machO) + let resolution = try SymbolicDemangler.demangleType(for: record.mangledTypeName, in: machO.context) .resolveOpaqueTypeCollectingConditionalCandidates( witnessMangledName: record.mangledTypeName, conformingTypeName: record.conformingTypeName, @@ -286,8 +286,8 @@ extension SwiftDeclarationPrinter { let recordName: String let mangledTypeName: MangledName do { - recordName = try record.name(in: machO) - mangledTypeName = try record.substitutedTypeName(in: machO) + recordName = try record.name(in: machO.context) + mangledTypeName = try record.substitutedTypeName(in: machO.context) } catch { continue } @@ -344,10 +344,11 @@ extension SwiftDeclarationPrinter { enumLayoutTransformer: configuration.enumLayoutTransformer, enumLayoutCaseTransformer: configuration.enumLayoutCaseTransformer, staticFieldLayoutProvider: staticFieldLayoutProvider(), - staticLayoutDependencyResolution: configuration.staticLayoutDependencyResolution + staticLayoutDependencyResolution: configuration.staticLayoutDependencyResolution, + marksOptionalContent: configuration.marksOptionalContent ) let fieldLayoutRenderer = FieldLayoutRenderer(type: typeContext, metadata: typeDefinition.metadata, machO: machO, configuration: renderConfiguration) - let fieldRecords = try typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.fieldDescriptor(in: machO).records(in: machO) + let fieldRecords = try typeDefinition.typeContextDescriptorWrapper.typeContextDescriptor.fieldDescriptor(in: machO.context).records(in: machO.context) let fieldOffsets = isEnum ? nil : fieldLayoutRenderer.fieldOffsets // Specialized definitions substitute each field's generic-parameter @@ -390,7 +391,7 @@ extension SwiftDeclarationPrinter { let field = indexedField.element BreakLine() let fieldRecord = fieldRecords[safe: fieldIndex] - let mangledTypeName = try fieldRecord?.mangledTypeName(in: machO) + let mangledTypeName = try fieldRecord?.mangledTypeName(in: machO.context) // Per-record metadata comments (single source of truth with the // `SwiftDump` dumpers): struct/class fields get the offset + // type-layout block; enum cases get the type-layout + enum-layout @@ -407,10 +408,12 @@ extension SwiftDeclarationPrinter { // the computed members get, so a stored property without any // vtable comment genuinely is statically dispatched rather than // silently unattributed (issue #106 §1). - if !isEnum, configuration.printVTableOffset { + if !isEnum { for accessor in field.accessors { if let accessorVTableOffset = accessor.vtableOffset { - renderConfiguration.vtableOffsetComment(slotOffset: accessorVTableOffset, label: accessor.kind.addressLabel) + renderConfiguration.optionalContent(.printVTableOffset) { + renderConfiguration.vtableOffsetComment(slotOffset: accessorVTableOffset, label: accessor.kind.addressLabel) + } } } } diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter+Members.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Members.swift similarity index 100% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter+Members.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+Members.swift diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift similarity index 64% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift index 5a10add4f..79b59d643 100644 --- a/Sources/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+ObjCImplementation.swift @@ -40,36 +40,35 @@ extension SwiftDeclarationPrinter { @SemanticStringBuilder func printThrowingObjCImplementationStoredProperty(_ variable: VariableDefinition, storage: ObjCImplementationClassFacts.InstanceVariable, level: Int) async throws -> SemanticString { - let objcFacts = variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence: trustsSelectorNameEvidence) - for attribute in objcFacts.attributes { - Keyword(attribute.keyword) - // An `@objc(name)` the source spelled out (evolution proposal - // `objc-member-selector-recovery`): the selector the ObjC method - // table carries is not the one the compiler derives from the name. - if attribute == .objc, let explicitSelector = objcFacts.explicitSelector { - Standard("(\(explicitSelector))") + try await printUnderObjCVerdicts(of: variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in + objcAttributes(objcFacts) + let isLazy = storage.lazyPropertyName != nil + if isLazy { + Keyword(.lazy) + Space() + Keyword(.var) + } else { + // A stored property with no setter symbol was declared `let`. + Keyword(variable.hasSetter ? .var : .let) } Space() - } - // A stored property with no setter symbol was declared `let`. - Keyword(variable.hasSetter ? .var : .let) - Space() - MemberDeclaration(variable.name) - Standard(":") - Space() - if let typeNode = storage.swiftTypeNode ?? Self.declaredTypeNode(ofVariableNode: variable.node) { - try await printThrowingType(typeNode.materialize(), isProtocol: false, level: level) - } else { - InlineComment("type not recoverable") + MemberDeclaration(variable.name) + Standard(":") + Space() + // A `lazy var` renders as a Swift type's own lazy field does: the + // getter's caller-facing type, not its storage's `Optional`. + let declaredTypeNode = WrappedPropertyRecovery.declaredTypeNode(of: variable) + let typeNode = isLazy + ? declaredTypeNode ?? storage.swiftTypeNode?.materialize() + : storage.swiftTypeNode?.materialize() ?? declaredTypeNode + if let typeNode { + try await printThrowingType(typeNode, isProtocol: false, level: level) + } else { + InlineComment("type not recoverable") + } } } - /// The `type` child of a `variable` node (context, identifier, type). - static func declaredTypeNode(ofVariableNode node: NodeReference) -> NodeReference? { - guard let last = node.children.last, last.kind == .type else { return nil } - return last - } - /// The ivars no member definition accounts for — their accessor symbols /// were stripped, or they never had any. One with a field-offset symbol /// still renders as a declaration (the symbol carries name and type); one @@ -82,12 +81,25 @@ extension SwiftDeclarationPrinter { await MemberList(level: level) { for instanceVariable in instanceVariables { await Rows(level: level) { - ObjCImplementationFieldOffsetComment(instanceVariable: instanceVariable, emit: configuration.printFieldOffset, transformer: configuration.fieldOffsetTransformer) + optionalContent(.printFieldOffset) { + ObjCImplementationFieldOffsetComment(instanceVariable: instanceVariable, emit: true, transformer: configuration.fieldOffsetTransformer) + } if let typeNode = instanceVariable.swiftTypeNode, let propertyName = instanceVariable.swiftPropertyName { SemanticString { - Keyword(.var) - Space() - MemberDeclaration(propertyName) + // With no getter joined, a `lazy var`'s storage + // type is the honest fallback, as for a Swift + // type's own lazy field. + if let lazyPropertyName = instanceVariable.lazyPropertyName { + Keyword(.lazy) + Space() + Keyword(.var) + Space() + MemberDeclaration(lazyPropertyName) + } else { + Keyword(.var) + Space() + MemberDeclaration(propertyName) + } Standard(":") Space() } diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter+PropertyWrapperSynthesis.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+PropertyWrapperSynthesis.swift similarity index 100% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter+PropertyWrapperSynthesis.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+PropertyWrapperSynthesis.swift diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift similarity index 98% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift index 761e42add..0cc723b5e 100644 --- a/Sources/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+RawLayoutBuiltinStorage.swift @@ -47,8 +47,8 @@ extension SwiftDeclarationPrinter { var storageByTypeName: [SwiftDeclaration.TypeName: RawLayoutBuiltinStorage] = [:] for descriptor in builtinTypeDescriptors { guard descriptor.layout.size > 0, - let mangledTypeName = try? descriptor.typeName(in: machO), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machO), + let mangledTypeName = try? descriptor.typeName(in: machO.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machO.context), typeNode.kind == .type, typeNode.firstChild?.kind == .structure else { continue } diff --git a/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+VisibilityRegions.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+VisibilityRegions.swift new file mode 100644 index 000000000..9c5f298fe --- /dev/null +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter+VisibilityRegions.swift @@ -0,0 +1,66 @@ +import SwiftDeclaration +import SwiftDeclarationRendering +import Semantic + +// MARK: - Marking Optional Content + +/// What `SwiftDeclarationPrintConfiguration.marksOptionalContent` changes in +/// the printer (evolution proposal `visibility-regions`): each piece of output +/// an option would decide is printed regardless and marked with a +/// `VisibilityRegion` conditioned on that option. The layout comments the +/// field renderers produce are marked the same way, through +/// `DeclarationRenderConfiguration.marksOptionalContent`. +extension SwiftDeclarationPrinter { + /// `content` when `option` is on; when marking, always, in a region + /// conditioned on `option`. + @SemanticStringBuilder + func optionalContent(_ option: SwiftVisibilityOption, @SemanticStringBuilder content: () -> SemanticString) -> SemanticString { + if configuration.marksOptionalContent { + VisibilityRegion(.enabled(option.rawValue), content: content()) + } else if configuration.isEnabled(option, resolvesOpaqueTypes: true) { + content() + } + } + + /// A member declaration under the configured verdict on name-only ObjC + /// evidence — or, when marking and the two verdicts give different + /// facts, under each, conditioned on + /// `.infersObjCOverridesFromSelectorNames` being on or off. Acting on the + /// evidence does not only add `@objc` / `override` / `class`: it also + /// takes `final` away, so neither verdict's declaration contains the + /// other's. + @SemanticStringBuilder + func printUnderObjCVerdicts( + of facts: (_ trustingSelectorNameEvidence: Bool) -> ResolvedObjCMemberFacts, + @SemanticStringBuilder render: (ResolvedObjCMemberFacts) async throws -> SemanticString + ) async rethrows -> SemanticString { + let trustingFacts = facts(true) + let distrustingFacts = facts(false) + if configuration.marksOptionalContent, trustingFacts != distrustingFacts { + try await VisibilityRegion(.enabled(SwiftVisibilityOption.infersObjCOverridesFromSelectorNames.rawValue)) { + try await render(trustingFacts) + } + try await VisibilityRegion(.disabled(SwiftVisibilityOption.infersObjCOverridesFromSelectorNames.rawValue)) { + try await render(distrustingFacts) + } + } else { + try await render(trustsSelectorNameEvidence ? trustingFacts : distrustingFacts) + } + } + + /// The attributes a member's ObjC facts call for, each followed by a + /// space. + @SemanticStringBuilder + func objcAttributes(_ objcFacts: ResolvedObjCMemberFacts) -> SemanticString { + for attribute in objcFacts.attributes { + Keyword(attribute.keyword) + // An `@objc(name)` the source spelled out (evolution proposal + // `objc-member-selector-recovery`): the selector the ObjC method + // table carries is not the one the compiler derives from the name. + if attribute == .objc, let explicitSelector = objcFacts.explicitSelector { + Standard("(\(explicitSelector))") + } + Space() + } + } +} diff --git a/Sources/SwiftPrinting/SwiftDeclarationPrinter.swift b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift similarity index 86% rename from Sources/SwiftPrinting/SwiftDeclarationPrinter.swift rename to Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift index 501d4e1bb..591964bd9 100644 --- a/Sources/SwiftPrinting/SwiftDeclarationPrinter.swift +++ b/Sources/Output/SwiftPrinting/SwiftDeclarationPrinter.swift @@ -120,7 +120,7 @@ public final class SwiftDeclarationPrinter: S return provider } let provider: (any StaticFieldLayoutProvider)? - if configurationSnapshot.printFieldOffset || configurationSnapshot.printTypeLayout || configurationSnapshot.printEnumLayout || configurationSnapshot.printExpandedFieldOffsets { + if configurationSnapshot.marksOptionalContent || configurationSnapshot.printFieldOffset || configurationSnapshot.printTypeLayout || configurationSnapshot.printEnumLayout || configurationSnapshot.printExpandedFieldOffsets { // Reader-type-dispatched (no runtime cast): only `MachOFile` builds a // provider; `MachOImage` returns nil. provider = MachO.makeStaticFieldLayoutProvider(machO: machO, resolution: configurationSnapshot.staticLayoutDependencyResolution) @@ -276,7 +276,7 @@ public final class SwiftDeclarationPrinter: S // This print operation's single wrapper materialization (proposal // 0002), threaded into the header and field renderers below. - let materializedTypeContext = try typeDefinition.materializedTypeContext(in: machO) + let materializedTypeContext = try typeDefinition.materializedTypeContext(in: machO.context) try await DeclarationBlock(level: level) { try await renderTypeDeclarationHeader(for: materializedTypeContext, displayParentName: displayParentName, level: level, specializedMetadata: specializedMetadata) @@ -350,7 +350,7 @@ public final class SwiftDeclarationPrinter: S // This print operation's single wrapper materialization (proposal // 0002), threaded into the header and associated-type renderers below. - let dumpedProtocol = try protocolDefinition.materializedProtocol(in: machO) + let dumpedProtocol = try protocolDefinition.materializedProtocol(in: machO.context) if !protocolDefinition.isIndexed { try await protocolDefinition.index(in: machO) @@ -363,11 +363,15 @@ public final class SwiftDeclarationPrinter: S try await printDefinition(protocolDefinition, level: level) - if configuration.printStrippedSymbolicItem, !protocolDefinition.strippedSymbolicRequirements.isEmpty { - for strippedSymbolicRequirement in protocolDefinition.strippedSymbolicRequirements { - MemberList(level: level) { - OffsetComment(prefix: "PWT offset", offset: strippedSymbolicRequirement.pwtOffset, emit: configuration.printPWTOffset) - strippedSymbolicRequirement.strippedSymbolicInfo() + if !protocolDefinition.strippedSymbolicRequirements.isEmpty { + optionalContent(.printStrippedSymbolicItem) { + for strippedSymbolicRequirement in protocolDefinition.strippedSymbolicRequirements { + MemberList(level: level) { + optionalContent(.printPWTOffset) { + OffsetComment(prefix: "PWT offset", offset: strippedSymbolicRequirement.pwtOffset, emit: true) + } + strippedSymbolicRequirement.strippedSymbolicInfo() + } } } } @@ -509,7 +513,7 @@ public final class SwiftDeclarationPrinter: S // conformance clause, `@retroactive`, and global-actor markers // silently missing (a `try?` here once conflated that failure with // "no conformance at all"). - let materializedProtocolConformance = try extensionDefinition.materializedProtocolConformance(in: machO) + let materializedProtocolConformance = try extensionDefinition.materializedProtocolConformance(in: machO.context) let conformanceProtocolName = await printConformanceProtocolName( of: materializedProtocolConformance, @@ -525,8 +529,8 @@ public final class SwiftDeclarationPrinter: S Space() } if let globalActorReference = protocolConformance.globalActorReference, - let globalActorTypeName = try? globalActorReference.typeName(in: machO), - let globalActorNode = try? SymbolicDemangler.demangleType(for: globalActorTypeName, in: machO) { + let globalActorTypeName = try? globalActorReference.typeName(in: machO.context), + let globalActorNode = try? SymbolicDemangler.demangleType(for: globalActorTypeName, in: machO.context) { Standard("@") try await printThrowingType(globalActorNode, isProtocol: false, level: level) Space() @@ -575,7 +579,7 @@ public final class SwiftDeclarationPrinter: S private func printConformanceProtocolName(of protocolConformance: ProtocolConformance?, isProtocol: Bool, level: Int) async -> SemanticString? { guard let protocolConformance else { return nil } do { - guard let protocolNode = try protocolConformance.protocolNode(in: machO) else { return SemanticString() } + guard let protocolNode = try protocolConformance.protocolNode(in: machO.context) else { return SemanticString() } return try await printThrowingType(protocolNode, isProtocol: isProtocol, level: level) } catch { return nil @@ -607,16 +611,14 @@ public final class SwiftDeclarationPrinter: S @SemanticStringBuilder private func printMembersByOffset(_ definition: some Definition, level: Int, isProtocol: Bool) async -> SemanticString { let offsetCommentPrefix = isProtocol ? "PWT offset" : "Field offset" - let emitOffsetComment = isProtocol ? configuration.printPWTOffset : configuration.printFieldOffset - let printMemberAddress = configuration.printMemberAddress - let printVTableOffset = configuration.printVTableOffset + let offsetCommentOption: SwiftVisibilityOption = isProtocol ? .printPWTOffset : .printFieldOffset let printExportStatus = configuration.printExportStatus let vtableTransformerClosure = vtableOffsetTransformerClosure let synthesizedPropertyWrapperMembers = synthesizedPropertyWrapperMembers(of: definition) await MemberList(level: level) { for member in definition.orderedMembers where !isExcludedByExportFilter(member) && !synthesizedPropertyWrapperMembers.contains(member) { - await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, emitOffsetComment: emitOffsetComment, printVTableOffset: printVTableOffset, printMemberAddress: printMemberAddress, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) + await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) } // Terminal step: emit `deinit` for classes and noncopyable @@ -630,8 +632,12 @@ public final class SwiftDeclarationPrinter: S // body on classes. The destructor variant collapses to nothing // when the type is an actor or value type. if let typeDefinition = definition as? TypeDefinition, let deallocatorSymbol = typeDefinition.deallocatorSymbol { - AddressComment(addressString: memberAddressString(forOffset: deallocatorSymbol.offset), emit: printMemberAddress) - AddressComment(addressString: memberAddressString(forOffset: typeDefinition.destructorSymbol?.offset), label: "destructor", emit: printMemberAddress) + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: deallocatorSymbol.offset), emit: true) + } + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: typeDefinition.destructorSymbol?.offset), label: "destructor", emit: true) + } Keyword(.deinit) } } @@ -640,9 +646,7 @@ public final class SwiftDeclarationPrinter: S @SemanticStringBuilder private func printMembersByCategory(_ definition: some Definition, level: Int, isProtocol: Bool) async -> SemanticString { let offsetCommentPrefix = isProtocol ? "PWT offset" : "Field offset" - let emitOffsetComment = isProtocol ? configuration.printPWTOffset : configuration.printFieldOffset - let printMemberAddress = configuration.printMemberAddress - let printVTableOffset = configuration.printVTableOffset + let offsetCommentOption: SwiftVisibilityOption = isProtocol ? .printPWTOffset : .printFieldOffset let printExportStatus = configuration.printExportStatus let vtableTransformerClosure = vtableOffsetTransformerClosure @@ -656,13 +660,13 @@ public final class SwiftDeclarationPrinter: S // exactly as before. await MemberList(level: level) { for member in OrderedMember.vtableOrdered(OrderedMember.allMembers(from: definition)) where !isExcludedByExportFilter(member) && !synthesizedPropertyWrapperMembers.contains(member) { - await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, emitOffsetComment: emitOffsetComment, printVTableOffset: printVTableOffset, printMemberAddress: printMemberAddress, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) + await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) } } for category in MemberCategory.allCases { await MemberList(level: level) { for member in definition.members(in: category) where member.minVTableOffset == nil && !isExcludedByExportFilter(member) && !synthesizedPropertyWrapperMembers.contains(member) { - await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, emitOffsetComment: emitOffsetComment, printVTableOffset: printVTableOffset, printMemberAddress: printMemberAddress, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) + await renderMember(member, level: level, offsetCommentPrefix: offsetCommentPrefix, offsetCommentOption: offsetCommentOption, printExportStatus: printExportStatus, vtableTransformerClosure: vtableTransformerClosure, synthesizedPropertyWrapperMembers: synthesizedPropertyWrapperMembers) } } } @@ -672,8 +676,12 @@ public final class SwiftDeclarationPrinter: S // and the rationale behind the two address comments. if let typeDefinition = definition as? TypeDefinition, let deallocatorSymbol = typeDefinition.deallocatorSymbol { MemberList(level: level) { - AddressComment(addressString: memberAddressString(forOffset: deallocatorSymbol.offset), emit: printMemberAddress) - AddressComment(addressString: memberAddressString(forOffset: typeDefinition.destructorSymbol?.offset), label: "destructor", emit: printMemberAddress) + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: deallocatorSymbol.offset), emit: true) + } + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: typeDefinition.destructorSymbol?.offset), label: "destructor", emit: true) + } Keyword(.deinit) } } @@ -695,9 +703,7 @@ public final class SwiftDeclarationPrinter: S _ member: OrderedMember, level: Int, offsetCommentPrefix: String, - emitOffsetComment: Bool, - printVTableOffset: Bool, - printMemberAddress: Bool, + offsetCommentOption: SwiftVisibilityOption, printExportStatus: Bool, vtableTransformerClosure: (@Sendable (Int, String?) -> SemanticString)?, synthesizedPropertyWrapperMembers: SynthesizedPropertyWrapperMembers @@ -705,15 +711,23 @@ public final class SwiftDeclarationPrinter: S await Rows(level: level) { switch member { case .allocator(let function), .function(let function): - OffsetComment(prefix: offsetCommentPrefix, offset: function.offset, emit: emitOffsetComment) - VTableOffsetComment(vtableOffset: function.vtableOffset, emit: printVTableOffset, transformer: vtableTransformerClosure) - AddressComment(addressString: memberAddressString(forOffset: function.symbol.offset), emit: printMemberAddress) + optionalContent(offsetCommentOption) { + OffsetComment(prefix: offsetCommentPrefix, offset: function.offset, emit: true) + } + optionalContent(.printVTableOffset) { + VTableOffsetComment(vtableOffset: function.vtableOffset, emit: true, transformer: vtableTransformerClosure) + } + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: function.symbol.offset), emit: true) + } // Qualifies the address above (evolution proposal 0007): the // witness resolved to a protocol-extension DEFAULT — the code // lives on the protocol, and several such witnesses typically // share one identical-code-folded address. - if printMemberAddress, function.isProtocolExtensionDefault { - Comment("protocol-extension default") + if function.isProtocolExtensionDefault { + optionalContent(.printMemberAddress) { + Comment("protocol-extension default") + } } // Export status is only ruled on for members whose OWN // symbols are the linkage surface: an `override` links @@ -734,16 +748,26 @@ public final class SwiftDeclarationPrinter: S // REAL field offset (from the ObjC ivar list), so the generic // symbol-offset comment gives way to the field-offset one. if let storage = variable.objcImplementationStorage { - ObjCImplementationFieldOffsetComment(instanceVariable: storage, emit: configuration.printFieldOffset, transformer: configuration.fieldOffsetTransformer) + optionalContent(.printFieldOffset) { + ObjCImplementationFieldOffsetComment(instanceVariable: storage, emit: true, transformer: configuration.fieldOffsetTransformer) + } } else { - OffsetComment(prefix: offsetCommentPrefix, offset: variable.offset, emit: emitOffsetComment) + optionalContent(offsetCommentOption) { + OffsetComment(prefix: offsetCommentPrefix, offset: variable.offset, emit: true) + } } for accessor in variable.accessors { - VTableOffsetComment(vtableOffset: accessor.vtableOffset, label: accessor.kind.addressLabel, emit: printVTableOffset, transformer: vtableTransformerClosure) - AddressComment(addressString: memberAddressString(forOffset: accessor.symbol.offset), label: accessor.kind.addressLabel, emit: printMemberAddress) + optionalContent(.printVTableOffset) { + VTableOffsetComment(vtableOffset: accessor.vtableOffset, label: accessor.kind.addressLabel, emit: true, transformer: vtableTransformerClosure) + } + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: accessor.symbol.offset), label: accessor.kind.addressLabel, emit: true) + } } - if printMemberAddress, variable.isProtocolExtensionDefault { - Comment("protocol-extension default") + if variable.isProtocolExtensionDefault { + optionalContent(.printMemberAddress) { + Comment("protocol-extension default") + } } let objcFacts = variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence: trustsSelectorNameEvidence) if printExportStatus, !objcFacts.isOverride, !objcFacts.isObjC { @@ -756,13 +780,21 @@ public final class SwiftDeclarationPrinter: S } case .subscript(let `subscript`): - OffsetComment(prefix: offsetCommentPrefix, offset: `subscript`.offset, emit: emitOffsetComment) + optionalContent(offsetCommentOption) { + OffsetComment(prefix: offsetCommentPrefix, offset: `subscript`.offset, emit: true) + } for accessor in `subscript`.accessors { - VTableOffsetComment(vtableOffset: accessor.vtableOffset, label: accessor.kind.addressLabel, emit: printVTableOffset, transformer: vtableTransformerClosure) - AddressComment(addressString: memberAddressString(forOffset: accessor.symbol.offset), label: accessor.kind.addressLabel, emit: printMemberAddress) + optionalContent(.printVTableOffset) { + VTableOffsetComment(vtableOffset: accessor.vtableOffset, label: accessor.kind.addressLabel, emit: true, transformer: vtableTransformerClosure) + } + optionalContent(.printMemberAddress) { + AddressComment(addressString: memberAddressString(forOffset: accessor.symbol.offset), label: accessor.kind.addressLabel, emit: true) + } } - if printMemberAddress, `subscript`.isProtocolExtensionDefault { - Comment("protocol-extension default") + if `subscript`.isProtocolExtensionDefault { + optionalContent(.printMemberAddress) { + Comment("protocol-extension default") + } } let objcFacts = `subscript`.resolvedObjCMemberFacts(trustingSelectorNameEvidence: trustsSelectorNameEvidence) if printExportStatus, !objcFacts.isOverride, !objcFacts.isObjC { @@ -860,53 +892,29 @@ public final class SwiftDeclarationPrinter: S try await printThrowingType(propertyWrapperAttributeTypeNode, isProtocol: false, level: level) Space() } - let objcFacts = variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence: trustsSelectorNameEvidence) - for attribute in objcFacts.attributes { - Keyword(attribute.keyword) - // An `@objc(name)` the source spelled out (evolution proposal - // `objc-member-selector-recovery`): the selector the ObjC method - // table carries is not the one the compiler derives from the name. - if attribute == .objc, let explicitSelector = objcFacts.explicitSelector { - Standard("(\(explicitSelector))") - } - Space() + try await printUnderObjCVerdicts(of: variable.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in + objcAttributes(objcFacts) + var printer = SemanticVariableNodePrinter(isStored: variable.isStored, isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, hasSetter: variable.hasSetter, indentation: level, delegate: self) + try await printer.printRoot(variable.node.materialize()) } - var printer = SemanticVariableNodePrinter(isStored: variable.isStored, isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, hasSetter: variable.hasSetter, indentation: level, delegate: self) - try await printer.printRoot(variable.node.materialize()) } @SemanticStringBuilder public func printThrowingFunction(_ function: FunctionDefinition, level: Int) async throws -> SemanticString { - let objcFacts = function.resolvedObjCMemberFacts(trustingSelectorNameEvidence: trustsSelectorNameEvidence) - for attribute in objcFacts.attributes { - Keyword(attribute.keyword) - // An `@objc(name)` the source spelled out (evolution proposal - // `objc-member-selector-recovery`): the selector the ObjC method - // table carries is not the one the compiler derives from the name. - if attribute == .objc, let explicitSelector = objcFacts.explicitSelector { - Standard("(\(explicitSelector))") - } - Space() + try await printUnderObjCVerdicts(of: function.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in + objcAttributes(objcFacts) + var printer = SemanticFunctionNodePrinter(isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, delegate: self) + try await printer.printRoot(function.node.materialize()) } - var printer = SemanticFunctionNodePrinter(isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, delegate: self) - try await printer.printRoot(function.node.materialize()) } @SemanticStringBuilder public func printThrowingSubscript(_ `subscript`: SubscriptDefinition, level: Int) async throws -> SemanticString { - let objcFacts = `subscript`.resolvedObjCMemberFacts(trustingSelectorNameEvidence: trustsSelectorNameEvidence) - for attribute in objcFacts.attributes { - Keyword(attribute.keyword) - // An `@objc(name)` the source spelled out (evolution proposal - // `objc-member-selector-recovery`): the selector the ObjC method - // table carries is not the one the compiler derives from the name. - if attribute == .objc, let explicitSelector = objcFacts.explicitSelector { - Standard("(\(explicitSelector))") - } - Space() + try await printUnderObjCVerdicts(of: `subscript`.resolvedObjCMemberFacts(trustingSelectorNameEvidence:)) { objcFacts in + objcAttributes(objcFacts) + var printer = SemanticSubscriptNodePrinter(isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, hasSetter: `subscript`.hasSetter, indentation: level, delegate: self) + try await printer.printRoot(`subscript`.node.materialize()) } - var printer = SemanticSubscriptNodePrinter(isOverride: objcFacts.isOverride, isClassMember: objcFacts.isClassMember, isFinal: objcFacts.isFinal, hasSetter: `subscript`.hasSetter, indentation: level, delegate: self) - try await printer.printRoot(`subscript`.node.materialize()) } @SemanticStringBuilder @@ -995,4 +1003,8 @@ extension SwiftDeclarationPrinter: NodePrintableDelegate { public func opaqueType(forNode node: Node, index: Int?) async -> String? { await typeNameResolverRegistry.opaqueTypeResolvers.asyncFirstNonNil { await $0.opaqueType(forNode: node, index: index) } } + + var marksOptionalContent: Bool { + configuration.marksOptionalContent + } } diff --git a/Sources/MachOMacros/LayoutMacro.swift b/Sources/Support/MachOMacros/LayoutMacro.swift similarity index 100% rename from Sources/MachOMacros/LayoutMacro.swift rename to Sources/Support/MachOMacros/LayoutMacro.swift diff --git a/Sources/MachOMacros/LocatableLayoutWrappingMacro.swift b/Sources/Support/MachOMacros/LocatableLayoutWrappingMacro.swift similarity index 100% rename from Sources/MachOMacros/LocatableLayoutWrappingMacro.swift rename to Sources/Support/MachOMacros/LocatableLayoutWrappingMacro.swift diff --git a/Sources/MachOMacros/MachOMacroPlugin.swift b/Sources/Support/MachOMacros/MachOMacroPlugin.swift similarity index 100% rename from Sources/MachOMacros/MachOMacroPlugin.swift rename to Sources/Support/MachOMacros/MachOMacroPlugin.swift diff --git a/Sources/Utilities/Alignment.swift b/Sources/Support/Utilities/Alignment.swift similarity index 100% rename from Sources/Utilities/Alignment.swift rename to Sources/Support/Utilities/Alignment.swift diff --git a/Sources/Utilities/AsyncExtensions.swift b/Sources/Support/Utilities/AsyncExtensions.swift similarity index 100% rename from Sources/Utilities/AsyncExtensions.swift rename to Sources/Support/Utilities/AsyncExtensions.swift diff --git a/Sources/Utilities/BoundedConcurrentMap.swift b/Sources/Support/Utilities/BoundedConcurrentMap.swift similarity index 100% rename from Sources/Utilities/BoundedConcurrentMap.swift rename to Sources/Support/Utilities/BoundedConcurrentMap.swift diff --git a/Sources/Utilities/ConcurrentMap.swift b/Sources/Support/Utilities/ConcurrentMap.swift similarity index 100% rename from Sources/Utilities/ConcurrentMap.swift rename to Sources/Support/Utilities/ConcurrentMap.swift diff --git a/Sources/Utilities/Macros/Layout.swift b/Sources/Support/Utilities/Macros/Layout.swift similarity index 100% rename from Sources/Utilities/Macros/Layout.swift rename to Sources/Support/Utilities/Macros/Layout.swift diff --git a/Sources/Utilities/Macros/LocatableLayoutWrapping.swift b/Sources/Support/Utilities/Macros/LocatableLayoutWrapping.swift similarity index 100% rename from Sources/Utilities/Macros/LocatableLayoutWrapping.swift rename to Sources/Support/Utilities/Macros/LocatableLayoutWrapping.swift diff --git a/Sources/Utilities/OffsetEnumeratedSequence.swift b/Sources/Support/Utilities/OffsetEnumeratedSequence.swift similarity index 100% rename from Sources/Utilities/OffsetEnumeratedSequence.swift rename to Sources/Support/Utilities/OffsetEnumeratedSequence.swift diff --git a/Sources/Utilities/OrFunctions.swift b/Sources/Support/Utilities/OrFunctions.swift similarity index 100% rename from Sources/Utilities/OrFunctions.swift rename to Sources/Support/Utilities/OrFunctions.swift diff --git a/Sources/Utilities/StringBuilder.swift b/Sources/Support/Utilities/StringBuilder.swift similarity index 100% rename from Sources/Utilities/StringBuilder.swift rename to Sources/Support/Utilities/StringBuilder.swift diff --git a/Sources/Utilities/SubstitutionMap.swift b/Sources/Support/Utilities/SubstitutionMap.swift similarity index 87% rename from Sources/Utilities/SubstitutionMap.swift rename to Sources/Support/Utilities/SubstitutionMap.swift index c56b72233..24fae5516 100644 --- a/Sources/Utilities/SubstitutionMap.swift +++ b/Sources/Support/Utilities/SubstitutionMap.swift @@ -1,3 +1,5 @@ +import FoundationToolbox + /// A data structure for managing directed substitutions, forming chains of transformations. /// /// This map is designed to find the beginning (root original) or the end (final substitution) @@ -59,7 +61,7 @@ package struct SubstitutionMap { // Check for a cycle. If we've seen this element before, break. guard visited.insert(next).inserted else { // Cycle detected. Return the current element to avoid infinite loop. - print("Warning: Cycle detected at \(next). Aborting traversal.") + #log(.error, "cycle detected at \(String(describing: next), privacy: .public); traversal aborted") break } current = next @@ -83,7 +85,7 @@ package struct SubstitutionMap { // Check for a cycle. guard visited.insert(previous).inserted else { // Cycle detected. - print("Warning: Cycle detected at \(previous). Aborting traversal.") + #log(.error, "cycle detected at \(String(describing: previous), privacy: .public); traversal aborted") break } current = previous @@ -91,3 +93,10 @@ package struct SubstitutionMap { return current } } + +// Protocol-form `@Loggable`: the type is generic, and the direct form's +// static stored logger is illegal there. +@Loggable(.fileprivate, subsystem: "com.machoswiftsection.utilities", category: "SubstitutionMap") +fileprivate protocol SubstitutionMapLogging {} + +extension SubstitutionMap: SubstitutionMapLogging {} diff --git a/Sources/Support/Utilities/ThrowingBitPatternInitializers.swift b/Sources/Support/Utilities/ThrowingBitPatternInitializers.swift new file mode 100644 index 000000000..56a8551b0 --- /dev/null +++ b/Sources/Support/Utilities/ThrowingBitPatternInitializers.swift @@ -0,0 +1,47 @@ +// Throwing counterparts of the standard library's failable `init(bitPattern:)`. +// +// They used to be public in MachOKitExtensions. Swift makes an imported +// module's extension members visible in every file of the importing module, so +// there they shadowed the failable initializer in every module that imported +// the package — MachOObjCSection's core target among them. This package is the +// only one that calls them, and `package` keeps them inside it. + +extension UnsafeRawPointer { + package enum Error: Swift.Error { + case initFailed + } + + package init(bitPattern: UInt) throws { + guard let pointer = Self(bitPattern: bitPattern) else { + throw Error.initFailed + } + self = pointer + } + + package init(bitPattern: Int) throws { + guard let pointer = Self(bitPattern: bitPattern) else { + throw Error.initFailed + } + self = pointer + } +} + +extension UnsafePointer { + package enum Error: Swift.Error { + case initFailed + } + + package init(bitPattern: UInt) throws { + guard let pointer = Self(bitPattern: bitPattern) else { + throw Error.initFailed + } + self = pointer + } + + package init(bitPattern: Int) throws { + guard let pointer = Self(bitPattern: bitPattern) else { + throw Error.initFailed + } + self = pointer + } +} diff --git a/Sources/SwiftDeclaration/Extensions/AssociatedType+Names.swift b/Sources/SwiftDeclaration/Extensions/AssociatedType+Names.swift deleted file mode 100644 index 7a02f7c9d..000000000 --- a/Sources/SwiftDeclaration/Extensions/AssociatedType+Names.swift +++ /dev/null @@ -1,26 +0,0 @@ -import Demangling -import MachOSwiftSection -@_spi(Internals) import MachOSymbols -@_spi(Internals) import SwiftInspection - -extension AssociatedType { - package func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeName? { - let node = try SymbolicDemangler.demangleType(for: conformingTypeName, in: machO) - guard let kind = node.typeKind else { return nil } - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: machO), kind: kind) - } - - package func typeName() throws -> TypeName? { - let node = try SymbolicDemangler.demangleType(for: conformingTypeName) - guard let kind = node.typeKind else { return nil } - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node), kind: kind) - } - - package func protocolName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolName { - ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleType(for: protocolTypeName, in: machO), in: machO)) - } - - package func protocolName() throws -> ProtocolName { - ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleType(for: protocolTypeName))) - } -} diff --git a/Sources/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift b/Sources/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift deleted file mode 100644 index 0d8a35df4..000000000 --- a/Sources/SwiftDeclaration/Extensions/FieldRecord+DemangledType.swift +++ /dev/null @@ -1,22 +0,0 @@ -import Demangling -import MachOSwiftSection -@_spi(Internals) import MachOSymbols -@_spi(Internals) import SwiftInspection -import Semantic -extension FieldRecord { - package func demangledTypeNode(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - try SymbolicDemangler.demangleType(for: mangledTypeName(in: machO), in: machO) - } - - package func demangledTypeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SemanticString { - try demangledTypeNode(in: machO).printSemantic(using: .interfaceTypeBuilderOnly) - } - - package func demangledTypeNode() throws -> Node { - try SymbolicDemangler.demangleType(for: mangledTypeName()) - } - - package func demangledTypeName() throws -> SemanticString { - try demangledTypeNode().printSemantic(using: .interfaceTypeBuilderOnly) - } -} diff --git a/Sources/SwiftDeclaration/Extensions/Protocol+Names.swift b/Sources/SwiftDeclaration/Extensions/Protocol+Names.swift deleted file mode 100644 index 97d06e6f3..000000000 --- a/Sources/SwiftDeclaration/Extensions/Protocol+Names.swift +++ /dev/null @@ -1,24 +0,0 @@ -import Demangling -import MachOSwiftSection -@_spi(Internals) import MachOSymbols -@_spi(Internals) import SwiftInspection - -extension MachOSwiftSection.`Protocol` { - package func protocolName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolName { - try descriptor.protocolName(in: machO) - } - - package func protocolName() throws -> ProtocolName { - try descriptor.protocolName() - } -} - -extension ProtocolDescriptor { - package func protocolName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolName { - ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleContext(for: .protocol(self), in: machO), in: machO)) - } - - package func protocolName() throws -> ProtocolName { - ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleContext(for: .protocol(self)))) - } -} diff --git a/Sources/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift b/Sources/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift deleted file mode 100644 index 0fbbe4ea2..000000000 --- a/Sources/SwiftDeclaration/Extensions/ProtocolConformance+Names.swift +++ /dev/null @@ -1,72 +0,0 @@ -import Demangling -import MachOSwiftSection -@_spi(Internals) import MachOSymbols -@_spi(Internals) import SwiftInspection - -extension ProtocolConformance { - package func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeName? { - switch typeReference { - case .directTypeDescriptor(let descriptor): - return try descriptor?.typeContextDescriptorWrapper?.typeName(in: machO) - case .indirectTypeDescriptor(let descriptorOrSymbol): - switch descriptorOrSymbol { - case .symbol(let symbol): - guard let node = try SymbolicDemangler.demangleType(for: symbol, in: machO)?.first(of: .type) else { return nil } - guard let kind = node.typeKind else { return nil } - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: machO), kind: kind) - - case .element(let element): - return try element.typeContextDescriptorWrapper?.typeName(in: machO) - - case nil: - return nil - } - case .directObjCClassName, - .indirectObjCClass: - guard let node = try typeNode(in: machO) else { return nil } - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: machO), kind: .class) - } - } - - package func typeName() throws -> TypeName? { - switch typeReference { - case .directTypeDescriptor(let descriptor): - return try descriptor?.typeContextDescriptorWrapper?.typeName() - case .indirectTypeDescriptor(let descriptorOrSymbol): - switch descriptorOrSymbol { - case .symbol(let symbol): - guard let node = try SymbolicDemangler.demangleType(for: symbol)?.first(of: .type) else { return nil } - let allChildren = node.map { $0 } - let kind: TypeKind - if allChildren.contains(.enum) || allChildren.contains(.boundGenericEnum) { - kind = .enum - } else if allChildren.contains(.structure) || allChildren.contains(.boundGenericStructure) { - kind = .struct - } else if allChildren.contains(.class) || allChildren.contains(.boundGenericClass) { - kind = .class - } else { - return nil - } - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node), kind: kind) - case .element(let element): - return try element.typeContextDescriptorWrapper?.typeName() - case nil: - return nil - } - case .directObjCClassName, - .indirectObjCClass: - guard let node = try typeNode() else { return nil } - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: node), kind: .class) - } - } - - package func protocolName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ProtocolName? { - guard let node = try protocolNode(in: machO) else { return nil } - return ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: node, in: machO)) - } - - package func protocolName() throws -> ProtocolName? { - guard let node = try protocolNode() else { return nil } - return ProtocolName(node: InternedNodeReferenceCache.shared.reference(interning: node)) - } -} diff --git a/Sources/SwiftDeclaration/Extensions/TypeContext+Names.swift b/Sources/SwiftDeclaration/Extensions/TypeContext+Names.swift deleted file mode 100644 index 868d4681c..000000000 --- a/Sources/SwiftDeclaration/Extensions/TypeContext+Names.swift +++ /dev/null @@ -1,35 +0,0 @@ -import Demangling -import MachOSwiftSection -@_spi(Internals) import MachOSymbols -@_spi(Internals) import SwiftInspection - -extension TypeContextWrapper { - package func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeName { - try typeContextDescriptorWrapper.typeName(in: machO) - } - - package func typeName() throws -> TypeName { - try typeContextDescriptorWrapper.typeName() - } -} - -extension TypeContextDescriptorWrapper { - package var kind: TypeKind { - switch self { - case .enum: - .enum - case .struct: - .struct - case .class: - .class - } - } - - package func typeName(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> TypeName { - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleContext(for: .type(self), in: machO), in: machO), kind: kind) - } - - package func typeName() throws -> TypeName { - return TypeName(node: InternedNodeReferenceCache.shared.reference(interning: try SymbolicDemangler.demangleContext(for: .type(self))), kind: kind) - } -} diff --git a/Sources/SwiftDeclarationRendering/Extensions/ContextDescriptorWrapper+Dump.swift b/Sources/SwiftDeclarationRendering/Extensions/ContextDescriptorWrapper+Dump.swift deleted file mode 100644 index eaf4f28e3..000000000 --- a/Sources/SwiftDeclarationRendering/Extensions/ContextDescriptorWrapper+Dump.swift +++ /dev/null @@ -1,15 +0,0 @@ -import MachOKit -import MachOSwiftSection -import Semantic -import Demangling -@_spi(Internals) import SwiftInspection - -extension ContextDescriptorWrapper { - package func dumpName(using options: DemangleOptions, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> SemanticString { - try dumpNameNode(in: machO).printSemantic(using: options) - } - - package func dumpNameNode(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node { - try SymbolicDemangler.demangleContext(for: self, in: machO) - } -} diff --git a/Sources/SwiftDeclarationRendering/Extensions/ProtocolConformance+.swift b/Sources/SwiftDeclarationRendering/Extensions/ProtocolConformance+.swift deleted file mode 100644 index 9a18f0057..000000000 --- a/Sources/SwiftDeclarationRendering/Extensions/ProtocolConformance+.swift +++ /dev/null @@ -1,36 +0,0 @@ -import MachOKit -import MachOSwiftSection -import Demangling -@_spi(Internals) import SwiftInspection - -extension ProtocolConformance { - package func typeNode(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - return try typeReference.node(in: machO) - } - - package func typeNode() throws -> Node? { - return try typeReference.node() - } - - package func protocolNode(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - switch `protocol` { - case .symbol(let symbol): - return try SymbolicDemangler.demangleType(for: symbol, in: machO) - case .element(let element): - return try SymbolicDemangler.demangleContext(for: .protocol(element), in: machO) - case .none: - return nil - } - } - - package func protocolNode() throws -> Node? { - switch `protocol` { - case .symbol(let symbol): - return try SymbolicDemangler.demangleType(for: symbol) - case .element(let element): - return try SymbolicDemangler.demangleContext(for: .protocol(element)) - case .none: - return nil - } - } -} diff --git a/Sources/SwiftDeclarationRendering/Extensions/ResolvedTypeReference+.swift b/Sources/SwiftDeclarationRendering/Extensions/ResolvedTypeReference+.swift deleted file mode 100644 index 989b75a5b..000000000 --- a/Sources/SwiftDeclarationRendering/Extensions/ResolvedTypeReference+.swift +++ /dev/null @@ -1,74 +0,0 @@ -import MachOKit -import MachOSwiftSection -@_spi(Internals) import Demangling -@_spi(Internals) import SwiftInspection - -extension ResolvedTypeReference { - package func node(in machO: some MachOSwiftSectionRepresentableWithCache) throws -> Node? { - switch self { - case .directTypeDescriptor(let descriptor): - return try descriptor.map { try SymbolicDemangler.demangleContext(for: $0, in: machO) } - case .indirectTypeDescriptor(let descriptor): - switch descriptor { - case .symbol(let symbol): - return try SymbolicDemangler.demangleType(for: symbol, in: machO) - case .element(let element): - return try SymbolicDemangler.demangleContext(for: element, in: machO) - case nil: - return nil - } - case .directObjCClassName(let objcClassName): - guard let objcClassName, !objcClassName.isEmpty else { return nil } - return Node.createTransient(kind: .type, children: [ - Node.createTransient(kind: .class, children: [ - .createTransient(kind: .module, text: objcModule), - .createTransient(kind: .identifier, text: objcClassName), - ]) - ]) - case .indirectObjCClass(let objcClass): - switch objcClass { - case .symbol(let symbol): - return try SymbolicDemangler.demangleType(for: symbol, in: machO) - case .element(let element): - guard let classDescriptor = try element.descriptor.resolve(in: machO) else { return nil } - return try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machO) - case nil: - return nil - } - } - } - - package func node() throws -> Node? { - switch self { - case .directTypeDescriptor(let descriptor): - return try descriptor.map { try SymbolicDemangler.demangleContext(for: $0) } - case .indirectTypeDescriptor(let descriptor): - switch descriptor { - case .symbol(let symbol): - return try SymbolicDemangler.demangleType(for: symbol) - case .element(let element): - return try SymbolicDemangler.demangleContext(for: element) - case nil: - return nil - } - case .directObjCClassName(let objcClassName): - guard let objcClassName, !objcClassName.isEmpty else { return nil } - return Node.createTransient(kind: .type, children: [ - Node.createTransient(kind: .class, children: [ - .createTransient(kind: .module, text: objcModule), - .createTransient(kind: .identifier, text: objcClassName), - ]) - ]) - case .indirectObjCClass(let objcClass): - switch objcClass { - case .symbol(let symbol): - return try SymbolicDemangler.demangleType(for: symbol) - case .element(let element): - guard let classDescriptor = try element.descriptor.resolve() else { return nil } - return try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor))) - case nil: - return nil - } - } - } -} diff --git a/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift b/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift deleted file mode 100644 index f6c43194a..000000000 --- a/Sources/SwiftDump/Dumpable/AssociatedType+Dumpable.swift +++ /dev/null @@ -1,23 +0,0 @@ -import Foundation -import MachOKit -import MachOSwiftSection -import MachOFoundation -import Semantic -import Utilities -import SwiftDeclarationRendering - -extension AssociatedType: ConformedDumpable { - public func dumpTypeName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await AssociatedTypeDumper(self, using: configuration, in: machO).typeName - } - - public func dumpProtocolName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await AssociatedTypeDumper(self, using: configuration, in: machO).protocolName - } - - public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await LargeStackTaskExecution.run { - try await AssociatedTypeDumper(self, using: configuration, in: machO).body - } - } -} diff --git a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift b/Sources/SwiftDump/Dumpable/Class+Dumpable.swift deleted file mode 100644 index d2c7b6851..000000000 --- a/Sources/SwiftDump/Dumpable/Class+Dumpable.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Semantic -import Demangling -import MachOKit -import MachOSwiftSection -import MachOFoundation -import Utilities -import SwiftDeclarationRendering - -extension Class: NamedDumpable { - public func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await ClassDumper(self, using: configuration, in: machO).name - } - - public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await LargeStackTaskExecution.run { - try await ClassDumper(self, using: configuration, in: machO).body - } - } -} diff --git a/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift b/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift deleted file mode 100644 index 022c7af45..000000000 --- a/Sources/SwiftDump/Dumpable/Enum+Dumpable.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation -import MachOKit -import MachOSwiftSection -import MachOFoundation -import Semantic -import Utilities -import SwiftDeclarationRendering - -extension Enum: NamedDumpable { - public func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await EnumDumper(self, using: configuration, in: machO).name - } - - public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await LargeStackTaskExecution.run { - try await EnumDumper(self, using: configuration, in: machO).body - } - } -} diff --git a/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift b/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift deleted file mode 100644 index 45c4c51b9..000000000 --- a/Sources/SwiftDump/Dumpable/Protocol+Dumpable.swift +++ /dev/null @@ -1,21 +0,0 @@ -import Foundation -import MachOKit -import MachOSwiftSection -import MachOFoundation -import Semantic -import Utilities -import Demangling -import SwiftDeclarationRendering -import OrderedCollections - -extension MachOSwiftSection.`Protocol`: NamedDumpable { - public func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await ProtocolDumper(self, using: configuration, in: machO).name - } - - public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await LargeStackTaskExecution.run { - try await ProtocolDumper(self, using: configuration, in: machO).body - } - } -} diff --git a/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift b/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift deleted file mode 100644 index 5fbed0b9d..000000000 --- a/Sources/SwiftDump/Dumpable/ProtocolConformance+Dumpable.swift +++ /dev/null @@ -1,25 +0,0 @@ -import Foundation -import MachOKit -import MachOSwiftSection -import MachOFoundation -import Semantic -import Demangling -import Utilities -import SwiftDeclarationRendering -import OrderedCollections - -extension ProtocolConformance: ConformedDumpable { - public func dumpTypeName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await ProtocolConformanceDumper(self, using: configuration, in: machO).typeName - } - - public func dumpProtocolName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await ProtocolConformanceDumper(self, using: configuration, in: machO).protocolName - } - - public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await LargeStackTaskExecution.run { - try await ProtocolConformanceDumper(self, using: configuration, in: machO).body - } - } -} diff --git a/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift b/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift deleted file mode 100644 index e909b11de..000000000 --- a/Sources/SwiftDump/Dumpable/Struct+Dumpable.swift +++ /dev/null @@ -1,19 +0,0 @@ -import Foundation -import MachOKit -import MachOSwiftSection -import MachOFoundation -import Semantic -import Utilities -import SwiftDeclarationRendering - -extension Struct: NamedDumpable { - public func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await StructDumper(self, using: configuration, in: machO).name - } - - public func dump(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString { - try await LargeStackTaskExecution.run { - try await StructDumper(self, using: configuration, in: machO).body - } - } -} diff --git a/Sources/SwiftDump/Protocols/ConformedDumpable.swift b/Sources/SwiftDump/Protocols/ConformedDumpable.swift deleted file mode 100644 index a4b9302c6..000000000 --- a/Sources/SwiftDump/Protocols/ConformedDumpable.swift +++ /dev/null @@ -1,9 +0,0 @@ -import MachOKit -import Semantic -import MachOSwiftSection -import SwiftDeclarationRendering - -public protocol ConformedDumpable: Dumpable { - func dumpTypeName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString - func dumpProtocolName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString -} diff --git a/Sources/SwiftDump/Protocols/NamedDumpable.swift b/Sources/SwiftDump/Protocols/NamedDumpable.swift deleted file mode 100644 index 61b4af607..000000000 --- a/Sources/SwiftDump/Protocols/NamedDumpable.swift +++ /dev/null @@ -1,8 +0,0 @@ -import MachOKit -import Semantic -import MachOSwiftSection -import SwiftDeclarationRendering - -public protocol NamedDumpable: Dumpable { - func dumpName(using configuration: DumperConfiguration, in machO: some MachOFieldLayoutRenderable) async throws -> SemanticString -} diff --git a/Sources/MachOFixtureSupport/Baseline/BaselineEmitter.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineEmitter.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/BaselineEmitter.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineEmitter.swift diff --git a/Sources/MachOFixtureSupport/Baseline/BaselineFixturePicker.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineFixturePicker.swift similarity index 93% rename from Sources/MachOFixtureSupport/Baseline/BaselineFixturePicker.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineFixturePicker.swift index b23c10ae8..69366747d 100644 --- a/Sources/MachOFixtureSupport/Baseline/BaselineFixturePicker.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineFixturePicker.swift @@ -17,7 +17,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "StructTest" + try descriptor.name(in: machO.context) == "StructTest" }) ) } @@ -31,7 +31,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "Decimal" && descriptor.isCImportedContextDescriptor(in: machO) + try descriptor.name(in: machO.context) == "Decimal" && descriptor.isCImportedContextDescriptor(in: machO.context) }) ) } @@ -44,7 +44,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "GenericStructNonRequirement" + try descriptor.name(in: machO.context) == "GenericStructNonRequirement" }) ) } @@ -60,7 +60,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "GenericStructLayoutRequirement" + try descriptor.name(in: machO.context) == "GenericStructLayoutRequirement" }) ) } @@ -76,7 +76,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "GenericStructSwiftProtocolRequirement" + try descriptor.name(in: machO.context) == "GenericStructSwiftProtocolRequirement" }) ) } @@ -92,7 +92,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "GenericStructObjCProtocolRequirement" + try descriptor.name(in: machO.context) == "GenericStructObjCProtocolRequirement" }) ) } @@ -108,7 +108,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "SameTypeRequirementTest" + try descriptor.name(in: machO.context) == "SameTypeRequirementTest" }) ) } @@ -123,7 +123,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "ParameterPackRequirementTest" + try descriptor.name(in: machO.context) == "ParameterPackRequirementTest" }) ) } @@ -141,7 +141,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "InvertibleProtocolRequirementTest" + try descriptor.name(in: machO.context) == "InvertibleProtocolRequirementTest" }) ) } @@ -157,7 +157,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "BaseClassRequirementTest" + try descriptor.name(in: machO.context) == "BaseClassRequirementTest" }) ) } @@ -172,13 +172,13 @@ package enum BaselineFixturePicker { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> AnonymousContextDescriptor { for typeDescriptor in try machO.swift.contextDescriptors { - var current: SymbolOrElement? = try typeDescriptor.parent(in: machO) + var current: SymbolOrElement? = try typeDescriptor.parent(in: machO.context) while let cursor = current { if let resolved = cursor.resolved { if let anonymous = resolved.anonymousContextDescriptor { return anonymous } - current = try resolved.parent(in: machO) + current = try resolved.parent(in: machO.context) } else { current = nil } @@ -196,14 +196,14 @@ package enum BaselineFixturePicker { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> ModuleContextDescriptor { for typeDescriptor in try machO.swift.contextDescriptors { - var current: SymbolOrElement? = try typeDescriptor.parent(in: machO) + var current: SymbolOrElement? = try typeDescriptor.parent(in: machO.context) while let cursor = current { if let resolved = cursor.resolved { if let module = resolved.moduleContextDescriptor, - try module.name(in: machO) == "SymbolTestsCore" { + try module.name(in: machO.context) == "SymbolTestsCore" { return module } - current = try resolved.parent(in: machO) + current = try resolved.parent(in: machO.context) } else { current = nil } @@ -223,13 +223,13 @@ package enum BaselineFixturePicker { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> ExtensionContextDescriptor { for typeDescriptor in try machO.swift.contextDescriptors { - var current: SymbolOrElement? = try typeDescriptor.parent(in: machO) + var current: SymbolOrElement? = try typeDescriptor.parent(in: machO.context) while let cursor = current { if let resolved = cursor.resolved { if let ext = resolved.extensionContextDescriptor { return ext } - current = try resolved.parent(in: machO) + current = try resolved.parent(in: machO.context) } else { current = nil } @@ -247,7 +247,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "ClassTest" + try descriptor.name(in: machO.context) == "ClassTest" }) ) } @@ -262,7 +262,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "VTableBaseTest" + try descriptor.name(in: machO.context) == "VTableBaseTest" }) ) } @@ -275,7 +275,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "SubclassTest" + try descriptor.name(in: machO.context) == "SubclassTest" }) ) } @@ -289,7 +289,7 @@ package enum BaselineFixturePicker { ) throws -> EnumDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.enum).first(where: { descriptor in - try descriptor.name(in: machO) == "NoPayloadEnumTest" + try descriptor.name(in: machO.context) == "NoPayloadEnumTest" }) ) } @@ -303,7 +303,7 @@ package enum BaselineFixturePicker { ) throws -> EnumDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.enum).first(where: { descriptor in - try descriptor.name(in: machO) == "SinglePayloadEnumTest" + try descriptor.name(in: machO.context) == "SinglePayloadEnumTest" }) ) } @@ -318,7 +318,7 @@ package enum BaselineFixturePicker { ) throws -> EnumDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.enum).first(where: { descriptor in - try descriptor.name(in: machO) == "MultiPayloadEnumTests" + try descriptor.name(in: machO.context) == "MultiPayloadEnumTests" }) ) } @@ -340,7 +340,7 @@ package enum BaselineFixturePicker { let targetOffset = enumDescriptor.offset return try required( try machO.swift.multiPayloadEnumDescriptors.first(where: { descriptor in - let mangledName = try descriptor.mangledTypeName(in: machO) + let mangledName = try descriptor.mangledTypeName(in: machO.context) for lookup in mangledName.lookupElements { guard case .relative(let relative) = lookup.reference else { continue } let resolvedOffset = lookup.offset + Int(relative.relativeOffset) @@ -363,7 +363,7 @@ package enum BaselineFixturePicker { ) throws -> ProtocolDescriptor { try required( try machO.swift.protocolDescriptors.first(where: { descriptor in - try descriptor.name(in: machO) == "ProtocolTest" + try descriptor.name(in: machO.context) == "ProtocolTest" }) ) } @@ -378,7 +378,7 @@ package enum BaselineFixturePicker { ) throws -> ProtocolDescriptor { try required( try machO.swift.protocolDescriptors.first(where: { descriptor in - try descriptor.name(in: machO) == "ProtocolWitnessTableTest" + try descriptor.name(in: machO.context) == "ProtocolWitnessTableTest" }) ) } @@ -393,7 +393,7 @@ package enum BaselineFixturePicker { ) throws -> ProtocolDescriptor { try required( try machO.swift.protocolDescriptors.first(where: { descriptor in - try descriptor.name(in: machO) == "BasicDefaultProtocol" + try descriptor.name(in: machO.context) == "BasicDefaultProtocol" }) ) } @@ -407,7 +407,7 @@ package enum BaselineFixturePicker { ) throws -> ProtocolDescriptor { try required( try machO.swift.protocolDescriptors.first(where: { descriptor in - try descriptor.name(in: machO) == "BaseProtocolTest" + try descriptor.name(in: machO.context) == "BaseProtocolTest" }) ) } @@ -549,7 +549,7 @@ package enum BaselineFixturePicker { ) throws -> String? { guard let protocolReference = conformance.protocol else { return nil } guard case .element(let descriptor) = protocolReference else { return nil } - return try descriptor.name(in: machO) + return try descriptor.name(in: machO.context) } /// Helper: extract the conforming-type-descriptor name from a @@ -562,7 +562,7 @@ package enum BaselineFixturePicker { switch conformance.typeReference { case .directTypeDescriptor(let wrapper): guard let wrapper else { return nil } - return try wrapper.namedContextDescriptor?.name(in: machO) + return try wrapper.namedContextDescriptor?.name(in: machO.context) case .indirectTypeDescriptor: return nil case .directObjCClassName: @@ -585,10 +585,10 @@ package enum BaselineFixturePicker { ) throws -> ObjCProtocolPrefix { let inheritingProtoDescriptor = try required( try machO.swift.protocolDescriptors.first(where: { descriptor in - try descriptor.name(in: machO) == "ObjCInheritingProtocolTest" + try descriptor.name(in: machO.context) == "ObjCInheritingProtocolTest" }) ) - let protocolType = try `Protocol`(descriptor: inheritingProtoDescriptor, in: machO) + let protocolType = try `Protocol`(descriptor: inheritingProtoDescriptor, in: machO.context) for requirementInSignature in protocolType.requirementInSignatures { if case .protocol(let symbolOrElement) = requirementInSignature.content, case .element(let descriptorWithObjCInterop) = symbolOrElement, @@ -626,7 +626,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "ResilientChild" + try descriptor.name(in: machO.context) == "ResilientChild" }) ) } @@ -645,7 +645,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "ObjCBridge" + try descriptor.name(in: machO.context) == "ObjCBridge" }) ) } @@ -661,7 +661,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "ObjCBridgeWithProto" + try descriptor.name(in: machO.context) == "ObjCBridgeWithProto" }) ) } @@ -682,7 +682,7 @@ package enum BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "ResilientObjCStubChild" + try descriptor.name(in: machO.context) == "ResilientObjCStubChild" }) ) } @@ -710,13 +710,13 @@ package enum BaselineFixturePicker { ) throws -> AssociatedTypeDescriptor { let conformingDescriptor = try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "ConcreteWitnessTest" + try descriptor.name(in: machO.context) == "ConcreteWitnessTest" }) ) let targetOffset = conformingDescriptor.offset return try required( try machO.swift.associatedTypeDescriptors.first(where: { descriptor in - let mangledName = try descriptor.conformingTypeName(in: machO) + let mangledName = try descriptor.conformingTypeName(in: machO.context) for lookup in mangledName.lookupElements { guard case .relative(let relative) = lookup.reference else { continue } let resolvedOffset = lookup.offset + Int(relative.relativeOffset) @@ -768,7 +768,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "InnerMostConstrainedTest" + try descriptor.name(in: machO.context) == "InnerMostConstrainedTest" }) ) } @@ -788,7 +788,7 @@ package enum BaselineFixturePicker { ) throws -> StructDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.struct).first(where: { descriptor in - try descriptor.name(in: machO) == "FixedSizeArray" + try descriptor.name(in: machO.context) == "FixedSizeArray" }) ) } @@ -870,7 +870,7 @@ extension BaselineFixturePicker { forSymbolNamed symbolName: String, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> PropertyDescriptor { - try PropertyDescriptor.resolve(from: offset(forSymbolNamed: symbolName, in: machO), in: machO) + try PropertyDescriptor.resolve(at: offset(forSymbolNamed: symbolName, in: machO), in: machO.context) } /// The module's shared trivial descriptor — header word zero, no body. @@ -937,7 +937,7 @@ extension BaselineFixturePicker { forSymbolNamed symbolName: String, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> AsyncFunctionPointer { - try AsyncFunctionPointer.resolve(from: offset(forSymbolNamed: symbolName, in: machO), in: machO) + try AsyncFunctionPointer.resolve(at: offset(forSymbolNamed: symbolName, in: machO), in: machO.context) } /// A top-level `async` function's record. @@ -980,7 +980,7 @@ extension BaselineFixturePicker { ) throws -> AccessibleFunctionRecord { try required( try accessibleFunctionRecords(in: machO).first(where: { record in - try record.name(in: machO).contains("remoteMethod") && record.resolvedDirectOffset(from: \.genericEnvironment) == nil + try record.name(in: machO.context).contains("remoteMethod") && record.resolvedDirectOffset(from: \.genericEnvironment) == nil }) ) } @@ -1048,7 +1048,7 @@ extension BaselineFixturePicker { ) throws -> ClassDescriptor { try required( try machO.swift.typeContextDescriptors.compactMap(\.class).first(where: { descriptor in - try descriptor.name(in: machO) == "GenericClassNonRequirement" + try descriptor.name(in: machO.context) == "GenericClassNonRequirement" }) ) } @@ -1060,9 +1060,9 @@ extension BaselineFixturePicker { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> GenericValueMetadataPattern { let descriptor = try struct_GenericStructNonRequirement(in: machO) - let genericContext = try required(try descriptor.typeGenericContext(in: machO)) + let genericContext = try required(try descriptor.typeGenericContext(in: machO.context)) let patternOffset = try required(genericContext.header.resolvedDirectOffset(from: \.defaultInstantiationPattern)) - return try GenericValueMetadataPattern.resolve(from: patternOffset, in: machO) + return try GenericValueMetadataPattern.resolve(at: patternOffset, in: machO.context) } /// The class metadata pattern of `GenericClassNonRequirement`, reached @@ -1071,9 +1071,9 @@ extension BaselineFixturePicker { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> GenericClassMetadataPattern { let descriptor = try class_GenericClassNonRequirement(in: machO) - let genericContext = try required(try descriptor.typeGenericContext(in: machO)) + let genericContext = try required(try descriptor.typeGenericContext(in: machO.context)) let patternOffset = try required(genericContext.header.resolvedDirectOffset(from: \.defaultInstantiationPattern)) - return try GenericClassMetadataPattern.resolve(from: patternOffset, in: machO) + return try GenericClassMetadataPattern.resolve(at: patternOffset, in: machO.context) } /// The resilient class pattern of `ResilientClassFixtures.ResilientChild` @@ -1084,9 +1084,9 @@ extension BaselineFixturePicker { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> ResilientClassMetadataPattern { let descriptor = try class_ResilientChild(in: machO) - let resilientChild = try Class(descriptor: descriptor, in: machO) + let resilientChild = try Class(descriptor: descriptor, in: machO.context) let initialization = try required(resilientChild.singletonMetadataInitialization) let patternOffset = try required(initialization.resolvedDirectOffset(from: \.incompleteMetadata)) - return try ResilientClassMetadataPattern.resolve(from: patternOffset, in: machO) + return try ResilientClassMetadataPattern.resolve(at: patternOffset, in: machO.context) } } diff --git a/Sources/MachOFixtureSupport/Baseline/BaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/BaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/BaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift index de1e7cb54..b401fc8ed 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AccessibleFunction/AccessibleFunctionRecordBaselineGenerator.swift @@ -79,12 +79,12 @@ package enum AccessibleFunctionRecordBaselineGenerator { let expr: ExprSyntax = """ Entry( offset: \(raw: BaselineEmitter.hex(record.offset)), - name: \(literal: try record.name(in: machO)), + name: \(literal: try record.name(in: machO.context)), functionOffset: \(raw: BaselineEmitter.optionalHex(record.resolvedDirectOffset(from: \.function))), genericEnvironmentOffset: \(raw: BaselineEmitter.optionalHex(record.resolvedDirectOffset(from: \.genericEnvironment))), flagsRawValue: \(raw: BaselineEmitter.hex(record.flags.rawValue)), isDistributed: \(literal: record.isDistributed), - hasFunctionType: \(literal: !(try record.functionType(in: machO).isEmpty)) + hasFunctionType: \(literal: !(try record.functionType(in: machO.context).isEmpty)) ) """ return expr.description diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift index 8fd04b68a..06506a13b 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextBaselineGenerator.swift @@ -19,7 +19,7 @@ package enum AnonymousContextBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.anonymous_first(in: machO) - let context = try AnonymousContext(descriptor: descriptor, in: machO) + let context = try AnonymousContext(descriptor: descriptor, in: machO.context) let entryExpr = emitEntryExpr(for: context) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AnonymousContextDescriptorProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift index 85a889e4d..b5a94d982 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeBaselineGenerator.swift @@ -25,7 +25,7 @@ package enum AssociatedTypeBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machO) - let associatedType = try AssociatedType(descriptor: descriptor, in: machO) + let associatedType = try AssociatedType(descriptor: descriptor, in: machO.context) let entryExpr = emitEntryExpr(for: associatedType) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift index 527287966..9ffa49018 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeDescriptorBaselineGenerator.swift @@ -85,10 +85,10 @@ package enum AssociatedTypeDescriptorBaselineGenerator { let layoutNumAssociatedTypes = descriptor.layout.numAssociatedTypes let layoutAssociatedTypeRecordSize = descriptor.layout.associatedTypeRecordSize let actualSize = descriptor.actualSize - let records = try descriptor.associatedTypeRecords(in: machO) + let records = try descriptor.associatedTypeRecords(in: machO.context) let recordsCount = records.count - let hasConformingTypeName = (try? descriptor.conformingTypeName(in: machO)) != nil - let hasProtocolTypeName = (try? descriptor.protocolTypeName(in: machO)) != nil + let hasConformingTypeName = (try? descriptor.conformingTypeName(in: machO.context)) != nil + let hasProtocolTypeName = (try? descriptor.protocolTypeName(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift index 5be1841e8..fa67ea943 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/AssociatedType/AssociatedTypeRecordBaselineGenerator.swift @@ -23,7 +23,7 @@ package enum AssociatedTypeRecordBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machO) - let records = try descriptor.associatedTypeRecords(in: machO) + let records = try descriptor.associatedTypeRecords(in: machO.context) let firstRecord = try required(records.first) let entryExpr = try emitEntryExpr(for: firstRecord, in: machO) @@ -77,8 +77,8 @@ package enum AssociatedTypeRecordBaselineGenerator { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { let offset = record.offset - let name = try record.name(in: machO) - let hasSubstitutedTypeName = (try? record.substitutedTypeName(in: machO)) != nil + let name = try record.name(in: machO.context) + let hasSubstitutedTypeName = (try? record.substitutedTypeName(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift index 04cfa7b5a..ebd29db0e 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeBaselineGenerator.swift @@ -16,7 +16,7 @@ package enum BuiltinTypeBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machO) - let builtin = try BuiltinType(descriptor: descriptor, in: machO) + let builtin = try BuiltinType(descriptor: descriptor, in: machO.context) let entryExpr = emitEntryExpr(for: builtin) // Public members declared in BuiltinType.swift. The two MachO diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/BuiltinType/BuiltinTypeDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift index f2885eedc..2f425f37f 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureDescriptorBaselineGenerator.swift @@ -77,8 +77,8 @@ package enum CaptureDescriptorBaselineGenerator { for descriptor: CaptureDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { - let mangledMetadataSources = try descriptor.metadataSourceRecords(in: machO).map { - try $0.mangledMetadataSource(in: machO).rawString + let mangledMetadataSources = try descriptor.metadataSourceRecords(in: machO.context).map { + try $0.mangledMetadataSource(in: machO.context).rawString } let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureFixtureDescriptors.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureFixtureDescriptors.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureFixtureDescriptors.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureFixtureDescriptors.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift index 6ec8006bc..75fae01cf 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/CaptureTypeRecordBaselineGenerator.swift @@ -31,11 +31,11 @@ package enum CaptureTypeRecordBaselineGenerator { """ let entries = try descriptors.all.map { descriptor -> String in - let record = try descriptor.captureTypeRecords(in: machO)[0] + let record = try descriptor.captureTypeRecords(in: machO.context)[0] let expr: ExprSyntax = """ Entry( offset: \(raw: BaselineEmitter.hex(record.offset)), - hasMangledTypeName: \(literal: !(try record.mangledTypeName(in: machO).isEmpty)) + hasMangledTypeName: \(literal: !(try record.mangledTypeName(in: machO.context).isEmpty)) ) """ return expr.description diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift similarity index 94% rename from Sources/MachOFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift index a22aa6e00..fe6b8de95 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Capture/MetadataSourceRecordBaselineGenerator.swift @@ -29,12 +29,12 @@ package enum MetadataSourceRecordBaselineGenerator { // unparsed recipe for recovering it. """ - let entries = try descriptor.metadataSourceRecords(in: machO).map { record -> String in + let entries = try descriptor.metadataSourceRecords(in: machO.context).map { record -> String in let expr: ExprSyntax = """ Entry( offset: \(raw: BaselineEmitter.hex(record.offset)), - mangledTypeName: \(literal: try record.mangledTypeName(in: machO).rawString), - mangledMetadataSource: \(literal: try record.mangledMetadataSource(in: machO).rawString) + mangledTypeName: \(literal: try record.mangledTypeName(in: machO.context).rawString), + mangledMetadataSource: \(literal: try record.mangledMetadataSource(in: machO.context).rawString) ) """ return expr.description diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataObjCInteropProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/AnyClassMetadataProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift index 0388759c9..00ee8546a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassBaselineGenerator.swift @@ -25,8 +25,8 @@ package enum ClassBaselineGenerator { let classTestDescriptor = try BaselineFixturePicker.class_ClassTest(in: machO) let subclassTestDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machO) - let classTestClass = try Class(descriptor: classTestDescriptor, in: machO) - let subclassTestClass = try Class(descriptor: subclassTestDescriptor, in: machO) + let classTestClass = try Class(descriptor: classTestDescriptor, in: machO.context) + let subclassTestClass = try Class(descriptor: subclassTestDescriptor, in: machO.context) let classTestExpr = emitEntryExpr(for: classTestClass) let subclassTestExpr = emitEntryExpr(for: subclassTestClass) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift index 9952f9157..920da1f2d 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassDescriptorBaselineGenerator.swift @@ -112,7 +112,7 @@ package enum ClassDescriptorBaselineGenerator { let hasResilientSuperclass = descriptor.hasResilientSuperclass let areImmediateMembersNegative = descriptor.areImmediateMembersNegative let hasObjCResilientClassStub = descriptor.hasObjCResilientClassStub - let hasSuperclassTypeMangledName = (try descriptor.superclassTypeMangledName(in: machO)) != nil + let hasSuperclassTypeMangledName = (try descriptor.superclassTypeMangledName(in: machO.context)) != nil let immediateMemberSize = UInt(descriptor.immediateMemberSize) let nonResilientImmediateMembersOffset = descriptor.nonResilientImmediateMembersOffset diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataBoundsProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ClassMetadataObjCInteropBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ExtraClassDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/FinalClassMetadataProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDefaultOverrideTableHeaderBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift index 6290a735b..ddb55de3f 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorBaselineGenerator.swift @@ -17,7 +17,7 @@ package enum MethodDescriptorBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let firstMethod = try required(classWrapper.methodDescriptors.first) let entryExpr = emitEntryExpr(for: firstMethod) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift index 5bf497a60..45f01c529 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorFlagsBaselineGenerator.swift @@ -17,7 +17,7 @@ package enum MethodDescriptorFlagsBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let firstMethod = try required(classWrapper.methodDescriptors.first) let flags = firstMethod.layout.flags diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodDescriptorKindBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift index a8a84fa27..3a78ee4ed 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/MethodOverrideDescriptorBaselineGenerator.swift @@ -19,7 +19,7 @@ package enum MethodOverrideDescriptorBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.class_SubclassTest(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let firstOverride = try required(classWrapper.methodOverrideDescriptors.first) let entryExpr = emitEntryExpr(for: firstOverride) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ObjCClassWrapperMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift index 431d7bc9d..4215421a6 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ObjCResilientClassStubInfoBaselineGenerator.swift @@ -33,7 +33,7 @@ package enum ObjCResilientClassStubInfoBaselineGenerator { ] let descriptor = try BaselineFixturePicker.class_ResilientObjCStubChild(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let stubInfo = try required(classWrapper.objcResilientClassStubInfo) let header = """ diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift index 2fdc9a5f9..d0a0cdd33 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/OverrideTableHeaderBaselineGenerator.swift @@ -16,7 +16,7 @@ package enum OverrideTableHeaderBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.class_SubclassTest(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let header = try required(classWrapper.overrideTableHeader) let entryExpr = emitEntryExpr(for: header) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift index 3c97a3158..5073a291a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/ResilientSuperclassBaselineGenerator.swift @@ -27,7 +27,7 @@ package enum ResilientSuperclassBaselineGenerator { ] let descriptor = try BaselineFixturePicker.class_ResilientChild(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let resilientSuperclass = try required(classWrapper.resilientSuperclass) let header = """ diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/StoredClassMetadataBoundsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift index 52b3401d9..34812f88d 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Class/VTableDescriptorHeaderBaselineGenerator.swift @@ -16,7 +16,7 @@ package enum VTableDescriptorHeaderBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) let header = try required(classWrapper.vTableDescriptorHeader) let entryExpr = emitEntryExpr(for: header) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorKindSpecificFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift index 9cbb95d2a..98bb1b2c7 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorProtocolBaselineGenerator.swift @@ -23,10 +23,10 @@ package enum ContextDescriptorProtocolBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machO) - let hasParent = (try descriptor.parent(in: machO)) != nil - let hasGenericContext = try descriptor.genericContext(in: machO) != nil - let hasModuleContextDescriptor = try descriptor.moduleContextDescriptor(in: machO) != nil - let isCImported = try descriptor.isCImportedContextDescriptor(in: machO) + let hasParent = (try descriptor.parent(in: machO.context)) != nil + let hasGenericContext = try descriptor.genericContext(in: machO.context) != nil + let hasModuleContextDescriptor = try descriptor.moduleContextDescriptor(in: machO.context) != nil + let isCImported = try descriptor.isCImportedContextDescriptor(in: machO.context) // The dynamic-member subscript routes to `layout.flags`; pick a stable // scalar (`kind.rawValue`) to assert against. let subscriptKindRawValue = descriptor.kind.rawValue diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift index e62fc59c8..5c5c87b3a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextDescriptorWrapperBaselineGenerator.swift @@ -127,8 +127,8 @@ package enum ContextDescriptorWrapperBaselineGenerator { let hasTypeContextDescriptor = wrapper.typeContextDescriptor != nil let hasTypeContextDescriptorWrapper = wrapper.typeContextDescriptorWrapper != nil let hasNamedContextDescriptor = wrapper.namedContextDescriptor != nil - let hasParent = (try wrapper.parent(in: machO)) != nil - let hasGenericContext = (try wrapper.genericContext(in: machO)) != nil + let hasParent = (try wrapper.parent(in: machO.context)) != nil + let hasGenericContext = (try wrapper.genericContext(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift index 7c02fba31..6e86650a6 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextProtocolBaselineGenerator.swift @@ -20,8 +20,8 @@ package enum ContextProtocolBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machO) - let context = try Struct(descriptor: descriptor, in: machO) - let hasParent = (try context.parent(in: machO)) != nil + let context = try Struct(descriptor: descriptor, in: machO.context) + let hasParent = (try context.parent(in: machO.context)) != nil let entryExpr = emitEntryExpr(hasParent: hasParent) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift similarity index 95% rename from Sources/MachOFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift index cef7420ca..359a26bcd 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ContextWrapperBaselineGenerator.swift @@ -23,7 +23,7 @@ package enum ContextWrapperBaselineGenerator { ) throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machO) let descriptorWrapper = ContextDescriptorWrapper.type(.struct(descriptor)) - let wrapper = try ContextWrapper.forContextDescriptorWrapper(descriptorWrapper, in: machO) + let wrapper = try ContextWrapper.forContextDescriptorWrapper(descriptorWrapper, in: machO.context) let entryExpr = try emitEntryExpr(for: wrapper, in: machO) let registered = [ @@ -63,7 +63,7 @@ package enum ContextWrapperBaselineGenerator { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { let descriptorOffset = wrapper.context.descriptor.offset - let hasParent = (try wrapper.parent(in: machO)) != nil + let hasParent = (try wrapper.parent(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/DispatchClass/DispatchClassMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift index af38b9719..c53d60658 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumBaselineGenerator.swift @@ -25,7 +25,7 @@ package enum EnumBaselineGenerator { ) throws { let noPayloadDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machO) - let noPayloadEnum = try Enum(descriptor: noPayloadDescriptor, in: machO) + let noPayloadEnum = try Enum(descriptor: noPayloadDescriptor, in: machO.context) let noPayloadExpr = emitEntryExpr(for: noPayloadEnum) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumFunctionsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/EnumMetadataProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift index ae196e7b2..2bfe7be29 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Enum/MultiPayloadEnumDescriptorBaselineGenerator.swift @@ -98,7 +98,7 @@ package enum MultiPayloadEnumDescriptorBaselineGenerator { ) throws -> String { let offset = descriptor.offset let layoutSizeFlags = descriptor.layout.sizeFlags - let mangledTypeName = try descriptor.mangledTypeName(in: machO) + let mangledTypeName = try descriptor.mangledTypeName(in: machO.context) let mangledTypeNameRawString = mangledTypeName.rawString let contentsSizeInWord = descriptor.contentsSizeInWord let flags = descriptor.flags @@ -107,10 +107,10 @@ package enum MultiPayloadEnumDescriptorBaselineGenerator { let payloadSpareBitMaskByteCountIndex = descriptor.payloadSpareBitMaskByteCountIndex let payloadSpareBitsIndex = descriptor.payloadSpareBitsIndex let actualSize = descriptor.actualSize - let contentsCount = try descriptor.contents(in: machO).count - let payloadSpareBitsCount = try descriptor.payloadSpareBits(in: machO).count - let payloadSpareBitMaskByteOffset = try descriptor.payloadSpareBitMaskByteOffset(in: machO) - let payloadSpareBitMaskByteCount = try descriptor.payloadSpareBitMaskByteCount(in: machO) + let contentsCount = try descriptor.contents(in: machO.context).count + let payloadSpareBitsCount = try descriptor.payloadSpareBits(in: machO.context).count + let payloadSpareBitMaskByteOffset = try descriptor.payloadSpareBitMaskByteOffset(in: machO.context) + let payloadSpareBitMaskByteCount = try descriptor.payloadSpareBitMaskByteCount(in: machO.context) let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialMetatypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExistentialTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/ExtendedExistentialTypeShapeFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExistentialType/NonUniqueExtendedExistentialTypeShapeBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift index a6bbed3e8..f59387682 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextBaselineGenerator.swift @@ -18,7 +18,7 @@ package enum ExtensionContextBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.extension_first(in: machO) - let context = try ExtensionContext(descriptor: descriptor, in: machO) + let context = try ExtensionContext(descriptor: descriptor, in: machO.context) let entryExpr = emitEntryExpr(for: context) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift index a6879b249..132cb3808 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ExtensionContextDescriptorProtocolBaselineGenerator.swift @@ -25,7 +25,7 @@ package enum ExtensionContextDescriptorProtocolBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.extension_first(in: machO) - let hasExtendedContext = (try descriptor.extendedContext(in: machO)) != nil + let hasExtendedContext = (try descriptor.extendedContext(in: machO.context)) != nil let entryExpr = emitEntryExpr(hasExtendedContext: hasExtendedContext) // Public members declared in protocol extensions on diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift index cf88e3d7b..66873bf91 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldDescriptor/FieldDescriptorBaselineGenerator.swift @@ -31,10 +31,10 @@ package enum FieldDescriptorBaselineGenerator { outputDirectory: URL ) throws { let genericDescriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machO) - let genericFieldDescriptor = try required(try genericDescriptor.fieldDescriptor(in: machO)) + let genericFieldDescriptor = try required(try genericDescriptor.fieldDescriptor(in: machO.context)) let structTestDescriptor = try BaselineFixturePicker.struct_StructTest(in: machO) - let structTestFieldDescriptor = try required(try structTestDescriptor.fieldDescriptor(in: machO)) + let structTestFieldDescriptor = try required(try structTestDescriptor.fieldDescriptor(in: machO.context)) let genericExpr = try emitEntryExpr(for: genericFieldDescriptor, in: machO) let structTestExpr = try emitEntryExpr(for: structTestFieldDescriptor, in: machO) @@ -97,9 +97,9 @@ package enum FieldDescriptorBaselineGenerator { let kindRawValue = descriptor.layout.kind let layoutNumFields = Int(descriptor.layout.numFields) let layoutFieldRecordSize = Int(descriptor.layout.fieldRecordSize) - let records = try descriptor.records(in: machO) + let records = try descriptor.records(in: machO.context) let recordsCount = records.count - let hasMangledTypeName = (try? descriptor.mangledTypeName(in: machO)) != nil + let hasMangledTypeName = (try? descriptor.mangledTypeName(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift similarity index 95% rename from Sources/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift index f3a92abde..9615b8baf 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordBaselineGenerator.swift @@ -23,8 +23,8 @@ package enum FieldRecordBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machO) - let fieldDescriptor = try required(try descriptor.fieldDescriptor(in: machO)) - let records = try fieldDescriptor.records(in: machO) + let fieldDescriptor = try required(try descriptor.fieldDescriptor(in: machO.context)) + let records = try fieldDescriptor.records(in: machO.context) let firstRecord = try required(records.first) let secondRecord = try required(records.dropFirst().first) @@ -85,8 +85,8 @@ package enum FieldRecordBaselineGenerator { ) throws -> String { let offset = record.offset let layoutFlagsRawValue = record.layout.flags.rawValue - let fieldName = try record.fieldName(in: machO) - let hasMangledTypeName = (try? record.mangledTypeName(in: machO)) != nil + let fieldName = try record.fieldName(in: machO.context) + let hasMangledTypeName = (try? record.mangledTypeName(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FieldRecord/FieldRecordFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignClassMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ForeignType/ForeignReferenceTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Function/FunctionTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/FunctionPointer/AsyncFunctionPointerFixtureRecords.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift index a10d82ef7..428a1a16a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextBaselineGenerator.swift @@ -159,7 +159,7 @@ package enum GenericContextBaselineGenerator { for descriptor: StructDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> TypeGenericContext { - try required(try descriptor.typeGenericContext(in: machO)) + try required(try descriptor.typeGenericContext(in: machO.context)) } private static func emitEntryExpr( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift index c95258ad3..7587e6e28 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericContextDescriptorHeaderBaselineGenerator.swift @@ -72,15 +72,15 @@ package enum GenericContextDescriptorHeaderBaselineGenerator { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> GenericContextDescriptorHeader { for typeDescriptor in try machO.swift.contextDescriptors { - var current: SymbolOrElement? = try typeDescriptor.parent(in: machO) + var current: SymbolOrElement? = try typeDescriptor.parent(in: machO.context) while let cursor = current { if let resolved = cursor.resolved { if let ext = resolved.extensionContextDescriptor, ext.flags.isGeneric, - let context = try ext.genericContext(in: machO) { + let context = try ext.genericContext(in: machO.context) { return context.header } - current = try resolved.parent(in: machO) + current = try resolved.parent(in: machO.context) } else { current = nil } diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericEnvironmentFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift index 90b2c04c9..b36cca706 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeDescriptorBaselineGenerator.swift @@ -20,7 +20,7 @@ package enum GenericPackShapeDescriptorBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machO) - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) let pack = try required(context.typePacks.first) let entryExpr = emitEntryExpr(for: pack) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift index c858f1422..24555a724 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericPackShapeHeaderBaselineGenerator.swift @@ -19,7 +19,7 @@ package enum GenericPackShapeHeaderBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machO) - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) let header = try required(context.typePackHeader) let entryExpr = emitEntryExpr(for: header) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift index 7a05f1ca8..762c1c0d6 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericParamDescriptorBaselineGenerator.swift @@ -23,11 +23,11 @@ package enum GenericParamDescriptorBaselineGenerator { outputDirectory: URL ) throws { let layoutDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machO) - let layoutContext = try required(try layoutDescriptor.typeGenericContext(in: machO)) + let layoutContext = try required(try layoutDescriptor.typeGenericContext(in: machO.context)) let layoutParam = try required(layoutContext.parameters.first) let packDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machO) - let packContext = try required(try packDescriptor.typeGenericContext(in: machO)) + let packContext = try required(try packDescriptor.typeGenericContext(in: machO.context)) let packParam = try required(packContext.parameters.first) let layoutExpr = emitEntryExpr(for: layoutParam) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift index 2541fc0ca..e56f5449f 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementBaselineGenerator.swift @@ -96,9 +96,9 @@ package enum GenericRequirementBaselineGenerator { for descriptor: StructDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> GenericRequirement { - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) let firstRequirement = try required(context.currentRequirements.first) - return try GenericRequirement(descriptor: firstRequirement, in: machO) + return try GenericRequirement(descriptor: firstRequirement, in: machO.context) } private static func emitEntryExpr(for requirement: GenericRequirement) -> String { diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift index c0b42dfeb..586bb3c95 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementContentBaselineGenerator.swift @@ -26,7 +26,7 @@ package enum GenericRequirementContentBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machO) - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) // Look at the conditional invertible protocols requirements first; // fall back to scanning the regular requirements for the // invertedProtocols kind. diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift index 268099dc5..09376569a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementDescriptorBaselineGenerator.swift @@ -106,7 +106,7 @@ package enum GenericRequirementDescriptorBaselineGenerator { of descriptor: StructDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> GenericRequirementDescriptor { - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) return try required(context.currentRequirements.first) } diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericRequirementFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift index afbc80c89..1a6a31d21 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueDescriptorBaselineGenerator.swift @@ -20,7 +20,7 @@ package enum GenericValueDescriptorBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_FixedSizeArray(in: machO) - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) let value = try required(context.values.first) let entryExpr = emitEntryExpr(for: value) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift index 6982a3e75..2d191ce0e 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericValueHeaderBaselineGenerator.swift @@ -20,7 +20,7 @@ package enum GenericValueHeaderBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_FixedSizeArray(in: machO) - let context = try required(try descriptor.typeGenericContext(in: machO)) + let context = try required(try descriptor.typeGenericContext(in: machO.context)) let header = try required(context.valueHeader) let entryExpr = emitEntryExpr(for: header) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/GenericWitnessTableBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericClassMetadataPatternBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift index 5ce51147d..10f63df8e 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPartialPatternBaselineGenerator.swift @@ -14,7 +14,7 @@ package enum GenericMetadataPartialPatternBaselineGenerator { outputDirectory: URL ) throws { let classPattern = try GenericMetadataPatternFixtures(in: machO).classPattern - let partialPattern = try required(try classPattern.partialPatterns(in: machO).first) + let partialPattern = try required(try classPattern.partialPatterns(in: machO.context).first) let registered = ["layout", "offset"] diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternFixtures.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift index 6572be6f1..19e7d8a58 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericMetadataPatternProtocolBaselineGenerator.swift @@ -56,7 +56,7 @@ package enum GenericMetadataPatternProtocolBaselineGenerator { hasTrailingFlags: fixtures.valuePattern.hasTrailingFlags, partialPatternsOffset: fixtures.valuePattern.partialPatternsOffset, size: fixtures.valuePattern.size, - partialPatternCount: try fixtures.valuePattern.partialPatterns(in: machO).count + partialPatternCount: try fixtures.valuePattern.partialPatterns(in: machO.context).count ) let classEntry = emitEntry( offset: fixtures.classPattern.offset, @@ -65,7 +65,7 @@ package enum GenericMetadataPatternProtocolBaselineGenerator { hasTrailingFlags: fixtures.classPattern.hasTrailingFlags, partialPatternsOffset: fixtures.classPattern.partialPatternsOffset, size: fixtures.classPattern.size, - partialPatternCount: try fixtures.classPattern.partialPatterns(in: machO).count + partialPatternCount: try fixtures.classPattern.partialPatterns(in: machO.context).count ) let file: SourceFileSyntax = """ diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/GenericValueMetadataPatternBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/Pattern/ResilientClassMetadataPatternBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift index aadc79a2a..cf278df70 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Generic/TypeGenericContextDescriptorHeaderBaselineGenerator.swift @@ -19,7 +19,7 @@ package enum TypeGenericContextDescriptorHeaderBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machO) - let typeContext = try required(try descriptor.typeGenericContext(in: machO)) + let typeContext = try required(try descriptor.typeGenericContext(in: machO.context)) let header = typeContext.header let entryExpr = emitEntryExpr(for: header) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/GenericBoxHeapMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Heap/HeapLocalVariableMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComponentHeaderBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift index 30ebd55f2..aa576c0e4 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathComputedPropertyBodyBaselineGenerator.swift @@ -15,7 +15,7 @@ package enum KeyPathComputedPropertyBodyBaselineGenerator { outputDirectory: URL ) throws { let descriptors = try KeyPathFixtureDescriptors(in: machO) - let body = try required(descriptors.computedSettable.computedPropertyBody(in: machO)) + let body = try required(descriptors.computedSettable.computedPropertyBody(in: machO.context)) let registered = [ "getter", diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathFixtureDescriptors.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift index be2b20013..d9065b464 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/KeyPathStoredFieldOffsetBaselineGenerator.swift @@ -17,8 +17,8 @@ package enum KeyPathStoredFieldOffsetBaselineGenerator { outputDirectory: URL ) throws { let descriptors = try KeyPathFixtureDescriptors(in: machO) - let inlineOffset = try required(descriptors.inlineStoredOffset.storedFieldOffset(in: machO)) - let unresolvedOffset = try required(descriptors.unresolvedFieldOffset.storedFieldOffset(in: machO)) + let inlineOffset = try required(descriptors.inlineStoredOffset.storedFieldOffset(in: machO.context)) + let unresolvedOffset = try required(descriptors.unresolvedFieldOffset.storedFieldOffset(in: machO.context)) let registered = ["kind", "rawValue", "staticFieldOffset"] diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift index 78d8937b4..f652a1a8d 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/KeyPath/PropertyDescriptorBaselineGenerator.swift @@ -79,8 +79,8 @@ package enum PropertyDescriptorBaselineGenerator { for descriptor: PropertyDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { - let storedFieldOffset = try descriptor.storedFieldOffset(in: machO) - let computedBody = try descriptor.computedPropertyBody(in: machO) + let storedFieldOffset = try descriptor.storedFieldOffset(in: machO.context) + let computedBody = try descriptor.computedPropertyBody(in: machO.context) let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift index 070771079..9d7ee643c 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Mangling/MangledNameBaselineGenerator.swift @@ -24,7 +24,7 @@ package enum MangledNameBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machO) - let mangledName = try descriptor.mangledTypeName(in: machO) + let mangledName = try descriptor.mangledTypeName(in: machO.context) let entryExpr = emitEntryExpr(for: mangledName) // Public members declared in MangledName.swift. The three diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/BorrowTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadataAccessorsListEntryBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasCachingOnceTokenBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListCountBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/CanonicalSpecializedMetadatasListEntryBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FixedArrayTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/FullMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/HeapMetadataHeaderPrefixBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaseBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataHeaderBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/Headers/TypeMetadataLayoutPrefixBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataAccessorFunctionBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataBoundsProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/ForeignMetadataInitializationBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift index 985430337..544e4a45d 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataInitialization/SingletonMetadataInitializationBaselineGenerator.swift @@ -28,7 +28,7 @@ package enum SingletonMetadataInitializationBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.class_singletonMetadataInitFirst(in: machO) - let classObject = try Class(descriptor: descriptor, in: machO) + let classObject = try Class(descriptor: descriptor, in: machO.context) let initialization = try required(classObject.singletonMetadataInitialization) let entryExpr = emitEntryExpr(for: initialization, descriptorOffset: descriptor.offset) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataRequestBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataResponseBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetadataWrapperBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/MetatypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Metadata/SingletonMetadataPointerBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift index 0ac61e85c..62905b112 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextBaselineGenerator.swift @@ -17,7 +17,7 @@ package enum ModuleContextBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.module_SymbolTestsCore(in: machO) - let context = try ModuleContext(descriptor: descriptor, in: machO) + let context = try ModuleContext(descriptor: descriptor, in: machO.context) let entryExpr = emitEntryExpr(for: context) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ModuleContextDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift index 6002b78af..425696bce 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/NamedContextDescriptorProtocolBaselineGenerator.swift @@ -19,8 +19,8 @@ package enum NamedContextDescriptorProtocolBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machO) - let name = try descriptor.name(in: machO) - let hasMangledName = (try? descriptor.mangledName(in: machO)) != nil + let name = try descriptor.name(in: machO.context) + let hasMangledName = (try? descriptor.mangledName(in: machO.context)) != nil let entryExpr = emitEntryExpr(name: name, hasMangledName: hasMangledName) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/OpaqueType/OpaqueTypeDescriptorProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolSetBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/Invertible/InvertibleProtocolsRequirementCountBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift index 624535178..c3f81dd7e 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/ObjCProtocolPrefixBaselineGenerator.swift @@ -18,7 +18,7 @@ package enum ObjCProtocolPrefixBaselineGenerator { outputDirectory: URL ) throws { let prefix = try BaselineFixturePicker.objcProtocolPrefix_first(in: machO) - let name = try prefix.name(in: machO) + let name = try prefix.name(in: machO.context) let entryExpr = emitEntryExpr(offset: prefix.offset, name: name) // Public members declared directly in ObjCProtocolPrefix.swift. diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ObjC/RelativeObjCProtocolPrefixBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift index b8df424b6..b6b7f4649 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaseRequirementBaselineGenerator.swift @@ -18,7 +18,7 @@ package enum ProtocolBaseRequirementBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machO) - let protocolType = try `Protocol`(descriptor: descriptor, in: machO) + let protocolType = try `Protocol`(descriptor: descriptor, in: machO.context) let baseRequirement = try required(protocolType.baseRequirement) let entryExpr = emitEntryExpr(for: baseRequirement) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift index a95e2f057..15ef07b1b 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolBaselineGenerator.swift @@ -22,11 +22,11 @@ package enum ProtocolBaselineGenerator { outputDirectory: URL ) throws { let protocolTestDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machO) - let protocolTest = try `Protocol`(descriptor: protocolTestDescriptor, in: machO) + let protocolTest = try `Protocol`(descriptor: protocolTestDescriptor, in: machO.context) let protocolTestExpr = emitEntryExpr(for: protocolTest) let witnessTableTestDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machO) - let witnessTableTest = try `Protocol`(descriptor: witnessTableTestDescriptor, in: machO) + let witnessTableTest = try `Protocol`(descriptor: witnessTableTestDescriptor, in: machO.context) let witnessTableTestExpr = emitEntryExpr(for: witnessTableTest) // Public members declared directly in Protocol.swift (across the main diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolContextDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift index 175a3104f..36495331f 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorBaselineGenerator.swift @@ -71,7 +71,7 @@ package enum ProtocolDescriptorBaselineGenerator { let layoutNumRequirementsInSignature = descriptor.layout.numRequirementsInSignature let layoutNumRequirements = descriptor.layout.numRequirements let layoutFlagsRawValue = descriptor.layout.flags.rawValue - let associatedTypes = try descriptor.associatedTypes(in: machO) + let associatedTypes = try descriptor.associatedTypes(in: machO.context) let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift index 070d1413f..1c197e8fd 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolDescriptorRefBaselineGenerator.swift @@ -25,7 +25,7 @@ package enum ProtocolDescriptorRefBaselineGenerator { ) throws { let objcPrefix = try BaselineFixturePicker.objcProtocolPrefix_first(in: machO) let objcPrefixOffset = objcPrefix.offset - let objcName = try objcPrefix.name(in: machO) + let objcName = try objcPrefix.name(in: machO.context) let swiftEntryExpr = emitSyntheticEntryExpr(storage: 0xDEAD_BEEF_0000, isObjC: false) let objcEntryExpr = emitSyntheticEntryExpr(storage: 0xDEAD_BEEF_0001, isObjC: true) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift index 13b8621ae..512c3d4f5 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRecordBaselineGenerator.swift @@ -17,9 +17,9 @@ package enum ProtocolRecordBaselineGenerator { outputDirectory: URL ) throws { let record = try BaselineFixturePicker.protocolRecord_first(in: machO) - let resolvedDescriptor = try required(record.protocolDescriptor(in: machO)) + let resolvedDescriptor = try required(record.protocolDescriptor(in: machO.context)) let resolvedDescriptorOffset = resolvedDescriptor.offset - let resolvedDescriptorName = try resolvedDescriptor.name(in: machO) + let resolvedDescriptorName = try resolvedDescriptor.name(in: machO.context) let entryExpr = emitEntryExpr( recordOffset: record.offset, diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift index e54105039..dfc416b86 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementBaselineGenerator.swift @@ -32,13 +32,13 @@ package enum ProtocolRequirementBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machO) - let protocolType = try `Protocol`(descriptor: descriptor, in: machO) + let protocolType = try `Protocol`(descriptor: descriptor, in: machO.context) let firstRequirement = try required(protocolType.requirements.first) let firstRequirementExpr = try emitRequirementEntryExpr(for: firstRequirement, in: machO) let defaultedDescriptor = try BaselineFixturePicker.protocol_BasicDefaultProtocol(in: machO) - let defaultedProtocol = try `Protocol`(descriptor: defaultedDescriptor, in: machO) + let defaultedProtocol = try `Protocol`(descriptor: defaultedDescriptor, in: machO.context) let firstDefaultedRequirement = try required(defaultedProtocol.requirements.first { $0.layout.defaultImplementation.isValid }) let firstDefaultedRequirementExpr = try emitRequirementEntryExpr(for: firstDefaultedRequirement, in: machO) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift index 9250a4c4c..48f438dc7 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementFlagsBaselineGenerator.swift @@ -26,7 +26,7 @@ package enum ProtocolRequirementFlagsBaselineGenerator { outputDirectory: URL ) throws { let descriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machO) - let protocolType = try `Protocol`(descriptor: descriptor, in: machO) + let protocolType = try `Protocol`(descriptor: descriptor, in: machO.context) let firstRequirement = try required(protocolType.requirements.first) let liveFlags = firstRequirement.layout.flags diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolRequirementKindBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ProtocolWitnessTableBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift similarity index 79% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift index 0d857f7c2..7c5eb575a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessBaselineGenerator.swift @@ -14,8 +14,8 @@ import MachOFoundation /// Picker: the first `ProtocolConformance` from the fixture with a /// non-empty `resilientWitnesses` array. We pin the resolved offset of /// the first witness's `requirement(in:)` and its `implementationOffset` -/// (pure relative-pointer arithmetic). `implementationAddress(in:)` is a -/// MachO-only debug formatter (see `ResilientWitness.swift` doc-comment) +/// (pure relative-pointer arithmetic). `implementationAddressString(in:)` +/// is a Mach-O display helper (see `ResilientWitness.swift` doc-comment) /// — we register the name but do not assert on the live address string /// (it's a base-16 representation of an in-memory pointer). package enum ResilientWitnessBaselineGenerator { @@ -26,7 +26,7 @@ package enum ResilientWitnessBaselineGenerator { let conformance = try BaselineFixturePicker.protocolConformance_resilientWitnessFirst(in: machO) let firstWitness = try required(conformance.resilientWitnesses.first) - let requirement = try firstWitness.requirement(in: machO) + let requirement = try firstWitness.requirement(in: machO.context) let hasRequirement = requirement != nil let implementationOffset = firstWitness.implementationOffset @@ -37,14 +37,18 @@ package enum ResilientWitnessBaselineGenerator { ) // Public members declared directly in ResilientWitness.swift. - // The `requirement(in:)` overloads (MachO + InProcess + - // ReadingContext) collapse to a single MethodKey under the scanner's - // name-based deduplication, as do the two `implementationAddress(in:)` - // forms (the MachO-only debug formatter and the ReadingContext - // address). Symbol attribution (`implementationSymbols(in:)`) lives in - // SwiftInspection since evolution proposal `self-contained-abi-layer`. + // The `requirement(in:)` overloads (the ReadingContext form and its + // deprecated Mach-O and pointer forwarders) collapse to a single + // MethodKey under the scanner's name-based deduplication, as do the + // two `implementationAddress(in:)` forms (the ReadingContext address + // and the deprecated name of the display helper, which is + // `implementationAddressString(in:)` since evolution proposal + // `reading-context-migration`). Symbol attribution + // (`implementationSymbols(in:)`) lives in SwiftInspection since + // evolution proposal `self-contained-abi-layer`. let registered = [ "implementationAddress", + "implementationAddressString", "implementationOffset", "layout", "offset", diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Protocol/ResilientWitnessesHeaderBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift index cf3664367..a285da59a 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/GlobalActorReferenceBaselineGenerator.swift @@ -29,7 +29,7 @@ package enum GlobalActorReferenceBaselineGenerator { ) throws { let conformance = try BaselineFixturePicker.protocolConformance_globalActorFirst(in: machO) let reference = try required(conformance.globalActorReference) - let typeName = try reference.typeName(in: machO) + let typeName = try reference.typeName(in: machO.context) let entryExpr = emitEntryExpr(offset: reference.offset, typeNameString: typeName.symbolString) // Public members declared directly in GlobalActorReference.swift. diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift index 7e1837f75..9c13a17b5 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceDescriptorBaselineGenerator.swift @@ -80,9 +80,9 @@ package enum ProtocolConformanceDescriptorBaselineGenerator { let offset = descriptor.offset let layoutFlagsRawValue = descriptor.layout.flags.rawValue let typeReferenceKindRawValue = descriptor.layout.flags.typeReferenceKind.rawValue - let hasProtocolDescriptor = (try descriptor.protocolDescriptor(in: machO)) != nil - let hasWitnessTablePattern = (try descriptor.witnessTablePattern(in: machO)) != nil - let resolvedTypeReference = try descriptor.resolvedTypeReference(in: machO) + 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) let isDirectTypeDescriptor: Bool if case .directTypeDescriptor = resolvedTypeReference { isDirectTypeDescriptor = true diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ProtocolConformance/ProtocolConformanceFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift index 29b6ef033..43edcf2ec 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructBaselineGenerator.swift @@ -35,8 +35,8 @@ package enum StructBaselineGenerator { let structTestDescriptor = try BaselineFixturePicker.struct_StructTest(in: machO) let genericStructDescriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machO) - let structTestStruct = try Struct(descriptor: structTestDescriptor, in: machO) - let genericStructStruct = try Struct(descriptor: genericStructDescriptor, in: machO) + let structTestStruct = try Struct(descriptor: structTestDescriptor, in: machO.context) + let genericStructStruct = try Struct(descriptor: genericStructDescriptor, in: machO.context) let structTestExpr = emitEntryExpr(for: structTestStruct) let genericStructExpr = emitEntryExpr(for: genericStructStruct) diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructDescriptorBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/StructMetadataProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/TupleType/TupleTypeMetadataElementBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift index 45de4d815..b36b9b345 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorBaselineGenerator.swift @@ -79,9 +79,9 @@ package enum TypeContextDescriptorBaselineGenerator { ) throws -> String { let offset = descriptor.offset let flagsRaw = descriptor.layout.flags.rawValue - let hasEnumDescriptor = (try descriptor.enumDescriptor(in: machO)) != nil - let hasStructDescriptor = (try descriptor.structDescriptor(in: machO)) != nil - let hasClassDescriptor = (try descriptor.classDescriptor(in: machO)) != nil + let hasEnumDescriptor = (try descriptor.enumDescriptor(in: machO.context)) != nil + let hasStructDescriptor = (try descriptor.structDescriptor(in: machO.context)) != nil + let hasClassDescriptor = (try descriptor.classDescriptor(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift index 5e752bcf2..03f786fd0 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorProtocolBaselineGenerator.swift @@ -106,9 +106,9 @@ package enum TypeContextDescriptorProtocolBaselineGenerator { for descriptor: StructDescriptor, in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { - let hasFieldDescriptor = (try? descriptor.fieldDescriptor(in: machO)) != nil - let hasGenericContext = (try descriptor.genericContext(in: machO)) != nil - let hasTypeGenericContext = (try descriptor.typeGenericContext(in: machO)) != nil + let hasFieldDescriptor = (try? descriptor.fieldDescriptor(in: machO.context)) != nil + let hasGenericContext = (try descriptor.genericContext(in: machO.context)) != nil + let hasTypeGenericContext = (try descriptor.typeGenericContext(in: machO.context)) != nil let hasSingletonMetadataInitialization = descriptor.hasSingletonMetadataInitialization let hasForeignMetadataInitialization = descriptor.hasForeignMetadataInitialization let hasImportInfo = descriptor.hasImportInfo @@ -116,7 +116,7 @@ package enum TypeContextDescriptorProtocolBaselineGenerator { let hasLayoutString = descriptor.hasLayoutString let hasCanonicalMetadataPrespecializations = descriptor.hasCanonicalMetadataPrespecializations let hasSingletonMetadataPointer = descriptor.hasSingletonMetadataPointer - let typeImportInfo = try descriptor.typeImportInfo(in: machO) + let typeImportInfo = try descriptor.typeImportInfo(in: machO.context) let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift similarity index 96% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift index e583c9eea..cf84721ec 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextDescriptorWrapperBaselineGenerator.swift @@ -76,9 +76,9 @@ package enum TypeContextDescriptorWrapperBaselineGenerator { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { let descriptorOffset = wrapper.contextDescriptor.offset - let hasParent = (try wrapper.parent(in: machO)) != nil - let hasGenericContext = (try wrapper.genericContext(in: machO)) != nil - let hasTypeGenericContext = (try wrapper.typeGenericContext(in: machO)) != nil + let hasParent = (try wrapper.parent(in: machO.context)) != nil + let hasGenericContext = (try wrapper.genericContext(in: machO.context)) != nil + let hasTypeGenericContext = (try wrapper.typeGenericContext(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift index 4a8b95a7e..a55c2a3c3 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeContextWrapperBaselineGenerator.swift @@ -27,7 +27,7 @@ package enum TypeContextWrapperBaselineGenerator { ) throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machO) let descriptorWrapper = TypeContextDescriptorWrapper.struct(descriptor) - let wrapper = try TypeContextWrapper.forTypeContextDescriptorWrapper(descriptorWrapper, in: machO) + let wrapper = try TypeContextWrapper.forTypeContextDescriptorWrapper(descriptorWrapper, in: machO.context) let entryExpr = emitEntryExpr(for: wrapper) let registered = [ diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift similarity index 98% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift index 3996f9b0f..59f12f124 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeMetadataRecordBaselineGenerator.swift @@ -90,7 +90,7 @@ package enum TypeMetadataRecordBaselineGenerator { numberOfElements: section.size / recordSize ) for record in records { - guard let resolved = try? record.contextDescriptor(in: machO) else { continue } + guard let resolved = try? record.contextDescriptor(in: machO.context) else { continue } if resolved.contextDescriptor.offset == targetOffset { return record } @@ -110,7 +110,7 @@ package enum TypeMetadataRecordBaselineGenerator { // directly; hex-as-zero-extended-UInt64 wouldn't compile. let layoutRelativeOffset = record.layout.nominalTypeDescriptor.relativeOffset let typeKindRawValue = record.typeKind.rawValue - let contextDescriptorOffset = try required(record.contextDescriptor(in: machO)).contextDescriptor.offset + let contextDescriptorOffset = try required(record.contextDescriptor(in: machO.context)).contextDescriptor.offset let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift similarity index 99% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift index 207ae5824..9b3b14abd 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/TypeReferenceBaselineGenerator.swift @@ -97,7 +97,7 @@ package enum TypeReferenceBaselineGenerator { numberOfElements: section.size / recordSize ) for record in records { - guard let resolved = try? record.contextDescriptor(in: machO) else { continue } + guard let resolved = try? record.contextDescriptor(in: machO.context) else { continue } if resolved.contextDescriptor.offset == targetOffset { return record } diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueMetadataProtocolBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift similarity index 97% rename from Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift index b7b731007..16b185d66 100644 --- a/Sources/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/Type/ValueTypeDescriptorWrapperBaselineGenerator.swift @@ -75,8 +75,8 @@ package enum ValueTypeDescriptorWrapperBaselineGenerator { in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> String { let descriptorOffset = wrapper.contextDescriptor.offset - let hasParent = (try wrapper.parent(in: machO)) != nil - let hasGenericContext = (try wrapper.genericContext(in: machO)) != nil + let hasParent = (try wrapper.parent(in: machO.context)) != nil + let hasGenericContext = (try wrapper.genericContext(in: machO.context)) != nil let expr: ExprSyntax = """ Entry( diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/TypeLayoutBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessFlagsBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift b/Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift similarity index 100% rename from Sources/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift rename to Sources/TestSupport/MachOFixtureSupport/Baseline/Generators/ValueWitnessTable/ValueWitnessTableBaselineGenerator.swift diff --git a/Sources/MachOFixtureSupport/Coverage/CoverageAllowlist.swift b/Sources/TestSupport/MachOFixtureSupport/Coverage/CoverageAllowlist.swift similarity index 100% rename from Sources/MachOFixtureSupport/Coverage/CoverageAllowlist.swift rename to Sources/TestSupport/MachOFixtureSupport/Coverage/CoverageAllowlist.swift diff --git a/Sources/MachOFixtureSupport/Coverage/FixtureSuite.swift b/Sources/TestSupport/MachOFixtureSupport/Coverage/FixtureSuite.swift similarity index 90% rename from Sources/MachOFixtureSupport/Coverage/FixtureSuite.swift rename to Sources/TestSupport/MachOFixtureSupport/Coverage/FixtureSuite.swift index 1c6a76933..435788969 100644 --- a/Sources/MachOFixtureSupport/Coverage/FixtureSuite.swift +++ b/Sources/TestSupport/MachOFixtureSupport/Coverage/FixtureSuite.swift @@ -5,7 +5,7 @@ import Foundation /// Each Suite type provides: /// - `testedTypeName`: the source-code Type whose public members the Suite covers /// (e.g. "StructDescriptor"). Must match the type name exactly as it appears in -/// `Sources/MachOSwiftSection/Models/`. +/// `Sources/ABI/MachOSwiftSection/Models/`. /// - `registeredTestMethodNames`: the member names covered by `@Test` methods in this Suite. /// For each entry "foo", the Coverage Invariant test expects a public member /// `.foo` (any overload group) to exist in the source. @@ -15,7 +15,7 @@ import Foundation /// Code iterating `[any FixtureSuite.Type]` (e.g., the Coverage Invariant Test in /// Task 16) must run on the main actor too. /// -/// **Suite inclusion rule:** Every Swift file under `Sources/MachOSwiftSection/Models/` +/// **Suite inclusion rule:** Every Swift file under `Sources/ABI/MachOSwiftSection/Models/` /// gets a corresponding `Tests.swift` Suite UNLESS: /// - The file declares only `*Layout` types (covered by LayoutTests). /// - The file declares only enums/flags/protocols with no public func/var/init. diff --git a/Sources/MachOFixtureSupport/Coverage/MethodKey.swift b/Sources/TestSupport/MachOFixtureSupport/Coverage/MethodKey.swift similarity index 100% rename from Sources/MachOFixtureSupport/Coverage/MethodKey.swift rename to Sources/TestSupport/MachOFixtureSupport/Coverage/MethodKey.swift diff --git a/Sources/MachOFixtureSupport/Coverage/PublicMemberScanner.swift b/Sources/TestSupport/MachOFixtureSupport/Coverage/PublicMemberScanner.swift similarity index 100% rename from Sources/MachOFixtureSupport/Coverage/PublicMemberScanner.swift rename to Sources/TestSupport/MachOFixtureSupport/Coverage/PublicMemberScanner.swift diff --git a/Sources/MachOFixtureSupport/Coverage/SuiteBehaviorScanner.swift b/Sources/TestSupport/MachOFixtureSupport/Coverage/SuiteBehaviorScanner.swift similarity index 100% rename from Sources/MachOFixtureSupport/Coverage/SuiteBehaviorScanner.swift rename to Sources/TestSupport/MachOFixtureSupport/Coverage/SuiteBehaviorScanner.swift diff --git a/Sources/MachOFixtureSupport/DemangleOptions.swift b/Sources/TestSupport/MachOFixtureSupport/DemangleOptions.swift similarity index 100% rename from Sources/MachOFixtureSupport/DemangleOptions.swift rename to Sources/TestSupport/MachOFixtureSupport/DemangleOptions.swift diff --git a/Sources/MachOFixtureSupport/DumpableTests.swift b/Sources/TestSupport/MachOFixtureSupport/DumpableTests.swift similarity index 91% rename from Sources/MachOFixtureSupport/DumpableTests.swift rename to Sources/TestSupport/MachOFixtureSupport/DumpableTests.swift index 52a086e7b..11dcb298f 100644 --- a/Sources/MachOFixtureSupport/DumpableTests.swift +++ b/Sources/TestSupport/MachOFixtureSupport/DumpableTests.swift @@ -46,7 +46,7 @@ extension DumpableTests { package func dumpProtocols(for machO: some MachOFieldLayoutRenderable) async throws { let protocolDescriptors = try machO.swift.protocolDescriptors for protocolDescriptor in protocolDescriptors { - try await Protocol(descriptor: protocolDescriptor, in: machO).dump(using: .test, in: machO).string.print() + try await Protocol(descriptor: protocolDescriptor, in: machO.context).dump(using: .test, in: machO).string.print() } } @@ -54,7 +54,7 @@ extension DumpableTests { let protocolConformanceDescriptors = try machO.swift.protocolConformanceDescriptors for protocolConformanceDescriptor in protocolConformanceDescriptors { - try await ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machO).dump(using: .test, in: machO).string.print() + try await ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machO.context).dump(using: .test, in: machO).string.print() } } @@ -66,7 +66,7 @@ extension DumpableTests { guard options.contains(.enum) else { continue } do { if isDetail { - let enumType = try Enum(descriptor: enumDescriptor, in: machO) + let enumType = try Enum(descriptor: enumDescriptor, in: machO.context) try await enumType.dump(using: configuration ?? .test, in: machO).string.print() } else { print(enumDescriptor) @@ -78,7 +78,7 @@ extension DumpableTests { guard options.contains(.struct) else { continue } do { if isDetail { - let structType = try Struct(descriptor: structDescriptor, in: machO) + let structType = try Struct(descriptor: structDescriptor, in: machO.context) try await structType.dump(using: configuration ?? .test, in: machO).string.print() } else { print(structDescriptor) @@ -90,7 +90,7 @@ extension DumpableTests { guard options.contains(.class) else { continue } do { if isDetail { - let classType = try Class(descriptor: classDescriptor, in: machO) + let classType = try Class(descriptor: classDescriptor, in: machO.context) try await classType.dump(using: configuration ?? .test, in: machO).string.print() } else { print(classDescriptor) @@ -108,9 +108,9 @@ extension DumpableTests { let symbols = symbolIndexStore.symbols(of: .opaqueTypeDescriptor, in: machO) for symbol in symbols where symbol.offset != 0 { let opaqueTypeDescriptor = try machO.readWrapperElement(offset: symbol.offset) as OpaqueTypeDescriptor - let opaqueType = try OpaqueType(descriptor: opaqueTypeDescriptor, in: machO) + let opaqueType = try OpaqueType(descriptor: opaqueTypeDescriptor, in: machO.context) for underlyingTypeArgumentMangledName in opaqueType.underlyingTypeArgumentMangledNames { - try await SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO).print(using: .interface).print() + try await SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO.context).print(using: .interface).print() } "-----".print() } @@ -119,14 +119,14 @@ extension DumpableTests { package func dumpAssociatedTypes(for machO: some MachOFieldLayoutRenderable) async throws { let associatedTypeDescriptors = try machO.swift.associatedTypeDescriptors for associatedTypeDescriptor in associatedTypeDescriptors { - try await AssociatedType(descriptor: associatedTypeDescriptor, in: machO).dump(using: .test, in: machO).string.print() + try await AssociatedType(descriptor: associatedTypeDescriptor, in: machO.context).dump(using: .test, in: machO).string.print() } } package func dumpBuiltinTypes(for machO: some MachOFieldLayoutRenderable) async throws { let descriptors = try machO.swift.builtinTypeDescriptors for descriptor in descriptors { - try print(BuiltinType(descriptor: descriptor, in: machO)) + try print(BuiltinType(descriptor: descriptor, in: machO.context)) } } } diff --git a/Sources/TestSupport/MachOFixtureSupport/DyldSharedCachePath.swift b/Sources/TestSupport/MachOFixtureSupport/DyldSharedCachePath.swift new file mode 100644 index 000000000..a9b811fb8 --- /dev/null +++ b/Sources/TestSupport/MachOFixtureSupport/DyldSharedCachePath.swift @@ -0,0 +1,56 @@ +/// A dyld shared cache file the tests open, and what a version axis calls it. +/// +/// A struct with static members rather than an enum, so that besides the +/// caches named below any archived cache can be named by its version: +/// `.macOS("26.6")`. Not `RawRepresentable`: every value carries a label, +/// which a path alone does not give. +package struct DyldSharedCachePath: Hashable, Sendable { + package let rawValue: String + + /// What a version axis calls this cache, such as the evolution dumps' + /// labels: the version an archived cache was named by, or the label a + /// named cache states. Not necessarily a system version — `current` is + /// labeled `current`. + package let versionLabel: String + + package init(rawValue: String, versionLabel: String) { + self.rawValue = rawValue + self.versionLabel = versionLabel + } + + /// The archived macOS cache of `version`, labeled `version`: + /// `/Volumes/DyldSharedCaches/macOS//dyld_shared_cache_arm64e`. + /// + /// `version` is the directory name on the volume (`26.5.2`, + /// `14.0(Internal)`). Whether that directory holds a cache is the + /// caller's to check; some hold only exported headers. + package static func macOS(_ version: String) -> DyldSharedCachePath { + archived(platformDirectoryName: "macOS", version: version) + } + + /// The archived iOS device cache of `version`, labeled `version`: + /// `/Volumes/DyldSharedCaches/iOS//dyld_shared_cache_arm64e`. + package static func iOS(_ version: String) -> DyldSharedCachePath { + archived(platformDirectoryName: "iOS", version: version) + } + + private static func archived(platformDirectoryName: String, version: String) -> DyldSharedCachePath { + DyldSharedCachePath( + rawValue: "/Volumes/DyldSharedCaches/\(platformDirectoryName)/\(version)/dyld_shared_cache_arm64e", + versionLabel: version + ) + } + + /// The running system's cache. + package static let current = DyldSharedCachePath(rawValue: "/System/Volumes/Preboot/Cryptexes/OS/System/Library/dyld/dyld_shared_cache_arm64e", versionLabel: "current") + package static let iOS_18_5 = DyldSharedCachePath(rawValue: "/Volumes/Generic/iOS Systems/22F76__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "18.5") + package static let iOS_26_1 = DyldSharedCachePath(rawValue: "/Volumes/Generic/iOS Systems/23B85__iPhone17,5/dyld_shared_cache_arm64e", versionLabel: "26.1") + package static let macOS_15_5 = macOS("15.5") + package static let macOS_26_5_1 = macOS("26.5.1") + package static let macOS_26_5_2 = macOS("26.5.2") + package static let macOS_27_0 = macOS("27.0") + /// From iOS 27 beta 3 on a simulator runtime ships its frameworks in a + /// cache of its own instead of as files under `RuntimeRoot`. The runtime's + /// volume is named after its build, so no version alone spells this path. + package static let iOS_27_0_Simulator = DyldSharedCachePath(rawValue: "/Library/Developer/CoreSimulator/Volumes/iOS_24A434/Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 27.0.simruntime/Contents/Resources/RuntimeRoot/System/Library/Caches/com.apple.dyld/dyld_sim_shared_cache_arm64", versionLabel: "27.0") +} diff --git a/Sources/MachOFixtureSupport/Extensions.swift b/Sources/TestSupport/MachOFixtureSupport/Extensions.swift similarity index 100% rename from Sources/MachOFixtureSupport/Extensions.swift rename to Sources/TestSupport/MachOFixtureSupport/Extensions.swift diff --git a/Sources/MachOFixtureSupport/FixtureLoadError.swift b/Sources/TestSupport/MachOFixtureSupport/FixtureLoadError.swift similarity index 100% rename from Sources/MachOFixtureSupport/FixtureLoadError.swift rename to Sources/TestSupport/MachOFixtureSupport/FixtureLoadError.swift diff --git a/Sources/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift b/Sources/TestSupport/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift similarity index 96% rename from Sources/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift rename to Sources/TestSupport/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift index 8912f7f82..2cf560d9b 100644 --- a/Sources/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift +++ b/Sources/TestSupport/MachOFixtureSupport/InProcess/InProcessMetadataPicker.swift @@ -240,14 +240,15 @@ extension InProcessMetadataPicker { }() /// Resolve a relative `MachOImageName` path (rooted at the package-relative - /// `../../Tests/...` convention used by `loadFromFile`) to an absolute path. + /// `../../../Tests/...` convention used by `loadFromFile`) to an absolute path. /// /// Caveat: `MachOImageName.SymbolTestsCore.rawValue` is rooted as if the - /// caller lives in `Sources//Foo.swift`, i.e. exactly two + /// caller lives in `Sources///Foo.swift`, i.e. exactly three /// `../` hops to reach the package root. This file lives one level deeper - /// in `Sources/MachOFixtureSupport/InProcess/`, so we anchor against - /// `Sources/MachOFixtureSupport/` (one path component up from `#filePath`'s - /// parent) to make the existing `../../...` rawValue resolve correctly. + /// in `Sources/TestSupport/MachOFixtureSupport/InProcess/`, so we anchor + /// against `Sources/TestSupport/MachOFixtureSupport/` (one path component up + /// from `#filePath`'s parent) to make the existing `../../../...` rawValue + /// resolve correctly. private static func resolveFixturePath(_ relativePath: String) -> String { if relativePath.hasPrefix("/") { return relativePath } let parentOfThisFile = URL(fileURLWithPath: #filePath).deletingLastPathComponent() diff --git a/Sources/MachOFixtureSupport/MachOFileName.swift b/Sources/TestSupport/MachOFixtureSupport/MachOFileName.swift similarity index 80% rename from Sources/MachOFixtureSupport/MachOFileName.swift rename to Sources/TestSupport/MachOFixtureSupport/MachOFileName.swift index d89f38fcb..089a173a4 100644 --- a/Sources/MachOFixtureSupport/MachOFileName.swift +++ b/Sources/TestSupport/MachOFixtureSupport/MachOFileName.swift @@ -17,11 +17,11 @@ package enum MachOFileName: String { case ControlCenter = "/System/Library/CoreServices/ControlCenter.app" case Freeform = "/System/Applications/Freeform.app" - 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" + 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" /// SymbolTestsCore's resilient-parent dependency. Kept OUT of the shared /// suites deliberately: `PerImageCacheEvictionTests` needs an image no /// concurrently-running suite touches, so its cache-membership /// assertions cannot race another suite's indexer lifecycle. - case SymbolTestsHelper = "../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsHelper.framework/Versions/A/SymbolTestsHelper" + case SymbolTestsHelper = "../../../Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsHelper.framework/Versions/A/SymbolTestsHelper" } diff --git a/Sources/MachOFixtureSupport/MachOImageName.swift b/Sources/TestSupport/MachOFixtureSupport/MachOImageName.swift similarity index 62% rename from Sources/MachOFixtureSupport/MachOImageName.swift rename to Sources/TestSupport/MachOFixtureSupport/MachOImageName.swift index 4360674bf..2641f86f2 100644 --- a/Sources/MachOFixtureSupport/MachOImageName.swift +++ b/Sources/TestSupport/MachOFixtureSupport/MachOImageName.swift @@ -21,8 +21,8 @@ package enum MachOImageName: String { 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" + 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" var path: String { "/\(rawValue)" diff --git a/Sources/MachOFixtureSupport/SnapshotDumpableTests.swift b/Sources/TestSupport/MachOFixtureSupport/SnapshotDumpableTests.swift similarity index 95% rename from Sources/MachOFixtureSupport/SnapshotDumpableTests.swift rename to Sources/TestSupport/MachOFixtureSupport/SnapshotDumpableTests.swift index 9a0ecbeed..f952c3c70 100644 --- a/Sources/MachOFixtureSupport/SnapshotDumpableTests.swift +++ b/Sources/TestSupport/MachOFixtureSupport/SnapshotDumpableTests.swift @@ -24,7 +24,7 @@ extension SnapshotDumpableTests { case .enum(let enumDescriptor): guard options.contains(.enum) else { continue } do { - let enumType = try Enum(descriptor: enumDescriptor, in: machO) + let enumType = try Enum(descriptor: enumDescriptor, in: machO.context) let output = try await enumType.dump(using: configuration ?? .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -33,7 +33,7 @@ extension SnapshotDumpableTests { case .struct(let structDescriptor): guard options.contains(.struct) else { continue } do { - let structType = try Struct(descriptor: structDescriptor, in: machO) + let structType = try Struct(descriptor: structDescriptor, in: machO.context) let output = try await structType.dump(using: configuration ?? .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -42,7 +42,7 @@ extension SnapshotDumpableTests { case .class(let classDescriptor): guard options.contains(.class) else { continue } do { - let classType = try Class(descriptor: classDescriptor, in: machO) + let classType = try Class(descriptor: classDescriptor, in: machO.context) let output = try await classType.dump(using: configuration ?? .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -60,7 +60,7 @@ extension SnapshotDumpableTests { var results: [String] = [] for protocolDescriptor in protocolDescriptors { do { - let output = try await Protocol(descriptor: protocolDescriptor, in: machO) + let output = try await Protocol(descriptor: protocolDescriptor, in: machO.context) .dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -77,7 +77,7 @@ extension SnapshotDumpableTests { var results: [String] = [] for protocolConformanceDescriptor in protocolConformanceDescriptors { do { - let output = try await ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machO) + let output = try await ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machO.context) .dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -94,7 +94,7 @@ extension SnapshotDumpableTests { var results: [String] = [] for associatedTypeDescriptor in associatedTypeDescriptors { do { - let output = try await AssociatedType(descriptor: associatedTypeDescriptor, in: machO) + let output = try await AssociatedType(descriptor: associatedTypeDescriptor, in: machO.context) .dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -121,10 +121,10 @@ extension SnapshotDumpableTests { of descriptor: TypeContextDescriptorWrapper, in machO: some MachOFieldLayoutRenderable ) throws -> String? { - let selfName = try descriptor.namedContextDescriptor.name(in: machO) + let selfName = try descriptor.namedContextDescriptor.name(in: machO.context) return try walkRootNamespace( initialName: selfName, - startingParent: try descriptor.parent(in: machO), + startingParent: try descriptor.parent(in: machO.context), in: machO ) } @@ -136,10 +136,10 @@ extension SnapshotDumpableTests { of descriptor: ProtocolDescriptor, in machO: some MachOFieldLayoutRenderable ) throws -> String? { - let selfName = try descriptor.name(in: machO) + let selfName = try descriptor.name(in: machO.context) return try walkRootNamespace( initialName: selfName, - startingParent: try descriptor.parent(in: machO), + startingParent: try descriptor.parent(in: machO.context), in: machO ) } @@ -165,9 +165,9 @@ extension SnapshotDumpableTests { break } if let namedDescriptor = parentWrapper.namedContextDescriptor { - lastNamedName = try namedDescriptor.name(in: machO) + lastNamedName = try namedDescriptor.name(in: machO.context) } - currentParent = try parentWrapper.parent(in: machO) + currentParent = try parentWrapper.parent(in: machO.context) } return lastNamedName @@ -189,7 +189,7 @@ extension SnapshotDumpableTests { case .enum(let enumDescriptor): guard options.contains(.enum) else { continue } do { - let enumType = try Enum(descriptor: enumDescriptor, in: machO) + let enumType = try Enum(descriptor: enumDescriptor, in: machO.context) let output = try await enumType.dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -198,7 +198,7 @@ extension SnapshotDumpableTests { case .struct(let structDescriptor): guard options.contains(.struct) else { continue } do { - let structType = try Struct(descriptor: structDescriptor, in: machO) + let structType = try Struct(descriptor: structDescriptor, in: machO.context) let output = try await structType.dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -207,7 +207,7 @@ extension SnapshotDumpableTests { case .class(let classDescriptor): guard options.contains(.class) else { continue } do { - let classType = try Class(descriptor: classDescriptor, in: machO) + let classType = try Class(descriptor: classDescriptor, in: machO.context) let output = try await classType.dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -228,7 +228,7 @@ extension SnapshotDumpableTests { for protocolDescriptor in protocolDescriptors { guard (try? rootNamespace(of: protocolDescriptor, in: machO)) == category else { continue } do { - let output = try await Protocol(descriptor: protocolDescriptor, in: machO) + let output = try await Protocol(descriptor: protocolDescriptor, in: machO.context) .dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -264,7 +264,7 @@ extension SnapshotDumpableTests { in: machO ) else { continue } do { - let output = try await ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machO) + let output = try await ProtocolConformance(descriptor: protocolConformanceDescriptor, in: machO.context) .dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -279,7 +279,7 @@ extension SnapshotDumpableTests { category: String, in machO: some MachOFieldLayoutRenderable ) throws -> Bool { - let resolvedTypeReference = try descriptor.resolvedTypeReference(in: machO) + let resolvedTypeReference = try descriptor.resolvedTypeReference(in: machO.context) let defaultRuleNamespace = try conformingTypeRootNamespace( resolvedTypeReference: resolvedTypeReference, in: machO @@ -374,7 +374,7 @@ extension SnapshotDumpableTests { ) guard owningNamespace == category else { continue } do { - let output = try await AssociatedType(descriptor: associatedTypeDescriptor, in: machO) + let output = try await AssociatedType(descriptor: associatedTypeDescriptor, in: machO.context) .dump(using: .demangleOptions(.test), in: machO).string results.append(output) } catch { @@ -392,11 +392,11 @@ extension SnapshotDumpableTests { for protocolDescriptor in protocolDescriptors { let name: String do { - name = try protocolDescriptor.name(in: machO) + name = try protocolDescriptor.name(in: machO.context) } catch { continue } - let moduleName = (try? protocolDescriptor.moduleContextDescriptor(in: machO)?.name(in: machO)) ?? "" + let moduleName = (try? protocolDescriptor.moduleContextDescriptor(in: machO.context)?.name(in: machO.context)) ?? "" let key = "\(moduleName).\(name)" // First writer wins; this produces stable behavior if duplicates exist. if lookup[key] == nil { @@ -411,10 +411,10 @@ extension SnapshotDumpableTests { protocolIndex: [String: ProtocolDescriptor], in machO: some MachOFieldLayoutRenderable ) throws -> String? { - let protocolTypeName = try descriptor.protocolTypeName(in: machO) + let protocolTypeName = try descriptor.protocolTypeName(in: machO.context) let protocolNode: Node do { - protocolNode = try SymbolicDemangler.demangleType(for: protocolTypeName, in: machO) + protocolNode = try SymbolicDemangler.demangleType(for: protocolTypeName, in: machO.context) } catch { return nil } diff --git a/Sources/MachOFixtureSupport/SnapshotInterfaceTests.swift b/Sources/TestSupport/MachOFixtureSupport/SnapshotInterfaceTests.swift similarity index 100% rename from Sources/MachOFixtureSupport/SnapshotInterfaceTests.swift rename to Sources/TestSupport/MachOFixtureSupport/SnapshotInterfaceTests.swift diff --git a/Sources/MachOFixtureSupport/SwiftStdlibDemangle.swift b/Sources/TestSupport/MachOFixtureSupport/SwiftStdlibDemangle.swift similarity index 100% rename from Sources/MachOFixtureSupport/SwiftStdlibDemangle.swift rename to Sources/TestSupport/MachOFixtureSupport/SwiftStdlibDemangle.swift diff --git a/Sources/MachOFixtureSupport/URL+.swift b/Sources/TestSupport/MachOFixtureSupport/URL+.swift similarity index 100% rename from Sources/MachOFixtureSupport/URL+.swift rename to Sources/TestSupport/MachOFixtureSupport/URL+.swift diff --git a/Sources/MachOFixtureSupport/XcodeMachOFileName.swift b/Sources/TestSupport/MachOFixtureSupport/XcodeMachOFileName.swift similarity index 100% rename from Sources/MachOFixtureSupport/XcodeMachOFileName.swift rename to Sources/TestSupport/MachOFixtureSupport/XcodeMachOFileName.swift diff --git a/Sources/TestSupport/MachOTestingSupport/DefinitionName+DeclaredNameForTesting.swift b/Sources/TestSupport/MachOTestingSupport/DefinitionName+DeclaredNameForTesting.swift new file mode 100644 index 000000000..9d0793c3e --- /dev/null +++ b/Sources/TestSupport/MachOTestingSupport/DefinitionName+DeclaredNameForTesting.swift @@ -0,0 +1,38 @@ +import Demangling +import SwiftDeclaration + +extension DefinitionName { + /// The declaration's own name, read from its node: `Int` for `Swift.Int`, + /// `Inner` for `Outer.Inner`, `MemberKey` for a type declared in a + /// function body. What a test compares against when it looks a definition + /// up by its short name. + /// + /// Tests must not use `currentName` for that. It is the display name dump + /// and interface print in a declaration header, taken as the last + /// dot-separated component of the printed name — and a function-local + /// type prints as `MemberKey #1 in Module.f() -> Swift.Int`, so its + /// `currentName` is the tail of the enclosing function's signature. The + /// indexer sees such types whenever it indexes the test binary itself: a + /// local `Hashable` enum in a function returning `Int` read as a second + /// `Int` candidate, and whichever of the two a `Set` put first decided + /// what a specialization test specialized (ReviewAdjudications A52). + /// + /// A node of a shape not handled here answers the full printed `name`, + /// so a short-name comparison against it fails rather than matching the + /// wrong definition. + package var declaredNameForTesting: String { + var declarationNode = node + while declarationNode.kind == .type, let wrappedNode = declarationNode.children.first { + declarationNode = wrappedNode + } + guard let nameNode = declarationNode.children.at(1) else { return name } + switch nameNode.kind { + case .identifier: + return nameNode.text ?? name + case .localDeclName, .privateDeclName: + return nameNode.children.last { $0.kind == .identifier }?.text ?? name + default: + return name + } + } +} diff --git a/Sources/MachOTestingSupport/DyldCacheTests.swift b/Sources/TestSupport/MachOTestingSupport/DyldCacheTests.swift similarity index 100% rename from Sources/MachOTestingSupport/DyldCacheTests.swift rename to Sources/TestSupport/MachOTestingSupport/DyldCacheTests.swift diff --git a/Sources/MachOTestingSupport/ExclusiveImageAccess.swift b/Sources/TestSupport/MachOTestingSupport/ExclusiveImageAccess.swift similarity index 100% rename from Sources/MachOTestingSupport/ExclusiveImageAccess.swift rename to Sources/TestSupport/MachOTestingSupport/ExclusiveImageAccess.swift diff --git a/Sources/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift similarity index 94% rename from Sources/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift rename to Sources/TestSupport/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift index 3ea16da5c..fc7822dc1 100644 --- a/Sources/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift +++ b/Sources/TestSupport/MachOTestingSupport/GenericSpecializationTestingEnvironment.swift @@ -96,7 +96,7 @@ extension GenericSpecializationTestingEnvironment { package func structDescriptor(named nameContains: String) throws -> StructDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.struct?.name(in: machO).contains(nameContains) == true + try $0.struct?.name(in: machO.context).contains(nameContains) == true }?.struct, "expected a struct context descriptor whose name contains \"\(nameContains)\"" ) @@ -116,7 +116,7 @@ extension GenericSpecializationTestingEnvironment { package func enumDescriptor(named nameContains: String) throws -> EnumDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.enum?.name(in: machO).contains(nameContains) == true + try $0.enum?.name(in: machO.context).contains(nameContains) == true }?.enum, "expected an enum context descriptor whose name contains \"\(nameContains)\"" ) @@ -127,7 +127,7 @@ extension GenericSpecializationTestingEnvironment { package func classDescriptor(named nameContains: String) throws -> ClassDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.class?.name(in: machO).contains(nameContains) == true + try $0.class?.name(in: machO.context).contains(nameContains) == true }?.class, "expected a class context descriptor whose name contains \"\(nameContains)\"" ) @@ -141,7 +141,7 @@ extension GenericSpecializationTestingEnvironment { ) throws -> (descriptor: StructDescriptor, genericContext: GenericContext) { let descriptor = try structDescriptor(named: nameContains) let genericContext = try #require( - try descriptor.genericContext(in: machO), + try descriptor.genericContext(in: machO.context), "expected genericContext on \(nameContains)" ) return (descriptor, genericContext) diff --git a/Sources/MachOTestingSupport/MachOFileTests.swift b/Sources/TestSupport/MachOTestingSupport/MachOFileTests.swift similarity index 100% rename from Sources/MachOTestingSupport/MachOFileTests.swift rename to Sources/TestSupport/MachOTestingSupport/MachOFileTests.swift diff --git a/Sources/MachOTestingSupport/MachOImageTests.swift b/Sources/TestSupport/MachOTestingSupport/MachOImageTests.swift similarity index 100% rename from Sources/MachOTestingSupport/MachOImageTests.swift rename to Sources/TestSupport/MachOTestingSupport/MachOImageTests.swift diff --git a/Sources/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift b/Sources/TestSupport/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift similarity index 98% rename from Sources/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift rename to Sources/TestSupport/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift index da69a78e5..6ee5f3680 100644 --- a/Sources/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift +++ b/Sources/TestSupport/MachOTestingSupport/MachOSwiftSectionFixtureTests.swift @@ -75,10 +75,10 @@ package class MachOSwiftSectionFixtureTests: Sendable { _ = dlopenOnce } - /// Resolve a relative MachOImageName path (rooted at the package-relative `../../Tests/...` + /// 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/MachOTestingSupport/`). + /// this source file (i.e. `Sources/TestSupport/MachOTestingSupport/`). 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/MachOTestingSupport/ObjCImplementationFixture.swift b/Sources/TestSupport/MachOTestingSupport/ObjCImplementationFixture.swift similarity index 96% rename from Sources/MachOTestingSupport/ObjCImplementationFixture.swift rename to Sources/TestSupport/MachOTestingSupport/ObjCImplementationFixture.swift index 3cd26ad8d..f1d6914bd 100644 --- a/Sources/MachOTestingSupport/ObjCImplementationFixture.swift +++ b/Sources/TestSupport/MachOTestingSupport/ObjCImplementationFixture.swift @@ -36,6 +36,13 @@ import Testing /// images, since the runtime attaches it where the readers do not look). /// `dependencySearchPaths()` names the dylib for a resolver. /// +/// `Widget` also carries the two stored properties whose field-offset symbols +/// name the variable through a `privateDeclName` instead of an `identifier`: +/// a `private` property, and the synthesized storage of a `lazy var`, which +/// the compiler makes private whatever the property's own access level. The +/// recognition's first version accepted only the `identifier` shape and left +/// both untyped even with every symbol present. +/// /// Five link/strip variants exercise the evidence tiers and the bind formats: /// - `.full`: every symbol present — accessor, field-offset globals, `To` /// thunks at the class's own IMPs. @@ -132,6 +139,9 @@ package enum ObjCImplementationFixture { var title: String var count: Int final var swiftOnlyCache: [Int] = [] + // Their field-offset symbols carry a private discriminator. + private final var hiddenTally: Int = 0 + final lazy var summary: String = "\\(title) x\\(count)" init(title: String) { self.title = title diff --git a/Sources/MachOTestingSupport/ProcessMemory.swift b/Sources/TestSupport/MachOTestingSupport/ProcessMemory.swift similarity index 100% rename from Sources/MachOTestingSupport/ProcessMemory.swift rename to Sources/TestSupport/MachOTestingSupport/ProcessMemory.swift diff --git a/Sources/MachOTestingSupport/RenamedObjCClassFixture.swift b/Sources/TestSupport/MachOTestingSupport/RenamedObjCClassFixture.swift similarity index 100% rename from Sources/MachOTestingSupport/RenamedObjCClassFixture.swift rename to Sources/TestSupport/MachOTestingSupport/RenamedObjCClassFixture.swift diff --git a/Sources/MachOTestingSupport/SpecializedMangledNameFixtures.swift b/Sources/TestSupport/MachOTestingSupport/SpecializedMangledNameFixtures.swift similarity index 100% rename from Sources/MachOTestingSupport/SpecializedMangledNameFixtures.swift rename to Sources/TestSupport/MachOTestingSupport/SpecializedMangledNameFixtures.swift diff --git a/Sources/MachOTestingSupport/SwiftIndexEventCollector.swift b/Sources/TestSupport/MachOTestingSupport/SwiftIndexEventCollector.swift similarity index 100% rename from Sources/MachOTestingSupport/SwiftIndexEventCollector.swift rename to Sources/TestSupport/MachOTestingSupport/SwiftIndexEventCollector.swift diff --git a/Sources/MachOTestingSupport/TestActor.swift b/Sources/TestSupport/MachOTestingSupport/TestActor.swift similarity index 100% rename from Sources/MachOTestingSupport/TestActor.swift rename to Sources/TestSupport/MachOTestingSupport/TestActor.swift diff --git a/Sources/MachOTestingSupport/XcodeMachOFileTests.swift b/Sources/TestSupport/MachOTestingSupport/XcodeMachOFileTests.swift similarity index 100% rename from Sources/MachOTestingSupport/XcodeMachOFileTests.swift rename to Sources/TestSupport/MachOTestingSupport/XcodeMachOFileTests.swift diff --git a/Sources/MachOTestingSupportC/CDemangleTree.cpp b/Sources/TestSupport/MachOTestingSupportC/CDemangleTree.cpp similarity index 100% rename from Sources/MachOTestingSupportC/CDemangleTree.cpp rename to Sources/TestSupport/MachOTestingSupportC/CDemangleTree.cpp diff --git a/Sources/MachOTestingSupportC/include/CDemangleTree.h b/Sources/TestSupport/MachOTestingSupportC/include/CDemangleTree.h similarity index 100% rename from Sources/MachOTestingSupportC/include/CDemangleTree.h rename to Sources/TestSupport/MachOTestingSupportC/include/CDemangleTree.h diff --git a/Sources/swift-section/Commands/DiffCommand.swift b/Sources/swift-section/Commands/DiffCommand.swift deleted file mode 100644 index 2b56c27bb..000000000 --- a/Sources/swift-section/Commands/DiffCommand.swift +++ /dev/null @@ -1,260 +0,0 @@ -import SwiftInterface -import SwiftIndexing -import SwiftDiffing -import Foundation -import MachOKit -import MachOFoundation -import ArgumentParser -import Rainbow - -/// The output format for the annotated interface (`--interface`). -enum DiffOutputFormat: String, CaseIterable, ExpressibleByArgument { - /// git-diff-style `+`/`-`/` ` line prefixes (the default). - case inline - /// A real unified diff (`--- old`/`+++ new` + `@@` hunks), consumable by - /// `git apply` / `patch` / `delta`. - case unified - /// The inline body wrapped in a Markdown ```` ```diff ```` fence. - case markdown -} - -struct DiffCommand: AsyncParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "diff", - abstract: "Diff the Swift ABI of two Mach-O binaries (or persisted baseline snapshots)." - ) - - @Argument(help: "The old (baseline) side: a Mach-O file path or a snapshot JSON produced by `swift-section snapshot`.", completion: .file()) - var oldPath: String - - @Argument(help: "The new side: a Mach-O file path or a snapshot JSON.", completion: .file()) - var newPath: String - - @Option(name: .shortAndLong, help: "The architecture slice to use for fat binaries. Required when either path is a fat (universal) binary.") - var architecture: Architecture? - - @Flag(name: [.customLong("dyld-shared-cache")], help: "Treat both paths as dyld shared caches and extract the same image (--cache-image-name) from each.") - var isDyldSharedCache: Bool = false - - @Option(name: [.long, .customShort("n")], help: "Image name to extract from each dyld shared cache (e.g. SwiftUICore).") - var cacheImageName: String? - - @Option(name: [.long, .customShort("p")], help: "Image path to extract from each dyld shared cache.") - var cacheImagePath: String? - - @Flag(help: "Print only the breaking/backward-compatible verdict, not the full report.") - var summaryOnly: Bool = false - - @Flag(help: "Emit the ABI diff as JSON (with provenance) instead of the text report.") - var json: Bool = false - - @Flag(help: "Emit the full Swift interface annotated with diff markers instead of the change-list.") - var interface: Bool = false - - @Option(name: .long, help: "Annotated-interface format: inline (git-diff style), unified (real unified diff), or markdown (```diff fence). Requires --interface; defaults to inline.") - var format: DiffOutputFormat? - - @Flag(help: "Exit with a nonzero status when the diff contains an ABI-breaking change, for CI gating. Honored with --interface too.") - var failOnBreaking: Bool = false - - @Option(name: .shortAndLong, help: "Write the report to this path instead of stdout.", completion: .file()) - var outputPath: String? - - @Option(name: .long, help: "How many inputs to index at once (default: the processor count). Pass 1 to index the old side, then the new side.") - var jobs: Int? - - /// The concurrency window for indexing the two sides (evolution proposal - /// `large-stack-executor-and-cross-version-parallelism`): both inputs are - /// independent files, so by default they index in parallel. - private var maximumConcurrentPreparations: Int { - jobs ?? ProcessInfo.processInfo.activeProcessorCount - } - - func run() async throws { - let abiDiff: ABIDiff? - if interface { - // The annotated interface renders from the live models, so both - // sides must be binaries — a persisted snapshot carries no - // renderable interface. - if try ABISnapshotInputLoader.isSnapshotDocument(atPath: oldPath) - || ABISnapshotInputLoader.isSnapshotDocument(atPath: newPath) { - throw ValidationError("--interface needs two binaries; snapshot JSON inputs only support the change-list report.") - } - - let oldMachO = try loadMachO(at: oldPath) - let newMachO = try loadMachO(at: newPath) - - // A sink on both sides: the renderer hands each builder's dispatcher - // to its printers, so this is what puts a dropped declaration on - // stderr instead of leaving it to `Dispatcher`'s os_log floor, which - // a CLI operator never sees. - let oldBuilder = SwiftDiffableInterfaceBuilder(eventHandlers: [ConsoleEventHandler(label: "old")], in: oldMachO) - let newBuilder = SwiftDiffableInterfaceBuilder(eventHandlers: [ConsoleEventHandler(label: "new")], in: newMachO) - // Old side first in the window, so `--jobs 1` is the historical - // order; with a wider window the two index side by side and their - // diagnostics interleave on stderr. - log(maximumConcurrentPreparations > 1 ? "Indexing old and new binaries…" : "Indexing old binary, then new binary…") - _ = try await [oldBuilder, newBuilder].concurrentMap(maximumConcurrency: maximumConcurrentPreparations) { builder in - try await builder.prepare() - } - - // Only the `--fail-on-breaking` CI gate needs the ABI diff on the - // annotated-interface path. - abiDiff = failOnBreaking - ? ABIDiffer().diff(old: oldBuilder.abiModule(), new: newBuilder.abiModule()) - : nil - - log("Rendering annotated interface…") - let renderer = SwiftDiffableInterfaceRenderer(old: oldBuilder, new: newBuilder) - let diffFormat: DiffFormat - switch format ?? .inline { - case .inline: - diffFormat = .inline - case .unified: - diffFormat = .unified(oldLabel: oldPath, newLabel: newPath) - case .markdown: - diffFormat = .markdownFenced - } - let annotated = await renderer.printAnnotatedInterface(format: diffFormat) - try emit(annotated.string) - } else { - // The change-list path is snapshot-based either way, so each side - // may be a binary (indexed and frozen here) or a persisted - // baseline (decoded, with its format version validated). - let documents = try await [(path: oldPath, side: "old"), (path: newPath, side: "new")].concurrentMap(maximumConcurrency: maximumConcurrentPreparations) { input in - try await loadDocument(at: input.path, consoleLabel: input.side) - } - let (oldDocument, newDocument) = (documents[0], documents[1]) - - log("Diffing…") - let diff = ABIDiffer().diff(old: oldDocument, new: newDocument) - abiDiff = diff - - let verdict = "ABI-breaking: \(diff.hasBreakingChange) · backward-compatible: \(diff.isBackwardCompatible)" - if json { - let encoded = String(decoding: try ABIJSON.encoder().encode(diff), as: UTF8.self) - try emitPlain(encoded) - } else if summaryOnly { - print(verdict) - } else { - try emitPlain(ABIDiffReporter().report(diff) + "\n\n" + verdict) - } - } - - if failOnBreaking, let abiDiff, abiDiff.hasBreakingChange { - throw ExitCode.failure - } - } - - /// 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, summaryOnly { - throw ValidationError("--interface and --summary-only are mutually exclusive.") - } - if json, interface { - throw ValidationError("--json and --interface are mutually exclusive.") - } - if json, summaryOnly { - throw ValidationError("--json and --summary-only are mutually exclusive.") - } - if format != nil, !interface { - throw ValidationError("--format only applies to the annotated interface; pass --interface.") - } - if let jobs, jobs < 1 { - throw ValidationError("--jobs must be at least 1.") - } - if cacheImageName != nil, cacheImagePath != nil { - throw ValidationError("--cache-image-name and --cache-image-path are mutually exclusive; pass only one.") - } - if cacheImageName != nil || cacheImagePath != nil, !isDyldSharedCache { - throw ValidationError("--cache-image-name / --cache-image-path require --dyld-shared-cache.") - } - if isDyldSharedCache, cacheImageName == nil, cacheImagePath == nil { - throw ValidationError("--dyld-shared-cache requires --cache-image-name or --cache-image-path.") - } - } - - /// Loads a Mach-O for diffing: either an image extracted from a dyld shared - /// cache (so cross-image references into Foundation/libswiftCore resolve), or - /// a thin/fat file on disk. Both sides go through the shared - /// `MachOFile.load(...)` so the fat-binary affordance and cache-image - /// disambiguation match the rest of the CLI. `--dyld-shared-cache` here means - /// "treat each path as a cache and pull the same image from both", so the - /// system-cache path is never taken. - private func loadMachO(at path: String) throws -> MachOFile { - try MachOFile.load( - filePath: path, - isDyldSharedCache: isDyldSharedCache, - usesSystemDyldSharedCache: false, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - architecture: architecture - ) - } - - /// Loads one change-list-path input: a snapshot JSON is decoded, a binary - /// is indexed and frozen (with provenance stamped). - private func loadDocument(at path: String, consoleLabel: String) async throws -> ABISnapshotDocument { - try await ABISnapshotInputLoader.loadDocument( - path: path, - architecture: architecture, - isDyldSharedCache: isDyldSharedCache, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - label: nil, - consoleLabel: consoleLabel, - log: log - ) - } - - /// Writes an uncolorized report to `--output` or stdout. - private func emitPlain(_ text: String) throws { - if let outputPath { - try text.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - log("Report written to \(outputPath)") - } else { - print(text) - } - } - - /// Writes the annotated interface: plain text to `--output`, or per-line - /// colorized (added green, removed red) to the terminal. - private func emit(_ text: String) throws { - if let outputPath { - try text.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - log("Annotated interface written to \(outputPath)") - return - } - var output = "" - let lines = text.split(separator: "\n", omittingEmptySubsequences: false) - for (index, line) in lines.enumerated() { - let lineText = String(line) - // In a unified diff the first two lines are the `--- old` / `+++ new` - // file headers and `@@ … @@` lines are hunk headers; colorize those by - // position / prefix so an added/removed content line that happens to - // begin with `++` or `--` is never mistaken for a file header. - if format == .unified, index < 2 { - output += lineText.cyan - } else if format == .unified, lineText.hasPrefix("@@") { - output += lineText.cyan - } else if lineText.hasPrefix("+") { - output += lineText.green - } else if lineText.hasPrefix("-") { - output += lineText.red - } else { - output += lineText - } - output += "\n" - } - print(output, terminator: "") - } - - private func log(_ message: String) { - // `fputs`, not `FileHandle.standardError.write(_:)`: that overload is the - // Objective-C bridge and raises `NSFileHandleOperationException` on a - // closed or broken stderr, which Swift cannot catch — a diagnostic would - // abort the command instead of being printed. - fputs(message + "\n", stderr) - } -} diff --git a/Sources/swift-section/Commands/DumpCommand.swift b/Sources/swift-section/Commands/DumpCommand.swift deleted file mode 100644 index ace399e89..000000000 --- a/Sources/swift-section/Commands/DumpCommand.swift +++ /dev/null @@ -1,370 +0,0 @@ -import Foundation -import ArgumentParser -import MachOKit -import MachOFoundation -import MachOSwiftSection -import SwiftDump -import SwiftInspection -import OutputTransformer -import SwiftOutputTransformer -import SwiftDeclarationRendering -import SwiftPrinting -import Semantic - -struct DumpCommand: AsyncParsableCommand, Sendable { - private enum TopLevelContext { - case type(TypeContextWrapper) - case `protocol`(MachOSwiftSection.`Protocol`) - case protocolConformance(ProtocolConformance) - case associatedType(AssociatedType) - case objcImplementationClass(ObjCImplementationClass) - - var offset: Int { - switch self { - case .objcImplementationClass(let objcImplementationClass): - return objcImplementationClass.offset - case .type(let type): - switch type { - case .enum(let `enum`): - return `enum`.offset - case .struct(let `struct`): - return `struct`.offset - case .class(let `class`): - return `class`.offset - } - case .protocol(let `protocol`): - return `protocol`.offset - case .associatedType(let associatedType): - return associatedType.offset - case .protocolConformance(let protocolConformance): - return protocolConformance.offset - } - } - } - - static let configuration: CommandConfiguration = .init( - commandName: "dump", - abstract: "Dump Swift information from a Mach-O file or dyld shared cache." - ) - - private var dumpedString = "" - - @OptionGroup - var machOOptions: MachOOptionGroup - - @OptionGroup - var demangleOptions: DemangleOptionGroup - - @OptionGroup(title: "Comment Templates") - var transformerOptions: TransformerOptionGroup - - @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) - var outputPath: String? - - @Option(name: .shortAndLong, parsing: .upToNextOption, help: "The sections to dump. If not specified, all sections will be dumped.") - var sections: [SwiftSection] = [] - - @Option(name: .shortAndLong, help: "The color scheme for the output.") - var colorScheme: SemanticColorScheme = .none - - @Flag(help: "Generate member address comments for each member symbol") - var emitMemberAddresses: Bool = false - - @Flag(help: "Generate vtable offset comments for class methods") - var emitVtableOffsets: Bool = false - - @Flag(help: "Generate PWT (Protocol Witness Table) address comments for protocol conformances") - var emitPWTAddresses: Bool = false - - @Flag(help: "Generate field offset comments for struct/class stored properties, computed statically via SwiftLayout") - var emitFieldOffsets: Bool = false - - @Flag(help: "Generate type layout (size/stride/alignment) comments, computed statically via SwiftLayout") - var emitTypeLayout: Bool = false - - @Flag(help: "Generate enum layout (strategy/per-case/spare-bit) comments, computed statically via SwiftLayout") - var emitEnumLayout: Bool = false - - @Flag(help: "Expand nested struct fields with their absolute offsets (implies --emit-field-offsets)") - var emitExpandedFieldOffsets: Bool = false - - @Flag(help: "The definitions of types and protocols will be output in the order they are stored in the binary.") - var preferredBinaryOrder: Bool = false - - @Flag(help: "Emit a leading header comment block (generator, image path, UUID, architecture, library-evolution detection, unrecoverable-facts notes)") - var emitHeader: Bool = false - - @Flag(help: "Annotate member-symbol lines whose symbol has no export-trie entry with a `not exported` comment") - var emitExportStatus: Bool = false - - mutating func run() async throws { - try await AccessorThunkResolution.withResolver(from: machOOptions) { - try await dump() - } - } - - private mutating func dump() async throws { - let machOFile = try MachOFile.load(options: machOOptions) - // The ObjC ancestor chain behind the `overrides` / `explicit selector` - // comments follows a standalone file's binds into the same images the - // interface's indexer would use; `dump` has no indexer, so it installs - // the resolver itself. - ObjCAncestorResolverStore.shared.register( - ObjCAncestorResolver(root: machOFile, searchPaths: machOOptions.indexDependencySearchPaths), - for: machOFile - ) - var dumpConfiguration: DumperConfiguration = .demangleOptions(demangleOptions.buildSwiftDumpDemangleOptions()) - - dumpConfiguration.printMemberAddress = emitMemberAddresses - dumpConfiguration.printVTableOffset = emitVtableOffsets - dumpConfiguration.printExportStatus = emitExportStatus - dumpConfiguration.printConformancePWTAddress = emitPWTAddresses - dumpConfiguration.printFieldOffset = emitFieldOffsets || emitExpandedFieldOffsets - dumpConfiguration.printTypeLayout = emitTypeLayout - dumpConfiguration.printEnumLayout = emitEnumLayout - dumpConfiguration.printExpandedFieldOffsets = emitExpandedFieldOffsets - // Without any template option the slots stay empty, keeping the - // built-in rendering byte-for-byte identical. - if let transformers = try transformerOptions.buildTransformerConfiguration() { - dumpConfiguration.applyTransformersEnablingCommentKinds(transformers) - } - - // The static (offline) field-layout path needs a SwiftLayout-backed - // provider; build it once per session when any layout comment is - // requested. Without it the offline dumpers emit no layout comments - // (offline metadata is unavailable), exactly as before. - dumpConfiguration.staticLayoutDependencyResolution = machOOptions.staticLayoutDependencyResolution - if dumpConfiguration.printFieldOffset || dumpConfiguration.printTypeLayout || dumpConfiguration.printEnumLayout || dumpConfiguration.printExpandedFieldOffsets { - dumpConfiguration.staticFieldLayoutProvider = MachOFileStaticFieldLayoutProvider( - machOFile: machOFile, - resolution: dumpConfiguration.staticLayoutDependencyResolution - ) - } - - if emitHeader { - let headerInfo = InterfaceHeaderInfo( - machO: machOFile, - generatorName: "swift-section", - generatorVersion: BundledVersion.value - ) - await performDump { InterfaceHeaderBlock(headerInfo) } - } - - let isDefaultSections = sections.isEmpty - - if isDefaultSections { - sections = SwiftSection.allCases - } - - if preferredBinaryOrder { - var topLevelContexts: [TopLevelContext] = [] - if sections.contains(.types) { - do { - let types = try machOFile.swift.types.map { TopLevelContext.type($0) } - topLevelContexts.append(contentsOf: types) - } catch { - if !isDefaultSections { - dumpError(error) - } - } - } - - if sections.contains(.protocols) { - do { - let protocols = try machOFile.swift.protocols.map { TopLevelContext.protocol($0) } - topLevelContexts.append(contentsOf: protocols) - } catch { - if !isDefaultSections { - dumpError(error) - } - } - } - - if sections.contains(.objcImplementationClasses) { - topLevelContexts.append(contentsOf: ObjCImplementationClass.all(in: machOFile).map { TopLevelContext.objcImplementationClass($0) }) - } - - topLevelContexts.sort(by: { $0.offset < $1.offset }) - - if sections.contains(.protocolConformances) { - do { - let protocolConformances = try machOFile.swift.protocolConformances.map { TopLevelContext.protocolConformance($0) } - topLevelContexts.append(contentsOf: protocolConformances) - } catch { - if !isDefaultSections { - dumpError(error) - } - } - } - - if sections.contains(.associatedTypes) { - do { - let associatedTypes = try machOFile.swift.associatedTypes.map { TopLevelContext.associatedType($0) } - topLevelContexts.append(contentsOf: associatedTypes) - } catch { - if !isDefaultSections { - dumpError(error) - } - } - } - - for topLevelContext in topLevelContexts { - switch topLevelContext { - case .type(let type): - try? await dumpType(type, using: dumpConfiguration, in: machOFile) - case .protocol(let `protocol`): - try? await dumpProtocol(`protocol`, using: dumpConfiguration, in: machOFile) - case .protocolConformance(let protocolConformance): - try? await dumpProtocolConformance(protocolConformance, using: dumpConfiguration, in: machOFile) - case .associatedType(let associatedType): - try? await dumpAssociatedType(associatedType, using: dumpConfiguration, in: machOFile) - case .objcImplementationClass(let objcImplementationClass): - try? await dumpObjCImplementationClass(objcImplementationClass, using: dumpConfiguration, in: machOFile) - } - } - - } else { - for section in sections { - switch section { - case .types: - do { - for type in try machOFile.swift.types { - try await dumpType(type, using: dumpConfiguration, in: machOFile) - } - } catch { - if !isDefaultSections { - dumpError(error) - } - } - case .protocols: - do { - for `protocol` in try machOFile.swift.protocols { - try await dumpProtocol(`protocol`, using: dumpConfiguration, in: machOFile) - } - } catch { - if !isDefaultSections { - dumpError(error) - } - } - case .protocolConformances: - do { - for protocolConformance in try machOFile.swift.protocolConformances { - try await dumpProtocolConformance(protocolConformance, using: dumpConfiguration, in: machOFile) - } - } catch { - if !isDefaultSections { - dumpError(error) - } - } - case .associatedTypes: - do { - for associatedType in try machOFile.swift.associatedTypes { - try await dumpAssociatedType(associatedType, using: dumpConfiguration, in: machOFile) - } - } catch { - if !isDefaultSections { - dumpError(error) - } - } - case .objcImplementationClasses: - let objcImplementationClasses = ObjCImplementationClass.all(in: machOFile) - if objcImplementationClasses.isEmpty, !isDefaultSections { - // Asked for explicitly and nothing there: say so, as the - // section-backed cases do, rather than print nothing. - dumpOrPrint(SemanticString { Comment("No @objc @implementation classes recognized in this image.") }) - } - for objcImplementationClass in objcImplementationClasses { - try await dumpObjCImplementationClass(objcImplementationClass, using: dumpConfiguration, in: machOFile) - } - } - } - } - - if let outputPath { - let outputURL = URL(fileURLWithPath: outputPath) - try dumpedString.write(to: outputURL, atomically: true, encoding: .utf8) - } - } - - @MainActor - private mutating func dumpType(_ type: TypeContextWrapper, using configuration: DumperConfiguration, in machO: MachOFile) async throws { - switch type { - case .enum(let `enum`): - await performDump { - try await `enum`.dump(using: configuration, in: machO) - } - case .struct(let `struct`): - await performDump { - try await `struct`.dump(using: configuration, in: machO) - } - case .class(let `class`): - await performDump { - try await `class`.dump(using: configuration, in: machO) - } - } - } - - @MainActor - private mutating func dumpAssociatedType(_ associatedType: AssociatedType, using configuration: DumperConfiguration, in machO: MachOFile) async throws { - await performDump { - try await associatedType.dump(using: configuration, in: machO) - } - } - - @MainActor - private mutating func dumpProtocol(_ protocol: MachOSwiftSection.`Protocol`, using configuration: DumperConfiguration, in machO: MachOFile) async throws { - await performDump { - try await `protocol`.dump(using: configuration, in: machO) - } - } - - @MainActor - private mutating func dumpProtocolConformance(_ protocolConformance: ProtocolConformance, using configuration: DumperConfiguration, in machO: MachOFile) async throws { - await performDump { - try await protocolConformance.dump(using: configuration, in: machO) - } - } - - @MainActor - private mutating func dumpObjCImplementationClass(_ objcImplementationClass: ObjCImplementationClass, using configuration: DumperConfiguration, in machO: MachOFile) async throws { - await performDump { - try await objcImplementationClass.dump(using: configuration, in: machO) - } - } - - private mutating func performDump(@SemanticStringBuilder _ action: @Sendable () async throws -> SemanticString) async { - do { - try await dumpOrPrint(action()) - } catch { - dumpError(error) - } - } - - private mutating func dumpError(_ error: Swift.Error) { - SemanticString(components: [Semantic.Error(error.localizedDescription)]).printColorfully(using: colorScheme) - } - - private mutating func dumpOrPrint(_ semanticString: SemanticString) { - if outputPath != nil { - dumpedString.append(semanticString.string) - dumpedString.append("\n") - } else { - semanticString.printColorfully(using: colorScheme) - } - } - - private mutating func dumpOrPrint(_ string: String) { - if outputPath != nil { - dumpedString.append(string) - dumpedString.append("\n") - } else { - print(string) - } - } -} - -extension SemanticString { - func printColorfully(using colorScheme: SemanticColorScheme) { - print(components.map { $0.string.withColor(for: $0.type, colorScheme: colorScheme) }.joined()) - } -} diff --git a/Sources/swift-section/Commands/EvolutionCommand.swift b/Sources/swift-section/Commands/EvolutionCommand.swift deleted file mode 100644 index 1885859e3..000000000 --- a/Sources/swift-section/Commands/EvolutionCommand.swift +++ /dev/null @@ -1,240 +0,0 @@ -import ArgumentParser -import Foundation -import SwiftDiffing -import SwiftInterface -import SwiftIndexing -import MachOKit -import MachOFoundation -import Rainbow - -struct EvolutionCommand: AsyncParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "evolution", - abstract: "Track the Swift ABI of one module across an ordered series of binary versions.", - discussion: """ - Pass two or more inputs in version order (oldest first). Each input is either a \ - Mach-O / fat binary, a dyld shared cache (with --dyld-shared-cache, extracting the \ - same image from every cache), or a baseline snapshot produced by `swift-section snapshot`. - """ - ) - - @Argument(help: "The input paths in version order (oldest first); Mach-O binaries, dyld shared caches, or snapshot JSON files.", completion: .file()) - var inputPaths: [String] - - @Option(name: .long, help: "Comma-separated version labels for the axis (e.g. 17.0,18.0,26.0); one per input. Defaults to each snapshot's stored label or the input's file name.") - var labels: String? - - @Option(name: .shortAndLong, help: "The architecture slice to use for fat binaries. Required when any input is a fat (universal) binary.") - var architecture: Architecture? - - @Flag(name: [.customLong("dyld-shared-cache")], help: "Treat every binary input as a dyld shared cache and extract the same image (--cache-image-name) from each.") - var isDyldSharedCache: Bool = false - - @Option(name: [.long, .customShort("n")], help: "Image name to extract from each dyld shared cache (e.g. SwiftUICore).") - var cacheImageName: String? - - @Option(name: [.long, .customShort("p")], help: "Image path to extract from each dyld shared cache.") - var cacheImagePath: String? - - @Flag(help: "Print only the header and per-transition summary, not the full lineage report.") - var summaryOnly: Bool = false - - @Flag(help: "Emit the evolution as JSON instead of the text report.") - var json: Bool = false - - @Flag(help: "Emit the union Swift interface annotated with per-declaration lifecycle comments instead of the lineage report. Every input must be a binary (or dyld shared cache); snapshot JSON inputs are rejected.") - var interface: Bool = false - - @Flag(help: "Exit with a nonzero status when any transition contains an ABI-breaking change, for CI gating.") - var failOnBreaking: Bool = false - - @Option(name: .shortAndLong, help: "Write the report to this path instead of stdout.", completion: .file()) - var outputPath: String? - - @Option(name: .long, help: "How many inputs to index at once (default: the processor count). Pass 1 to index the versions one after the other, oldest first.") - var jobs: Int? - - /// The concurrency window for indexing the inputs (evolution proposal - /// `large-stack-executor-and-cross-version-parallelism`): every input is - /// an independent file, so by default up to one per processor index at - /// once. Each in-flight input holds its indexed image in memory, which is - /// what `--jobs` trades against. - private var maximumConcurrentPreparations: Int { - jobs ?? ProcessInfo.processInfo.activeProcessorCount - } - - func run() async throws { - let explicitLabels = try ABISnapshotInputLoader.parseLabels(labels, inputCount: inputPaths.count) - - if interface { - try await runAnnotatedInterface(explicitLabels: explicitLabels) - return - } - - let documents = try await Array(inputPaths.enumerated()).concurrentMap(maximumConcurrency: maximumConcurrentPreparations) { index, inputPath in - try await ABISnapshotInputLoader.loadDocument( - path: inputPath, - architecture: architecture, - isDyldSharedCache: isDyldSharedCache, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - label: explicitLabels[index], - log: log - ) - } - - // Snapshot inputs may already carry a provenance label; binaries fall - // back to their file name so the axis is always readable. - let resolvedLabels = documents.enumerated().map { index, document in - document.provenance?.label ?? ABISnapshotInputLoader.defaultLabel(forPath: inputPaths[index]) - } - - log("Tracking evolution…") - let evolution = try ABIEvolutionBuilder().evolution(of: documents, labels: resolvedLabels) - - let output: String - if json { - output = String(decoding: try ABIJSON.encoder().encode(evolution), as: UTF8.self) - } else if summaryOnly { - output = ABIEvolutionReporter().summary(evolution) - } else { - output = ABIEvolutionReporter().report(evolution) - } - if let outputPath { - try (output + "\n").write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - log("Report written to \(outputPath)") - } else { - print(output) - } - - if failOnBreaking, evolution.hasBreakingChange { - throw ExitCode.failure - } - } - - /// The `--interface` path: render the union interface with lifecycle - /// annotations from N live binaries. The annotated interface renders from - /// the live models, so every input must be a binary — a persisted snapshot - /// carries no renderable interface (same constraint as `diff --interface`). - private func runAnnotatedInterface(explicitLabels: [String?]) async throws { - for inputPath in inputPaths { - if try ABISnapshotInputLoader.isSnapshotDocument(atPath: inputPath) { - throw ValidationError("--interface needs binaries; snapshot JSON inputs (\(inputPath)) only support the lineage report.") - } - } - - var machOFiles: [MachOFile] = [] - for inputPath in inputPaths { - log("Loading \(inputPath)…") - machOFiles.append(try loadMachO(at: inputPath)) - } - let resolvedLabels = inputPaths.enumerated().map { index, inputPath in - explicitLabels[index] ?? ABISnapshotInputLoader.defaultLabel(forPath: inputPath) - } - - // A sink on every version: each version's builder hands this handler to - // its indexer AND printer, so a dropped declaration lands on stderr - // instead of the os_log floor a CLI operator never sees. The erased - // builder, because the version count is a runtime value here — the - // pack-generic SwiftEvolutionInterfaceBuilder's arity is compile-time. - let builder = try AnySwiftEvolutionInterfaceBuilder( - eventHandlersPerVersion: { _, label in [ConsoleEventHandler(label: label)] }, - versions: machOFiles, - labels: resolvedLabels - ) - log("Indexing \(machOFiles.count) versions (\(min(maximumConcurrentPreparations, machOFiles.count)) at a time)…") - try await builder.prepare(maximumConcurrentPreparations: maximumConcurrentPreparations) - log("Rendering annotated interface…") - let annotated = try await builder.printAnnotatedInterface() - try emitInterface(annotated.string) - - if failOnBreaking, let evolution = builder.evolution, evolution.hasBreakingChange { - throw ExitCode.failure - } - } - - /// Loads one `--interface`-path input: an image extracted from a dyld - /// shared cache, or a thin/fat file on disk — the same shared - /// `MachOFile.load(...)` the rest of the CLI uses (see `DiffCommand`). - private func loadMachO(at path: String) throws -> MachOFile { - try MachOFile.load( - filePath: path, - isDyldSharedCache: isDyldSharedCache, - usesSystemDyldSharedCache: false, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - architecture: architecture - ) - } - - /// Writes the annotated interface: plain text to `--output`, or per-line - /// colorized to the terminal — legend/warning comments cyan, and each - /// annotated line colored by its most severe lifecycle event (removed red, - /// modified yellow, added green). - private func emitInterface(_ text: String) throws { - if let outputPath { - try text.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - log("Annotated interface written to \(outputPath)") - return - } - var output = "" - for line in text.split(separator: "\n", omittingEmptySubsequences: false) { - let lineText = String(line) - if lineText.hasPrefix("//") { - // Legend and warnings blocks sit at column 0. - output += lineText.cyan - } else if let annotationRange = lineText.range(of: "// [") { - // A trailing lifecycle annotation, or an overflow annotation on - // its own (indented) line. Classify by the annotation text only - // so a declaration whose name mentions these words stays plain. - let annotation = lineText[annotationRange.lowerBound...] - if annotation.contains("removed in") { - output += lineText.red - } else if annotation.contains("modified in") { - output += lineText.yellow - } else { - output += lineText.green - } - } else { - output += lineText - } - output += "\n" - } - print(output, terminator: "") - } - - /// 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 inputPaths.count < 2 { - throw ValidationError("evolution needs at least 2 inputs in version order (oldest first).") - } - if json, summaryOnly { - throw ValidationError("--json and --summary-only are mutually exclusive.") - } - if let jobs, jobs < 1 { - throw ValidationError("--jobs must be at least 1.") - } - if cacheImageName != nil, cacheImagePath != nil { - throw ValidationError("--cache-image-name and --cache-image-path are mutually exclusive; pass only one.") - } - if cacheImageName != nil || cacheImagePath != nil, !isDyldSharedCache { - throw ValidationError("--cache-image-name / --cache-image-path require --dyld-shared-cache.") - } - if isDyldSharedCache, cacheImageName == nil, cacheImagePath == nil { - throw ValidationError("--dyld-shared-cache requires --cache-image-name or --cache-image-path.") - } - } - - private func log(_ message: String) { - // See `DiffCommand.log`: the raising `FileHandle` overload aborts the - // process on a closed or broken stderr. - fputs(message + "\n", stderr) - } -} diff --git a/Sources/swift-section/Commands/InterfaceCommand.swift b/Sources/swift-section/Commands/InterfaceCommand.swift deleted file mode 100644 index 373e3dc69..000000000 --- a/Sources/swift-section/Commands/InterfaceCommand.swift +++ /dev/null @@ -1,212 +0,0 @@ -import SwiftDeclaration -import SwiftIndexing -import SwiftPrinting -import Foundation -import MachOKit -import MachOFoundation -import MachOSwiftSection -import SwiftInterface -import SwiftDeclarationRendering -import ArgumentParser -#if os(macOS) -import TypeIndexing -#endif - -struct InterfaceCommand: AsyncParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "interface", - abstract: "Generate Swift interface from a Mach-O file." - ) - - @OptionGroup - var machOOptions: MachOOptionGroup - - @OptionGroup - var objcMemberOptions: ObjCMemberOptionGroup - - @OptionGroup(title: "Comment Templates") - var transformerOptions: TransformerOptionGroup - - @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output will be printed to the console.", completion: .file()) - var outputPath: String? - - @Flag(help: "Show imported C types in the generated Swift interface.") - var showCImportedTypes: Bool = false - - @Flag(help: "Parse opaque return value, this option is an experimental feature and may result in parsing errors for complex return types.") - var parseOpaqueReturnType: Bool = false - - @Flag(help: "Resolve __C/__ObjC type module names to their real modules (__C.NSString -> Foundation.NSString) by indexing the SDK modules the binary links, its APINotes, and its dependencies' ObjC metadata. Requires Xcode; the first run per SDK generates module interfaces through sourcekitd and caches the extraction.") - var resolveCModuleNames: Bool = false - - @Option(name: .customLong("supplementary-apinotes"), help: "A supplementary .apinotes file (or a directory of them) of user-provided type mappings for frameworks with no SDK module (e.g. AttributeGraph), loaded on top of the SDK's own APINotes. Repeatable; later paths override earlier ones. Only used with --resolve-c-module-names.", completion: .file()) - var supplementaryAPINotesPaths: [String] = [] - - @Flag(help: "Generate field offset and PWT offset comments, if possible") - var emitOffsetComments: Bool = false - - @Flag(help: "Generate member address comments for each member symbol") - var emitMemberAddresses: Bool = false - - @Flag(help: "Generate vtable offset comments for class methods, computed properties, and non-final stored properties' accessors") - var emitVtableOffsets: Bool = false - - @Flag(help: "Expand nested struct fields with their absolute offsets (implies --emit-offset-comments)") - var emitExpandedFieldOffsets: Bool = false - - @Flag(help: "Generate type layout (size/stride/alignment) comments, computed statically via SwiftLayout") - var emitTypeLayout: Bool = false - - @Flag(help: "Generate enum layout (strategy/per-case/spare-bit) comments, computed statically via SwiftLayout") - var emitEnumLayout: Bool = false - - @Flag(help: "Sort members by binary layout offset instead of grouping by category") - var sortMembersByOffset: Bool = false - - @Flag(help: "Emit a leading header comment block (generator, image path, UUID, architecture, library-evolution detection, unrecoverable-facts notes)") - var emitHeader: Bool = false - - @Flag(help: "Annotate members none of whose symbols have an export-trie entry with a `not exported` comment") - var emitExportStatus: Bool = false - - @Flag(name: .customLong("exported-only"), help: "Print only the declarations the image exports: types and protocols whose descriptor symbol has an export-trie entry, extensions targeting them, and members with at least one exported symbol (dispatch-thunk and other derived forms included). `override` / `@objc` members and anything without export evidence are kept.") - var exportedOnly: Bool = false - - @Option(name: .shortAndLong, help: "The color scheme for the output.") - var colorScheme: SemanticColorScheme = .none - - func run() async throws { - try await AccessorThunkResolution.withResolver(from: machOOptions) { - try await buildInterface() - } - } - - private func buildInterface() async throws { - let machOFile = try MachOFile.load(options: machOOptions) - - let effectiveEmitOffsetComments = emitOffsetComments || emitExpandedFieldOffsets - - var printConfiguration = SwiftDeclarationPrintConfiguration( - printStrippedSymbolicItem: true, - printFieldOffset: effectiveEmitOffsetComments, - printExpandedFieldOffsets: emitExpandedFieldOffsets, - printMemberAddress: emitMemberAddresses, - printVTableOffset: emitVtableOffsets, - printExportStatus: emitExportStatus, - printExportedDeclarationsOnly: exportedOnly, - memberSortOrder: sortMembersByOffset ? .byOffset : .byCategory, - printTypeLayout: emitTypeLayout, - printEnumLayout: emitEnumLayout - ) - - // Without any template option the slots stay empty, keeping the - // built-in rendering byte-for-byte identical. - if let transformers = try transformerOptions.buildTransformerConfiguration() { - printConfiguration.applyTransformersEnablingCommentKinds(transformers) - } - printConfiguration.staticLayoutDependencyResolution = machOOptions.staticLayoutDependencyResolution - // The index records the name-only ObjC tie either way; this decides - // whether it prints as `@objc override`. - printConfiguration.infersObjCOverridesFromSelectorNames = objcMemberOptions.infersOverridesFromSelectorNames - - var configuration = SwiftInterfaceBuilderConfiguration( - indexConfiguration: .init( - showCImportedTypes: showCImportedTypes, - dependencySearchPaths: machOOptions.indexDependencySearchPaths - ), - printConfiguration: printConfiguration - ) - - if emitHeader { - // The factory's dispatch-thunk count triggers the symbol-index - // build (which `prepare()` below then reuses), so announce - // progress BEFORE it — otherwise the tool sits silent for the - // whole index build. - print("Preparing to build Swift interface...") - configuration.interfaceHeaderInfo = InterfaceHeaderInfo( - machO: machOFile, - generatorName: "swift-section", - generatorVersion: BundledVersion.value - ) - } - - let builder = try SwiftInterfaceBuilder(configuration: configuration, eventHandlers: [ConsoleEventHandler()], in: machOFile) - - if parseOpaqueReturnType { - builder.addExtraDataProvider(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machOFile)) - } - - if resolveCModuleNames { - #if os(macOS) - if #available(macOS 13.0, *) { - let providerDependencies = SwiftInterfaceBuilderDependencies( - machO: machOFile, - searchPaths: [.systemDyldSharedCache], - eventHandlers: [ConsoleEventHandler()] - ) - // Dependency resolution against the HOST dyld cache matches - // install names exactly, then bare names; a non-macOS binary's - // paths mostly miss both, which silently guts the SDK-interface - // source. Say so — and name the misses — instead of degrading - // quietly. - if providerDependencies.dependencies.isEmpty { - fputs("warning: --resolve-c-module-names resolved no dependency images against this host (non-macOS binary?); attribution will be limited to SDK APINotes and supplementary files\n", stderr) - } else if !providerDependencies.unresolvedLoadNames.isEmpty { - fputs("warning: --resolve-c-module-names could not resolve \(providerDependencies.unresolvedLoadNames.count) dependency image(s) against this host; their types will not be attributed: \(providerDependencies.unresolvedLoadNames.joined(separator: ", "))\n", stderr) - } - // Bad supplementary paths are otherwise only os_log'd by the - // library floor; a CLI user who mistyped a path or handed a - // broken YAML deserves the same stderr warning the other - // degradations get. (Files inside a directory argument stay - // on the library's skip-and-log contract.) - for supplementaryAPINotesPath in supplementaryAPINotesPaths { - var pathIsDirectory: ObjCBool = false - guard FileManager.default.fileExists(atPath: supplementaryAPINotesPath, isDirectory: &pathIsDirectory) else { - fputs("warning: --supplementary-apinotes path does not exist: \(supplementaryAPINotesPath)\n", stderr) - continue - } - if !pathIsDirectory.boolValue { - do { - _ = try APINotesFile(path: supplementaryAPINotesPath) - } catch { - fputs("warning: --supplementary-apinotes file failed to parse and will be skipped: \(supplementaryAPINotesPath): \(error)\n", stderr) - } - } - } - let supplementaryAPINotesURLs = supplementaryAPINotesPaths.map { URL(fileURLWithPath: $0) } - if let typeNameProvider = SwiftInterfaceBuilderTypeNameProvider(machO: machOFile, dependencies: providerDependencies, supplementaryAPINotesURLs: supplementaryAPINotesURLs) { - builder.addExtraDataProvider(typeNameProvider) - } else { - fputs("warning: --resolve-c-module-names ignored: the binary carries no build-version command mapping to a known SDK platform\n", stderr) - } - } else { - fputs("warning: --resolve-c-module-names requires macOS 13 or later\n", stderr) - } - #else - fputs("warning: --resolve-c-module-names is only available on macOS\n", stderr) - #endif - } else if !supplementaryAPINotesPaths.isEmpty { - fputs("warning: --supplementary-apinotes has no effect without --resolve-c-module-names\n", stderr) - } - - if !emitHeader { - print("Preparing to build Swift interface...") - } - - try await builder.prepare() - - print("Building Swift interface...") - - let interfaceString = try await builder.printRoot() - - print("Swift interface built successfully.") - - if let outputPath { - print("Writing Swift interface to \(outputPath)...") - let outputURL = URL(fileURLWithPath: outputPath) - try interfaceString.string.write(to: outputURL, atomically: true, encoding: .utf8) - } else { - interfaceString.printColorfully(using: colorScheme) - } - } -} diff --git a/Sources/swift-section/Commands/SnapshotCommand.swift b/Sources/swift-section/Commands/SnapshotCommand.swift deleted file mode 100644 index a46fdc26d..000000000 --- a/Sources/swift-section/Commands/SnapshotCommand.swift +++ /dev/null @@ -1,66 +0,0 @@ -import ArgumentParser -import Foundation -import SwiftDeclarationRendering -import SwiftDiffing - -struct SnapshotCommand: AsyncParsableCommand { - static let configuration: CommandConfiguration = .init( - commandName: "snapshot", - abstract: "Index a Mach-O binary's Swift ABI and persist it as a baseline snapshot (JSON)." - ) - - @OptionGroup var machOOptions: MachOOptionGroup - - @Option(name: .long, help: "A human-readable version label stored in the snapshot's provenance (e.g. 17.0).") - var label: String? - - @Option(name: .shortAndLong, help: "Write the snapshot JSON to this path instead of stdout.", completion: .file()) - var outputPath: String? - - func run() async throws { - guard let filePath = machOOptions.filePath else { - throw ValidationError("A Mach-O file path is required.") - } - let document = try await AccessorThunkResolution.withResolver(from: machOOptions) { - try await ABISnapshotInputLoader.loadDocument( - path: filePath, - architecture: machOOptions.architecture, - isDyldSharedCache: machOOptions.isDyldSharedCache, - cacheImageName: machOOptions.cacheImageName, - cacheImagePath: machOOptions.cacheImagePath, - label: label, - log: log - ) - } - let encoded = try document.encoded() - if let outputPath { - try encoded.write(to: URL(fileURLWithPath: outputPath), options: .atomic) - log("Snapshot written to \(outputPath)") - } else { - // `fwrite`, not `FileHandle.standardOutput.write(_:)`. This is the - // command's product output, not a diagnostic, but it took the same - // raising Objective-C overload — so `swift-section snapshot … | head` - // aborted the process rather than stopping cleanly. - // `write(contentsOf:)` would be the throwing Swift spelling, but it - // needs macOS 10.15.4 and this package deploys to 10.15. - encoded.withUnsafeBytes { buffer in - _ = fwrite(buffer.baseAddress, 1, buffer.count, stdout) - } - fputs("\n", stdout) - } - } - - func validate() throws { - if machOOptions.usesSystemDyldSharedCache { - // A snapshot of "the current system cache" would have no stable - // path to record; require an explicit cache file for baselines. - throw ValidationError("snapshot requires an explicit file path; --uses-system-dyld-shared-cache is not supported here.") - } - } - - private func log(_ message: String) { - // See `DiffCommand.log`: the raising `FileHandle` overload aborts the - // process on a closed or broken stderr. - fputs(message + "\n", stderr) - } -} diff --git a/Sources/swift-section/Models/SwiftSection.swift b/Sources/swift-section/Models/SwiftSection.swift deleted file mode 100644 index c53dca6f7..000000000 --- a/Sources/swift-section/Models/SwiftSection.swift +++ /dev/null @@ -1,12 +0,0 @@ -import ArgumentParser - -enum SwiftSection: String, CaseIterable, ExpressibleByArgument, Sendable { - case types - case protocols - case protocolConformances - case associatedTypes - /// Classes implemented through `@objc @implementation` — no `__swift5_*` - /// presence; recognized from `__objc_classlist` joined with the symbol - /// table (evolution proposal `objc-implementation-class-recognition`). - case objcImplementationClasses -} diff --git a/Sources/swift-section/ObjC/Commands/ObjCDumpCommand.swift b/Sources/swift-section/ObjC/Commands/ObjCDumpCommand.swift deleted file mode 100644 index 92d60d432..000000000 --- a/Sources/swift-section/ObjC/Commands/ObjCDumpCommand.swift +++ /dev/null @@ -1,166 +0,0 @@ -import ArgumentParser -import Foundation -import MachOKit -import Semantic - -struct ObjCDumpCommand: AsyncParsableCommand, Sendable { - static let configuration: CommandConfiguration = .init( - commandName: "dump", - abstract: "Dump every Objective-C declaration in a Mach-O file or dyld shared cache image." - ) - - @OptionGroup - var machOOptions: ObjCMachOOptionGroup - - @OptionGroup(title: "Generation") - var generationOptions: ObjCGenerationOptionGroup - - @OptionGroup(title: "Comment Templates") - var transformerOptions: ObjCTransformerOptionGroup - - @Option( - name: .shortAndLong, - help: ArgumentHelp( - "The kinds of declaration to dump, comma-separated (e.g. classes,protocols). If not specified, all of them are dumped.", - valueName: "kinds" - ) - ) - var sections: ObjCSectionKindList? - - @Option(name: .shortAndLong, help: "Only dump declarations whose name contains this text, case-insensitively.") - var filter: String? - - @Option(name: .shortAndLong, help: "The output path for the dump. If not specified, the output is printed to stdout.", completion: .file()) - var outputPath: String? - - @Option(name: .shortAndLong, help: "The color scheme for the output.") - var colorScheme: SemanticColorScheme = .none - - @Flag(name: .shortAndLong, help: "Report indexing progress on stderr.") - var verbose: Bool = false - - func run() async throws { - let session = try await ObjCInterfaceSession.make( - machOOptions: machOOptions, - generationOptions: generationOptions, - transformerOptions: transformerOptions, - isVerbose: verbose - ) - - let requestedKinds = sections?.kinds - let kinds = requestedKinds ?? ObjCSectionKind.allCases - var nameCountByKind: [ObjCSectionKind: Int] = [:] - var emittedCount = 0 - var dumpedString = "" - - for kind in kinds { - let names = session.names(of: kind) - nameCountByKind[kind] = names.count - for name in names where matchesFilter(name) { - guard let interface = session.interface(of: kind, named: name) else { continue } - emit(interface, into: &dumpedString) - emittedCount += 1 - } - } - - if let outputPath { - try dumpedString.write(to: URL(fileURLWithPath: outputPath), atomically: true, encoding: .utf8) - } - - // `session.isEmpty` walks every kind, so it is only consulted once the - // requested ones have already come back empty. - let isEntireIndexEmpty = nameCountByKind.values.allSatisfy { $0 == 0 } && session.isEmpty - let outcome = Outcome( - imageDescription: machOOptions.imageDescription, - explicitKinds: requestedKinds, - nameCountByKind: nameCountByKind, - isEntireIndexEmpty: isEntireIndexEmpty, - filter: filter, - emittedCount: emittedCount - ) - for note in Self.diagnosticNotes(for: outcome) { - writeStandardErrorLine(note) - } - } - - /// Catches the spelling this option used to accept. `--sections classes protocols` - /// leaves `protocols` sitting in the positional slot, so the binary would be - /// looked for under a declaration kind's name — a confusing "no such file" - /// far from the real mistake. - /// - /// Only the two-token shape is recoverable here: with a path as well - /// (`--sections classes protocols /bin/ls`) the parser rejects the extra - /// positional argument before `validate()` ever runs. - func validate() throws { - guard let sections, - let filePath = machOOptions.filePath, - ObjCSectionKind(rawValue: filePath) != nil - else { return } - - let combinedKinds = (sections.kinds.map(\.rawValue) + [filePath]).joined(separator: ",") - throw ValidationError( - """ - '\(filePath)' was read as the input path, but it is also a declaration kind. \ - --sections takes one comma-separated value: write '--sections \(combinedKinds)' \ - and put the input path after it. - """ - ) - } - - /// What one run actually found, as far as the diagnostics care. - struct Outcome { - var imageDescription: String - /// The kinds the caller named with `--sections`, or `nil` when every - /// kind was dumped by default. Only named kinds are reported as empty: - /// otherwise every dump of a pure-Swift binary would nag about the four - /// kinds the caller never asked for. - var explicitKinds: [ObjCSectionKind]? - var nameCountByKind: [ObjCSectionKind: Int] - var isEntireIndexEmpty: Bool - var filter: String? - var emittedCount: Int - } - - /// Why a dump produced nothing, in the caller's terms. - /// - /// Without these, three unrelated situations are byte-for-byte identical — - /// empty stdout, empty stderr, exit code 0 — and there is no way to tell a - /// binary that carries no Objective-C from one whose metadata failed to - /// read. Pure so the wording can be tested without capturing a process's - /// stderr; the exit code deliberately stays 0 in every case, so no existing - /// script turns red over a diagnostic. - static func diagnosticNotes(for outcome: Outcome) -> [String] { - // Subsumes the per-kind notes: reporting each requested kind as empty - // would just be five ways of saying the same thing. - if outcome.isEntireIndexEmpty { - return ["no Objective-C metadata found in \(outcome.imageDescription)"] - } - - var notes: [String] = [] - for kind in outcome.explicitKinds ?? [] where outcome.nameCountByKind[kind, default: 0] == 0 { - notes.append("no \(kind.rawValue) found in \(outcome.imageDescription)") - } - - let totalNameCount = outcome.nameCountByKind.values.reduce(0, +) - if let filter = outcome.filter, !filter.isEmpty, outcome.emittedCount == 0, totalNameCount > 0 { - let declarationNoun = totalNameCount == 1 ? "declaration" : "declarations" - notes.append("--filter '\(filter)' matched none of the \(totalNameCount) \(declarationNoun) in \(outcome.imageDescription)") - } - return notes - } - - private func matchesFilter(_ name: String) -> Bool { - guard let filter, !filter.isEmpty else { return true } - return name.range(of: filter, options: .caseInsensitive) != nil - } - - private func emit(_ semanticString: SemanticString, into dumpedString: inout String) { - if outputPath != nil { - dumpedString.append(semanticString.string) - dumpedString.append("\n\n") - } else { - semanticString.printColorfully(using: colorScheme) - print("") - } - } -} diff --git a/Sources/swift-section/ObjC/Models/ObjCSectionKind.swift b/Sources/swift-section/ObjC/Models/ObjCSectionKind.swift deleted file mode 100644 index 191229647..000000000 --- a/Sources/swift-section/ObjC/Models/ObjCSectionKind.swift +++ /dev/null @@ -1,11 +0,0 @@ -import ArgumentParser - -/// The kinds of declaration `dump` can emit. With none given it emits all of -/// them, in the order listed here. -enum ObjCSectionKind: String, CaseIterable, ExpressibleByArgument, Sendable { - case classes - case protocols - case categories - case structs - case unions -} diff --git a/Sources/swift-section/ObjC/Utilities/ObjCInterfaceSession.swift b/Sources/swift-section/ObjC/Utilities/ObjCInterfaceSession.swift deleted file mode 100644 index fe16f4867..000000000 --- a/Sources/swift-section/ObjC/Utilities/ObjCInterfaceSession.swift +++ /dev/null @@ -1,162 +0,0 @@ -import Foundation -import MachOKit -import MachOKitExtensions -import ObjCDeclarationRendering -import ObjCIndexing -import ObjCInterface -import ObjCMetadataSource -import Semantic - -/// Everything a command needs after option parsing: the loaded binary, a -/// prepared index over it, and the builder plus the per-request rendering -/// arguments that every `*Interface` call takes. -/// -/// Both subcommands do exactly the same setup, and getting it wrong in one of -/// them would show up as a silent difference in output rather than as an -/// error — so it lives in one place. -struct ObjCInterfaceSession { - let machOFile: MachOFile - let indexer: ObjCInterfaceIndexer - let builder: ObjCInterfaceBuilder - - private let options: ObjCGenerationOptions - private let cTypeReplacements: [ObjCPrimitiveTypePattern: String] - private let ivarOffsetCommentBuilder: (@Sendable (Int) -> String)? - - static func make( - machOOptions: ObjCMachOOptionGroup, - generationOptions: ObjCGenerationOptionGroup, - transformerOptions: ObjCTransformerOptionGroup, - isVerbose: Bool - ) async throws -> ObjCInterfaceSession { - let machOFile = try MachOFile.load(options: machOOptions) - - // The handler is bound at `init`, not at `prepare()`: events are - // delivered during the walk and nothing is retained afterwards, so - // there is no way to attach one later and recover them. - // Progress goes to stderr so that a redirected dump stays a dump. - let eventHandler: (@Sendable (ObjCIndexingEvent) -> Void)? = isVerbose - ? { @Sendable event in reportProgress(event) } - : nil - let indexer = ObjCInterfaceIndexer( - machO: machOFile, - imagePath: machOFile.imagePath, - eventHandler: eventHandler - ) - try await indexer.prepare() - - var options = generationOptions.build() - // A template option on its own would otherwise be silently inert. - if transformerOptions.impliesIvarOffsetComments { - options.addIvarOffsetComments = true - } - - return ObjCInterfaceSession( - machOFile: machOFile, - indexer: indexer, - builder: ObjCInterfaceBuilder(indexer: indexer, machO: machOFile), - options: options, - cTypeReplacements: try transformerOptions.buildCTypeReplacements(), - ivarOffsetCommentBuilder: transformerOptions.buildIvarOffsetCommentBuilder() - ) - } - - // MARK: - Rendering - - func classInterface(named name: String) -> SemanticString? { - builder.classInterface( - named: name, - options: options, - cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder - ) - } - - func protocolInterface(named name: String) -> SemanticString? { - builder.protocolInterface( - named: name, - options: options, - cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder - ) - } - - func categoryInterface(uniqueName: String) -> SemanticString? { - builder.categoryInterface( - uniqueName: uniqueName, - options: options, - cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder - ) - } - - func structInterface(named name: String) -> SemanticString? { - builder.structInterface( - named: name, - options: options, - cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder - ) - } - - func unionInterface(named name: String) -> SemanticString? { - builder.unionInterface( - named: name, - options: options, - cTypeReplacements: cTypeReplacements, - ivarOffsetCommentBuilder: ivarOffsetCommentBuilder - ) - } - - /// The declaration names of `kind`, sorted, so that two runs over the same - /// binary print the same thing. The index stores them in dictionaries, - /// whose iteration order is not stable across runs. - func names(of kind: ObjCSectionKind) -> [String] { - switch kind { - case .classes: indexer.classNames.sorted() - case .protocols: indexer.protocolNames.sorted() - case .categories: indexer.categoryNames.sorted() - case .structs: indexer.structNames.sorted() - case .unions: indexer.unionNames.sorted() - } - } - - /// Whether the index holds no declaration at all, of any kind. This is what - /// separates "this binary carries no Objective-C metadata" from "the kinds - /// you asked for happen to be empty in it" — the two are otherwise - /// indistinguishable from an empty dump. - var isEmpty: Bool { - ObjCSectionKind.allCases.allSatisfy { names(of: $0).isEmpty } - } - - func interface(of kind: ObjCSectionKind, named name: String) -> SemanticString? { - switch kind { - case .classes: classInterface(named: name) - case .protocols: protocolInterface(named: name) - case .categories: categoryInterface(uniqueName: name) - case .structs: structInterface(named: name) - case .unions: unionInterface(named: name) - } - } - - // MARK: - Progress - - private static func reportProgress(_ event: ObjCIndexingEvent) { - guard case .progress(let phase, let itemDescription, let currentCount, let totalCount) = event else { - return - } - let phaseDescription = - switch phase { - case .indexingSubclasses: "Indexing subclasses" - case .indexingConformances: "Indexing conformances" - case .loadingClasses: "Loading classes" - case .loadingProtocols: "Loading protocols" - case .loadingCategories: "Loading categories" - } - var line = "\(phaseDescription) \(currentCount)/\(totalCount)" - if !itemDescription.isEmpty { - line += " \(itemDescription)" - } - writeStandardErrorLine(line) - } -} diff --git a/Sources/swift-section/ObjC/Utilities/ObjCSnapshotInputLoader.swift b/Sources/swift-section/ObjC/Utilities/ObjCSnapshotInputLoader.swift deleted file mode 100644 index 348a912cd..000000000 --- a/Sources/swift-section/ObjC/Utilities/ObjCSnapshotInputLoader.swift +++ /dev/null @@ -1,90 +0,0 @@ -import Foundation -import MachOKit -import ObjCDiffing -import ObjCIndexing -import ObjCInterface - -/// Shared input plumbing for the API commands (`snapshot` / `diff` / -/// `evolution`): a path is either a persisted `ObjCAPISnapshotDocument` -/// (JSON) or a Mach-O / fat binary / dyld shared cache to index and freeze. -/// Centralized so the three commands cannot drift in how they sniff, load, -/// index, or stamp provenance. -enum ObjCSnapshotInputLoader { - /// A snapshot document begins with `{` (after whitespace); every Mach-O, - /// fat, or cache input begins with a binary magic. One byte decides. - static func isSnapshotDocument(atPath path: String) throws -> Bool { - let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) - defer { fileHandle.closeFile() } - let prefix = fileHandle.readData(ofLength: 64) - let firstNonWhitespace = prefix.first { byte in - byte != UInt8(ascii: " ") && byte != UInt8(ascii: "\n") - && byte != UInt8(ascii: "\r") && byte != UInt8(ascii: "\t") - } - return firstNonWhitespace == UInt8(ascii: "{") - } - - /// Load one input as a frozen snapshot document. A JSON path decodes - /// (with the format-version check); a binary path is loaded, indexed, and - /// frozen, with provenance stamped from the load parameters. `label` - /// overrides the document's provenance label either way. - static func loadDocument( - path: String, - architecture: Architecture?, - isDyldSharedCache: Bool, - cacheImageName: String?, - cacheImagePath: String?, - label: String?, - log: (String) -> Void - ) async throws -> ObjCAPISnapshotDocument { - if try isSnapshotDocument(atPath: path) { - log("Reading snapshot \(path)…") - var document = try ObjCAPISnapshotDocument.decode(from: Data(contentsOf: URL(fileURLWithPath: path))) - if let label { - var provenance = document.provenance ?? ObjCAPIProvenance() - provenance.label = label - document.provenance = provenance - } - return document - } - - log("Indexing \(path)…") - let machOFile = try MachOFile.load( - filePath: path, - isDyldSharedCache: isDyldSharedCache, - usesSystemDyldSharedCache: false, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - architecture: architecture - ) - let indexer = ObjCInterfaceIndexer(machO: machOFile, imagePath: machOFile.imagePath) - try await indexer.prepare() - let snapshotBuilder = ObjCAPISnapshotBuilder(indexer: indexer) - let cacheImageSuffix = [cacheImageName, cacheImagePath].compactMap { $0 }.first.map { " (\($0))" } ?? "" - let provenance = ObjCAPIProvenance( - label: label, - binaryPath: path + cacheImageSuffix, - generatorVersion: BundledVersion.value, - createdAt: Date() - ) - return ObjCAPISnapshotDocument(provenance: provenance, snapshot: snapshotBuilder.snapshot()) - } - - /// Split a `--labels a,b,c` value and require one label per input. - static func parseLabels(_ commaSeparatedLabels: String?, inputCount: Int) throws -> [String?] { - guard let commaSeparatedLabels else { - return Array(repeating: nil, count: inputCount) - } - let labels = commaSeparatedLabels - .split(separator: ",", omittingEmptySubsequences: false) - .map { $0.trimmingCharacters(in: .whitespaces) } - guard labels.count == inputCount else { - throw ObjCAPIEvolutionError.labelCountMismatch(labelCount: labels.count, versionCount: inputCount) - } - return labels - } - - /// The fallback axis label for an input path: its file name. - static func defaultLabel(forPath path: String) -> String { - URL(fileURLWithPath: path).lastPathComponent - } -} diff --git a/Sources/swift-section/ObjC/Utilities/StandardErrorLog.swift b/Sources/swift-section/ObjC/Utilities/StandardErrorLog.swift deleted file mode 100644 index 4635c27df..000000000 --- a/Sources/swift-section/ObjC/Utilities/StandardErrorLog.swift +++ /dev/null @@ -1,11 +0,0 @@ -import Foundation - -/// Writes one line to stderr. -/// -/// Progress, warnings and diagnostics all go here so that a redirected stdout -/// stays a pure product: `swift-section objc dump … > Header.h` must not pick up a -/// progress line. Shared because every command needs it, and four hand-rolled -/// copies of this one line had already accumulated. -func writeStandardErrorLine(_ message: String) { - FileHandle.standardError.write(Data((message + "\n").utf8)) -} diff --git a/Sources/swift-section/Utilities/ABISnapshotInputLoader.swift b/Sources/swift-section/Utilities/ABISnapshotInputLoader.swift deleted file mode 100644 index 5f2220c74..000000000 --- a/Sources/swift-section/Utilities/ABISnapshotInputLoader.swift +++ /dev/null @@ -1,99 +0,0 @@ -import Foundation -import MachOKit -import MachOFoundation -import SwiftDiffing -import SwiftIndexing -import SwiftInterface - -/// Shared input plumbing for the ABI commands (`snapshot` / `diff` / -/// `evolution`): a path is either a persisted `ABISnapshotDocument` (JSON) or -/// a Mach-O / fat binary / dyld shared cache to index and freeze. Centralized -/// so the three commands cannot drift in how they sniff, load, index, or stamp -/// provenance. -enum ABISnapshotInputLoader { - /// A snapshot document begins with `{` (after whitespace); every Mach-O, - /// fat, or cache input begins with a binary magic. One byte decides. - static func isSnapshotDocument(atPath path: String) throws -> Bool { - let fileHandle = try FileHandle(forReadingFrom: URL(fileURLWithPath: path)) - defer { fileHandle.closeFile() } - let prefix = fileHandle.readData(ofLength: 64) - let firstNonWhitespace = prefix.first { byte in - byte != UInt8(ascii: " ") && byte != UInt8(ascii: "\n") - && byte != UInt8(ascii: "\r") && byte != UInt8(ascii: "\t") - } - return firstNonWhitespace == UInt8(ascii: "{") - } - - /// Load one input as a frozen snapshot document. A JSON path decodes (with - /// the format-version check); a binary path is loaded, indexed, and frozen, - /// with provenance stamped from the load parameters. `label` overrides the - /// document's provenance label either way. `consoleLabel` tags the - /// input's stderr diagnostics (inputs index concurrently under `--jobs`, - /// so an unlabeled line cannot be attributed); it defaults to `label`, - /// then to the input's file name. - static func loadDocument( - path: String, - architecture: Architecture?, - isDyldSharedCache: Bool, - cacheImageName: String?, - cacheImagePath: String?, - label: String?, - consoleLabel: String? = nil, - log: (String) -> Void - ) async throws -> ABISnapshotDocument { - if try isSnapshotDocument(atPath: path) { - log("Reading snapshot \(path)…") - var document = try ABISnapshotDocument.decode(from: Data(contentsOf: URL(fileURLWithPath: path))) - if let label { - var provenance = document.provenance ?? ABIProvenance() - provenance.label = label - document.provenance = provenance - } - return document - } - - log("Indexing \(path)…") - let machOFile = try MachOFile.load( - filePath: path, - isDyldSharedCache: isDyldSharedCache, - usesSystemDyldSharedCache: false, - cacheImageName: cacheImageName, - cacheImagePath: cacheImagePath, - architecture: architecture - ) - // Shared by `snapshot` / `evolution` / `diff`'s snapshot inputs, so this - // is where those three get a stderr sink for anything indexing drops. - let builder = SwiftDiffableInterfaceBuilder( - eventHandlers: [ConsoleEventHandler(label: consoleLabel ?? label ?? defaultLabel(forPath: path))], - in: machOFile - ) - try await builder.prepare() - let cacheImageSuffix = [cacheImageName, cacheImagePath].compactMap { $0 }.first.map { " (\($0))" } ?? "" - let provenance = ABIProvenance( - label: label, - binaryPath: path + cacheImageSuffix, - generatorVersion: BundledVersion.value, - createdAt: Date() - ) - return ABISnapshotDocument(provenance: provenance, snapshot: builder.snapshot()) - } - - /// Split a `--labels a,b,c` value and require one label per input. - static func parseLabels(_ commaSeparatedLabels: String?, inputCount: Int) throws -> [String?] { - guard let commaSeparatedLabels else { - return Array(repeating: nil, count: inputCount) - } - let labels = commaSeparatedLabels - .split(separator: ",", omittingEmptySubsequences: false) - .map { $0.trimmingCharacters(in: .whitespaces) } - guard labels.count == inputCount else { - throw ABIEvolutionError.labelCountMismatch(labelCount: labels.count, versionCount: inputCount) - } - return labels - } - - /// The fallback axis label for an input path: its file name. - static func defaultLabel(forPath path: String) -> String { - URL(fileURLWithPath: path).lastPathComponent - } -} diff --git a/Sources/swift-section/Utilities/Extensions.swift b/Sources/swift-section/Utilities/Extensions.swift deleted file mode 100644 index 26e1cf088..000000000 --- a/Sources/swift-section/Utilities/Extensions.swift +++ /dev/null @@ -1,136 +0,0 @@ -import Foundation -import MachOKit -import MachOFoundation -import Rainbow -import Semantic - -extension MachOFile { - /// The core loader shared by every command: either a thin/fat Mach-O file at - /// `filePath` (selecting `architecture` for a fat binary), or an image - /// extracted from a dyld shared cache (the running system's, or the cache at - /// `filePath`). Centralizing it keeps every command's fat-binary affordance - /// (the `availableArchitectures` hint) and cache-image disambiguation - /// identical instead of each command re-deriving them and drifting. - static func load( - filePath: String?, - isDyldSharedCache: Bool, - usesSystemDyldSharedCache: Bool, - cacheImageName: String?, - cacheImagePath: String?, - architecture: Architecture? - ) throws -> MachOFile { - if isDyldSharedCache || usesSystemDyldSharedCache { - let dyldCache: FullDyldCache - if usesSystemDyldSharedCache { - if let host = FullDyldCache.host { - dyldCache = host - } else { - throw SwiftSectionCommandError.unsupportedSystemVersionForDyldSharedCache - } - } else { - let url = try URL(fileURLWithPath: required(filePath, error: SwiftSectionCommandError.missingFilePath)) - dyldCache = try FullDyldCache(url: url) - } - - if cacheImagePath != nil, cacheImageName != nil { - throw SwiftSectionCommandError.ambiguousCacheImageNameAndCacheImagePath - } else if let cacheImageName { - return try required(dyldCache.machOFile(by: .name(cacheImageName)), error: SwiftSectionCommandError.imageNotFound) - } else if let cacheImagePath { - return try required(dyldCache.machOFile(by: .path(cacheImagePath)), error: SwiftSectionCommandError.imageNotFound) - } else { - throw SwiftSectionCommandError.missingCacheImageNameOrCacheImagePath - } - } else { - let url = try URL(fileURLWithPath: required(filePath, error: SwiftSectionCommandError.missingFilePath)) - let file = try File.loadFromFile(url: url) - switch file { - case .machO(let machOFile): - return machOFile - case .fat(let fatFile): - let machOFiles = try fatFile.machOFiles() - guard let architecture else { - let availableArchitectures = machOFiles.map { machOFile -> String in - Architecture(cpu: machOFile.header.cpu)?.rawValue ?? machOFile.header.cpu.description - } - throw SwiftSectionCommandError.fatBinaryRequiresArchitecture(availableArchitectures: availableArchitectures) - } - return try required(machOFiles.first { $0.header.cpu.subtype == architecture.cpu }, error: SwiftSectionCommandError.invalidArchitecture) - } - } - } - - static func load(options: MachOOptionGroup) throws -> MachOFile { - try load( - filePath: options.filePath, - isDyldSharedCache: options.isDyldSharedCache, - usesSystemDyldSharedCache: options.usesSystemDyldSharedCache, - cacheImageName: options.cacheImageName, - cacheImagePath: options.cacheImagePath, - architecture: options.architecture - ) - } -} - -extension String { - func withColorHex(for type: SemanticType, colorScheme: SemanticColorScheme) -> String? { - switch colorScheme { - case .none: - return nil - case .light: - switch type { - case .comment: - return "#56606B" - case .keyword: - return "#C33381" - case .type(_, .name): - return "#2E0D6E" - case .type(_, .declaration): - return "#004975" - case .function(.name), - .member(.name): - return "#5C2699" - case .function(.declaration), - .member(.declaration), - .variable: - return "#0F68A0" - case .numeric: - return "#000BFF" - default: - return nil - } - case .dark: - switch type { - case .comment: - return "#6C7987" - case .keyword: - return "#F2248C" - case .type(_, .name): - return "#D0A8FF" - case .type(_, .declaration): - return "#5DD8FF" - case .function(.name), - .member(.name): - return "#A167E6" - case .function(.declaration), - .member(.declaration): - return "#41A1C0" - case .numeric: - return "#D0BF69" - default: - return nil - } - } - } - - func withColor(for type: SemanticType, colorScheme: SemanticColorScheme) -> String { - if let colorHex = withColorHex(for: type, colorScheme: colorScheme) { - let resolved = hex(colorHex, to: .bit24) - return resolved - } else if type == .error { - return red - } else { - return self - } - } -} diff --git a/Sources/swift-section/Utilities/IgnoreCoding.swift b/Sources/swift-section/Utilities/IgnoreCoding.swift deleted file mode 100644 index 14521bc45..000000000 --- a/Sources/swift-section/Utilities/IgnoreCoding.swift +++ /dev/null @@ -1,17 +0,0 @@ -import MachOKitExtensions - - -@propertyWrapper -struct IgnoreCoding { - var wrappedValue: Value - - init(wrappedValue: Value) { - self.wrappedValue = wrappedValue - } -} - -extension IgnoreCoding: Codable where Value: OptionalProtocol { - func encode(to encoder: Encoder) throws {} - - init(from decoder: Decoder) throws { self.wrappedValue = nil } -} diff --git a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift index fbad8e4d9..37612520b 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/DyldCacheAssociatedTypeTests.swift @@ -14,14 +14,14 @@ final class DyldCacheAssociatedTypeTests: DyldCacheTests, @unchecked Sendable { let machO = machOFileInMainCache for associatedType in try machO.swift.associatedTypes { - let conformingTypeName = try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machO).print(using: .interfaceType) - let protocolTypeName = try SymbolicDemangler.demangleType(for: associatedType.protocolTypeName, in: machO).print(using: .interfaceType) + let conformingTypeName = try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machO.context).print(using: .interfaceType) + let protocolTypeName = try SymbolicDemangler.demangleType(for: associatedType.protocolTypeName, in: machO.context).print(using: .interfaceType) // if conformingTypeName == "SwiftUI.LeadingTrailingLabeledContentStyle", protocolTypeName == "SwiftUI.LabeledContentStyle" { conformingTypeName.print() protocolTypeName.print() for record in associatedType.records { - let substitutedTypeName = try record.substitutedTypeName(in: machO) - try SymbolicDemangler.demangleType(for: substitutedTypeName, in: machO).print().print() + let substitutedTypeName = try record.substitutedTypeName(in: machO.context) + try SymbolicDemangler.demangleType(for: substitutedTypeName, in: machO.context).print().print() // substitutedTypeName.startOffset.print() } "----------------".print() @@ -35,7 +35,7 @@ final class DyldCacheAssociatedTypeTests: DyldCacheTests, @unchecked Sendable { let machO = machOFileInCache for context in try machO.swift.typeContextDescriptors { - try context.typeName(in: machO).node.print(using: [.showPrivateDiscriminators]).print() + try context.typeName(in: machO.context).node.print(using: [.showPrivateDiscriminators]).print() } } } diff --git a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift index 63ac00e44..5e3742d38 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/MetadataAccessorTests.swift @@ -56,19 +56,19 @@ final class MetadataAccessorTests: MachOImageTests, @unchecked Sendable { let machO = machOImage for typeContextDescriptorWrapper in try machO.swift.typeContextDescriptors { guard !typeContextDescriptorWrapper.typeContextDescriptor.layout.flags.isGeneric else { continue } - if let metadataAccessor = try typeContextDescriptorWrapper.typeContextDescriptor.metadataAccessorFunction(in: machO) { + if let metadataAccessor = try typeContextDescriptorWrapper.typeContextDescriptor.metadataAccessorFunction(in: machO.context) { let metadataResponse = try metadataAccessor(request: .init()) print(metadataResponse.state) - let metadata = try metadataResponse.value.resolve(in: machO) + let metadata = try metadataResponse.value.resolve(in: machO.context) switch metadata { case .class(let classMetadata): - try print(classMetadata.fieldOffsets(in: machO)) + try print(classMetadata.fieldOffsets(in: machO.context)) case .struct(let structMetadata): - try print(structMetadata.fieldOffsets(in: machO)) + try print(structMetadata.fieldOffsets(in: machO.context)) case .enum(let enumMetadata): - try print(enumMetadata.payloadSize(in: machO) ?? 0) + try print(enumMetadata.payloadSize(in: machO.context) ?? 0) case .optional(let enumMetadata): - try print(enumMetadata.payloadSize(in: machO) ?? 0) + try print(enumMetadata.payloadSize(in: machO.context) ?? 0) default: continue } @@ -82,24 +82,24 @@ final class MetadataAccessorTests: MachOImageTests, @unchecked Sendable { for contextDescriptor in try machO.swift.contextDescriptors { guard let typeContextDescriptor = contextDescriptor.typeContextDescriptor else { continue } guard !typeContextDescriptor.layout.flags.isGeneric else { continue } - if let metadataAccessor = try typeContextDescriptor.metadataAccessorFunction(in: machO) { + if let metadataAccessor = try typeContextDescriptor.metadataAccessorFunction(in: machO.context) { let metadataResponse = try metadataAccessor(request: .init(state: .complete, isBlocking: true)) - let metadata = try metadataResponse.value.resolve(in: machO) + let metadata = try metadataResponse.value.resolve(in: machO.context) switch metadata { // case .class(let classMetadata): -// try print(classMetadata.fieldOffsets(in: machO)) +// try print(classMetadata.fieldOffsets(in: machO.context)) // case .struct(let structMetadata): -// try print(structMetadata.fieldOffsets(in: machO)) +// try print(structMetadata.fieldOffsets(in: machO.context)) case .enum(let enumMetadata): -// guard try enumMetadata.descriptor.resolve(in: machO).name(in: machO) == "MultiPayloadEnumTests" else { continue } - let descriptor = try enumMetadata.enumDescriptor(in: machO) - try await Enum(descriptor: descriptor, in: machO).dump(using: .demangleOptions(.default), in: machO).string.print() - let typeLayout = try enumMetadata.valueWitnesses(in: machO).typeLayout +// guard try enumMetadata.descriptor.resolve(in: machO.context).name(in: machO.context) == "MultiPayloadEnumTests" else { continue } + let descriptor = try enumMetadata.enumDescriptor(in: machO.context) + try await Enum(descriptor: descriptor, in: machO.context).dump(using: .demangleOptions(.default), in: machO).string.print() + let typeLayout = try enumMetadata.valueWitnesses(in: machO.context).typeLayout print(typeLayout) - try print("PayloadSize", enumMetadata.payloadSize(in: machO) ?? 0) + try print("PayloadSize", enumMetadata.payloadSize(in: machO.context) ?? 0) print(getEnumTagCounts(payloadSize: typeLayout.size, emptyCases: descriptor.numEmptyCases.cast(), payloadCases: descriptor.numberOfPayloadCases.cast())) // case .optional(let enumMetadata): -// try print(enumMetadata.payloadSize(in: machO) ?? 0) +// try print(enumMetadata.payloadSize(in: machO.context) ?? 0) default: continue } @@ -126,24 +126,24 @@ final class MetadataAccessorTests: MachOImageTests, @unchecked Sendable { continue case .struct(let `struct`): let inProcessStruct = `struct`.asPointerWrapper(in: machO) - let name = try inProcessStruct.name() + let name = try inProcessStruct.name(in: .inProcess) if name == "GenericStructSwiftProtocolRequirement" { try print( - #require(try inProcessStruct.metadataAccessorFunction()).callAsFunction( + #require(try inProcessStruct.metadataAccessorFunction(in: .inProcess)).callAsFunction( request: .init(), eachMetadatas: Metadata.createInProcess([Int].self), witnessTables: RuntimeFunctions.conformsToProtocol(metatype: [Int].self, protocolType: (any Equatable).self), RuntimeFunctions.conformsToProtocol(metatype: [Int].self, protocolType: (any Collection).self), RuntimeFunctions.conformsToProtocol(metatype: [Int].self, protocolType: (any Decodable).self), RuntimeFunctions.conformsToProtocol(metatype: [Int].self, protocolType: (any Encodable).self) - ).value.resolve() + ).value.resolve(in: .inProcess) ) } else if name == "GenericStructObjCProtocolRequirement" { - let metadata = try #require(try inProcessStruct.metadataAccessorFunction()).callAsFunction( + let metadata = try #require(try inProcessStruct.metadataAccessorFunction(in: .inProcess)).callAsFunction( request: .init(), eachMetadatas: Metadata.createInProcess(NSObject.self) - ).value.resolve() - try print(#require(metadata.struct).fieldOffsets()) + ).value.resolve(in: .inProcess) + try print(#require(metadata.struct).fieldOffsets(in: .inProcess)) } case .class: continue @@ -157,17 +157,17 @@ final class MetadataAccessorTests: MachOImageTests, @unchecked Sendable { for type in try machO.swift.typeContextDescriptors { switch type { case .enum(let enumDescriptor): - guard let genericContext = try enumDescriptor.genericContext(in: machO) else { continue } + guard let genericContext = try enumDescriptor.genericContext(in: machO.context) else { continue } // try mangleAsString(ContextDescriptorWrapper.type(.enum(enumDescriptor)).dumpNameNode(in: machO)).print() - try "\(ContextDescriptorWrapper.type(.enum(enumDescriptor)).dumpName(using: .default, in: machO).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO, isDumpCurrentLevelRequirements: false).string)".print() + try "\(ContextDescriptorWrapper.type(.enum(enumDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() case .struct(let structDescriptor): - guard let genericContext = try structDescriptor.genericContext(in: machO) else { continue } + guard let genericContext = try structDescriptor.genericContext(in: machO.context) else { continue } // try mangleAsString(ContextDescriptorWrapper.type(.struct(structDescriptor)).dumpNameNode(in: machO)).print() - try "\(ContextDescriptorWrapper.type(.struct(structDescriptor)).dumpName(using: .default, in: machO).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO, isDumpCurrentLevelRequirements: false).string)".print() + try "\(ContextDescriptorWrapper.type(.struct(structDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() case .class(let classDescriptor): - guard let genericContext = try classDescriptor.genericContext(in: machO) else { continue } + guard let genericContext = try classDescriptor.genericContext(in: machO.context) else { continue } // try mangleAsString(ContextDescriptorWrapper.type(.class(classDescriptor)).dumpNameNode(in: machO)).print() - try "\(ContextDescriptorWrapper.type(.class(classDescriptor)).dumpName(using: .default, in: machO).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO, isDumpCurrentLevelRequirements: false).string)".print() + try "\(ContextDescriptorWrapper.type(.class(classDescriptor)).dumpName(using: .default, in: machO.context).string)\(await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context, isDumpCurrentLevelRequirements: false).string)".print() } } } diff --git a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift index 8aebdc387..f95ad788b 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/OpaqueTypeTests.swift @@ -21,19 +21,19 @@ extension OpaqueTypeTests { print("Demangled:") await symbol.demangledNode.print(using: .default).print() symbol.demangledNode.description.print() - let opaqueTypeDescriptor = try OpaqueTypeDescriptor.resolve(from: symbol.offset, in: machO) - let opaqueType = try OpaqueType(descriptor: opaqueTypeDescriptor, in: machO) + let opaqueTypeDescriptor = try OpaqueTypeDescriptor.resolve(at: symbol.offset, in: machO.context) + let opaqueType = try OpaqueType(descriptor: opaqueTypeDescriptor, in: machO.context) print("Current Requirements:") for requirement in try opaqueType.requirements(in: machO) { - let requirementString = try await requirement.dump(using: .default, in: machO).string + let requirementString = try await requirement.dump(using: .default, in: machO.context).string requirementString.print() - if let node = try SymbolicDemangler.buildGenericSignature(for: [requirement], in: machO) { + if let node = try SymbolicDemangler.buildGenericSignature(for: [requirement], in: machO.context) { node.description.print() } } print("Underlying Types:") for underlyingTypeArgumentMangledName in opaqueType.underlyingTypeArgumentMangledNames { - let node = try SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO) + let node = try SymbolicDemangler.demangleType(for: underlyingTypeArgumentMangledName, in: machO.context) node.description.print() await node.print(using: .default).print() } @@ -53,7 +53,7 @@ final class OpaqueTypeDyldCacheTests: DyldCacheTests, OpaqueTypeTests, @unchecke @Test func test() async throws { let machO = machOFileInCache print(machO.startOffset) - try print(OpaqueType(descriptor: .resolve(from: 895065692, in: machO), in: machO)) + try print(OpaqueType(descriptor: .resolve(at: 895065692, in: machO.context), in: machO.context)) print(machO.symbols(offset: 895065692) as Symbols?) } } diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift index 4db8c3a27..cb517b0d0 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolGenericContextTests.swift @@ -13,8 +13,8 @@ final class ProtocolGenericContextTests: MachOFileTests, @unchecked Sendable { let protocols = try machO.swift.protocols for `protocol` in protocols { - if let genericContext = try `protocol`.descriptor.genericContext(in: machO) { - try await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO).string.print() + if let genericContext = try `protocol`.descriptor.genericContext(in: machO.context) { + try await genericContext.dumpGenericSignature(resolver: .using(options: .default), in: machO.context).string.print() } } } diff --git a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift index 7d04d4d47..47307d4f4 100644 --- a/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift +++ b/Tests/IntegrationTests/MachOSwiftSection/ProtocolRequirementSignatureTests.swift @@ -12,7 +12,7 @@ final class ProtocolRequirementSignatureTests: MachOFileTests, @unchecked Sendab let machO = machOFile let protocolDescriptors = try machO.swift.protocolDescriptors for protocolDescriptor in protocolDescriptors { - let proto = try Protocol(descriptor: protocolDescriptor, in: machO) + let proto = try Protocol(descriptor: protocolDescriptor, in: machO.context) for requirement in proto.requirements { print(requirement.flags.kind) } diff --git a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift index 73ee0a0f6..8e960a983 100644 --- a/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift +++ b/Tests/IntegrationTests/SwiftDiffing/ABIEvolutionTests.swift @@ -95,22 +95,39 @@ enum ABIEvolutionTestSuite { /// `SwiftDiffableInterfaceBuilderTestSuite.CrossVersionDyldCacheImageTests`. /// 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. + /// + /// 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. @TestActor class MultiVersionDyldCacheImageTests: Sendable { - let caches: [DyldCache] + let caches: [FullDyldCache] let versions: [(label: String, 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 cacheLabels: [String] { ["15.5", "26.5.2", "27.0"] } class var cacheImageName: MachOImageName { .SwiftUI } init() async throws { - var caches: [DyldCache] = [] + var caches: [FullDyldCache] = [] var versions: [(label: String, machO: MachOFile)] = [] - for (cachePath, cacheLabel) in zip(Self.cachePaths, Self.cacheLabels) { - let cache = try DyldCache(path: cachePath) + 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 { + continue + } caches.append(cache) - versions.append((cacheLabel, try #require(cache.machOFile(named: Self.cacheImageName)))) + versions.append((cachePath.versionLabel, machOFile)) } self.caches = caches self.versions = versions diff --git a/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift b/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift index 2b093b73d..3f5215bd6 100644 --- a/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift +++ b/Tests/IntegrationTests/SwiftInspection/MultiPayloadEnumTests.swift @@ -27,15 +27,15 @@ final class MultiPayloadEnumTests: MachOImageTests { let descriptors = try machO.swift.multiPayloadEnumDescriptors for descriptor in descriptors { let inProcessDescriptor = descriptor.asPointerWrapper(in: machO) - try await multiPayloadEnumDescriptorByMangledName[SymbolicDemangler.demangleType(for: inProcessDescriptor.mangledTypeName()).print(using: demangleOptions)] = inProcessDescriptor + try await multiPayloadEnumDescriptorByMangledName[SymbolicDemangler.demangleType(for: inProcessDescriptor.mangledTypeName(in: .inProcess), in: .inProcess).print(using: demangleOptions)] = inProcessDescriptor } } private func printMultiPayloadEnum(_ descriptor: MultiPayloadEnumDescriptor) throws { guard descriptor.usesPayloadSpareBits else { return } - let offset = try descriptor.payloadSpareBitMaskByteOffset() - let count = try descriptor.payloadSpareBitMaskByteCount() - let payloadSpareBits = try descriptor.payloadSpareBits() + let offset = try descriptor.payloadSpareBitMaskByteOffset(in: .inProcess) + let count = try descriptor.payloadSpareBitMaskByteCount(in: .inProcess) + let payloadSpareBits = try descriptor.payloadSpareBits(in: .inProcess) print("SpareBitMaskByteOffset:", offset) print("SpareBitMaskByteCount:", count) SpareBitAnalyzer.printAnalysis(bytes: payloadSpareBits, startOffset: offset.cast()) @@ -48,13 +48,13 @@ final class MultiPayloadEnumTests: MachOImageTests { let typeContextDescriptor = typeContextDescriptorWrapper.typeContextDescriptor.asPointerWrapper(in: machO) guard !typeContextDescriptor.layout.flags.isGeneric else { continue } guard case .enum(let enumDescriptor) = typeContextDescriptorWrapper else { continue } - guard case .enum(let enumMetadata) = try typeContextDescriptor.metadataAccessorFunction()?(request: .init()).value.resolve() else { continue } + guard case .enum(let enumMetadata) = try typeContextDescriptor.metadataAccessorFunction(in: .inProcess)?(request: .init()).value.resolve(in: .inProcess) else { continue } - let fieldDescriptor = try typeContextDescriptor.fieldDescriptor() - let records = try fieldDescriptor.records() + let fieldDescriptor = try typeContextDescriptor.fieldDescriptor(in: .inProcess) + let records = try fieldDescriptor.records(in: .inProcess) guard !records.isEmpty else { continue } - let typeName = try await SymbolicDemangler.demangleContext(for: .type(.enum(typeContextDescriptor as! EnumDescriptor))).print(using: demangleOptions) + let typeName = try await SymbolicDemangler.demangleContext(for: .type(.enum(typeContextDescriptor as! EnumDescriptor)), in: .inProcess).print(using: demangleOptions) print(typeName) print("") @@ -65,8 +65,8 @@ final class MultiPayloadEnumTests: MachOImageTests { defer { if enumDescriptor.isMultiPayload { if let multiPayloadEnumDescriptor = multiPayloadEnumDescriptorByMangledName[typeName], multiPayloadEnumDescriptor.usesPayloadSpareBits, - let spareBytes = try? multiPayloadEnumDescriptor.payloadSpareBits(), - let spareBytesOffset = try? multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset() { + let spareBytes = try? multiPayloadEnumDescriptor.payloadSpareBits(in: .inProcess), + let spareBytesOffset = try? multiPayloadEnumDescriptor.payloadSpareBitMaskByteOffset(in: .inProcess) { try? printMultiPayloadEnum(multiPayloadEnumDescriptor) let multiPayloadResult = Calculator.calculateMultiPayload( /* enumSize: enumTypeLayout.size.cast(), */ payloadSize: payloadSize.cast(), spareBytes: spareBytes, spareBytesOffset: spareBytesOffset.cast(), numPayloadCases: payloadCases.cast(), numEmptyCases: emptyCases.cast()) multiPayloadResult.print() @@ -85,14 +85,14 @@ final class MultiPayloadEnumTests: MachOImageTests { print("---------------------") } for record in records { - let mangledTypeName = try record.mangledTypeName() + let mangledTypeName = try record.mangledTypeName(in: .inProcess) let isIndirectCase = record.flags.contains(.isIndirectCase) var indirectCaseString = "" if isIndirectCase { indirectCaseString = "indirect " } guard !mangledTypeName.isEmpty else { - try print("\(indirectCaseString)case", record.fieldName()) + try print("\(indirectCaseString)case", record.fieldName(in: .inProcess)) emptyCases += 1 continue } @@ -101,7 +101,7 @@ final class MultiPayloadEnumTests: MachOImageTests { payloadCases += 1 } - let node = try SymbolicDemangler.demangleType(for: mangledTypeName) + let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: .inProcess) var isTuplePayload = false if node.firstChild?.isKind(of: .tuple) ?? false { isTuplePayload = true @@ -118,19 +118,19 @@ final class MultiPayloadEnumTests: MachOImageTests { let mangledTypeNameString = try await mangleAsString(node) if let metatype = try RuntimeFunctions.getTypeByMangledNameInContext(mangledTypeName, genericContext: nil, genericArguments: nil) { let currentMetadata = try Metadata.createInProcess(metatype) - try await print("\(indirectCaseString)case \(record.fieldName())\(payloadString("\(node.print(using: .interfaceTypeBuilderOnly))"))") - let metadataWrapper = try currentMetadata.asMetadataWrapper() - let typeLayout = try currentMetadata.asFullMetadata().valueWitnesses.resolve().typeLayout + try await print("\(indirectCaseString)case \(record.fieldName(in: .inProcess))\(payloadString("\(node.print(using: .interfaceTypeBuilderOnly))"))") + let metadataWrapper = try currentMetadata.asMetadataWrapper(in: .inProcess) + let typeLayout = try currentMetadata.asFullMetadata(in: .inProcess).valueWitnesses.resolve(in: .inProcess).typeLayout let indentLevel = 1 let indent = " " * indentLevel if let tupleMetadata = metadataWrapper.tuple { - for (index, element) in try tupleMetadata.elements().enumerated() { - let tupleElementMetadata = try element.type.resolve() - if let descriptor = try tupleElementMetadata.typeContextDescriptorWrapper()?.asContextDescriptorWrapper { + for (index, 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 { print(indent + "Index: " + index.description) - try await print(indent + "Type: " + SymbolicDemangler.demangleContext(for: descriptor).print(using: demangleOptions)) + try await print(indent + "Type: " + SymbolicDemangler.demangleContext(for: descriptor, in: .inProcess).print(using: demangleOptions)) } - let tupleElementTypeLayout = try tupleElementMetadata.asFullMetadata().valueWitnesses.resolve().typeLayout + let tupleElementTypeLayout = try tupleElementMetadata.asFullMetadata(in: .inProcess).valueWitnesses.resolve(in: .inProcess).typeLayout print(indent + "- " + tupleElementTypeLayout.description) } print(indent + "Total: ") @@ -140,11 +140,11 @@ final class MultiPayloadEnumTests: MachOImageTests { payloadSize = isIndirectCase ? max(payloadSize, 8) : max(payloadSize, typeLayout.size) let optionalMetadata = try Metadata.createInProcess(makeOptionalMetatype(metatype)) - let optionalTypeLayout = try optionalMetadata.asFullMetadata().valueWitnesses.resolve().typeLayout + let optionalTypeLayout = try optionalMetadata.asFullMetadata(in: .inProcess).valueWitnesses.resolve(in: .inProcess).typeLayout optionalSize = optionalTypeLayout.size.cast() } else { - try await print("NotFound:", "case", record.fieldName(), mangledTypeNameString, node.print(using: .default)) + try await print("NotFound:", "case", record.fieldName(in: .inProcess), mangledTypeNameString, node.print(using: .default)) } } print("") diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift index ab5fb1f48..b7a093fe4 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftDiffableInterfaceBuilderTests.swift @@ -221,6 +221,27 @@ enum SwiftDiffableInterfaceBuilderTestSuite { } } + /// The same image from two archived macOS caches, picked by version: point + /// the two versions at any directories under `/Volumes/DyldSharedCaches/macOS` + /// that hold a cache. + final class ArchivedDyldCacheTests: CrossVersionDyldCacheImageTests, SwiftDiffableInterfaceBuilderTests, @unchecked Sendable { + class var oldCacheVersion: String { "26.6" } + class var newCacheVersion: String { "27.0" } + override class var oldCachePath: DyldSharedCachePath { .macOS(oldCacheVersion) } + override class var newCachePath: DyldSharedCachePath { .macOS(newCacheVersion) } + override class var cacheImageName: MachOImageName { .AppKit } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func diffFile() async throws { + try await diffFile(old: oldMachOFileInCache, new: newMachOFileInCache) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func diffString() async throws { + try await diffString(old: oldMachOFileInCache, new: newMachOFileInCache) + } + } + /// The DVTProductsUI shared framework across two installed Xcode versions /// (26.3 → 26.4) — mirrors the framework the interface builder tests use, /// loaded by path so the diff can compare two Xcodes. diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift index 3d8eda99e..fdd7b9b95 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftEvolutionInterfaceBuilderTests.swift @@ -21,11 +21,11 @@ import SwiftDiffing /// dumps produce for the same axis — the two views must tell one story /// (annotation facts are the same lineages). /// -/// Every axis here is N == 3, on `MultiVersionDyldCacheImageTests`: an -/// evolution over fewer than three images is what `diff --interface` already -/// covers, and the stories this view exists for — introduced mid-axis, -/// removed mid-axis, modified twice, gone-and-back bitmaps — only appear -/// from three versions up. +/// Every axis here has three versions or more, on +/// `MultiVersionDyldCacheImageTests`: an evolution over fewer than three +/// images is what `diff --interface` already covers, and the stories this +/// view exists for — introduced mid-axis, removed mid-axis, modified twice, +/// gone-and-back bitmaps — only appear from three versions up. protocol SwiftEvolutionInterfaceDumpTests: SwiftInterfaceDumpTests {} @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) @@ -38,12 +38,14 @@ extension SwiftEvolutionInterfaceDumpTests { /// binaries is the real cost; the lineage join and rendering afterwards /// are cheap by comparison. private func preparedBuilder( - versions: [(label: String, machO: some MachOFieldLayoutRenderable)] + versions: [(label: String, machO: some MachOFieldLayoutRenderable)], + availabilityAnnotationPlatform: String? ) async throws -> AnySwiftEvolutionInterfaceBuilder { let builder = try AnySwiftEvolutionInterfaceBuilder( configuration: indexConfiguration, versions: versions.map(\.machO), - labels: versions.map(\.label) + labels: versions.map(\.label), + availabilityAnnotationPlatform: availabilityAnnotationPlatform ) try await measuringPreparation { try await builder.prepare() @@ -62,17 +64,25 @@ extension SwiftEvolutionInterfaceDumpTests { } /// Console analogue of `evolutionString`: prepares every version, then - /// prints the annotated union interface. - func evolutionInterfaceString(versions: [(label: String, machO: some MachOFieldLayoutRenderable)]) async throws { - let builder = try await preparedBuilder(versions: versions) + /// prints the annotated union interface. A platform adds the genuine + /// `@available` lines, as `evolution --interface --emit-available + /// --platform` does. + func evolutionInterfaceString( + versions: [(label: String, machO: some MachOFieldLayoutRenderable)], + availabilityAnnotationPlatform: String? = nil + ) async throws { + let builder = try await preparedBuilder(versions: versions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) printResult(try await annotatedInterfaceReport(of: builder)) } /// File analogue of `evolutionFile`: writes the annotated union interface /// (`-EvolutionInterface.swiftinterface`) next to the lineage-report and /// diff dumps, named after the *newest* version. - func evolutionInterfaceFile(versions: [(label: String, machO: some MachOFieldLayoutRenderable)]) async throws { - let builder = try await preparedBuilder(versions: versions) + func evolutionInterfaceFile( + versions: [(label: String, machO: some MachOFieldLayoutRenderable)], + availabilityAnnotationPlatform: String? = nil + ) async throws { + let builder = try await preparedBuilder(versions: versions, availabilityAnnotationPlatform: availabilityAnnotationPlatform) guard let newestVersion = versions.last else { return } try await write(annotatedInterfaceReport(of: builder), for: newestVersion.machO, suffix: "EvolutionInterface") } @@ -130,4 +140,83 @@ enum SwiftEvolutionInterfaceBuilderTestSuite { try await evolutionInterfaceString(versions: versions) } } + + /// The same image across archived macOS caches, picked by version: list + /// in `cacheVersions` the directories under + /// `/Volumes/DyldSharedCaches/macOS` that hold a cache, oldest first. A + /// cache named by its version is labeled with it, so every label is a + /// version number and the union interface also spells each lifecycle one + /// attribute can express as `@available(macOS, …)`. A version whose image + /// carries no Swift metadata drops off the axis (see + /// `MultiVersionDyldCacheImageTests`). + final class ArchivedDyldCacheTests: ABIEvolutionTestSuite.MultiVersionDyldCacheImageTests, SwiftEvolutionInterfaceDumpTests, @unchecked Sendable { + + class var cacheVersions: [String] { [ + "11.0.1", + "11.1", + "11.2", + "11.3", + "11.4", + "11.5", + "11.6", + "11.7", + "12.0.1", + "12.1", + "12.2", + "12.3", + "12.4", + "12.5", + "12.6", + "12.7", + "13.0", + "13.1", + "13.2", + "13.3", + "13.4", + "13.5", + "13.6", + "13.7", + "14.0", + "14.1", + "14.2", + "14.3", + "14.4", + "14.5", + "14.6", + "14.7", + "14.8", + "15.0", + "15.1", + "15.2", + "15.3", + "15.4", + "15.5", + "15.6", + "15.7", + "15.8", + "26.0", + "26.1", + "26.2", + "26.3", + "26.4", + "26.5", + "26.6", + "26.7", + "27.0", + ] } + + override class var cachePaths: [DyldSharedCachePath] { cacheVersions.map { .macOS($0) } } + + override class var cacheImageName: MachOImageName { .SwiftUI } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceFile() async throws { + try await evolutionInterfaceFile(versions: versions, availabilityAnnotationPlatform: "macOS") + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func evolutionInterfaceString() async throws { + try await evolutionInterfaceString(versions: versions, availabilityAnnotationPlatform: "macOS") + } + } } diff --git a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift index 31d287911..8f3439d45 100644 --- a/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift +++ b/Tests/IntegrationTests/SwiftInterface/SwiftInterfaceBuilderTests.swift @@ -84,6 +84,33 @@ 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 var cacheVersion: String { + "26.6" + } + + override class var cachePath: DyldSharedCachePath { + .macOS(cacheVersion) + } + + override class var cacheImageName: MachOImageName { + .AppKit + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func buildFile() async throws { + try await buildFile(in: machOFileInCache) + } + + @available(macOS 13.0, iOS 16.0, tvOS 16.0, watchOS 9.0, *) + @Test func buildString() async throws { + try await buildString(in: machOFileInCache) + } + } + class MachOFileTests: MachOTestingSupport.MachOFileTests, SwiftInterfaceBuilderTests, @unchecked Sendable { override class var fileName: MachOFileName { .SymbolTestsCore diff --git a/Tests/MachOCachesTests/SharedCacheKeyTests.swift b/Tests/MachOCachesTests/SharedCacheKeyTests.swift index 1a0c210b5..5f94f6980 100644 --- a/Tests/MachOCachesTests/SharedCacheKeyTests.swift +++ b/Tests/MachOCachesTests/SharedCacheKeyTests.swift @@ -3,11 +3,12 @@ import Testing import MachOKitExtensions @_spi(Internals) import MachOCaches -/// `SharedCacheKey` hashes a `uuidFile` identifier on its UUID alone 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 would hand one binary another binary's index. +/// `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() @@ -37,6 +38,27 @@ struct SharedCacheKeyTests { #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() } diff --git a/Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift b/Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift new file mode 100644 index 000000000..b80b472a2 --- /dev/null +++ b/Tests/MachODependenciesTests/CacheRootDependencyClosureTests.swift @@ -0,0 +1,80 @@ +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/FileDependencyLocatorTests.swift b/Tests/MachODependenciesTests/FileDependencyLocatorTests.swift index 76e6ba3fe..d21ffedfd 100644 --- a/Tests/MachODependenciesTests/FileDependencyLocatorTests.swift +++ b/Tests/MachODependenciesTests/FileDependencyLocatorTests.swift @@ -1,5 +1,5 @@ import Foundation -import MachOKit +@_spi(Support) import MachOKit import MachOKitExtensions import Testing @testable import MachODependencies @@ -17,7 +17,7 @@ struct FileDependencyLocatorTests { private static let catalystSwiftUIPath = "/System/iOSSupport/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" private func hostLocator() -> FileDependencyLocator? { - guard FullDyldCache.host != nil else { + guard FullDyldCache.cachedHost != nil else { print("skipped: no host dyld shared cache") return nil } @@ -80,7 +80,7 @@ struct FileDependencyLocatorTests { /// 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.host != nil else { + guard FullDyldCache.cachedHost != nil else { print("skipped: no host dyld shared cache") return } @@ -106,6 +106,20 @@ struct FileDependencyLocatorTests { #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) diff --git a/Tests/MachOSwiftSectionTests/DeprecatedReadingFormsTests.swift b/Tests/MachOSwiftSectionTests/DeprecatedReadingFormsTests.swift new file mode 100644 index 000000000..a8c673abb --- /dev/null +++ b/Tests/MachOSwiftSectionTests/DeprecatedReadingFormsTests.swift @@ -0,0 +1,56 @@ +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/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift index 0957a37db..a2402da90 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AccessibleFunction/AccessibleFunctionRecordTests.swift @@ -106,18 +106,12 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur /// `swift_findAccessibleFunction` matches against. @Test func name() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { try carrier.file.name(in: machOFile) }, - image: { try carrier.image.name(in: machOImage) }, - inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).name() } - ) - #expect(result == carrier.expected.name, "\(carrier.label)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try carrier.file.name(in: fileContext) }, - image: { try carrier.image.name(in: imageContext) } + image: { try carrier.image.name(in: imageContext) }, + inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).name(in: self.inProcessContext) } ) - #expect(fromContext == carrier.expected.name, "\(carrier.label)") + #expect(result == carrier.expected.name, "\(carrier.label)") } } @@ -127,26 +121,20 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur /// agreement. @Test func functionType() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { try carrier.file.functionType(in: machOFile).rawString }, - image: { try carrier.image.functionType(in: machOImage).rawString }, - inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).functionType().rawString } - ) - #expect(!result.isEmpty == carrier.expected.hasFunctionType, "\(carrier.label)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try carrier.file.functionType(in: fileContext).rawString }, - image: { try carrier.image.functionType(in: imageContext).rawString } + image: { try carrier.image.functionType(in: imageContext).rawString }, + inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).functionType(in: self.inProcessContext).rawString } ) - #expect(fromContext == result, "\(carrier.label)") + #expect(!result.isEmpty == carrier.expected.hasFunctionType, "\(carrier.label)") } } @Test func genericEnvironment() async throws { for carrier in try allCarriers() { - let resolvedOffset = try acrossAllReaders( - file: { try carrier.file.genericEnvironment(in: machOFile)?.offset }, - image: { try carrier.image.genericEnvironment(in: machOImage)?.offset } + let resolvedOffset = try acrossAllContexts( + file: { try carrier.file.genericEnvironment(in: fileContext)?.offset }, + image: { try carrier.image.genericEnvironment(in: imageContext)?.offset } ) #expect(resolvedOffset == carrier.expected.genericEnvironmentOffset, "\(carrier.label)") } @@ -169,7 +157,7 @@ final class AccessibleFunctionRecordTests: MachOSwiftSectionFixtureTests, Fixtur @Test func functionPointsAtAnAsyncRecordNotAtCode() async throws { for carrier in try allCarriers() { let functionOffset = try #require(carrier.file.resolvedDirectOffset(from: \.function), "\(carrier.label)") - let asyncRecord = try AsyncFunctionPointer.resolve(from: functionOffset, in: machOFile) + let asyncRecord = try AsyncFunctionPointer.resolve(at: functionOffset, in: fileContext) let entryPoint = try #require(asyncRecord.resolvedDirectOffset(from: \.function), "\(carrier.label)") #expect(entryPoint != functionOffset, "\(carrier.label)") #expect(asyncRecord.expectedContextSize > 0, "\(carrier.label)") diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift index a600754c7..46305bfda 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextDescriptorProtocolTests.swift @@ -42,12 +42,10 @@ final class AnonymousContextDescriptorProtocolTests: MachOSwiftSectionFixtureTes // MangledName: Hashable, but we use presence-only here for parity // with the wrapper Suite and because the picker's first anonymous // context happens to have no mangled name in this fixture.) - let filePresence = (try fileDescriptor.mangledName(in: machOFile)) != nil - let imagePresence = (try imageDescriptor.mangledName(in: machOImage)) != nil - let imageCtxPresence = (try imageDescriptor.mangledName(in: imageContext)) != nil + let filePresence = (try fileDescriptor.mangledName(in: fileContext)) != nil + let imagePresence = (try imageDescriptor.mangledName(in: imageContext)) != nil #expect(filePresence == imagePresence) - #expect(filePresence == imageCtxPresence) #expect(filePresence == AnonymousContextDescriptorProtocolBaseline.firstAnonymous.hasMangledName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift index 36464e0d5..b547c700f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Anonymous/AnonymousContextTests.swift @@ -12,10 +12,10 @@ import MachOFixtureSupport /// scopes and other unnamed contexts; they're discovered via the parent /// chain of generic types, not via top-level `__swift5_types` records. /// -/// `init(descriptor:in:)` (MachO + ReadingContext overloads) and -/// `init(descriptor:)` (in-process) are covered by dedicated tests; the -/// other ivars use the established presence-flag pattern (`MangledName` -/// and `GenericContext` aren't cheaply Equatable). +/// `init(descriptor:in:)` is covered by dedicated tests over the file and +/// image contexts and over the in-process context; the other ivars use the +/// established presence-flag pattern (`MangledName` and `GenericContext` +/// aren't cheaply Equatable). @Suite final class AnonymousContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "AnonymousContext" @@ -23,13 +23,13 @@ final class AnonymousContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, AnonymousContextBaseline.registeredTestMethodNames } - /// Helper: instantiate the `AnonymousContext` wrapper using the - /// MachO-direct initializer for both readers. + /// Helper: instantiate the `AnonymousContext` wrapper against both + /// readers through their reading contexts. private func loadFirstAnonymousContexts() throws -> (file: AnonymousContext, image: AnonymousContext) { let fileDescriptor = try BaselineFixturePicker.anonymous_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.anonymous_first(in: machOImage) - let file = try AnonymousContext(descriptor: fileDescriptor, in: machOFile) - let image = try AnonymousContext(descriptor: imageDescriptor, in: machOImage) + let file = try AnonymousContext(descriptor: fileDescriptor, in: fileContext) + let image = try AnonymousContext(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -39,26 +39,22 @@ final class AnonymousContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, let fileDescriptor = try BaselineFixturePicker.anonymous_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.anonymous_first(in: machOImage) - // Both file/image MachO-based initializers must succeed and produce - // a descriptor whose offset matches the baseline. The - // ReadingContext-based overload also exists. - let fileContext_ = try AnonymousContext(descriptor: fileDescriptor, in: machOFile) - let imageContext_ = try AnonymousContext(descriptor: imageDescriptor, in: machOImage) - let fileCtxContext = try AnonymousContext(descriptor: fileDescriptor, in: fileContext) - let imageCtxContext = try AnonymousContext(descriptor: imageDescriptor, in: imageContext) + // Both the file-context and the image-context initializers must + // succeed and produce a descriptor whose offset matches the baseline. + let fileContext_ = try AnonymousContext(descriptor: fileDescriptor, in: fileContext) + let imageContext_ = try AnonymousContext(descriptor: imageDescriptor, in: imageContext) #expect(fileContext_.descriptor.offset == AnonymousContextBaseline.firstAnonymous.descriptorOffset) #expect(imageContext_.descriptor.offset == AnonymousContextBaseline.firstAnonymous.descriptorOffset) - #expect(fileCtxContext.descriptor.offset == AnonymousContextBaseline.firstAnonymous.descriptorOffset) - #expect(imageCtxContext.descriptor.offset == AnonymousContextBaseline.firstAnonymous.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { - // The InProcess `init(descriptor:)` requires a pointer-form - // descriptor resolved against MachOImage; reproduce that here. + // `init(descriptor:in:)` over the in-process context requires a + // pointer-form descriptor resolved against MachOImage; reproduce + // that here. let imageDescriptor = try BaselineFixturePicker.anonymous_first(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcessContext_ = try AnonymousContext(descriptor: pointerDescriptor) + let inProcessContext_ = try AnonymousContext(descriptor: pointerDescriptor, in: inProcessContext) // The in-process `descriptor.offset` is a pointer bit pattern, not // a file offset — we just assert it resolved. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift index 47ef7497f..3678c1c43 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeDescriptorTests.swift @@ -74,40 +74,28 @@ final class AssociatedTypeDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur @Test func conformingTypeName() async throws { let descriptors = try loadDescriptors() - let presence = try acrossAllReaders( - file: { (try? descriptors.file.conformingTypeName(in: machOFile)) != nil }, - image: { (try? descriptors.image.conformingTypeName(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try? descriptors.file.conformingTypeName(in: fileContext)) != nil }, + image: { (try? descriptors.image.conformingTypeName(in: imageContext)) != nil } ) #expect(presence == AssociatedTypeDescriptorBaseline.concreteWitnessTest.hasConformingTypeName) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try? descriptors.image.conformingTypeName(in: imageContext)) != nil - #expect(imageCtxPresence == AssociatedTypeDescriptorBaseline.concreteWitnessTest.hasConformingTypeName) } @Test func protocolTypeName() async throws { let descriptors = try loadDescriptors() - let presence = try acrossAllReaders( - file: { (try? descriptors.file.protocolTypeName(in: machOFile)) != nil }, - image: { (try? descriptors.image.protocolTypeName(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try? descriptors.file.protocolTypeName(in: fileContext)) != nil }, + image: { (try? descriptors.image.protocolTypeName(in: imageContext)) != nil } ) #expect(presence == AssociatedTypeDescriptorBaseline.concreteWitnessTest.hasProtocolTypeName) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try? descriptors.image.protocolTypeName(in: imageContext)) != nil - #expect(imageCtxPresence == AssociatedTypeDescriptorBaseline.concreteWitnessTest.hasProtocolTypeName) } @Test func associatedTypeRecords() async throws { let descriptors = try loadDescriptors() - let count = try acrossAllReaders( - file: { try descriptors.file.associatedTypeRecords(in: machOFile).count }, - image: { try descriptors.image.associatedTypeRecords(in: machOImage).count } + let count = try acrossAllContexts( + file: { try descriptors.file.associatedTypeRecords(in: fileContext).count }, + image: { try descriptors.image.associatedTypeRecords(in: imageContext).count } ) #expect(count == AssociatedTypeDescriptorBaseline.concreteWitnessTest.recordsCount) - - // ReadingContext-based overload also exercised. - let imageCtxCount = try descriptors.image.associatedTypeRecords(in: imageContext).count - #expect(imageCtxCount == AssociatedTypeDescriptorBaseline.concreteWitnessTest.recordsCount) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift index a50f4479f..ea07af3d7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeRecordTests.swift @@ -28,8 +28,8 @@ final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSui private func loadFirstRecord() throws -> (file: AssociatedTypeRecord, image: AssociatedTypeRecord) { let fileDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOImage) - let fileRecords = try fileDescriptor.associatedTypeRecords(in: machOFile) - let imageRecords = try imageDescriptor.associatedTypeRecords(in: machOImage) + let fileRecords = try fileDescriptor.associatedTypeRecords(in: fileContext) + let imageRecords = try imageDescriptor.associatedTypeRecords(in: imageContext) let file = try required(fileRecords.first) let image = try required(imageRecords.first) return (file: file, image: image) @@ -53,9 +53,9 @@ final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSui // structural-presence anchor — it just verifies the layout // accessor is available and consistent across readers. let records = try loadFirstRecord() - let nameStringMatches = try acrossAllReaders( - file: { try records.file.name(in: machOFile) }, - image: { try records.image.name(in: machOImage) } + let nameStringMatches = try acrossAllContexts( + file: { try records.file.name(in: fileContext) }, + image: { try records.image.name(in: imageContext) } ) #expect(nameStringMatches == AssociatedTypeRecordBaseline.firstRecord.name) } @@ -64,27 +64,19 @@ final class AssociatedTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func name() async throws { let records = try loadFirstRecord() - let result = try acrossAllReaders( - file: { try records.file.name(in: machOFile) }, - image: { try records.image.name(in: machOImage) } + let result = try acrossAllContexts( + file: { try records.file.name(in: fileContext) }, + image: { try records.image.name(in: imageContext) } ) #expect(result == AssociatedTypeRecordBaseline.firstRecord.name) - - // ReadingContext-based overload also exercised. - let imageCtxResult = try records.image.name(in: imageContext) - #expect(imageCtxResult == AssociatedTypeRecordBaseline.firstRecord.name) } @Test func substitutedTypeName() async throws { let records = try loadFirstRecord() - let presence = try acrossAllReaders( - file: { (try? records.file.substitutedTypeName(in: machOFile)) != nil }, - image: { (try? records.image.substitutedTypeName(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try? records.file.substitutedTypeName(in: fileContext)) != nil }, + image: { (try? records.image.substitutedTypeName(in: imageContext)) != nil } ) #expect(presence == AssociatedTypeRecordBaseline.firstRecord.hasSubstitutedTypeName) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try? records.image.substitutedTypeName(in: imageContext)) != nil - #expect(imageCtxPresence == AssociatedTypeRecordBaseline.firstRecord.hasSubstitutedTypeName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift index d4c362764..eb31296b0 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/AssociatedType/AssociatedTypeTests.swift @@ -30,8 +30,8 @@ final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u private func loadAssociatedTypes() throws -> (file: AssociatedType, image: AssociatedType) { let fileDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOImage) - let file = try AssociatedType(descriptor: fileDescriptor, in: machOFile) - let image = try AssociatedType(descriptor: imageDescriptor, in: machOImage) + let file = try AssociatedType(descriptor: fileDescriptor, in: fileContext) + let image = try AssociatedType(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -41,24 +41,21 @@ final class AssociatedTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u let fileDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOImage) - let fileMachO = try AssociatedType(descriptor: fileDescriptor, in: machOFile) - let imageMachO = try AssociatedType(descriptor: imageDescriptor, in: machOImage) let fileCtx = try AssociatedType(descriptor: fileDescriptor, in: fileContext) let imageCtx = try AssociatedType(descriptor: imageDescriptor, in: imageContext) - #expect(fileMachO.descriptor.offset == AssociatedTypeBaseline.concreteWitnessTest.descriptorOffset) - #expect(imageMachO.descriptor.offset == AssociatedTypeBaseline.concreteWitnessTest.descriptorOffset) #expect(fileCtx.descriptor.offset == AssociatedTypeBaseline.concreteWitnessTest.descriptorOffset) #expect(imageCtx.descriptor.offset == AssociatedTypeBaseline.concreteWitnessTest.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { - // The InProcess `init(descriptor:)` walks the descriptor via raw - // pointer arithmetic; we just assert it succeeds and produces a - // non-zero descriptor offset (the absolute pointer is per-process). + // `init(descriptor:in:)` over the in-process context walks the + // descriptor via raw pointer arithmetic; we just assert it succeeds + // and produces a non-zero descriptor offset (the absolute pointer is + // per-process). let imageDescriptor = try BaselineFixturePicker.associatedTypeDescriptor_ConcreteWitnessTest(in: machOImage) let pointerWrapper = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcess = try AssociatedType(descriptor: pointerWrapper) + let inProcess = try AssociatedType(descriptor: pointerWrapper, in: inProcessContext) #expect(inProcess.descriptor.offset != 0) #expect(inProcess.records.count == AssociatedTypeBaseline.concreteWitnessTest.recordsCount) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift index e8fef8671..951ae9d4a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeDescriptorTests.swift @@ -94,16 +94,11 @@ final class BuiltinTypeDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu // baseline records whether the mangled-name pointer is non-null // (`hasMangledName`); the resolved name itself isn't byte-stable // across builds, so we only assert non-nil presence. - let viaFile = try descriptors.file.typeName(in: machOFile) - let viaImage = try descriptors.image.typeName(in: machOImage) + let viaFile = try descriptors.file.typeName(in: fileContext) + let viaImage = try descriptors.image.typeName(in: imageContext) if BuiltinTypeDescriptorBaseline.firstBuiltin.hasMangledName { #expect(viaFile != nil) #expect(viaImage != nil) } - // ReadingContext path also exercised. - let viaContext = try descriptors.image.typeName(in: imageContext) - if BuiltinTypeDescriptorBaseline.firstBuiltin.hasMangledName { - #expect(viaContext != nil) - } } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift index 983248d10..bdc9d34a2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/BuiltinType/BuiltinTypeTests.swift @@ -21,8 +21,8 @@ final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch private func loadBuiltins() throws -> (file: BuiltinType, image: BuiltinType) { let fileDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) - let file = try BuiltinType(descriptor: fileDescriptor, in: machOFile) - let image = try BuiltinType(descriptor: imageDescriptor, in: machOImage) + let file = try BuiltinType(descriptor: fileDescriptor, in: fileContext) + let image = try BuiltinType(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -30,24 +30,21 @@ final class BuiltinTypeTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch let fileDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) - let fileBuiltin = try BuiltinType(descriptor: fileDescriptor, in: machOFile) - let imageBuiltin = try BuiltinType(descriptor: imageDescriptor, in: machOImage) - let fileCtxBuiltin = try BuiltinType(descriptor: fileDescriptor, in: fileContext) - let imageCtxBuiltin = try BuiltinType(descriptor: imageDescriptor, in: imageContext) + let fileBuiltin = try BuiltinType(descriptor: fileDescriptor, in: fileContext) + let imageBuiltin = try BuiltinType(descriptor: imageDescriptor, in: imageContext) #expect(fileBuiltin.descriptor.offset == BuiltinTypeBaseline.firstBuiltin.descriptorOffset) #expect(imageBuiltin.descriptor.offset == BuiltinTypeBaseline.firstBuiltin.descriptorOffset) - #expect(fileCtxBuiltin.descriptor.offset == BuiltinTypeBaseline.firstBuiltin.descriptorOffset) - #expect(imageCtxBuiltin.descriptor.offset == BuiltinTypeBaseline.firstBuiltin.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { - // The InProcess `init(descriptor:)` walks the descriptor via raw - // pointer. We assert it succeeds and the descriptor offset is - // non-zero (the absolute pointer is per-process). + // `init(descriptor:in:)` over the in-process context walks the + // descriptor via raw pointer. We assert it succeeds and the + // descriptor offset is non-zero (the absolute pointer is + // per-process). let imageDescriptor = try BaselineFixturePicker.builtinTypeDescriptor_first(in: machOImage) let pointerWrapper = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcess = try BuiltinType(descriptor: pointerWrapper) + let inProcess = try BuiltinType(descriptor: pointerWrapper, in: inProcessContext) #expect(inProcess.descriptor.offset != 0) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift index 6d405ea81..5124655bb 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureDescriptorTests.swift @@ -122,41 +122,29 @@ final class CaptureDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func captureTypeRecords() async throws { for carrier in try allCarriers() { - let offsets = try acrossAllReaders( - file: { try carrier.file.captureTypeRecords(in: machOFile).map(\.offset) }, - image: { try carrier.image.captureTypeRecords(in: machOImage).map(\.offset) } - ) - #expect(offsets.count == carrier.expected.numberOfCaptureTypes, "\(carrier.label)") - #expect(offsets.first == carrier.expected.captureTypeRecordsOffset, "\(carrier.label)") - - let fromContext = try acrossAllContexts( + let offsets = try acrossAllContexts( file: { try carrier.file.captureTypeRecords(in: fileContext).map(\.offset) }, image: { try carrier.image.captureTypeRecords(in: imageContext).map(\.offset) } ) - #expect(fromContext == offsets, "\(carrier.label)") + #expect(offsets.count == carrier.expected.numberOfCaptureTypes, "\(carrier.label)") + #expect(offsets.first == carrier.expected.captureTypeRecordsOffset, "\(carrier.label)") // The in-process leg reads through a pointer, so its offsets are // pointers; only the count is comparable directly. - let inProcess = try carrier.image.asPointerWrapper(in: machOImage).captureTypeRecords() + let inProcess = try carrier.image.asPointerWrapper(in: machOImage).captureTypeRecords(in: inProcessContext) #expect(inProcess.count == carrier.expected.numberOfCaptureTypes, "\(carrier.label)") } } @Test func metadataSourceRecords() async throws { for carrier in try allCarriers() { - let sources = try acrossAllReaders( - file: { try carrier.file.metadataSourceRecords(in: machOFile).map { try $0.mangledMetadataSource(in: machOFile).rawString } }, - image: { try carrier.image.metadataSourceRecords(in: machOImage).map { try $0.mangledMetadataSource(in: machOImage).rawString } } - ) - #expect(sources == carrier.expected.mangledMetadataSources, "\(carrier.label)") - - let fromContext = try acrossAllContexts( + let sources = try acrossAllContexts( file: { try carrier.file.metadataSourceRecords(in: fileContext).map { try $0.mangledMetadataSource(in: fileContext).rawString } }, image: { try carrier.image.metadataSourceRecords(in: imageContext).map { try $0.mangledMetadataSource(in: imageContext).rawString } } ) - #expect(fromContext == carrier.expected.mangledMetadataSources, "\(carrier.label)") + #expect(sources == carrier.expected.mangledMetadataSources, "\(carrier.label)") - let inProcess = try carrier.image.asPointerWrapper(in: machOImage).metadataSourceRecords() + let inProcess = try carrier.image.asPointerWrapper(in: machOImage).metadataSourceRecords(in: inProcessContext) #expect(inProcess.count == carrier.expected.numberOfMetadataSources, "\(carrier.label)") } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift index 128af8adc..648497f06 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/CaptureTypeRecordTests.swift @@ -31,8 +31,8 @@ final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, return try zip(fileDescriptors, imageDescriptors).enumerated().map { index, pair in Carrier( index: index, - file: try pair.0.captureTypeRecords(in: machOFile)[0], - image: try pair.1.captureTypeRecords(in: machOImage)[0], + file: try pair.0.captureTypeRecords(in: fileContext)[0], + image: try pair.1.captureTypeRecords(in: imageContext)[0], expected: CaptureTypeRecordBaseline.firstRecords[index] ) } @@ -63,18 +63,12 @@ final class CaptureTypeRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func mangledTypeName() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { try carrier.file.mangledTypeName(in: machOFile).rawString }, - image: { try carrier.image.mangledTypeName(in: machOImage).rawString }, - inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).mangledTypeName().rawString } - ) - #expect(!result.isEmpty == carrier.expected.hasMangledTypeName, "record \(carrier.index)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try carrier.file.mangledTypeName(in: fileContext).rawString }, - image: { try carrier.image.mangledTypeName(in: imageContext).rawString } + image: { try carrier.image.mangledTypeName(in: imageContext).rawString }, + inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).mangledTypeName(in: self.inProcessContext).rawString } ) - #expect(fromContext == result, "record \(carrier.index)") + #expect(!result.isEmpty == carrier.expected.hasMangledTypeName, "record \(carrier.index)") } } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift index dc3b55259..2611c12e8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Capture/MetadataSourceRecordTests.swift @@ -29,8 +29,8 @@ final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, FixtureSui } private func allCarriers() throws -> [Carrier] { - let fileRecords = try CaptureFixtureDescriptors(in: machOFile).withMultipleMetadataSources.metadataSourceRecords(in: machOFile) - let imageRecords = try CaptureFixtureDescriptors(in: machOImage).withMultipleMetadataSources.metadataSourceRecords(in: machOImage) + let fileRecords = try CaptureFixtureDescriptors(in: machOFile).withMultipleMetadataSources.metadataSourceRecords(in: fileContext) + let imageRecords = try CaptureFixtureDescriptors(in: machOImage).withMultipleMetadataSources.metadataSourceRecords(in: imageContext) return zip(fileRecords, imageRecords).enumerated().map { index, pair in Carrier( index: index, @@ -64,40 +64,28 @@ final class MetadataSourceRecordTests: MachOSwiftSectionFixtureTests, FixtureSui @Test func mangledTypeName() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { try carrier.file.mangledTypeName(in: machOFile).rawString }, - image: { try carrier.image.mangledTypeName(in: machOImage).rawString }, - inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).mangledTypeName().rawString } - ) - #expect(result == carrier.expected.mangledTypeName, "record \(carrier.index)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try carrier.file.mangledTypeName(in: fileContext).rawString }, - image: { try carrier.image.mangledTypeName(in: imageContext).rawString } + image: { try carrier.image.mangledTypeName(in: imageContext).rawString }, + inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).mangledTypeName(in: self.inProcessContext).rawString } ) - #expect(fromContext == carrier.expected.mangledTypeName, "record \(carrier.index)") + #expect(result == carrier.expected.mangledTypeName, "record \(carrier.index)") } } @Test func mangledMetadataSource() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { try carrier.file.mangledMetadataSource(in: machOFile).rawString }, - image: { try carrier.image.mangledMetadataSource(in: machOImage).rawString }, - inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).mangledMetadataSource().rawString } - ) - #expect(result == carrier.expected.mangledMetadataSource, "record \(carrier.index)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try carrier.file.mangledMetadataSource(in: fileContext).rawString }, - image: { try carrier.image.mangledMetadataSource(in: imageContext).rawString } + image: { try carrier.image.mangledMetadataSource(in: imageContext).rawString }, + inProcess: { try carrier.image.asPointerWrapper(in: self.machOImage).mangledMetadataSource(in: self.inProcessContext).rawString } ) - #expect(fromContext == carrier.expected.mangledMetadataSource, "record \(carrier.index)") + #expect(result == carrier.expected.mangledMetadataSource, "record \(carrier.index)") } // The two entries are distinct bindings; if they collapsed to the // same recipe the fixture would no longer show the index varying. - let recipes = try allCarriers().map { try $0.file.mangledMetadataSource(in: machOFile).rawString } + let recipes = try allCarriers().map { try $0.file.mangledMetadataSource(in: fileContext).rawString } #expect(Set(recipes).count == recipes.count) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift index 690071fa1..20cb1b48f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorProtocolTests.swift @@ -28,60 +28,44 @@ final class ContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, Fixtu let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let presence = try acrossAllReaders( - file: { (try fileDescriptor.parent(in: machOFile)) != nil }, - image: { (try imageDescriptor.parent(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileDescriptor.parent(in: fileContext)) != nil }, + image: { (try imageDescriptor.parent(in: imageContext)) != nil } ) #expect(presence == ContextDescriptorProtocolBaseline.structTest.hasParent) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try imageDescriptor.parent(in: imageContext)) != nil - #expect(imageCtxPresence == ContextDescriptorProtocolBaseline.structTest.hasParent) } @Test func genericContext() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let presence = try acrossAllReaders( - file: { (try fileDescriptor.genericContext(in: machOFile)) != nil }, - image: { (try imageDescriptor.genericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileDescriptor.genericContext(in: fileContext)) != nil }, + image: { (try imageDescriptor.genericContext(in: imageContext)) != nil } ) #expect(presence == ContextDescriptorProtocolBaseline.structTest.hasGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try imageDescriptor.genericContext(in: imageContext)) != nil - #expect(imageCtxPresence == ContextDescriptorProtocolBaseline.structTest.hasGenericContext) } @Test func moduleContextDescriptor() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let presence = try acrossAllReaders( - file: { (try fileDescriptor.moduleContextDescriptor(in: machOFile)) != nil }, - image: { (try imageDescriptor.moduleContextDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileDescriptor.moduleContextDescriptor(in: fileContext)) != nil }, + image: { (try imageDescriptor.moduleContextDescriptor(in: imageContext)) != nil } ) #expect(presence == ContextDescriptorProtocolBaseline.structTest.hasModuleContextDescriptor) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try imageDescriptor.moduleContextDescriptor(in: imageContext)) != nil - #expect(imageCtxPresence == ContextDescriptorProtocolBaseline.structTest.hasModuleContextDescriptor) } @Test func isCImportedContextDescriptor() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let result = try acrossAllReaders( - file: { try fileDescriptor.isCImportedContextDescriptor(in: machOFile) }, - image: { try imageDescriptor.isCImportedContextDescriptor(in: machOImage) } + let result = try acrossAllContexts( + file: { try fileDescriptor.isCImportedContextDescriptor(in: fileContext) }, + image: { try imageDescriptor.isCImportedContextDescriptor(in: imageContext) } ) #expect(result == ContextDescriptorProtocolBaseline.structTest.isCImportedContextDescriptor) - - // ReadingContext-based overload also exercised. - let imageCtxResult = try imageDescriptor.isCImportedContextDescriptor(in: imageContext) - #expect(imageCtxResult == ContextDescriptorProtocolBaseline.structTest.isCImportedContextDescriptor) } @Test("subscript(dynamicMember:)") func subscriptDynamicMember() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift index 6f4da304e..26b9bcac9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextDescriptorWrapperTests.swift @@ -201,42 +201,34 @@ final class ContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixtur @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.parent(in: machOFile)) != nil }, - image: { (try wrappers.image.parent(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.parent(in: fileContext)) != nil }, + image: { (try wrappers.image.parent(in: imageContext)) != nil } ) #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasParent) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.parent(in: imageContext)) != nil - #expect(imageCtxPresence == ContextDescriptorWrapperBaseline.structTest.hasParent) } @Test func genericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.genericContext(in: machOFile)) != nil }, - image: { (try wrappers.image.genericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.genericContext(in: fileContext)) != nil }, + image: { (try wrappers.image.genericContext(in: imageContext)) != nil } ) #expect(presence == ContextDescriptorWrapperBaseline.structTest.hasGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.genericContext(in: imageContext)) != nil - #expect(imageCtxPresence == ContextDescriptorWrapperBaseline.structTest.hasGenericContext) } @Test func resolve() async throws { // `resolve` is a static func with multiple overloads; all collapse to - // one MethodKey. Exercise the MachO-based overload that returns - // `Self` (the path used by `ContextDescriptorWrapper.resolve(from:in:)` + // one MethodKey. Exercise the ReadingContext-based overload that + // returns `Self` (the path used by `ContextDescriptorWrapper.resolve(at:in:)` // when reading wrapper records out of a section). Type the result // explicitly as `ContextDescriptorWrapper` to disambiguate from the // `Self?`-returning sibling overload. let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let fileWrapper: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(from: fileDescriptor.offset, in: machOFile) - let imageWrapper: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(from: imageDescriptor.offset, in: machOImage) + let fileWrapper: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: fileDescriptor.offset, in: fileContext) + let imageWrapper: ContextDescriptorWrapper = try ContextDescriptorWrapper.resolve(at: imageDescriptor.offset, in: imageContext) #expect(fileWrapper.isStruct == true) #expect(imageWrapper.isStruct == true) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift index ab94b5ec7..30c5341f3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextProtocolTests.swift @@ -24,17 +24,13 @@ final class ContextProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func parent() async throws { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let fileContextWrapper = try Struct(descriptor: fileDescriptor, in: machOFile) - let imageContextWrapper = try Struct(descriptor: imageDescriptor, in: machOImage) + let fileContextWrapper = try Struct(descriptor: fileDescriptor, in: fileContext) + let imageContextWrapper = try Struct(descriptor: imageDescriptor, in: imageContext) - let presence = try acrossAllReaders( - file: { (try fileContextWrapper.parent(in: machOFile)) != nil }, - image: { (try imageContextWrapper.parent(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileContextWrapper.parent(in: fileContext)) != nil }, + image: { (try imageContextWrapper.parent(in: imageContext)) != nil } ) #expect(presence == ContextProtocolBaseline.structTest.hasParent) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try imageContextWrapper.parent(in: imageContext)) != nil - #expect(imageCtxPresence == ContextProtocolBaseline.structTest.hasParent) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift index e9dac8084..a099e9327 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/ContextWrapperTests.swift @@ -28,8 +28,8 @@ final class ContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u private func loadStructTestWrappers() throws -> (file: ContextWrapper, image: ContextWrapper) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let fileWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(fileDescriptor)), in: machOFile) - let imageWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(imageDescriptor)), in: machOImage) + let fileWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(fileDescriptor)), in: fileContext) + let imageWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(imageDescriptor)), in: imageContext) return (file: fileWrapper, image: imageWrapper) } @@ -49,27 +49,22 @@ final class ContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) // All three overloads (MachO, ReadingContext, InProcess) collapse to - // a single MethodKey. Exercise each path and assert the resulting - // wrapper's descriptor offset matches the baseline. - let fileWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(fileDescriptor)), in: machOFile) - let imageWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(imageDescriptor)), in: machOImage) - let imageCtxWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(imageDescriptor)), in: imageContext) + // a single MethodKey. Exercise the ReadingContext overload over both + // readers and assert the resulting wrapper's descriptor offset + // matches the baseline. + let fileWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(fileDescriptor)), in: fileContext) + let imageWrapper = try ContextWrapper.forContextDescriptorWrapper(.type(.struct(imageDescriptor)), in: imageContext) #expect(fileWrapper.context.descriptor.offset == ContextWrapperBaseline.structTest.descriptorOffset) #expect(imageWrapper.context.descriptor.offset == ContextWrapperBaseline.structTest.descriptorOffset) - #expect(imageCtxWrapper.context.descriptor.offset == ContextWrapperBaseline.structTest.descriptorOffset) } @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.parent(in: machOFile)) != nil }, - image: { (try wrappers.image.parent(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.parent(in: fileContext)) != nil }, + image: { (try wrappers.image.parent(in: imageContext)) != nil } ) #expect(presence == ContextWrapperBaseline.structTest.hasParent) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.parent(in: imageContext)) != nil - #expect(imageCtxPresence == ContextWrapperBaseline.structTest.hasParent) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift index 16a7ee455..b16600309 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ContextDescriptor/NamedContextDescriptorProtocolTests.swift @@ -26,15 +26,11 @@ final class NamedContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let result = try acrossAllReaders( - file: { try fileDescriptor.name(in: machOFile) }, - image: { try imageDescriptor.name(in: machOImage) } + let result = try acrossAllContexts( + file: { try fileDescriptor.name(in: fileContext) }, + image: { try imageDescriptor.name(in: imageContext) } ) #expect(result == NamedContextDescriptorProtocolBaseline.structTest.name) - - // ReadingContext-based overload also exercised. - let imageCtxName = try imageDescriptor.name(in: imageContext) - #expect(imageCtxName == NamedContextDescriptorProtocolBaseline.structTest.name) } @Test func mangledName() async throws { @@ -43,12 +39,10 @@ final class NamedContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, // MangledName isn't trivially Equatable for our needs; assert // presence at runtime against the baseline flag. - let filePresence = (try? fileDescriptor.mangledName(in: machOFile)) != nil - let imagePresence = (try? imageDescriptor.mangledName(in: machOImage)) != nil - let imageCtxPresence = (try? imageDescriptor.mangledName(in: imageContext)) != nil + let filePresence = (try? fileDescriptor.mangledName(in: fileContext)) != nil + let imagePresence = (try? imageDescriptor.mangledName(in: imageContext)) != nil #expect(filePresence == imagePresence) - #expect(filePresence == imageCtxPresence) #expect(filePresence == NamedContextDescriptorProtocolBaseline.structTest.hasMangledName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift b/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift index b93e097c6..e4053985b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/CoverageAllowlistEntries.swift @@ -2,7 +2,7 @@ import Foundation @testable import MachOTestingSupport import MachOFixtureSupport -/// Public members of `Sources/MachOSwiftSection/Models/` that are intentionally +/// Public members of `Sources/ABI/MachOSwiftSection/Models/` that are intentionally /// not under cross-reader fixture coverage. Each entry MUST carry either a /// legacy exemption reason or a typed `SentinelReason`. The Coverage Invariant /// Test treats listed entries as if they had been tested. diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift index 2e68a2aa7..1dddc56c6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextDescriptorProtocolTests.swift @@ -27,15 +27,10 @@ final class ExtensionContextDescriptorProtocolTests: MachOSwiftSectionFixtureTes // mangled name. The MangledName tree itself is Hashable but we // record presence-only in the baseline for parity with the // wrapper Suite. - let presence = try acrossAllReaders( - file: { (try fileSubject.extendedContext(in: machOFile)) != nil }, - image: { (try imageSubject.extendedContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileSubject.extendedContext(in: fileContext)) != nil }, + image: { (try imageSubject.extendedContext(in: imageContext)) != nil } ) #expect(presence == ExtensionContextDescriptorProtocolBaseline.firstExtension.hasExtendedContext) - - // Also exercise the ReadingContext-based overload to ensure the - // third reader axis agrees. - let imageCtxPresence = (try imageSubject.extendedContext(in: imageContext)) != nil - #expect(imageCtxPresence == ExtensionContextDescriptorProtocolBaseline.firstExtension.hasExtendedContext) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift index be6aac88f..a2a8ac5bf 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Extension/ExtensionContextTests.swift @@ -24,8 +24,8 @@ final class ExtensionContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, private func loadFirstExtensionContexts() throws -> (file: ExtensionContext, image: ExtensionContext) { let fileDescriptor = try BaselineFixturePicker.extension_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.extension_first(in: machOImage) - let file = try ExtensionContext(descriptor: fileDescriptor, in: machOFile) - let image = try ExtensionContext(descriptor: imageDescriptor, in: machOImage) + let file = try ExtensionContext(descriptor: fileDescriptor, in: fileContext) + let image = try ExtensionContext(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -35,21 +35,17 @@ final class ExtensionContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, let fileDescriptor = try BaselineFixturePicker.extension_first(in: machOFile) let imageDescriptor = try BaselineFixturePicker.extension_first(in: machOImage) - let fileContext_ = try ExtensionContext(descriptor: fileDescriptor, in: machOFile) - let imageContext_ = try ExtensionContext(descriptor: imageDescriptor, in: machOImage) - let fileCtxContext = try ExtensionContext(descriptor: fileDescriptor, in: fileContext) - let imageCtxContext = try ExtensionContext(descriptor: imageDescriptor, in: imageContext) + let fileContext_ = try ExtensionContext(descriptor: fileDescriptor, in: fileContext) + let imageContext_ = try ExtensionContext(descriptor: imageDescriptor, in: imageContext) #expect(fileContext_.descriptor.offset == ExtensionContextBaseline.firstExtension.descriptorOffset) #expect(imageContext_.descriptor.offset == ExtensionContextBaseline.firstExtension.descriptorOffset) - #expect(fileCtxContext.descriptor.offset == ExtensionContextBaseline.firstExtension.descriptorOffset) - #expect(imageCtxContext.descriptor.offset == ExtensionContextBaseline.firstExtension.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { let imageDescriptor = try BaselineFixturePicker.extension_first(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcessContext_ = try ExtensionContext(descriptor: pointerDescriptor) + let inProcessContext_ = try ExtensionContext(descriptor: pointerDescriptor, in: inProcessContext) #expect(inProcessContext_.descriptor.offset != 0) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift index 078a53ae9..0e2f996f7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldDescriptor/FieldDescriptorTests.swift @@ -31,16 +31,16 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ private func loadGenericStructFieldDescriptors() throws -> (file: FieldDescriptor, image: FieldDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOImage) - let file = try required(try fileDescriptor.fieldDescriptor(in: machOFile)) - let image = try required(try imageDescriptor.fieldDescriptor(in: machOImage)) + let file = try required(try fileDescriptor.fieldDescriptor(in: fileContext)) + let image = try required(try imageDescriptor.fieldDescriptor(in: imageContext)) return (file: file, image: image) } private func loadStructTestFieldDescriptors() throws -> (file: FieldDescriptor, image: FieldDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let file = try required(try fileDescriptor.fieldDescriptor(in: machOFile)) - let image = try required(try imageDescriptor.fieldDescriptor(in: machOImage)) + let file = try required(try fileDescriptor.fieldDescriptor(in: fileContext)) + let image = try required(try imageDescriptor.fieldDescriptor(in: imageContext)) return (file: file, image: image) } @@ -93,35 +93,27 @@ final class FieldDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ @Test func mangledTypeName() async throws { let descriptors = try loadGenericStructFieldDescriptors() - let presence = try acrossAllReaders( - file: { (try? descriptors.file.mangledTypeName(in: machOFile)) != nil }, - image: { (try? descriptors.image.mangledTypeName(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try? descriptors.file.mangledTypeName(in: fileContext)) != nil }, + image: { (try? descriptors.image.mangledTypeName(in: imageContext)) != nil } ) #expect(presence == FieldDescriptorBaseline.genericStructNonRequirement.hasMangledTypeName) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try? descriptors.image.mangledTypeName(in: imageContext)) != nil - #expect(imageCtxPresence == FieldDescriptorBaseline.genericStructNonRequirement.hasMangledTypeName) } @Test func records() async throws { // Fixture with non-empty records: GenericStructNonRequirement (3 fields). let genericDescriptors = try loadGenericStructFieldDescriptors() - let genericCount = try acrossAllReaders( - file: { try genericDescriptors.file.records(in: machOFile).count }, - image: { try genericDescriptors.image.records(in: machOImage).count } + let genericCount = try acrossAllContexts( + file: { try genericDescriptors.file.records(in: fileContext).count }, + image: { try genericDescriptors.image.records(in: imageContext).count } ) #expect(genericCount == FieldDescriptorBaseline.genericStructNonRequirement.recordsCount) - // ReadingContext-based overload also exercised. - let imageCtxCount = try genericDescriptors.image.records(in: imageContext).count - #expect(imageCtxCount == FieldDescriptorBaseline.genericStructNonRequirement.recordsCount) - // Fixture with empty records: StructTest (0 fields, only a computed body). let structTestDescriptors = try loadStructTestFieldDescriptors() - let structTestCount = try acrossAllReaders( - file: { try structTestDescriptors.file.records(in: machOFile).count }, - image: { try structTestDescriptors.image.records(in: machOImage).count } + let structTestCount = try acrossAllContexts( + file: { try structTestDescriptors.file.records(in: fileContext).count }, + image: { try structTestDescriptors.image.records(in: imageContext).count } ) #expect(structTestCount == FieldDescriptorBaseline.structTest.recordsCount) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift index 9077be08d..93d53f3ca 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FieldRecord/FieldRecordTests.swift @@ -29,10 +29,10 @@ final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch private func loadRecords() throws -> (file: [FieldRecord], image: [FieldRecord]) { let fileDescriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOImage) - let fileFieldDescriptor = try required(try fileDescriptor.fieldDescriptor(in: machOFile)) - let imageFieldDescriptor = try required(try imageDescriptor.fieldDescriptor(in: machOImage)) - let fileRecords = try fileFieldDescriptor.records(in: machOFile) - let imageRecords = try imageFieldDescriptor.records(in: machOImage) + let fileFieldDescriptor = try required(try fileDescriptor.fieldDescriptor(in: fileContext)) + let imageFieldDescriptor = try required(try imageDescriptor.fieldDescriptor(in: imageContext)) + let fileRecords = try fileFieldDescriptor.records(in: fileContext) + let imageRecords = try imageFieldDescriptor.records(in: imageContext) return (file: fileRecords, image: imageRecords) } @@ -71,37 +71,29 @@ final class FieldRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch @Test func fieldName() async throws { // First record: field1. let firstRecords = try loadFirstRecord() - let firstName = try acrossAllReaders( - file: { try firstRecords.file.fieldName(in: machOFile) }, - image: { try firstRecords.image.fieldName(in: machOImage) } + let firstName = try acrossAllContexts( + file: { try firstRecords.file.fieldName(in: fileContext) }, + image: { try firstRecords.image.fieldName(in: imageContext) } ) #expect(firstName == FieldRecordBaseline.firstRecord.fieldName) - // ReadingContext-based overload also exercised. - let imageCtxFirstName = try firstRecords.image.fieldName(in: imageContext) - #expect(imageCtxFirstName == FieldRecordBaseline.firstRecord.fieldName) - // Second record: field2. let allRecords = try loadRecords() let fileSecond = try required(allRecords.file.dropFirst().first) let imageSecond = try required(allRecords.image.dropFirst().first) - let secondName = try acrossAllReaders( - file: { try fileSecond.fieldName(in: machOFile) }, - image: { try imageSecond.fieldName(in: machOImage) } + let secondName = try acrossAllContexts( + file: { try fileSecond.fieldName(in: fileContext) }, + image: { try imageSecond.fieldName(in: imageContext) } ) #expect(secondName == FieldRecordBaseline.secondRecord.fieldName) } @Test func mangledTypeName() async throws { let records = try loadFirstRecord() - let presence = try acrossAllReaders( - file: { (try? records.file.mangledTypeName(in: machOFile)) != nil }, - image: { (try? records.image.mangledTypeName(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try? records.file.mangledTypeName(in: fileContext)) != nil }, + image: { (try? records.image.mangledTypeName(in: imageContext)) != nil } ) #expect(presence == FieldRecordBaseline.firstRecord.hasMangledTypeName) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try? records.image.mangledTypeName(in: imageContext)) != nil - #expect(imageCtxPresence == FieldRecordBaseline.firstRecord.hasMangledTypeName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift index 77353e077..52ac7a77b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/AsyncFunctionPointerTests.swift @@ -124,7 +124,7 @@ final class AsyncFunctionPointerTests: MachOSwiftSectionFixtureTests, FixtureSui /// "the implementation" is one hop short. @Test func vtableMethodDescriptorPointsAtTheRecordNotTheCode() async throws { let classDescriptor = try BaselineFixturePicker.class_VTableBaseTest(in: machOFile) - let vtableClass = try Class(descriptor: classDescriptor, in: machOFile) + let vtableClass = try Class(descriptor: classDescriptor, in: fileContext) let record = try AsyncFunctionPointerFixtureRecords(in: machOFile).vtableMethod let descriptorsPointingAtTheRecord = vtableClass.methodDescriptors.filter { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift index 6394c1d5e..622d4162e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/FunctionPointer/CoroFunctionPointerTests.swift @@ -146,7 +146,7 @@ final class CoroFunctionPointerTests: FixtureSuite, @unchecked Sendable { }), "the fixture carries no coro function pointer — CoroutineAccessors may no longer lower `_read` to `yield_once_2`" ) - return (machOFile, try CoroFunctionPointer.resolve(from: symbol.offset, in: machOFile)) + return (machOFile, try CoroFunctionPointer.resolve(at: symbol.offset, in: machOFile.context)) } /// File-offset range of `__TEXT,__text`, used to prove the resolved diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift index a7fb36d5c..5e0cd1b47 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericContextTests.swift @@ -39,14 +39,14 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u for picker: (MachOFile) throws -> StructDescriptor ) throws -> TypeGenericContext { let fileDescriptor = try picker(machOFile) - return try required(try fileDescriptor.typeGenericContext(in: machOFile)) + return try required(try fileDescriptor.typeGenericContext(in: fileContext)) } private func loadContextsFromImage( for picker: (MachOImage) throws -> StructDescriptor ) throws -> TypeGenericContext { let imageDescriptor = try picker(machOImage) - return try required(try imageDescriptor.typeGenericContext(in: machOImage)) + return try required(try imageDescriptor.typeGenericContext(in: imageContext)) } private func nonRequirementContexts() throws -> (file: TypeGenericContext, image: TypeGenericContext) { @@ -85,13 +85,9 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u let fileDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOImage) - let fileMachO = try TypeGenericContext(contextDescriptor: fileDescriptor, in: machOFile) - let imageMachO = try TypeGenericContext(contextDescriptor: imageDescriptor, in: machOImage) let fileCtx = try TypeGenericContext(contextDescriptor: fileDescriptor, in: fileContext) let imageCtx = try TypeGenericContext(contextDescriptor: imageDescriptor, in: imageContext) - #expect(fileMachO.offset == GenericContextBaseline.layoutRequirement.offset) - #expect(imageMachO.offset == GenericContextBaseline.layoutRequirement.offset) #expect(fileCtx.offset == GenericContextBaseline.layoutRequirement.offset) #expect(imageCtx.offset == GenericContextBaseline.layoutRequirement.offset) } @@ -99,10 +95,10 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("init(contextDescriptor:)") func initializerInProcess() async throws { let imageDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOImage) let pointerWrapper = imageDescriptor.asPointerWrapper(in: machOImage) - // The InProcess init walks the descriptor via raw pointer arithmetic; - // we just assert it succeeds and produces a non-zero offset (the - // absolute pointer is per-process). - let inProcess = try TypeGenericContext(contextDescriptor: pointerWrapper) + // The init over the in-process context walks the descriptor via raw + // pointer arithmetic; we just assert it succeeds and produces a + // non-zero offset (the absolute pointer is per-process). + let inProcess = try TypeGenericContext(contextDescriptor: pointerWrapper, in: inProcessContext) #expect(inProcess.offset != 0) } @@ -367,9 +363,9 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u // Top-level type with no parent generic context: every requirement // is unique. Cross-reader equality on the count. let contexts = try layoutRequirementContexts() - let count = try acrossAllReaders( - file: { contexts.file.uniqueCurrentRequirements(in: machOFile).count }, - image: { contexts.image.uniqueCurrentRequirements(in: machOImage).count } + let count = try acrossAllContexts( + file: { contexts.file.uniqueCurrentRequirements(in: fileContext).count }, + image: { contexts.image.uniqueCurrentRequirements(in: imageContext).count } ) #expect(count == GenericContextBaseline.layoutRequirement.requirementsCount) } @@ -377,8 +373,8 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test func uniqueCurrentRequirementsInProcess() async throws { let contexts = try layoutRequirementContexts() let count = try acrossAllReaders( - file: { contexts.file.uniqueCurrentRequirementsInProcess().count }, - image: { contexts.image.uniqueCurrentRequirementsInProcess().count } + file: { contexts.file.uniqueCurrentRequirements(in: inProcessContext).count }, + image: { contexts.image.uniqueCurrentRequirements(in: inProcessContext).count } ) #expect(count == GenericContextBaseline.layoutRequirement.requirementsCount) } @@ -511,9 +507,9 @@ final class GenericContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u @Test("uniqueCurrentRequirements deduplicates by content even when parents are cumulative") func nestedThreeLevelUniqueCurrentRequirements() async throws { let contexts = try nestedThreeLevelContexts() - let count = try acrossAllReaders( - file: { contexts.file.uniqueCurrentRequirements(in: machOFile).count }, - image: { contexts.image.uniqueCurrentRequirements(in: machOImage).count } + let count = try acrossAllContexts( + file: { contexts.file.uniqueCurrentRequirements(in: fileContext).count }, + image: { contexts.image.uniqueCurrentRequirements(in: imageContext).count } ) // InnerMost adds one requirement. uniqueCurrentRequirements walks // `parentRequirements.flatMap { $0 }` and uses `isContentEqual` to diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift index d3b21b27e..ae8e8b0ba 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeDescriptorTests.swift @@ -20,10 +20,10 @@ final class GenericPackShapeDescriptorTests: MachOSwiftSectionFixtureTests, Fixt private func loadFirstPack() throws -> (file: GenericPackShapeDescriptor, image: GenericPackShapeDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let filePack = try required(fileContext.typePacks.first) - let imagePack = try required(imageContext.typePacks.first) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let filePack = try required(fileGenericContext.typePacks.first) + let imagePack = try required(imageGenericContext.typePacks.first) return (file: filePack, image: imagePack) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift index ad293b14c..ee4ce36d8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericPackShapeHeaderTests.swift @@ -20,10 +20,10 @@ final class GenericPackShapeHeaderTests: MachOSwiftSectionFixtureTests, FixtureS private func loadHeaders() throws -> (file: GenericPackShapeHeader, image: GenericPackShapeHeader) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileHeader = try required(fileContext.typePackHeader) - let imageHeader = try required(imageContext.typePackHeader) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileHeader = try required(fileGenericContext.typePackHeader) + let imageHeader = try required(imageGenericContext.typePackHeader) return (file: fileHeader, image: imageHeader) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift index 287864baa..1a7592eab 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericParamDescriptorTests.swift @@ -24,20 +24,20 @@ final class GenericParamDescriptorTests: MachOSwiftSectionFixtureTests, FixtureS private func loadLayoutRequirementParam0() throws -> (file: GenericParamDescriptor, image: GenericParamDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileParam = try required(fileContext.parameters.first) - let imageParam = try required(imageContext.parameters.first) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileParam = try required(fileGenericContext.parameters.first) + let imageParam = try required(imageGenericContext.parameters.first) return (file: fileParam, image: imageParam) } private func loadParameterPackParam0() throws -> (file: GenericParamDescriptor, image: GenericParamDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_ParameterPackRequirementTest(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileParam = try required(fileContext.parameters.first) - let imageParam = try required(imageContext.parameters.first) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileParam = try required(fileGenericContext.parameters.first) + let imageParam = try required(imageGenericContext.parameters.first) return (file: fileParam, image: imageParam) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift index 0599bb16c..84ae11ecf 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementContentTests.swift @@ -30,10 +30,10 @@ final class GenericRequirementContentTests: MachOSwiftSectionFixtureTests, Fixtu private func loadInvertedProtocols() throws -> (file: GenericRequirementContent.InvertedProtocols, image: GenericRequirementContent.InvertedProtocols) { let fileDescriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_InvertibleProtocolRequirementTest(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileValue = try requireInvertedProtocols(in: fileContext) - let imageValue = try requireInvertedProtocols(in: imageContext) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileValue = try requireInvertedProtocols(in: fileGenericContext) + let imageValue = try requireInvertedProtocols(in: imageGenericContext) return (file: fileValue, image: imageValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift index 410267eaa..b89c09ffd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementDescriptorTests.swift @@ -31,8 +31,8 @@ final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, Fi ) throws -> (file: GenericRequirementDescriptor, image: GenericRequirementDescriptor) { let fileDescriptor = try filePicker(machOFile) let imageDescriptor = try imagePicker(machOImage) - let fileGenericCtx = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageGenericCtx = try required(try imageDescriptor.typeGenericContext(in: machOImage)) + let fileGenericCtx = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericCtx = try required(try imageDescriptor.typeGenericContext(in: imageContext)) let fileReq = try required(fileGenericCtx.currentRequirements.first) let imageReq = try required(imageGenericCtx.currentRequirements.first) return (file: fileReq, image: imageReq) @@ -155,14 +155,10 @@ final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, Fi // as a literal; cross-reader equality is meaningful on the parsed // result. MangledName is Hashable/Equatable so direct equality works. let layout = try layoutRequirements() - let fileName = try layout.file.paramMangledName(in: machOFile) - let imageName = try layout.image.paramMangledName(in: machOImage) - let fileCtxName = try layout.file.paramMangledName(in: fileContext) - let imageCtxName = try layout.image.paramMangledName(in: imageContext) + let fileName = try layout.file.paramMangledName(in: fileContext) + let imageName = try layout.image.paramMangledName(in: imageContext) #expect(fileName == imageName) - #expect(fileName == fileCtxName) - #expect(fileName == imageCtxName) } @Test func type() async throws { @@ -170,22 +166,18 @@ final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, Fi // baseClass / sameShape. The sameType requirement provides a clean // carrier. let sameType = try sameTypeRequirements() - let fileType = try sameType.file.type(in: machOFile) - let imageType = try sameType.image.type(in: machOImage) - let fileCtxType = try sameType.file.type(in: fileContext) + let fileType = try sameType.file.type(in: fileContext) + let imageType = try sameType.image.type(in: imageContext) #expect(fileType == imageType) - #expect(fileType == fileCtxType) } @Test func resolvedContent() async throws { let layout = try layoutRequirements() - let fileResolved = try layout.file.resolvedContent(in: machOFile) - let imageResolved = try layout.image.resolvedContent(in: machOImage) - let fileCtxResolved = try layout.file.resolvedContent(in: fileContext) + let fileResolved = try layout.file.resolvedContent(in: fileContext) + let imageResolved = try layout.image.resolvedContent(in: imageContext) #expect(fileResolved == imageResolved) - #expect(fileResolved == fileCtxResolved) #expect(describeResolvedKind(fileResolved) == GenericRequirementDescriptorBaseline.layoutRequirement.contentKindCase) } @@ -193,19 +185,17 @@ final class GenericRequirementDescriptorTests: MachOSwiftSectionFixtureTests, Fi // The descriptor offsets differ between MachOFile and MachOImage // readers; `isContentEqual(to:in:)` requires both descriptors to // be reachable through the supplied reader. We therefore exercise - // each overload with same-reader inputs (a descriptor is content- + // each context with same-reader inputs (a descriptor is content- // equal to itself). let layout = try layoutRequirements() - #expect(layout.file.isContentEqual(to: layout.file, in: machOFile)) - #expect(layout.image.isContentEqual(to: layout.image, in: machOImage)) #expect(layout.file.isContentEqual(to: layout.file, in: fileContext)) #expect(layout.image.isContentEqual(to: layout.image, in: imageContext)) - // The InProcess overload reads via the descriptor's resolved + // The in-process context reads via the descriptor's resolved // pointer — only the image-side descriptor carries a pointer-form // ivar set, so we exercise it from there. let imagePointerLeft = layout.image.asPointerWrapper(in: machOImage) let imagePointerRight = layout.image.asPointerWrapper(in: machOImage) - #expect(imagePointerLeft.isContentEqual(to: imagePointerRight)) + #expect(imagePointerLeft.isContentEqual(to: imagePointerRight, in: inProcessContext)) } // MARK: - Private helpers diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift index fd213041c..6cef1395b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericRequirementTests.swift @@ -29,12 +29,12 @@ final class GenericRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite ) throws -> (file: GenericRequirement, image: GenericRequirement) { let fileDescriptor = try filePicker(machOFile) let imageDescriptor = try imagePicker(machOImage) - let fileGenericCtx = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageGenericCtx = try required(try imageDescriptor.typeGenericContext(in: machOImage)) + let fileGenericCtx = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericCtx = try required(try imageDescriptor.typeGenericContext(in: imageContext)) let fileReqDesc = try required(fileGenericCtx.currentRequirements.first) let imageReqDesc = try required(imageGenericCtx.currentRequirements.first) - let fileReq = try GenericRequirement(descriptor: fileReqDesc, in: machOFile) - let imageReq = try GenericRequirement(descriptor: imageReqDesc, in: machOImage) + let fileReq = try GenericRequirement(descriptor: fileReqDesc, in: fileContext) + let imageReq = try GenericRequirement(descriptor: imageReqDesc, in: imageContext) return (file: fileReq, image: imageReq) } @@ -78,28 +78,27 @@ final class GenericRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test("init(descriptor:in:)") func initializerWithMachO() async throws { let fileDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileReqDesc = try required(fileContext.currentRequirements.first) - let imageReqDesc = try required(imageContext.currentRequirements.first) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileReqDesc = try required(fileGenericContext.currentRequirements.first) + let imageReqDesc = try required(imageGenericContext.currentRequirements.first) - let fileReq = try GenericRequirement(descriptor: fileReqDesc, in: machOFile) - let imageReq = try GenericRequirement(descriptor: imageReqDesc, in: machOImage) - let fileCtxReq = try GenericRequirement(descriptor: fileReqDesc, in: self.fileContext) + let fileReq = try GenericRequirement(descriptor: fileReqDesc, in: fileContext) + let imageReq = try GenericRequirement(descriptor: imageReqDesc, in: imageContext) #expect(fileReq.descriptor.offset == GenericRequirementBaseline.layoutRequirement.descriptorOffset) #expect(imageReq.descriptor.offset == GenericRequirementBaseline.layoutRequirement.descriptorOffset) - #expect(fileCtxReq.descriptor.offset == GenericRequirementBaseline.layoutRequirement.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { - // The InProcess init walks the descriptor via raw pointer arithmetic. - // We pull a descriptor from the image then re-wrap as a pointer-form. + // The init over the in-process context walks the descriptor via raw + // pointer arithmetic. We pull a descriptor from the image then + // re-wrap as a pointer-form. let imageDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOImage) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let imageReqDesc = try required(imageContext.currentRequirements.first) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let imageReqDesc = try required(imageGenericContext.currentRequirements.first) let pointerDescriptor = imageReqDesc.asPointerWrapper(in: machOImage) - let inProcess = try GenericRequirement(descriptor: pointerDescriptor) + let inProcess = try GenericRequirement(descriptor: pointerDescriptor, in: inProcessContext) // The in-process descriptor.offset is a pointer bit pattern; just // assert it resolved. #expect(inProcess.descriptor.offset != 0) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift index 366de2f6c..5a170a88b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueDescriptorTests.swift @@ -26,10 +26,10 @@ final class GenericValueDescriptorTests: MachOSwiftSectionFixtureTests, FixtureS private func loadFirstValue() throws -> (file: GenericValueDescriptor, image: GenericValueDescriptor) { let fileDescriptor = try BaselineFixturePicker.struct_FixedSizeArray(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_FixedSizeArray(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileValue = try required(fileContext.values.first) - let imageValue = try required(imageContext.values.first) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileValue = try required(fileGenericContext.values.first) + let imageValue = try required(imageGenericContext.values.first) return (file: fileValue, image: imageValue) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift index 081347527..7b5b53466 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/GenericValueHeaderTests.swift @@ -26,10 +26,10 @@ final class GenericValueHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite private func loadValueHeaders() throws -> (file: GenericValueHeader, image: GenericValueHeader) { let fileDescriptor = try BaselineFixturePicker.struct_FixedSizeArray(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_FixedSizeArray(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - let fileHeader = try required(fileContext.valueHeader) - let imageHeader = try required(imageContext.valueHeader) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + let fileHeader = try required(fileGenericContext.valueHeader) + let imageHeader = try required(imageGenericContext.valueHeader) return (file: fileHeader, image: imageHeader) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift index c7e97b7fc..91e704616 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericClassMetadataPatternTests.swift @@ -119,14 +119,14 @@ final class GenericClassMetadataPatternTests: MachOSwiftSectionFixtureTests, Fix @Test func immediateMembersPattern() async throws { let patterns = try loadPatterns() - let result = try acrossAllReaders( - file: { try patterns.file.immediateMembersPattern(in: machOFile)?.offset }, - image: { try patterns.image.immediateMembersPattern(in: machOImage)?.offset } + let result = try acrossAllContexts( + file: { try patterns.file.immediateMembersPattern(in: fileContext)?.offset }, + image: { try patterns.image.immediateMembersPattern(in: imageContext)?.offset } ) // This carrier has no immediate-members pattern; the accessor must // answer nil rather than hand back the extra-data one. #expect(result == nil) #expect(GenericClassMetadataPatternBaseline.hasImmediateMembersPattern == false) - #expect(try patterns.file.partialPatterns(in: machOFile).count == 1) + #expect(try patterns.file.partialPatterns(in: fileContext).count == 1) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift index d2ec97960..2acd05cfd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPartialPatternTests.swift @@ -21,8 +21,8 @@ final class GenericMetadataPartialPatternTests: MachOSwiftSectionFixtureTests, F let filePattern = try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOFile) let imagePattern = try BaselineFixturePicker.genericClassMetadataPattern_classNonRequirement(in: machOImage) return ( - file: try required(try filePattern.partialPatterns(in: machOFile).first), - image: try required(try imagePattern.partialPatterns(in: machOImage).first) + file: try required(try filePattern.partialPatterns(in: fileContext).first), + image: try required(try imagePattern.partialPatterns(in: imageContext).first) ) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift index 2c98c764e..a9092f7f3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/GenericMetadataPatternProtocolTests.swift @@ -87,26 +87,20 @@ final class GenericMetadataPatternProtocolTests: MachOSwiftSectionFixtureTests, @Test func partialPatterns() async throws { for carrier in try allCarriers() { - let offsets = try acrossAllReaders( - file: { try carrier.file.partialPatterns(in: machOFile).map(\.offset) }, - image: { try carrier.image.partialPatterns(in: machOImage).map(\.offset) } - ) - #expect(offsets.count == carrier.expected.partialPatternCount, "\(carrier.label)") - #expect(offsets.first == (carrier.expected.partialPatternCount > 0 ? carrier.expected.partialPatternsOffset : nil), "\(carrier.label)") - - let fromContext = try acrossAllContexts( + let offsets = try acrossAllContexts( file: { try carrier.file.partialPatterns(in: fileContext).map(\.offset) }, image: { try carrier.image.partialPatterns(in: imageContext).map(\.offset) } ) - #expect(fromContext == offsets, "\(carrier.label)") + #expect(offsets.count == carrier.expected.partialPatternCount, "\(carrier.label)") + #expect(offsets.first == (carrier.expected.partialPatternCount > 0 ? carrier.expected.partialPatternsOffset : nil), "\(carrier.label)") } } @Test func extraDataPattern() async throws { for carrier in try allCarriers() { - let result = try acrossAllReaders( - file: { try carrier.file.extraDataPattern(in: machOFile)?.offset }, - image: { try carrier.image.extraDataPattern(in: machOImage)?.offset } + let result = try acrossAllContexts( + file: { try carrier.file.extraDataPattern(in: fileContext)?.offset }, + image: { try carrier.image.extraDataPattern(in: imageContext)?.offset } ) let expected = carrier.expected.hasExtraDataPattern ? carrier.expected.partialPatternsOffset : nil #expect(result == expected, "\(carrier.label)") diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift index 78162d835..107ff0b4a 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/Pattern/ResilientClassMetadataPatternTests.swift @@ -37,7 +37,7 @@ final class ResilientClassMetadataPatternTests: MachOSwiftSectionFixtureTests, F // The pattern is reached through the singleton record's union field, // which is the whole point of this carrier. let descriptor = try BaselineFixturePicker.class_ResilientChild(in: machOFile) - let resilientChild = try Class(descriptor: descriptor, in: machOFile) + let resilientChild = try Class(descriptor: descriptor, in: fileContext) let initialization = try required(resilientChild.singletonMetadataInitialization) #expect(initialization.resolvedDirectOffset(from: \.incompleteMetadata) == result) #expect(descriptor.hasResilientSuperclass, "the union field only holds a pattern for a resilient-superclass class") diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift index 39dccce47..b228e4b11 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Generic/TypeGenericContextDescriptorHeaderTests.swift @@ -27,9 +27,9 @@ final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTes private func loadGenericStructLayoutRequirementHeaders() throws -> (file: TypeGenericContextDescriptorHeader, image: TypeGenericContextDescriptorHeader) { let fileDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_GenericStructLayoutRequirement(in: machOImage) - let fileContext = try required(try fileDescriptor.typeGenericContext(in: machOFile)) - let imageContext = try required(try imageDescriptor.typeGenericContext(in: machOImage)) - return (file: fileContext.header, image: imageContext.header) + let fileGenericContext = try required(try fileDescriptor.typeGenericContext(in: fileContext)) + let imageGenericContext = try required(try imageDescriptor.typeGenericContext(in: imageContext)) + return (file: fileGenericContext.header, image: imageGenericContext.header) } @Test func offset() async throws { @@ -85,7 +85,7 @@ final class TypeGenericContextDescriptorHeaderTests: MachOSwiftSectionFixtureTes // Resolving what it points at must produce a struct pattern, since // the carrier is a struct. - let pattern = try GenericValueMetadataPattern.resolve(from: try required(patternOffset), in: machOFile) + let pattern = try GenericValueMetadataPattern.resolve(at: try required(patternOffset), in: fileContext) #expect(pattern.metadataKind == .struct) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift index 417af6a87..1348cf1f1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathComputedPropertyBodyTests.swift @@ -27,8 +27,8 @@ final class KeyPathComputedPropertyBodyTests: MachOSwiftSectionFixtureTests, Fix let fileDescriptors = try KeyPathFixtureDescriptors(in: machOFile) let imageDescriptors = try KeyPathFixtureDescriptors(in: machOImage) return ( - file: try required(fileDescriptors.computedSettable.computedPropertyBody(in: machOFile)), - image: try required(imageDescriptors.computedSettable.computedPropertyBody(in: machOImage)) + file: try required(fileDescriptors.computedSettable.computedPropertyBody(in: fileContext)), + image: try required(imageDescriptors.computedSettable.computedPropertyBody(in: imageContext)) ) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift index cf090d728..adaa82157 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/KeyPathStoredFieldOffsetTests.swift @@ -33,14 +33,14 @@ final class KeyPathStoredFieldOffsetTests: MachOSwiftSectionFixtureTests, Fixtur return [ Shape( label: "inlineStoredOffset", - file: try required(fileDescriptors.inlineStoredOffset.storedFieldOffset(in: machOFile)), - image: try required(imageDescriptors.inlineStoredOffset.storedFieldOffset(in: machOImage)), + file: try required(fileDescriptors.inlineStoredOffset.storedFieldOffset(in: fileContext)), + image: try required(imageDescriptors.inlineStoredOffset.storedFieldOffset(in: imageContext)), expected: KeyPathStoredFieldOffsetBaseline.inlineStoredOffset ), Shape( label: "unresolvedFieldOffset", - file: try required(fileDescriptors.unresolvedFieldOffset.storedFieldOffset(in: machOFile)), - image: try required(imageDescriptors.unresolvedFieldOffset.storedFieldOffset(in: machOImage)), + file: try required(fileDescriptors.unresolvedFieldOffset.storedFieldOffset(in: fileContext)), + image: try required(imageDescriptors.unresolvedFieldOffset.storedFieldOffset(in: imageContext)), expected: KeyPathStoredFieldOffsetBaseline.unresolvedFieldOffset ), ] diff --git a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift index bd1e9459b..d39a7c3db 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/KeyPath/PropertyDescriptorTests.swift @@ -151,18 +151,12 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite /// file offset and must agree on the value. @Test func storedFieldOffset() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { try shape.file.storedFieldOffset(in: machOFile)?.rawValue }, - image: { try shape.image.storedFieldOffset(in: machOImage)?.rawValue }, - inProcess: { try shape.image.asPointerWrapper(in: self.machOImage).storedFieldOffset()?.rawValue } - ) - #expect(result == shape.expected.storedFieldOffsetRawValue, "\(shape.label)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try shape.file.storedFieldOffset(in: fileContext)?.rawValue }, - image: { try shape.image.storedFieldOffset(in: imageContext)?.rawValue } + image: { try shape.image.storedFieldOffset(in: imageContext)?.rawValue }, + inProcess: { try shape.image.asPointerWrapper(in: self.machOImage).storedFieldOffset(in: self.inProcessContext)?.rawValue } ) - #expect(fromContext == shape.expected.storedFieldOffsetRawValue, "\(shape.label)") + #expect(result == shape.expected.storedFieldOffsetRawValue, "\(shape.label)") } } @@ -170,22 +164,16 @@ final class PropertyDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite /// so it is identical across readers and pinned as a literal. @Test func computedPropertyBody() async throws { for shape in try allShapes() { - let result = try acrossAllReaders( - file: { try shape.file.computedPropertyBody(in: machOFile)?.getterOffset }, - image: { try shape.image.computedPropertyBody(in: machOImage)?.getterOffset } - ) - #expect(result == shape.expected.computedGetterOffset, "\(shape.label)") - - let fromContext = try acrossAllContexts( + let result = try acrossAllContexts( file: { try shape.file.computedPropertyBody(in: fileContext)?.getterOffset }, image: { try shape.image.computedPropertyBody(in: imageContext)?.getterOffset } ) - #expect(fromContext == shape.expected.computedGetterOffset, "\(shape.label)") + #expect(result == shape.expected.computedGetterOffset, "\(shape.label)") // The in-process leg reads through a pointer, so its offsets are // pointers too; only the relative words can be compared directly. - let inProcessBody = try shape.image.asPointerWrapper(in: machOImage).computedPropertyBody() - #expect(inProcessBody?.getter.relativeOffset == (try shape.file.computedPropertyBody(in: machOFile))?.getter.relativeOffset, "\(shape.label)") + let inProcessBody = try shape.image.asPointerWrapper(in: machOImage).computedPropertyBody(in: inProcessContext) + #expect(inProcessBody?.getter.relativeOffset == (try shape.file.computedPropertyBody(in: fileContext))?.getter.relativeOffset, "\(shape.label)") } } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift index 622862ade..064e47e38 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/MachOSwiftSectionCoverageInvariantTests.swift @@ -32,7 +32,7 @@ struct MachOSwiftSectionCoverageInvariantTests { .deletingLastPathComponent() // Fixtures/ .deletingLastPathComponent() // MachOSwiftSectionTests/ .deletingLastPathComponent() // Tests/ - .appendingPathComponent("../Sources/MachOSwiftSection/Models") + .appendingPathComponent("../Sources/ABI/MachOSwiftSection/Models") .standardizedFileURL } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift index cfa73f133..d2efe03b4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Mangling/MangledNameTests.swift @@ -22,8 +22,8 @@ final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch private func loadMangledNames() throws -> (file: MangledName, image: MangledName) { let fileDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOImage) - let file = try fileDescriptor.mangledTypeName(in: machOFile) - let image = try imageDescriptor.mangledTypeName(in: machOImage) + let file = try fileDescriptor.mangledTypeName(in: fileContext) + let image = try imageDescriptor.mangledTypeName(in: imageContext) return (file: file, image: image) } @@ -81,8 +81,8 @@ final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch @Test func resolve() async throws { // Static `resolve` overloads collapse to one MethodKey. Exercise - // the MachO-based overloads against the descriptor's - // mangledTypeName offset. + // the ReadingContext-based overload over both readers against the + // descriptor's mangledTypeName offset. let fileDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.multiPayloadEnumDescriptor_MultiPayloadEnumTest(in: machOImage) let mangledNameOffset = fileDescriptor.offset(of: \.mangledTypeName) @@ -90,8 +90,8 @@ final class MangledNameTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unch let relativeFile = fileDescriptor.layout.mangledTypeName.relativeOffset let relativeImage = imageDescriptor.layout.mangledTypeName.relativeOffset - let fileResolved = try MangledName.resolve(from: mangledNameOffset + Int(relativeFile), in: machOFile) - let imageResolved = try MangledName.resolve(from: imageOffset + Int(relativeImage), in: machOImage) + let fileResolved = try MangledName.resolve(at: mangledNameOffset + Int(relativeFile), in: fileContext) + let imageResolved = try MangledName.resolve(at: imageOffset + Int(relativeImage), in: imageContext) #expect(fileResolved.lookupElements.count == MangledNameBaseline.multiPayloadEnumName.lookupElementsCount) #expect(imageResolved.lookupElements.count == MangledNameBaseline.multiPayloadEnumName.lookupElementsCount) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift index 9b829559a..cd295d2f7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/FullMetadataTests.swift @@ -14,8 +14,8 @@ import MachOFixtureSupport /// no MachOFile path materialises one. /// /// **Reader asymmetry:** `MachOImage` is the only reader that surfaces a -/// live carrier. The Suite asserts the structural members agree across -/// the (image, imageContext, inProcess) reader axes. +/// live carrier, so the Suite reads every member through the image +/// context. /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite @@ -29,10 +29,10 @@ final class FullMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unc /// from a MachOImage metadata accessor. private func loadFullStructMetadata() throws -> FullMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let structMetadata = try required(try response.value.resolve(in: machOImage).struct) - return try structMetadata.asFullMetadata(in: machOImage) + let structMetadata = try required(try response.value.resolve(in: imageContext).struct) + return try structMetadata.asFullMetadata(in: imageContext) } @Test func offset() async throws { @@ -48,14 +48,5 @@ final class FullMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unc // value-type carrier; the header sub-layout's `valueWitnesses` // pointer must be non-nil (the reflexive lookup succeeded). #expect(full.layout.metadata.kind == StoredPointer(MetadataKind.struct.rawValue)) - - // ReadingContext path also exercised — the layout values must - // round-trip through `asFullMetadata(in: imageContext)`. - let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) - let response = try accessor(request: .init()) - let structMetadata = try required(try response.value.resolve(in: machOImage).struct) - let viaImageContext = try structMetadata.asFullMetadata(in: imageContext) - #expect(viaImageContext.layout.metadata.kind == full.layout.metadata.kind) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift index 0bd91ef8c..bc78d8459 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderPrefixTests.swift @@ -38,9 +38,9 @@ final class HeapMetadataHeaderPrefixTests: MachOSwiftSectionFixtureTests, Fixtur /// three-word heap-header layout). private func loadClassTestHeapHeaderPrefix() throws -> HeapMetadataHeaderPrefix { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let interop = try required(try response.value.resolve(in: machOImage).class) + let interop = try required(try response.value.resolve(in: imageContext).class) let prefixOffset = interop.offset - HeapMetadataHeader.layoutSize + TypeMetadataLayoutPrefix.layoutSize diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift index 442ead6f8..a6fad261d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/HeapMetadataHeaderTests.swift @@ -28,9 +28,9 @@ final class HeapMetadataHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite /// `interop.offset - HeapMetadataHeader.layoutSize`. private func loadClassTestHeapHeader() throws -> HeapMetadataHeader { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let interop = try required(try response.value.resolve(in: machOImage).class) + let interop = try required(try response.value.resolve(in: imageContext).class) return try machOImage.readWrapperElement(offset: interop.offset - HeapMetadataHeader.layoutSize) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift index 829b12188..dda61dd4e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/Headers/TypeMetadataHeaderTests.swift @@ -27,10 +27,10 @@ final class TypeMetadataHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuite /// header projection. private func loadStructTestTypeHeader() throws -> TypeMetadataHeader { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let structMetadata = try required(try response.value.resolve(in: machOImage).struct) - let fullMetadata = try structMetadata.asFullMetadata(in: machOImage) + let structMetadata = try required(try response.value.resolve(in: imageContext).struct) + let fullMetadata = try structMetadata.asFullMetadata(in: imageContext) // Header lives at structMetadata.offset - layoutSize. return try machOImage.readWrapperElement(offset: fullMetadata.offset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift index ed0906231..18cb1765d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataAccessorFunctionTests.swift @@ -30,18 +30,17 @@ final class MetadataAccessorFunctionTests: MachOSwiftSectionFixtureTests, Fixtur /// witness-table arguments and returns a complete metadata response. @Test func callAsFunction() async throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) // Zero-argument variant. let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) #expect(wrapper.isStruct) - // Same accessor, asserting the in-process variant returns the same - // wrapper kind (the response's value pointer is stable across - // invocations). + // Calling the same accessor a second time must answer the same + // wrapper kind again, read through the same image context. let response2 = try accessor(request: .init()) - let wrapper2 = try response2.value.resolve(in: machOImage) + let wrapper2 = try response2.value.resolve(in: imageContext) #expect(wrapper2.isStruct) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift index 9fd5ba466..1aa1103ee 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataInitialization/SingletonMetadataInitializationTests.swift @@ -26,8 +26,8 @@ final class SingletonMetadataInitializationTests: MachOSwiftSectionFixtureTests, private func loadInits() throws -> (file: SingletonMetadataInitialization, image: SingletonMetadataInitialization) { let fileDescriptor = try BaselineFixturePicker.class_singletonMetadataInitFirst(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_singletonMetadataInitFirst(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) return ( file: try required(fileClass.singletonMetadataInitialization), image: try required(imageClass.singletonMetadataInitialization) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift index ba47edad0..f35635b91 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataProtocolTests.swift @@ -16,7 +16,7 @@ import MachOFixtureSupport /// /// **Reader asymmetry:** the metadata carrier originates from MachOImage's /// accessor; `MachOFile` cannot invoke metadata accessors. Members are -/// exercised via the carrier's MachOImage / imageContext / in-process paths. +/// exercised via the carrier's imageContext / in-process paths. @Suite final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "MetadataProtocol" @@ -28,9 +28,20 @@ final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, /// `Structs.StructTest` from a MachOImage metadata accessor. private func loadStructTestStructMetadata() throws -> StructMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - return try required(try response.value.resolve(in: machOImage).struct) + return try required(try response.value.resolve(in: imageContext).struct) + } + + /// Materialise the same carrier through `inProcessContext` (offset = + /// runtime pointer bits) for the in-process legs. The accessor's + /// response `value` is the runtime metadata pointer, which the + /// in-process context reads as a raw address. + private func loadStructTestInProcessStructMetadata() throws -> StructMetadata { + let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) + let response = try accessor(request: .init()) + return try required(try response.value.resolve(in: inProcessContext).struct) } /// `createInMachO(_:)` recovers the (MachOImage, metadata) pair from a @@ -56,20 +67,16 @@ final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, /// `MetadataWrapper` enum and projects the matching arm. @Test func asMetadataWrapper() async throws { let carrier = try loadStructTestStructMetadata() - let imageWrapper = try carrier.asMetadataWrapper(in: machOImage) - let imageCtxWrapper = try carrier.asMetadataWrapper(in: imageContext) + let imageWrapper = try carrier.asMetadataWrapper(in: imageContext) #expect(imageWrapper.isStruct) - #expect(imageCtxWrapper.isStruct) } /// `asMetadata()` re-reads the kind-erased one-pointer prefix at the /// carrier's offset. The recovered `kind` must match. @Test func asMetadata() async throws { let carrier = try loadStructTestStructMetadata() - let imageMetadata = try carrier.asMetadata(in: machOImage) - let imageCtxMetadata = try carrier.asMetadata(in: imageContext) + let imageMetadata = try carrier.asMetadata(in: imageContext) #expect(imageMetadata.kind == .struct) - #expect(imageCtxMetadata.kind == .struct) } /// `kind` projects the carrier's metadata kind from the `layout.kind` @@ -91,24 +98,24 @@ final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, } /// `asFullMetadata()` returns the (header + metadata) pair preceded - /// by the metadata pointer; the wrapped header must agree across - /// readers. + /// by the metadata pointer. The metadata sub-layout's `kind` must + /// decode to `.struct` for our value-type carrier. @Test func asFullMetadata() async throws { let carrier = try loadStructTestStructMetadata() - let imageFull = try carrier.asFullMetadata(in: machOImage) - let imageCtxFull = try carrier.asFullMetadata(in: imageContext) - // Both readers must agree on the metadata sub-layout. - #expect(imageFull.layout.metadata.kind == imageCtxFull.layout.metadata.kind) + let imageFullMetadata = try carrier.asFullMetadata(in: imageContext) + #expect(imageFullMetadata.layout.metadata.kind == StoredPointer(MetadataKind.struct.rawValue)) } /// `valueWitnesses()` resolves the witness table through the - /// full-metadata header. + /// full-metadata header. The same carrier read through the in-process + /// context must resolve a table whose type layout agrees with the + /// image-context one. @Test func valueWitnesses() async throws { - let carrier = try loadStructTestStructMetadata() - let imageVW = try carrier.valueWitnesses(in: machOImage) - let imageCtxVW = try carrier.valueWitnesses(in: imageContext) - // Type layouts must agree across readers (size/stride/flags). - #expect(imageVW.typeLayout.size == imageCtxVW.typeLayout.size) + let imageValueWitnesses = try loadStructTestStructMetadata().valueWitnesses(in: imageContext) + let inProcessValueWitnesses = try loadStructTestInProcessStructMetadata().valueWitnesses(in: inProcessContext) + #expect(inProcessValueWitnesses.typeLayout.size == imageValueWitnesses.typeLayout.size) + #expect(inProcessValueWitnesses.typeLayout.stride == imageValueWitnesses.typeLayout.stride) + #expect(inProcessValueWitnesses.typeLayout.flags == imageValueWitnesses.typeLayout.flags) } /// `isAnyExistentialType` is `false` for the struct carrier. @@ -118,24 +125,25 @@ final class MetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, } /// `typeLayout()` resolves the type layout from the value-witnesses - /// table; cross-reader equality on `size`. + /// table; the in-process reading of the same carrier must agree with + /// the image-context one on every field. @Test func typeLayout() async throws { - let carrier = try loadStructTestStructMetadata() - let imageTL = try carrier.typeLayout(in: machOImage) - let imageCtxTL = try carrier.typeLayout(in: imageContext) - #expect(imageTL.size == imageCtxTL.size) + let imageTypeLayout = try loadStructTestStructMetadata().typeLayout(in: imageContext) + let inProcessTypeLayout = try loadStructTestInProcessStructMetadata().typeLayout(in: inProcessContext) + #expect(inProcessTypeLayout.size == imageTypeLayout.size) + #expect(inProcessTypeLayout.stride == imageTypeLayout.stride) + #expect(inProcessTypeLayout.flags == imageTypeLayout.flags) + #expect(inProcessTypeLayout.extraInhabitantCount == imageTypeLayout.extraInhabitantCount) } /// `typeContextDescriptorWrapper()` recovers the descriptor wrapper - /// for the carrier; for our `StructTest` this is the `.struct` arm. + /// for the carrier; for our `StructTest` this is the `.struct` arm, + /// holding the descriptor we picked from the MachOImage's type list. @Test func typeContextDescriptorWrapper() async throws { + let pickedDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let carrier = try loadStructTestStructMetadata() - let imageWrapper = try required(try carrier.typeContextDescriptorWrapper(in: machOImage)) - let imageCtxWrapper = try required(try carrier.typeContextDescriptorWrapper(in: imageContext)) - // ValueTypeDescriptorWrapper isn't trivially Equatable; compare - // via the `.struct` payload's offset. - let imageStructOffset = try required(imageWrapper.struct).offset - let imageCtxStructOffset = try required(imageCtxWrapper.struct).offset - #expect(imageStructOffset == imageCtxStructOffset) + let imageWrapper = try required(try carrier.typeContextDescriptorWrapper(in: imageContext)) + let imageStructDescriptor = try required(imageWrapper.struct) + #expect(imageStructDescriptor.offset == pickedDescriptor.offset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift index b0048a5b1..6101e5bff 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataResponseTests.swift @@ -25,7 +25,7 @@ final class MetadataResponseTests: MachOSwiftSectionFixtureTests, FixtureSuite, private func loadStructTestResponse() throws -> MetadataResponse { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) return try accessor(request: .completeAndBlocking) } @@ -33,7 +33,7 @@ final class MetadataResponseTests: MachOSwiftSectionFixtureTests, FixtureSuite, /// requested struct's wrapper. @Test func value() async throws { let response = try loadStructTestResponse() - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) #expect(wrapper.isStruct) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift index e826de8fb..4b90e56d6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataTests.swift @@ -27,9 +27,9 @@ final class MetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @uncheck /// Materialize a kind-erased `Metadata` for `Structs.StructTest`. private func loadStructTestMetadata() throws -> Metadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let structMetadata = try required(try response.value.resolve(in: machOImage).struct) + let structMetadata = try required(try response.value.resolve(in: imageContext).struct) // Re-read the kind-erased prefix at the same offset. return try machOImage.readWrapperElement(offset: structMetadata.offset) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift index 885493921..d6ed039b1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Metadata/MetadataWrapperTests.swift @@ -26,24 +26,26 @@ final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ MetadataWrapperBaseline.registeredTestMethodNames } - /// Materialise an image-relative wrapper for the MachOImage / - /// imageContext code paths. + /// Materialise an image-relative wrapper for the imageContext code + /// paths. private func loadStructTestImageWrapper() throws -> MetadataWrapper { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - return try response.value.resolve(in: machOImage) + return try response.value.resolve(in: imageContext) } /// Materialise an in-process wrapper (offset = runtime pointer bits) - /// for the no-arg projection paths (`metadata`, `valueWitnessTable()`). - /// The accessor's response `value` is the runtime metadata pointer; the - /// no-arg `Pointer.resolve()` interprets `address` as a raw pointer. + /// for the in-process projection paths (`metadata`, + /// `valueWitnessTable(in: inProcessContext)`). The accessor's response + /// `value` is the runtime metadata pointer; + /// `Pointer.resolve(in: inProcessContext)` interprets `address` as a raw + /// pointer. private func loadStructTestInProcessWrapper() throws -> MetadataWrapper { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - return try response.value.resolve() + return try response.value.resolve(in: inProcessContext) } /// `anyMetadata` projects the wrapped metadata as an existential @@ -59,52 +61,44 @@ final class MetadataWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ /// `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 without the `in:` reader. + /// pointer, so we materialise the wrapper through `inProcessContext`. @Test func metadata() async throws { let wrapper = try loadStructTestInProcessWrapper() - let metadata = try wrapper.metadata + let metadata = try wrapper.anyMetadata.asMetadata(in: inProcessContext) #expect(metadata.kind == .struct) } - /// `valueWitnessTable(in:)` (the MachO and ReadingContext overloads) - /// resolves the value-witness table through the full-metadata header. - /// Cross-reader equality on `typeLayout.size`. + /// `valueWitnessTable(in:)` resolves the value-witness table through + /// the full-metadata header. /// - /// The no-arg `valueWitnessTable()` overload requires an in-process + /// `valueWitnessTable(in: inProcessContext)` requires an in-process /// wrapper (offset = runtime pointer); we exercise it against the /// in-process variant and assert its `typeLayout.size` agrees with the - /// image variant. + /// image-context variant. @Test func valueWitnessTable() async throws { let imageWrapper = try loadStructTestImageWrapper() - let imageVW = try imageWrapper.valueWitnessTable(in: machOImage) - let imageCtxVW = try imageWrapper.valueWitnessTable(in: imageContext) - #expect(imageVW.typeLayout.size == imageCtxVW.typeLayout.size) + let imageVW = try imageWrapper.valueWitnessTable(in: imageContext) let inProcessWrapper = try loadStructTestInProcessWrapper() - let inProcessVW = try inProcessWrapper.valueWitnessTable() + let inProcessVW = try inProcessWrapper.valueWitnessTable(in: inProcessContext) #expect(inProcessVW.typeLayout.size == imageVW.typeLayout.size) } /// `resolve(...)` (3 overloads) materialises a wrapper at the given /// offset; the dispatch must select the same case as the original - /// accessor invocation. We exercise the MachO-based and - /// ReadingContext-based overloads (the `from ptr:` overload requires - /// a runtime raw pointer and is covered by the no-arg - /// `Pointer.resolve()` flow exercised in `metadata()`). + /// accessor invocation. We exercise the ReadingContext-based overload + /// (an in-process address requires a runtime raw pointer and is + /// covered by the `Pointer.resolve(in: inProcessContext)` flow + /// exercised in `metadata()`). @Test func resolve() async throws { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let original = try response.value.resolve(in: machOImage) + let original = try response.value.resolve(in: imageContext) let originalOffset = try required(original.struct).offset - // Re-resolve at the same offset via the MachOImage path. - let viaImage = try MetadataWrapper.resolve(from: originalOffset, in: machOImage) + // Re-resolve at the same offset through the image context. + let viaImage = try MetadataWrapper.resolve(at: originalOffset, in: imageContext) #expect(viaImage.isStruct) - - // Re-resolve via ReadingContext. - let imageAddress = try imageContext.addressFromOffset(originalOffset) - let viaImageContext = try MetadataWrapper.resolve(at: imageAddress, in: imageContext) - #expect(viaImageContext.isStruct) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift index 8aae8af0f..15daa4ea1 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Module/ModuleContextTests.swift @@ -22,8 +22,8 @@ final class ModuleContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un private func loadSymbolTestsCoreContexts() throws -> (file: ModuleContext, image: ModuleContext) { let fileDescriptor = try BaselineFixturePicker.module_SymbolTestsCore(in: machOFile) let imageDescriptor = try BaselineFixturePicker.module_SymbolTestsCore(in: machOImage) - let file = try ModuleContext(descriptor: fileDescriptor, in: machOFile) - let image = try ModuleContext(descriptor: imageDescriptor, in: machOImage) + let file = try ModuleContext(descriptor: fileDescriptor, in: fileContext) + let image = try ModuleContext(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -33,22 +33,18 @@ final class ModuleContextTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un let fileDescriptor = try BaselineFixturePicker.module_SymbolTestsCore(in: machOFile) let imageDescriptor = try BaselineFixturePicker.module_SymbolTestsCore(in: machOImage) - let fileContext_ = try ModuleContext(descriptor: fileDescriptor, in: machOFile) - let imageContext_ = try ModuleContext(descriptor: imageDescriptor, in: machOImage) - let fileCtxContext = try ModuleContext(descriptor: fileDescriptor, in: fileContext) - let imageCtxContext = try ModuleContext(descriptor: imageDescriptor, in: imageContext) + let fileContext_ = try ModuleContext(descriptor: fileDescriptor, in: fileContext) + let imageContext_ = try ModuleContext(descriptor: imageDescriptor, in: imageContext) #expect(fileContext_.descriptor.offset == ModuleContextBaseline.symbolTestsCore.descriptorOffset) #expect(imageContext_.descriptor.offset == ModuleContextBaseline.symbolTestsCore.descriptorOffset) - #expect(fileCtxContext.descriptor.offset == ModuleContextBaseline.symbolTestsCore.descriptorOffset) - #expect(imageCtxContext.descriptor.offset == ModuleContextBaseline.symbolTestsCore.descriptorOffset) #expect(fileContext_.name == ModuleContextBaseline.symbolTestsCore.name) } @Test("init(descriptor:)") func initializerInProcess() async throws { let imageDescriptor = try BaselineFixturePicker.module_SymbolTestsCore(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcessContext_ = try ModuleContext(descriptor: pointerDescriptor) + let inProcessContext_ = try ModuleContext(descriptor: pointerDescriptor, in: inProcessContext) #expect(inProcessContext_.descriptor.offset != 0) #expect(inProcessContext_.name == ModuleContextBaseline.symbolTestsCore.name) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift index a54387d1a..39d01769e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ObjC/ObjCProtocolPrefixTests.swift @@ -49,23 +49,18 @@ final class ObjCProtocolPrefixTests: MachOSwiftSectionFixtureTests, FixtureSuite @Test func name() async throws { let (file, image) = try loadFirstPrefixes() - let result = try acrossAllReaders( - file: { try file.name(in: machOFile) }, - image: { try image.name(in: machOImage) } + let result = try acrossAllContexts( + file: { try file.name(in: fileContext) }, + image: { try image.name(in: imageContext) } ) #expect(result == ObjCProtocolPrefixBaseline.firstPrefix.name) - - // ReadingContext overload also exercised. - let imageContextResult = try image.name(in: imageContext) - #expect(imageContextResult == ObjCProtocolPrefixBaseline.firstPrefix.name) } @Test func mangledName() async throws { // `mangledName(in:)` returns a MangledName payload; we exercise // its accessibility and ensure it resolves without error. let (file, image) = try loadFirstPrefixes() - _ = try file.mangledName(in: machOFile) - _ = try image.mangledName(in: machOImage) + _ = try file.mangledName(in: fileContext) _ = try image.mangledName(in: imageContext) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift index 690e1ec8e..ecc20625e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolBaseRequirementTests.swift @@ -21,8 +21,8 @@ final class ProtocolBaseRequirementTests: MachOSwiftSectionFixtureTests, Fixture private func loadBaseRequirements() throws -> (file: ProtocolBaseRequirement, image: ProtocolBaseRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) - let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: machOFile) - let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: machOImage) + let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: fileContext) + let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: imageContext) let file = try required(fileProtocol.baseRequirement) let image = try required(imageProtocol.baseRequirement) return (file: file, image: image) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift index 6cc16fcab..f4a047a88 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorRefTests.swift @@ -69,8 +69,8 @@ final class ProtocolDescriptorRefTests: MachOSwiftSectionFixtureTests, FixtureSu @Test func objcProtocol() async throws { let prefixFromFile = try BaselineFixturePicker.objcProtocolPrefix_first(in: machOFile) let prefixFromImage = try BaselineFixturePicker.objcProtocolPrefix_first(in: machOImage) - let nameFromFile = try prefixFromFile.name(in: machOFile) - let nameFromImage = try prefixFromImage.name(in: machOImage) + let nameFromFile = try prefixFromFile.name(in: fileContext) + let nameFromImage = try prefixFromImage.name(in: imageContext) #expect(nameFromFile == ProtocolDescriptorRefBaseline.liveObjc.name) #expect(nameFromImage == ProtocolDescriptorRefBaseline.liveObjc.name) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift index 70383d682..f984549d9 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolDescriptorTests.swift @@ -57,17 +57,13 @@ final class ProtocolDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite /// `associatedTypes(in:)` is exposed in three overloads (MachO + /// in-process + ReadingContext) that all collapse to a single /// `MethodKey` under PublicMemberScanner's name-based key. Exercise - /// the MachO and ReadingContext overloads here. + /// the ReadingContext overload over both readers here. @Test func associatedTypes() async throws { let (file, image) = try loadProtocolTestDescriptors() - let result = try acrossAllReaders( - file: { try file.associatedTypes(in: machOFile) }, - image: { try image.associatedTypes(in: machOImage) } + let result = try acrossAllContexts( + file: { try file.associatedTypes(in: fileContext) }, + image: { try image.associatedTypes(in: imageContext) } ) #expect(result == ProtocolDescriptorBaseline.protocolTest.associatedTypes) - - // ReadingContext overload also exercised. - let imageContextResult = try image.associatedTypes(in: imageContext) - #expect(imageContextResult == ProtocolDescriptorBaseline.protocolTest.associatedTypes) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift index db1bef131..956a360cd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRecordTests.swift @@ -36,25 +36,21 @@ final class ProtocolRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u let (file, image) = try loadFirstRecords() // The layout's `protocol` is a relative-pointer pair; we exercise // its presence by resolving and comparing the descriptor offset. - let resolvedFile = try required(file.protocolDescriptor(in: machOFile)) - let resolvedImage = try required(image.protocolDescriptor(in: machOImage)) + let resolvedFile = try required(file.protocolDescriptor(in: fileContext)) + let resolvedImage = try required(image.protocolDescriptor(in: imageContext)) #expect(resolvedFile.offset == ProtocolRecordBaseline.firstRecord.resolvedDescriptorOffset) #expect(resolvedImage.offset == ProtocolRecordBaseline.firstRecord.resolvedDescriptorOffset) } @Test func protocolDescriptor() async throws { let (file, image) = try loadFirstRecords() - let fileResolved = try required(file.protocolDescriptor(in: machOFile)) - let imageResolved = try required(image.protocolDescriptor(in: machOImage)) + let fileResolved = try required(file.protocolDescriptor(in: fileContext)) + let imageResolved = try required(image.protocolDescriptor(in: imageContext)) #expect(fileResolved.offset == ProtocolRecordBaseline.firstRecord.resolvedDescriptorOffset) #expect(imageResolved.offset == ProtocolRecordBaseline.firstRecord.resolvedDescriptorOffset) - // ReadingContext overload also exercised. - let imageContextResolved = try required(image.protocolDescriptor(in: imageContext)) - #expect(imageContextResolved.offset == ProtocolRecordBaseline.firstRecord.resolvedDescriptorOffset) - // Verify the resolved name is the deterministic baseline string. - let resolvedName = try fileResolved.name(in: machOFile) + let resolvedName = try fileResolved.name(in: fileContext) #expect(resolvedName == ProtocolRecordBaseline.firstRecord.resolvedDescriptorName) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift index 994a505da..ed577fe60 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementFlagsTests.swift @@ -22,8 +22,8 @@ final class ProtocolRequirementFlagsTests: MachOSwiftSectionFixtureTests, Fixtur private func loadFirstRequirementFlags() throws -> (file: ProtocolRequirementFlags, image: ProtocolRequirementFlags) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) - let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: machOFile) - let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: machOImage) + let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: fileContext) + let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: imageContext) let file = try required(fileProtocol.requirements.first?.layout.flags) let image = try required(imageProtocol.requirements.first?.layout.flags) return (file: file, image: image) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift index 48e1665ff..729d7f1b2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolRequirementTests.swift @@ -27,8 +27,8 @@ final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuit private func loadFirstRequirements() throws -> (file: ProtocolRequirement, image: ProtocolRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) - let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: machOFile) - let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: machOImage) + let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: fileContext) + let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: imageContext) let file = try required(fileProtocol.requirements.first) let image = try required(imageProtocol.requirements.first) return (file: file, image: image) @@ -37,8 +37,8 @@ final class ProtocolRequirementTests: MachOSwiftSectionFixtureTests, FixtureSuit private func loadFirstDefaultedRequirements() throws -> (file: ProtocolRequirement, image: ProtocolRequirement) { let fileDescriptor = try BaselineFixturePicker.protocol_BasicDefaultProtocol(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_BasicDefaultProtocol(in: machOImage) - let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: machOFile) - let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: machOImage) + let fileProtocol = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: fileContext) + let imageProtocol = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: imageContext) let file = try required(fileProtocol.requirements.first { $0.layout.defaultImplementation.isValid }) let image = try required(imageProtocol.requirements.first { $0.layout.defaultImplementation.isValid }) return (file: file, image: image) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift index 72e16c5ad..af21d4ff6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ProtocolTests.swift @@ -22,16 +22,16 @@ final class ProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @uncheck private func loadProtocolTestProtocols() throws -> (file: MachOSwiftSection.`Protocol`, image: MachOSwiftSection.`Protocol`) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) - let file = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: machOFile) - let image = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: machOImage) + let file = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: fileContext) + let image = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } private func loadWitnessTableTestProtocols() throws -> (file: MachOSwiftSection.`Protocol`, image: MachOSwiftSection.`Protocol`) { let fileDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolWitnessTableTest(in: machOImage) - let file = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: machOFile) - let image = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: machOImage) + let file = try MachOSwiftSection.`Protocol`(descriptor: fileDescriptor, in: fileContext) + let image = try MachOSwiftSection.`Protocol`(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -115,21 +115,21 @@ final class ProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @uncheck @Test("init(descriptor:in:)") func initializerWithDescriptorAndMachO() async throws { let descriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOFile) - let protocolType = try MachOSwiftSection.`Protocol`(descriptor: descriptor, in: machOFile) + let protocolType = try MachOSwiftSection.`Protocol`(descriptor: descriptor, in: fileContext) #expect(protocolType.name == ProtocolBaseline.protocolTest.name) #expect(protocolType.descriptor.offset == ProtocolBaseline.protocolTest.descriptorOffset) } @Test("init(descriptor:)") func initializerWithDescriptor() async throws { - // The descriptor-only init reads via `descriptor.asPointer` (in-process - // pointer dereference, treating `offset` as the carrier pointer). It + // The init over the in-process context reads through in-process + // pointer dereference, treating `offset` as the carrier pointer. It // requires the descriptor's `offset` to be a valid raw pointer // bit-pattern — true only if the descriptor was loaded via // `asPointerWrapper(in: machOImage)`, NOT via the section walk // (which carries offsets relative to the image base). let imageDescriptor = try BaselineFixturePicker.protocol_ProtocolTest(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let protocolType = try MachOSwiftSection.`Protocol`(descriptor: pointerDescriptor) + let protocolType = try MachOSwiftSection.`Protocol`(descriptor: pointerDescriptor, in: inProcessContext) #expect(protocolType.name == ProtocolBaseline.protocolTest.name) // The descriptor offset on a pointer-form wrapper is the raw pointer // bit-pattern, not the image-relative offset; validate the name diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift index 0e6bc5f65..374a87d96 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Protocol/ResilientWitnessTests.swift @@ -9,11 +9,12 @@ import MachOFixtureSupport /// /// Picker: the first `ProtocolConformance` from the fixture with a /// non-empty `resilientWitnesses` array. We pick its first witness and -/// exercise the `requirement(in:)` resolution path (MachO + ReadingContext -/// overloads), the `implementationOffset` derived var (pinned as a -/// literal), and the two `implementationAddress(in:)` forms: the -/// ReadingContext address must equal the offset, and the MachO-only debug -/// formatter must produce a non-empty hex string. +/// exercise the `requirement(in:)` resolution path over both readers' +/// contexts, the `implementationOffset` derived var (pinned as a literal), +/// and the implementation address in both forms: the ReadingContext +/// address from `implementationAddress(in:)` must equal the offset, and the +/// MachO-only debug formatter `implementationAddressString(in:)` must +/// produce a non-empty hex string. @Suite final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "ResilientWitness" @@ -49,15 +50,11 @@ final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, @Test func requirement() async throws { let (file, image) = try loadFirstWitnesses() - let result = try acrossAllReaders( - file: { (try file.requirement(in: machOFile)) != nil }, - image: { (try image.requirement(in: machOImage)) != nil } + let result = try acrossAllContexts( + file: { (try file.requirement(in: fileContext)) != nil }, + image: { (try image.requirement(in: imageContext)) != nil } ) #expect(result == ResilientWitnessBaseline.firstWitness.hasRequirement) - - // ReadingContext overload also exercised. - let imageContextResult = (try image.requirement(in: imageContext)) != nil - #expect(imageContextResult == ResilientWitnessBaseline.firstWitness.hasRequirement) } @Test func implementationOffset() async throws { @@ -69,22 +66,26 @@ final class ResilientWitnessTests: MachOSwiftSectionFixtureTests, FixtureSuite, #expect(result == ResilientWitnessBaseline.firstWitness.implementationOffset) } - /// `implementationAddress(in:)` is a MachO-only debug formatter — we - /// don't pin the address string (it differs between MachOFile vs - /// MachOImage by file vs in-memory base), but we verify it produces - /// non-empty hex from both readers. + /// The ReadingContext form answers the typed location of the + /// implementation, which for a Mach-O context is its offset. @Test func implementationAddress() async throws { let (file, image) = try loadFirstWitnesses() - let fileAddress = file.implementationAddress(in: machOFile) - let imageAddress = image.implementationAddress(in: machOImage) - #expect(fileAddress?.isEmpty == false) - #expect(imageAddress?.isEmpty == false) - - // The ReadingContext form is the typed location, not a string. let fileContextAddress = try file.implementationAddress(in: fileContext) let imageContextAddress = try image.implementationAddress(in: imageContext) #expect(fileContextAddress == file.implementationOffset) #expect(imageContextAddress == image.implementationOffset) #expect(imageContextAddress == ResilientWitnessBaseline.firstWitness.implementationOffset) } + + /// `implementationAddressString(in:)` is a Mach-O display helper — we + /// don't pin the address string (it differs between MachOFile vs + /// MachOImage by file vs in-memory base), but we verify it produces + /// non-empty hex from both readers. + @Test func implementationAddressString() async throws { + let (file, image) = try loadFirstWitnesses() + let fileAddress = file.implementationAddressString(in: machOFile) + let imageAddress = image.implementationAddressString(in: machOImage) + #expect(fileAddress?.isEmpty == false) + #expect(imageAddress?.isEmpty == false) + } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift index 75a14f629..5dc03f16d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/GlobalActorReferenceTests.swift @@ -53,18 +53,14 @@ final class GlobalActorReferenceTests: MachOSwiftSectionFixtureTests, FixtureSui /// `typeName(in:)` is exposed in three overloads (MachO + in-process /// + ReadingContext) that all collapse to a single `MethodKey` under - /// PublicMemberScanner's name-based key. Exercise the MachO and - /// ReadingContext overloads here. + /// PublicMemberScanner's name-based key. Exercise the ReadingContext + /// overload over both readers here. @Test func typeName() async throws { let (file, image) = try loadFirstReferences() - let result = try acrossAllReaders( - file: { try file.typeName(in: machOFile).symbolString }, - image: { try image.typeName(in: machOImage).symbolString } + let result = try acrossAllContexts( + file: { try file.typeName(in: fileContext).symbolString }, + image: { try image.typeName(in: imageContext).symbolString } ) #expect(result == GlobalActorReferenceBaseline.firstReference.typeNameSymbolString) - - // ReadingContext overload also exercised. - let imageContextResult = try image.typeName(in: imageContext).symbolString - #expect(imageContextResult == GlobalActorReferenceBaseline.firstReference.typeNameSymbolString) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift index 0f68eb39c..67a61aea2 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceDescriptorTests.swift @@ -73,31 +73,28 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F /// `protocolDescriptor(in:)` is exposed in three overloads (MachO + /// in-process + ReadingContext) that all collapse to a single - /// `MethodKey`. Exercise the MachO and ReadingContext overloads here. + /// `MethodKey`. Exercise the ReadingContext overload over both readers + /// here. @Test func protocolDescriptor() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let result = try acrossAllReaders( - file: { (try file.protocolDescriptor(in: machOFile)) != nil }, - image: { (try image.protocolDescriptor(in: machOImage)) != nil } + let result = try acrossAllContexts( + file: { (try file.protocolDescriptor(in: fileContext)) != nil }, + image: { (try image.protocolDescriptor(in: imageContext)) != nil } ) #expect(result == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.hasProtocolDescriptor) - - // ReadingContext overload also exercised. - let imageContextResult = (try image.protocolDescriptor(in: imageContext)) != nil - #expect(imageContextResult == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.hasProtocolDescriptor) } /// `resolvedTypeReference(in:)` is exposed in three overloads (MachO + /// in-process + ReadingContext) that all collapse to a single - /// `MethodKey`. Exercise the MachO and ReadingContext overloads here. + /// `MethodKey`. Exercise the ReadingContext overload over both readers + /// here. @Test func resolvedTypeReference() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let fileResolved = try file.resolvedTypeReference(in: machOFile) - let imageResolved = try image.resolvedTypeReference(in: machOImage) - let imageContextResolved = try image.resolvedTypeReference(in: imageContext) + let fileResolved = try file.resolvedTypeReference(in: fileContext) + let imageResolved = try image.resolvedTypeReference(in: imageContext) - for (label, resolved) in [("file", fileResolved), ("image", imageResolved), ("imageContext", imageContextResolved)] { + for (label, resolved) in [("file", fileResolved), ("image", imageResolved)] { if case .directTypeDescriptor = resolved { // Expected. } else { @@ -109,17 +106,14 @@ final class ProtocolConformanceDescriptorTests: MachOSwiftSectionFixtureTests, F /// `witnessTablePattern(in:)` is exposed in three overloads (MachO + /// in-process + ReadingContext) that all collapse to a single - /// `MethodKey`. Exercise the MachO and ReadingContext overloads here. + /// `MethodKey`. Exercise the ReadingContext overload over both readers + /// here. @Test func witnessTablePattern() async throws { let (file, image) = try loadStructTestProtocolTestDescriptors() - let result = try acrossAllReaders( - file: { (try file.witnessTablePattern(in: machOFile)) != nil }, - image: { (try image.witnessTablePattern(in: machOImage)) != nil } + let result = try acrossAllContexts( + file: { (try file.witnessTablePattern(in: fileContext)) != nil }, + image: { (try image.witnessTablePattern(in: imageContext)) != nil } ) #expect(result == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.hasWitnessTablePattern) - - // ReadingContext overload also exercised. - let imageContextResult = (try image.witnessTablePattern(in: imageContext)) != nil - #expect(imageContextResult == ProtocolConformanceDescriptorBaseline.structTestProtocolTest.hasWitnessTablePattern) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift index 39619fe54..9ed27cbe4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ProtocolConformance/ProtocolConformanceTests.swift @@ -180,26 +180,26 @@ final class ProtocolConformanceTests: MachOSwiftSectionFixtureTests, FixtureSuit /// Exercise both reader paths here. @Test("init(descriptor:in:)") func initializerWithDescriptorAndMachO() async throws { let descriptor = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOFile).descriptor - let conformance = try ProtocolConformance(descriptor: descriptor, in: machOFile) + let conformance = try ProtocolConformance(descriptor: descriptor, in: fileContext) #expect(conformance.descriptor.offset == ProtocolConformanceBaseline.structTestProtocolTest.descriptorOffset) #expect(conformance.flags.rawValue == ProtocolConformanceBaseline.structTestProtocolTest.flagsRawValue) - // ReadingContext overload also exercised (collapsed to the same - // MethodKey in the scanner). + // The same initializer over the image reader's context. let imageDescriptor = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOImage).descriptor let imageConformance = try ProtocolConformance(descriptor: imageDescriptor, in: imageContext) #expect(imageConformance.descriptor.offset == ProtocolConformanceBaseline.structTestProtocolTest.descriptorOffset) } - /// `init(descriptor:)` reads via `descriptor.asPointer` (in-process - /// pointer dereference). It requires the descriptor's `offset` to be - /// a valid raw pointer bit-pattern — true only if the descriptor - /// was loaded via `asPointerWrapper(in: machOImage)`, NOT via the - /// section walk (which carries offsets relative to the image base). + /// `init(descriptor:in:)` over the in-process context reads through + /// in-process pointer dereference. It requires the descriptor's + /// `offset` to be a valid raw pointer bit-pattern — true only if the + /// descriptor was loaded via `asPointerWrapper(in: machOImage)`, NOT + /// via the section walk (which carries offsets relative to the image + /// base). @Test("init(descriptor:)") func initializerWithDescriptor() async throws { let imageDescriptor = try BaselineFixturePicker.protocolConformance_StructTestProtocolTest(in: machOImage).descriptor let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let conformance = try ProtocolConformance(descriptor: pointerDescriptor) + let conformance = try ProtocolConformance(descriptor: pointerDescriptor, in: inProcessContext) #expect(conformance.flags.rawValue == ProtocolConformanceBaseline.structTestProtocolTest.flagsRawValue) #expect(conformance.protocol != nil) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift index 8adfe3680..deb83bd3d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassDescriptorTests.swift @@ -196,10 +196,11 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ } /// `resilientMetadataBounds(in:)` only succeeds on classes with a - /// resilient superclass. For `ClassTest` we just verify the predicate; - /// for resilient cases we'd add a dedicated test once a fixture surfaces - /// one. We exercise both the MachO and ReadingContext overloads here on - /// the no-resilient case to confirm they raise (or return) consistently. + /// resilient superclass. For `ClassTest` we only verify the predicate + /// that rules it out (`hasResilientSuperclass == false`); the method + /// itself is not called here. The resilient case + /// (`ResilientClassFixtures.ResilientChild`) is read through the + /// in-process context by `StoredClassMetadataBoundsTests`. @Test func resilientMetadataBounds() async throws { let (fileSubject, _) = try loadClassTestDescriptors() // Predicate: no resilient superclass. @@ -210,20 +211,16 @@ final class ClassDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, @ /// non-nil mangled name for `SubclassTest`. @Test func superclassTypeMangledName() async throws { let (classTestFile, classTestImage) = try loadClassTestDescriptors() - let classTestPresence = try acrossAllReaders( - file: { (try classTestFile.superclassTypeMangledName(in: machOFile)) != nil }, - image: { (try classTestImage.superclassTypeMangledName(in: machOImage)) != nil } + let classTestPresence = try acrossAllContexts( + file: { (try classTestFile.superclassTypeMangledName(in: fileContext)) != nil }, + image: { (try classTestImage.superclassTypeMangledName(in: imageContext)) != nil } ) #expect(classTestPresence == ClassDescriptorBaseline.classTest.hasSuperclassTypeMangledName) - // ReadingContext-based overload also exercised. - let classTestImageCtxPresence = (try classTestImage.superclassTypeMangledName(in: imageContext)) != nil - #expect(classTestImageCtxPresence == ClassDescriptorBaseline.classTest.hasSuperclassTypeMangledName) - let (subclassFile, subclassImage) = try loadSubclassTestDescriptors() - let subclassPresence = try acrossAllReaders( - file: { (try subclassFile.superclassTypeMangledName(in: machOFile)) != nil }, - image: { (try subclassImage.superclassTypeMangledName(in: machOImage)) != nil } + let subclassPresence = try acrossAllContexts( + file: { (try subclassFile.superclassTypeMangledName(in: fileContext)) != nil }, + image: { (try subclassImage.superclassTypeMangledName(in: imageContext)) != nil } ) #expect(subclassPresence == ClassDescriptorBaseline.subclassTest.hasSuperclassTypeMangledName) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift index 28d115f76..1f0886f4d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/ClassTests.swift @@ -14,8 +14,8 @@ import MachOFixtureSupport /// descriptors) because the heavy types (`TypeGenericContext`, /// `MethodDescriptor`, etc.) don't satisfy `Equatable` cheaply. /// -/// `init(descriptor:in:)` (MachO + ReadingContext overloads) and -/// `init(descriptor:)` (in-process) are exercised by dedicated tests. +/// `init(descriptor:in:)` is exercised by dedicated tests over the file +/// and image contexts and over the in-process context. @Suite final class ClassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "Class" @@ -24,22 +24,22 @@ final class ClassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked } /// Helper: instantiate the `Class` wrapper for `Classes.ClassTest` - /// against both readers using the MachO-direct initializer. + /// against both readers through their reading contexts. private func loadClassTestClasses() throws -> (file: Class, image: Class) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let file = try Class(descriptor: fileDescriptor, in: machOFile) - let image = try Class(descriptor: imageDescriptor, in: machOImage) + let file = try Class(descriptor: fileDescriptor, in: fileContext) + let image = try Class(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } /// Helper: instantiate the `Class` wrapper for `Classes.SubclassTest` - /// against both readers using the MachO-direct initializer. + /// against both readers through their reading contexts. private func loadSubclassTestClasses() throws -> (file: Class, image: Class) { let fileDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOImage) - let file = try Class(descriptor: fileDescriptor, in: machOFile) - let image = try Class(descriptor: imageDescriptor, in: machOImage) + let file = try Class(descriptor: fileDescriptor, in: fileContext) + let image = try Class(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -49,21 +49,17 @@ final class ClassTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) - let fileCtxClass = try Class(descriptor: fileDescriptor, in: fileContext) - let imageCtxClass = try Class(descriptor: imageDescriptor, in: imageContext) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) #expect(fileClass.descriptor.offset == ClassBaseline.classTest.descriptorOffset) #expect(imageClass.descriptor.offset == ClassBaseline.classTest.descriptorOffset) - #expect(fileCtxClass.descriptor.offset == ClassBaseline.classTest.descriptorOffset) - #expect(imageCtxClass.descriptor.offset == ClassBaseline.classTest.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcessClass = try Class(descriptor: pointerDescriptor) + let inProcessClass = try Class(descriptor: pointerDescriptor, in: inProcessContext) // The in-process `descriptor.offset` is a pointer bit pattern. #expect(inProcessClass.descriptor.offset != 0) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift index a69b076e5..8c491d67b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataProtocolTests.swift @@ -30,23 +30,21 @@ final class AnyClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, Fixtur /// re-resolve at the same offset as a slim `AnyClassMetadata`. private func loadAnyClassMetadata() throws -> AnyClassMetadata { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) let interop = try required(wrapper.class) - return try AnyClassMetadata.resolve(from: interop.offset, in: machOImage) + return try AnyClassMetadata.resolve(at: interop.offset, in: imageContext) } /// `asFinalClassMetadata(in:)` re-resolves the metadata at its own /// offset as an `AnyClassMetadata`. The slim view's offset must - /// agree with the source's offset across reader paths. + /// agree with the source's offset. @Test func asFinalClassMetadata() async throws { let any = try loadAnyClassMetadata() - let imageView: AnyClassMetadata = try any.asFinalClassMetadata(in: machOImage) - let imageCtxView: AnyClassMetadata = try any.asFinalClassMetadata(in: imageContext) + let imageView: AnyClassMetadata = try any.asFinalClassMetadata(in: imageContext) #expect(imageView.offset == any.offset) - #expect(imageCtxView.offset == any.offset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift index 1b57d2ed3..4c4cf93c4 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadata/AnyClassMetadataTests.swift @@ -36,11 +36,11 @@ final class AnyClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, /// superclass), so the slim re-resolution succeeds. private func loadAnyClassMetadata() throws -> AnyClassMetadata { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) let interop = try required(wrapper.class) - return try AnyClassMetadata.resolve(from: interop.offset, in: machOImage) + return try AnyClassMetadata.resolve(at: interop.offset, in: imageContext) } @Test func offset() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift index 85c9ce802..6737afe77 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropProtocolTests.swift @@ -22,9 +22,9 @@ final class AnyClassMetadataObjCInteropProtocolTests: MachOSwiftSectionFixtureTe private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.class) } @@ -33,24 +33,18 @@ final class AnyClassMetadataObjCInteropProtocolTests: MachOSwiftSectionFixtureTe @Test func asFinalClassMetadata() async throws { let interop = try loadInteropMetadata() - let imageView: ClassMetadataObjCInterop = try interop.asFinalClassMetadata(in: machOImage) - let imageCtxView: ClassMetadataObjCInterop = try interop.asFinalClassMetadata(in: imageContext) + let imageView: ClassMetadataObjCInterop = try interop.asFinalClassMetadata(in: imageContext) #expect(imageView.offset == interop.offset) - #expect(imageCtxView.offset == interop.offset) } /// `superclass(in:)` returns the metaclass / superclass slim view. /// For a Swift class with an implicit Swift root, this is non-nil. @Test func superclass() async throws { let interop = try loadInteropMetadata() - let imageSuper = try interop.superclass(in: machOImage) - let imageCtxSuper = try interop.superclass(in: imageContext) + let imageSuper = try interop.superclass(in: imageContext) #expect(imageSuper != nil) - #expect(imageCtxSuper != nil) - // The two readers should agree on the superclass offset. - #expect(imageSuper?.offset == imageCtxSuper?.offset) } /// `isPureObjC` is true when `data & 2 == 0` (i.e. NOT a Swift type). diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift index 2c3fe55e9..155b0b2ff 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/AnyClassMetadataObjCInterop/AnyClassMetadataObjCInteropTests.swift @@ -24,13 +24,13 @@ final class AnyClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, Fix /// its superclass to get an `AnyClassMetadataObjCInterop` slim view. private func loadAnyInteropSuperclass() throws -> AnyClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) let interop = try required(wrapper.class) // ClassTest's superclass is the implicit Swift root `SwiftObject`, // which surfaces as a non-nil ObjC-interop class metadata pointer. - return try required(try interop.superclass(in: machOImage)) + return try required(try interop.superclass(in: imageContext)) } @Test func offset() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift index 9ab039a06..7d4057b75 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadata/ClassMetadataTests.swift @@ -26,9 +26,9 @@ final class ClassMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un /// static lookup on `ClassMetadata`. private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.class) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift index 1fe2a5e50..f0fd4c0dd 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/ClassMetadataObjCInterop/ClassMetadataObjCInteropTests.swift @@ -22,9 +22,9 @@ final class ClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, Fixtur private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.class) } @@ -44,7 +44,7 @@ final class ClassMetadataObjCInteropTests: MachOSwiftSectionFixtureTests, Fixtur // should return a non-nil ClassDescriptor whose offset matches // the picker. let pickedDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let resolvedDescriptor = try metadata.layout.descriptor.resolve(in: machOImage) + let resolvedDescriptor = try metadata.layout.descriptor.resolve(in: imageContext) #expect(resolvedDescriptor?.offset == pickedDescriptor.offset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift index 6556f7177..7507dbe5f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Metadata/FinalClassMetadataProtocolTests.swift @@ -14,7 +14,7 @@ import MachOFixtureSupport /// /// **Reader asymmetry:** the metadata source originates from MachOImage; /// the protocol methods accept any `ReadingContext` so we exercise the -/// MachO + ReadingContext overloads here. +/// ReadingContext overloads here. @Suite final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "FinalClassMetadataProtocol" @@ -24,24 +24,21 @@ final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, Fixt private func loadInteropMetadata() throws -> ClassMetadataObjCInterop { let descriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.class) } /// `descriptor(in:)` returns the `ClassDescriptor` referenced by the - /// metadata's `descriptor` pointer. The result must match the picker - /// across reader paths. + /// metadata's `descriptor` pointer. The result must match the picker. @Test func descriptor() async throws { let pickedDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) let metadata = try loadInteropMetadata() - let imageDescriptor = try metadata.descriptor(in: machOImage) - let imageCtxDescriptor = try metadata.descriptor(in: imageContext) + let imageDescriptor = try metadata.descriptor(in: imageContext) #expect(imageDescriptor?.offset == pickedDescriptor.offset) - #expect(imageCtxDescriptor?.offset == pickedDescriptor.offset) } /// `fieldOffsets(for:in:)` returns the per-field byte-offsets vector @@ -50,10 +47,8 @@ final class FinalClassMetadataProtocolTests: MachOSwiftSectionFixtureTests, Fixt @Test func fieldOffsets() async throws { let metadata = try loadInteropMetadata() - let imageOffsets: [StoredPointer] = try metadata.fieldOffsets(in: machOImage) - let imageCtxOffsets: [StoredPointer] = try metadata.fieldOffsets(in: imageContext) + let imageOffsets: [StoredPointer] = try metadata.fieldOffsets(in: imageContext) - #expect(imageOffsets == imageCtxOffsets) // ClassTest has no stored properties. #expect(imageOffsets.isEmpty) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift index b70b7f2c6..58943b59c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorFlagsTests.swift @@ -23,8 +23,8 @@ final class MethodDescriptorFlagsTests: MachOSwiftSectionFixtureTests, FixtureSu private func loadFirstFlags() throws -> (file: MethodDescriptorFlags, image: MethodDescriptorFlags) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) let fileFlags = try required(fileClass.methodDescriptors.first?.layout.flags) let imageFlags = try required(imageClass.methodDescriptors.first?.layout.flags) return (file: fileFlags, image: imageFlags) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift index 3e00280ac..d8582118f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodDescriptorTests.swift @@ -25,8 +25,8 @@ final class MethodDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSuite, private func loadFirstMethods() throws -> (file: MethodDescriptor, image: MethodDescriptor) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) let fileMethod = try required(fileClass.methodDescriptors.first) let imageMethod = try required(imageClass.methodDescriptors.first) return (file: fileMethod, image: imageMethod) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift index 81795e6e6..d404dd0a7 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/MethodOverrideDescriptorTests.swift @@ -23,8 +23,8 @@ final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur private func loadFirstOverrides() throws -> (file: MethodOverrideDescriptor, image: MethodOverrideDescriptor) { let fileDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) let fileOverride = try required(fileClass.methodOverrideDescriptors.first) let imageOverride = try required(imageClass.methodOverrideDescriptors.first) return (file: fileOverride, image: imageOverride) @@ -55,24 +55,20 @@ final class MethodOverrideDescriptorTests: MachOSwiftSectionFixtureTests, Fixtur /// ancestor depending on layout). Verify cross-reader presence. @Test func classDescriptor() async throws { let overrides = try loadFirstOverrides() - let presence = try acrossAllReaders( - file: { (try overrides.file.classDescriptor(in: machOFile)) != nil }, - image: { (try overrides.image.classDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try overrides.file.classDescriptor(in: fileContext)) != nil }, + image: { (try overrides.image.classDescriptor(in: imageContext)) != nil } ) #expect(presence == true) - - // ReadingContext-based overload. - let imageCtxPresence = (try overrides.image.classDescriptor(in: imageContext)) != nil - #expect(imageCtxPresence == true) } /// `methodDescriptor(in:)` returns the underlying method being overridden. - /// Exercise both the MachO and pointer-based overloads. + /// Exercise the ReadingContext overload across both readers. @Test func methodDescriptor() async throws { let overrides = try loadFirstOverrides() - let presence = try acrossAllReaders( - file: { (try overrides.file.methodDescriptor(in: machOFile)) != nil }, - image: { (try overrides.image.methodDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try overrides.file.methodDescriptor(in: fileContext)) != nil }, + image: { (try overrides.image.methodDescriptor(in: imageContext)) != nil } ) #expect(presence == true) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift index f05ec016e..f1b6a648c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/OverrideTableHeaderTests.swift @@ -19,8 +19,8 @@ final class OverrideTableHeaderTests: MachOSwiftSectionFixtureTests, FixtureSuit private func loadSubclassOverrideHeaders() throws -> (file: OverrideTableHeader, image: OverrideTableHeader) { let fileDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_SubclassTest(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) let fileHeader = try required(fileClass.overrideTableHeader) let imageHeader = try required(imageClass.overrideTableHeader) return (file: fileHeader, image: imageHeader) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift index c2c51202a..3a1e5f2a3 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Method/VTableDescriptorHeaderTests.swift @@ -19,8 +19,8 @@ final class VTableDescriptorHeaderTests: MachOSwiftSectionFixtureTests, FixtureS private func loadClassTestVTableHeaders() throws -> (file: VTableDescriptorHeader, image: VTableDescriptorHeader) { let fileDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.class_ClassTest(in: machOImage) - let fileClass = try Class(descriptor: fileDescriptor, in: machOFile) - let imageClass = try Class(descriptor: imageDescriptor, in: machOImage) + let fileClass = try Class(descriptor: fileDescriptor, in: fileContext) + let imageClass = try Class(descriptor: imageDescriptor, in: imageContext) let fileHeader = try required(fileClass.vTableDescriptorHeader) let imageHeader = try required(imageClass.vTableDescriptorHeader) return (file: fileHeader, image: imageHeader) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift index d96f8665e..920cf2111 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ObjCResilientClassStubInfoTests.swift @@ -29,7 +29,7 @@ final class ObjCResilientClassStubInfoTests: MachOSwiftSectionFixtureTests, Fixt in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> ObjCResilientClassStubInfo { let descriptor = try BaselineFixturePicker.class_ResilientObjCStubChild(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) return try required(classWrapper.objcResilientClassStubInfo) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift index 09ffc6bf7..d5d27db12 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Class/Resilient/ResilientSuperclassTests.swift @@ -29,7 +29,7 @@ final class ResilientSuperclassTests: MachOSwiftSectionFixtureTests, FixtureSuit in machO: some MachOSwiftSectionRepresentableWithCache ) throws -> ResilientSuperclass { let descriptor = try BaselineFixturePicker.class_ResilientChild(in: machO) - let classWrapper = try Class(descriptor: descriptor, in: machO) + let classWrapper = try Class(descriptor: descriptor, in: machO.context) return try required(classWrapper.resilientSuperclass) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift index 30b417112..942cdf0c8 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/EnumTests.swift @@ -14,8 +14,8 @@ import MachOFixtureSupport /// descriptors) because the heavy types (`TypeGenericContext`, /// `SingletonMetadataPointer`, etc.) don't satisfy `Equatable` cheaply. /// -/// `init(descriptor:in:)` (MachO + ReadingContext overloads) and -/// `init(descriptor:)` (in-process) are exercised by dedicated tests. +/// `init(descriptor:in:)` is exercised by dedicated tests over the file +/// and image contexts and over the in-process context. @Suite final class EnumTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "Enum" @@ -24,12 +24,12 @@ final class EnumTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked S } /// Helper: instantiate the `Enum` wrapper for `Enums.NoPayloadEnumTest` - /// against both readers using the MachO-direct initializer. + /// against both readers through their reading contexts. private func loadNoPayloadEnums() throws -> (file: Enum, image: Enum) { let fileDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) - let file = try Enum(descriptor: fileDescriptor, in: machOFile) - let image = try Enum(descriptor: imageDescriptor, in: machOImage) + let file = try Enum(descriptor: fileDescriptor, in: fileContext) + let image = try Enum(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -39,21 +39,17 @@ final class EnumTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked S let fileDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) - let fileEnum = try Enum(descriptor: fileDescriptor, in: machOFile) - let imageEnum = try Enum(descriptor: imageDescriptor, in: machOImage) - let fileCtxEnum = try Enum(descriptor: fileDescriptor, in: fileContext) - let imageCtxEnum = try Enum(descriptor: imageDescriptor, in: imageContext) + let fileEnum = try Enum(descriptor: fileDescriptor, in: fileContext) + let imageEnum = try Enum(descriptor: imageDescriptor, in: imageContext) #expect(fileEnum.descriptor.offset == EnumBaseline.noPayloadEnumTest.descriptorOffset) #expect(imageEnum.descriptor.offset == EnumBaseline.noPayloadEnumTest.descriptorOffset) - #expect(fileCtxEnum.descriptor.offset == EnumBaseline.noPayloadEnumTest.descriptorOffset) - #expect(imageCtxEnum.descriptor.offset == EnumBaseline.noPayloadEnumTest.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { let imageDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcessEnum = try Enum(descriptor: pointerDescriptor) + let inProcessEnum = try Enum(descriptor: pointerDescriptor, in: inProcessContext) // The in-process `descriptor.offset` is a pointer bit pattern. #expect(inProcessEnum.descriptor.offset != 0) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift index f8b2cdb61..037480c28 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataProtocolTests.swift @@ -29,43 +29,40 @@ final class EnumMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSui private func loadNoPayloadEnumMetadata() throws -> EnumMetadata { let descriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.enum) } - /// `enumDescriptor(in:)` / `enumDescriptor()` — the descriptor recovered - /// from the metadata must match the one we picked from the MachOImage's - /// type list (same descriptor offset). + /// `enumDescriptor(in:)` — the descriptor recovered from the metadata + /// must match the one we picked from the MachOImage's type list (same + /// descriptor offset). @Test func enumDescriptor() async throws { let pickedDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) let metadata = try loadNoPayloadEnumMetadata() - let imageDescriptor = try metadata.enumDescriptor(in: machOImage) - let imageCtxDescriptor = try metadata.enumDescriptor(in: imageContext) - let inProcessDescriptor = try metadata.enumDescriptor() + let imageDescriptor = try metadata.enumDescriptor(in: imageContext) + let inProcessDescriptor = try metadata.enumDescriptor(in: inProcessContext) - // The two MachO-backed paths agree on the descriptor offset. + // The image-context path agrees with the picker on the descriptor + // offset. #expect(imageDescriptor.offset == pickedDescriptor.offset) - #expect(imageCtxDescriptor.offset == pickedDescriptor.offset) // The InProcess path returns the same descriptor by name. - #expect(try inProcessDescriptor.name() == "NoPayloadEnumTest") + #expect(try inProcessDescriptor.name(in: inProcessContext) == "NoPayloadEnumTest") } - /// `payloadSize(descriptor:in:)` / `payloadSize(descriptor:)` — for - /// `Enums.NoPayloadEnumTest` (no payload cases, `payloadSizeOffset == 0`), - /// this returns nil regardless of the reader. + /// `payloadSize(descriptor:in:)` — for `Enums.NoPayloadEnumTest` (no + /// payload cases, `payloadSizeOffset == 0`), this returns nil + /// regardless of the reader. @Test func payloadSize() async throws { let metadata = try loadNoPayloadEnumMetadata() - let imagePayload = try metadata.payloadSize(in: machOImage) - let imageCtxPayload = try metadata.payloadSize(in: imageContext) - let inProcessPayload = try metadata.payloadSize() + let imagePayload = try metadata.payloadSize(in: imageContext) + let inProcessPayload = try metadata.payloadSize(in: inProcessContext) - // No payload cases ⇒ no `payloadSizeOffset` ⇒ all nil. + // No payload cases ⇒ no `payloadSizeOffset` ⇒ both nil. #expect(imagePayload == nil) - #expect(imageCtxPayload == nil) #expect(inProcessPayload == nil) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift index 717273fc9..706bc6963 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/Metadata/EnumMetadataTests.swift @@ -8,11 +8,11 @@ import MachOFixtureSupport /// Fixture-based Suite for `EnumMetadata`. /// /// Materializing an `EnumMetadata` requires invoking the metadata accessor -/// function on a *loaded* MachOImage. As a consequence, the cross-reader -/// equality block here is asymmetric: the metadata instance only originates -/// from `MachOImage`, but methods on it accept any `MachOContext` / -/// `InProcessContext` so we still validate the readers agree on the layout -/// values. +/// function on a *loaded* MachOImage. As a consequence, the reader +/// coverage here is asymmetric: the metadata instance only originates from +/// `MachOImage`, but methods on it accept any `MachOContext` / +/// `InProcessContext`, so the layout's descriptor is read through both the +/// image context and the in-process context. /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite @@ -27,9 +27,9 @@ final class EnumMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unc /// response's value-type wrapper. private func loadNoPayloadEnumMetadata() throws -> EnumMetadata { let descriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.enum) } @@ -43,20 +43,19 @@ final class EnumMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unc } @Test func layout() async throws { + let pickedDescriptor = try BaselineFixturePicker.enum_NoPayloadEnumTest(in: machOImage) let metadata = try loadNoPayloadEnumMetadata() - // Cross-reader equality on the descriptor pointer and kind. The - // descriptor reachable via `descriptor(in:)` should be the same - // ValueTypeDescriptorWrapper kind across MachOImage/imageContext/ - // inProcess paths. - let imageDescriptor = try metadata.descriptor(in: machOImage) - let imageCtxDescriptor = try metadata.descriptor(in: imageContext) - let inProcessDescriptor = try metadata.descriptor() + // The descriptor reachable via `descriptor(in:)` should be the same + // ValueTypeDescriptorWrapper kind across the imageContext and + // inProcessContext paths. + let imageDescriptor = try metadata.descriptor(in: imageContext) + let inProcessDescriptor = try metadata.descriptor(in: inProcessContext) // ValueTypeDescriptorWrapper isn't Equatable, so compare via the - // concrete `enum` payload's offset. + // concrete `enum` payload's offset: through the image context it is + // the descriptor we picked from the MachOImage's type list. let imageEnumOffset = try required(imageDescriptor.enum).offset - let imageCtxEnumOffset = try required(imageCtxDescriptor.enum).offset - #expect(imageEnumOffset == imageCtxEnumOffset) + #expect(imageEnumOffset == pickedDescriptor.offset) // InProcess offset is a pointer bit pattern — it must be non-zero. let inProcessEnumOffset = try required(inProcessDescriptor.enum).offset #expect(inProcessEnumOffset != 0) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift index 05fadbf53..5d21e6c9e 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Enum/MultiPayloadEnumDescriptorTests.swift @@ -58,57 +58,45 @@ final class MultiPayloadEnumDescriptorTests: MachOSwiftSectionFixtureTests, Fixt @Test func mangledTypeName() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let rawString = try acrossAllReaders( - file: { try fileSubject.mangledTypeName(in: machOFile).rawString }, - image: { try imageSubject.mangledTypeName(in: machOImage).rawString } + let rawString = try acrossAllContexts( + file: { try fileSubject.mangledTypeName(in: fileContext).rawString }, + image: { try imageSubject.mangledTypeName(in: imageContext).rawString } ) #expect(rawString == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.mangledTypeNameRawString) - - // ReadingContext-based overload also exercised. - let fileCtxRaw = try fileSubject.mangledTypeName(in: fileContext).rawString - let imageCtxRaw = try imageSubject.mangledTypeName(in: imageContext).rawString - #expect(fileCtxRaw == rawString) - #expect(imageCtxRaw == rawString) } @Test func contents() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let count = try acrossAllReaders( - file: { try fileSubject.contents(in: machOFile).count }, - image: { try imageSubject.contents(in: machOImage).count } + let count = try acrossAllContexts( + file: { try fileSubject.contents(in: fileContext).count }, + image: { try imageSubject.contents(in: imageContext).count } ) #expect(count == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.contentsCount) - - // ReadingContext overloads. - let fileCtxCount = try fileSubject.contents(in: fileContext).count - let imageCtxCount = try imageSubject.contents(in: imageContext).count - #expect(fileCtxCount == count) - #expect(imageCtxCount == count) } @Test func payloadSpareBits() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let count = try acrossAllReaders( - file: { try fileSubject.payloadSpareBits(in: machOFile).count }, - image: { try imageSubject.payloadSpareBits(in: machOImage).count } + let count = try acrossAllContexts( + file: { try fileSubject.payloadSpareBits(in: fileContext).count }, + image: { try imageSubject.payloadSpareBits(in: imageContext).count } ) #expect(count == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitsCount) } @Test func payloadSpareBitMaskByteOffset() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { try fileSubject.payloadSpareBitMaskByteOffset(in: machOFile) }, - image: { try imageSubject.payloadSpareBitMaskByteOffset(in: machOImage) } + let result = try acrossAllContexts( + file: { try fileSubject.payloadSpareBitMaskByteOffset(in: fileContext) }, + image: { try imageSubject.payloadSpareBitMaskByteOffset(in: imageContext) } ) #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitMaskByteOffset) } @Test func payloadSpareBitMaskByteCount() async throws { let (fileSubject, imageSubject) = try loadDescriptors() - let result = try acrossAllReaders( - file: { try fileSubject.payloadSpareBitMaskByteCount(in: machOFile) }, - image: { try imageSubject.payloadSpareBitMaskByteCount(in: machOImage) } + let result = try acrossAllContexts( + file: { try fileSubject.payloadSpareBitMaskByteCount(in: fileContext) }, + image: { try imageSubject.payloadSpareBitMaskByteCount(in: imageContext) } ) #expect(result == MultiPayloadEnumDescriptorBaseline.multiPayloadEnumTest.payloadSpareBitMaskByteCount) } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift index 61d112b79..17b78333f 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataProtocolTests.swift @@ -21,42 +21,38 @@ final class StructMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureS private func loadStructTestMetadata() throws -> StructMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.struct) } - /// `structDescriptor(in:)` / `structDescriptor()` — the descriptor - /// recovered from the metadata must match the one we picked from the - /// MachOImage's type list (same descriptor offset). + /// `structDescriptor(in:)` — the descriptor recovered from the metadata + /// must match the one we picked from the MachOImage's type list (same + /// descriptor offset). @Test func structDescriptor() async throws { let pickedDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let metadata = try loadStructTestMetadata() - let imageDescriptor = try metadata.structDescriptor(in: machOImage) - let imageCtxDescriptor = try metadata.structDescriptor(in: imageContext) - let inProcessDescriptor = try metadata.structDescriptor() + let imageDescriptor = try metadata.structDescriptor(in: imageContext) + let inProcessDescriptor = try metadata.structDescriptor(in: inProcessContext) - // The two MachO-backed paths agree on the descriptor offset. + // The image-context path agrees with the picker on the descriptor + // offset. #expect(imageDescriptor.offset == pickedDescriptor.offset) - #expect(imageCtxDescriptor.offset == pickedDescriptor.offset) // The InProcess path returns the same descriptor by name. - #expect(try inProcessDescriptor.name() == "StructTest") + #expect(try inProcessDescriptor.name(in: inProcessContext) == "StructTest") } - /// `fieldOffsets(for:in:)` / `fieldOffsets(for:)` — for a concrete - /// struct with no stored fields (`Structs.StructTest`), this returns - /// the empty array. We verify cross-reader equality on the returned - /// `[UInt32]`. + /// `fieldOffsets(for:in:)` — for a concrete struct with no stored + /// fields (`Structs.StructTest`), this returns the empty array. We + /// verify cross-reader equality on the returned `[UInt32]`. @Test func fieldOffsets() async throws { let metadata = try loadStructTestMetadata() - let imageOffsets = try metadata.fieldOffsets(in: machOImage) - let imageCtxOffsets = try metadata.fieldOffsets(in: imageContext) - let inProcessOffsets = try metadata.fieldOffsets() + let imageOffsets = try metadata.fieldOffsets(in: imageContext) + let inProcessOffsets = try metadata.fieldOffsets(in: inProcessContext) - #expect(imageOffsets == imageCtxOffsets) #expect(imageOffsets == inProcessOffsets) // `Structs.StructTest` has no stored fields (only a computed `body`). #expect(imageOffsets.isEmpty) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift index 5ef58b3bc..d2f148405 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructMetadataTests.swift @@ -8,11 +8,11 @@ import MachOFixtureSupport /// Fixture-based Suite for `StructMetadata`. /// /// Materializing a `StructMetadata` requires invoking the metadata accessor -/// function on a *loaded* MachOImage. As a consequence, the cross-reader -/// equality block here is asymmetric: the metadata instance only originates -/// from `MachOImage`, but methods on it accept any `MachOContext` / -/// `InProcessContext` so we still validate the readers agree on the layout -/// values. +/// function on a *loaded* MachOImage. As a consequence, the reader +/// coverage here is asymmetric: the metadata instance only originates from +/// `MachOImage`, but methods on it accept any `MachOContext` / +/// `InProcessContext`, so the layout's descriptor is read through both the +/// image context and the in-process context. /// /// `init(layout:offset:)` is filtered as memberwise-synthesized. @Suite @@ -28,9 +28,9 @@ final class StructMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u /// treat as a fixture-build failure). private func loadStructTestMetadata() throws -> StructMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let wrapper = try response.value.resolve(in: machOImage) + let wrapper = try response.value.resolve(in: imageContext) return try required(wrapper.struct) } @@ -59,20 +59,19 @@ final class StructMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @u } @Test func layout() async throws { + let pickedDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let metadata = try loadStructTestMetadata() - // Cross-reader equality on the descriptor pointer and kind. The - // descriptor reachable via `descriptor(in:)` should be the same - // ValueTypeDescriptorWrapper kind across MachOImage/imageContext/ - // inProcess paths. - let imageDescriptor = try metadata.descriptor(in: machOImage) - let imageCtxDescriptor = try metadata.descriptor(in: imageContext) - let inProcessDescriptor = try metadata.descriptor() + // The descriptor reachable via `descriptor(in:)` should be the same + // ValueTypeDescriptorWrapper kind across the imageContext and + // inProcessContext paths. + let imageDescriptor = try metadata.descriptor(in: imageContext) + let inProcessDescriptor = try metadata.descriptor(in: inProcessContext) // ValueTypeDescriptorWrapper isn't Equatable, so compare via the - // concrete `struct` payload's offset. + // concrete `struct` payload's offset: through the image context it + // is the descriptor we picked from the MachOImage's type list. let imageStructOffset = try required(imageDescriptor.struct).offset - let imageCtxStructOffset = try required(imageCtxDescriptor.struct).offset - #expect(imageStructOffset == imageCtxStructOffset) + #expect(imageStructOffset == pickedDescriptor.offset) // InProcess offset is a pointer bit pattern — it must be non-zero. let inProcessStructOffset = try required(inProcessDescriptor.struct).offset #expect(inProcessStructOffset != 0) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift index 1011f069a..c953009b6 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/Struct/StructTests.swift @@ -16,10 +16,10 @@ import MachOFixtureSupport /// Presence + cardinality is the meaningful invariant: it fails if a reader /// disagrees about whether a field exists, which is what we care about. /// -/// `init(descriptor:in:)` (MachO + ReadingContext overloads) and -/// `init(descriptor:)` (in-process) are exercised by the same tests that -/// instantiate the `Struct`; we surface explicit `@Test func init...` entries -/// for coverage purposes. +/// `init(descriptor:in:)` (over the file and image contexts and the +/// in-process context) is exercised by the same tests that instantiate the +/// `Struct`; we surface explicit `@Test func init...` entries for coverage +/// purposes. @Suite final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked Sendable { static let testedTypeName = "Struct" @@ -28,15 +28,15 @@ final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked } /// Helper: instantiate the `Struct` wrapper for `Structs.StructTest` against - /// both the file and image readers using the MachO-direct initializer. - /// Used by every ivar test — the in-process and ReadingContext-based + /// both the file and image readers through their reading contexts. + /// Used by every ivar test — the file/image-context and in-process /// initializer paths are exercised separately by `initializerWithMachO()` /// / `initializerInProcess()`. private func loadStructTestStructs() throws -> (file: Struct, image: Struct) { let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let file = try Struct(descriptor: fileDescriptor, in: machOFile) - let image = try Struct(descriptor: imageDescriptor, in: machOImage) + let file = try Struct(descriptor: fileDescriptor, in: fileContext) + let image = try Struct(descriptor: imageDescriptor, in: imageContext) return (file: file, image: image) } @@ -46,25 +46,21 @@ final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - // Both file/image MachO-based initializers must succeed and produce a - // descriptor whose offset matches the baseline. - let fileStruct = try Struct(descriptor: fileDescriptor, in: machOFile) - let imageStruct = try Struct(descriptor: imageDescriptor, in: machOImage) - let fileCtxStruct = try Struct(descriptor: fileDescriptor, in: fileContext) - let imageCtxStruct = try Struct(descriptor: imageDescriptor, in: imageContext) + // Both file/image context-based initializers must succeed and produce + // a descriptor whose offset matches the baseline. + let fileStruct = try Struct(descriptor: fileDescriptor, in: fileContext) + let imageStruct = try Struct(descriptor: imageDescriptor, in: imageContext) #expect(fileStruct.descriptor.offset == StructBaseline.structTest.descriptorOffset) #expect(imageStruct.descriptor.offset == StructBaseline.structTest.descriptorOffset) - #expect(fileCtxStruct.descriptor.offset == StructBaseline.structTest.descriptorOffset) - #expect(imageCtxStruct.descriptor.offset == StructBaseline.structTest.descriptorOffset) } @Test("init(descriptor:)") func initializerInProcess() async throws { - // The InProcess `init(descriptor:)` requires a pointer-form descriptor - // resolved against MachOImage; reproduce that here. + // Initializing through `inProcessContext` requires a pointer-form + // descriptor resolved against MachOImage; reproduce that here. let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let pointerDescriptor = imageDescriptor.asPointerWrapper(in: machOImage) - let inProcessStruct = try Struct(descriptor: pointerDescriptor) + let inProcessStruct = try Struct(descriptor: pointerDescriptor, in: inProcessContext) // The in-process `descriptor.offset` is a pointer bit pattern, not a // file offset — we just assert a non-zero offset (i.e. resolution @@ -96,11 +92,11 @@ final class StructTests: MachOSwiftSectionFixtureTests, FixtureSuite, @unchecked // Generic struct (`GenericStructNonRequirement`): has a generic context. let genericFile = try Struct( descriptor: try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOFile), - in: machOFile + in: fileContext ) let genericImage = try Struct( descriptor: try BaselineFixturePicker.struct_GenericStructNonRequirement(in: machOImage), - in: machOImage + in: imageContext ) let genericPresence = try acrossAllReaders( file: { genericFile.genericContext != nil }, diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift index 4a28a84fe..acb7db040 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorProtocolTests.swift @@ -34,60 +34,40 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F @Test func fieldDescriptor() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let presence = try acrossAllReaders( - file: { (try? fileSubject.fieldDescriptor(in: machOFile)) != nil }, - image: { (try? imageSubject.fieldDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try? fileSubject.fieldDescriptor(in: fileContext)) != nil }, + image: { (try? imageSubject.fieldDescriptor(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorProtocolBaseline.structTest.hasFieldDescriptor) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try? imageSubject.fieldDescriptor(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorProtocolBaseline.structTest.hasFieldDescriptor) } @Test func genericContext() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let presence = try acrossAllReaders( - file: { (try fileSubject.genericContext(in: machOFile)) != nil }, - image: { (try imageSubject.genericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileSubject.genericContext(in: fileContext)) != nil }, + image: { (try imageSubject.genericContext(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorProtocolBaseline.structTest.hasGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try imageSubject.genericContext(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorProtocolBaseline.structTest.hasGenericContext) } @Test func typeGenericContext() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let presence = try acrossAllReaders( - file: { (try fileSubject.typeGenericContext(in: machOFile)) != nil }, - image: { (try imageSubject.typeGenericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try fileSubject.typeGenericContext(in: fileContext)) != nil }, + image: { (try imageSubject.typeGenericContext(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorProtocolBaseline.structTest.hasTypeGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try imageSubject.typeGenericContext(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorProtocolBaseline.structTest.hasTypeGenericContext) } - /// `metadataAccessorFunction(in:)` is a `MachOImage`-only path: the - /// MachO-based overload guards on `as? MachOImage` and returns nil - /// otherwise; the ReadingContext-based overload uses - /// `context.runtimePointer(at:)` which only resolves when the - /// underlying reader is image-backed. We exercise both overloads - /// against the image path and assert non-nil. + /// `metadataAccessorFunction(in:)` is a `MachOImage`-only path: it uses + /// `context.runtimePointer(at:)`, which only resolves when the + /// underlying reader is image-backed and answers nil for a file + /// context. We exercise it against the image context and assert + /// non-nil. @Test func metadataAccessorFunction() async throws { let (_, imageSubject) = try loadStructTestDescriptors() - let imagePresence = (try imageSubject.metadataAccessorFunction(in: machOImage)) != nil + let imagePresence = (try imageSubject.metadataAccessorFunction(in: imageContext)) != nil #expect(imagePresence) - - // ReadingContext-based overload exercised but not asserted on - // value: the underlying runtime-pointer lookup may return nil - // depending on the field's relative offset relative to the loaded - // image. The call itself completing without throwing is the - // contract we verify here. - _ = try imageSubject.metadataAccessorFunction(in: imageContext) } // MARK: - Derived booleans (StructTest witnesses; all read false) @@ -124,18 +104,18 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F /// C-typedef namespace, identically through every reader. @Test func typeImportInfo() async throws { let (fileSubject, imageSubject) = try loadStructTestDescriptors() - let swiftResult = try acrossAllReaders( - file: { try fileSubject.typeImportInfo(in: machOFile) }, - image: { try imageSubject.typeImportInfo(in: machOImage) } + let swiftResult = try acrossAllContexts( + file: { try fileSubject.typeImportInfo(in: fileContext) }, + image: { try imageSubject.typeImportInfo(in: imageContext) } ) #expect(swiftResult == nil) #expect(TypeContextDescriptorProtocolBaseline.structTest.typeImportInfoABIName == nil) let foreignFile = try BaselineFixturePicker.struct_ForeignDecimal(in: machOFile) let foreignImage = try BaselineFixturePicker.struct_ForeignDecimal(in: machOImage) - let foreignResult = try acrossAllReaders( - file: { try foreignFile.typeImportInfo(in: machOFile) }, - image: { try foreignImage.typeImportInfo(in: machOImage) } + let foreignResult = try acrossAllContexts( + file: { try foreignFile.typeImportInfo(in: fileContext) }, + image: { try foreignImage.typeImportInfo(in: imageContext) } ) let expected = TypeContextDescriptorProtocolBaseline.foreignDecimal #expect(foreignResult?.abiName == expected.typeImportInfoABIName) @@ -143,13 +123,6 @@ final class TypeContextDescriptorProtocolTests: MachOSwiftSectionFixtureTests, F #expect(foreignResult?.relatedEntityName == expected.typeImportInfoRelatedEntityName) #expect(foreignResult?.isCTypedef == true) #expect(foreignResult?.isRelatedEntity == false) - - // ReadingContext-based overload also exercised. (The pointer-based - // in-process overload needs a descriptor whose offset is a live - // address, which a `MachOImage`-read descriptor is not — same as - // `fieldDescriptor()` above.) - let imageContextResult = try foreignImage.typeImportInfo(in: imageContext) - #expect(imageContextResult == foreignResult) } @Test func hasCanonicalMetadataPrespecializationsOrSingletonMetadataPointer() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift index ad0832956..67fe231da 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorTests.swift @@ -64,30 +64,22 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu /// is exercised end-to-end via the Type/Enum Suites. @Test func enumDescriptor() async throws { let descriptors = try loadStructTestDescriptors() - let presence = try acrossAllReaders( - file: { (try descriptors.file.enumDescriptor(in: machOFile)) != nil }, - image: { (try descriptors.image.enumDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try descriptors.file.enumDescriptor(in: fileContext)) != nil }, + image: { (try descriptors.image.enumDescriptor(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorBaseline.structTest.hasEnumDescriptor) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try descriptors.image.enumDescriptor(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorBaseline.structTest.hasEnumDescriptor) } /// `structDescriptor(in:)` returns the underlying `StructDescriptor` /// for our struct fixture. Witnesses the true branch. @Test func structDescriptor() async throws { let descriptors = try loadStructTestDescriptors() - let presence = try acrossAllReaders( - file: { (try descriptors.file.structDescriptor(in: machOFile)) != nil }, - image: { (try descriptors.image.structDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try descriptors.file.structDescriptor(in: fileContext)) != nil }, + image: { (try descriptors.image.structDescriptor(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorBaseline.structTest.hasStructDescriptor) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try descriptors.image.structDescriptor(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorBaseline.structTest.hasStructDescriptor) } /// `classDescriptor(in:)` returns `nil` for our struct fixture (kind @@ -95,14 +87,10 @@ final class TypeContextDescriptorTests: MachOSwiftSectionFixtureTests, FixtureSu /// is exercised end-to-end via the Type/Class Suites. @Test func classDescriptor() async throws { let descriptors = try loadStructTestDescriptors() - let presence = try acrossAllReaders( - file: { (try descriptors.file.classDescriptor(in: machOFile)) != nil }, - image: { (try descriptors.image.classDescriptor(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try descriptors.file.classDescriptor(in: fileContext)) != nil }, + image: { (try descriptors.image.classDescriptor(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorBaseline.structTest.hasClassDescriptor) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try descriptors.image.classDescriptor(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorBaseline.structTest.hasClassDescriptor) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift index a27625fc2..920bddf6c 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextDescriptorWrapperTests.swift @@ -83,52 +83,40 @@ final class TypeContextDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fi @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.parent(in: machOFile)) != nil }, - image: { (try wrappers.image.parent(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.parent(in: fileContext)) != nil }, + image: { (try wrappers.image.parent(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorWrapperBaseline.structTest.hasParent) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.parent(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorWrapperBaseline.structTest.hasParent) } @Test func genericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.genericContext(in: machOFile)) != nil }, - image: { (try wrappers.image.genericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.genericContext(in: fileContext)) != nil }, + image: { (try wrappers.image.genericContext(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorWrapperBaseline.structTest.hasGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.genericContext(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorWrapperBaseline.structTest.hasGenericContext) } @Test func typeGenericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.typeGenericContext(in: machOFile)) != nil }, - image: { (try wrappers.image.typeGenericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.typeGenericContext(in: fileContext)) != nil }, + image: { (try wrappers.image.typeGenericContext(in: imageContext)) != nil } ) #expect(presence == TypeContextDescriptorWrapperBaseline.structTest.hasTypeGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.typeGenericContext(in: imageContext)) != nil - #expect(imageCtxPresence == TypeContextDescriptorWrapperBaseline.structTest.hasTypeGenericContext) } @Test func resolve() async throws { // Static `resolve(...)` overloads collapse to one MethodKey under - // PublicMemberScanner. Exercise the MachO-based overload that - // returns `Self`. + // PublicMemberScanner. Exercise the ReadingContext-based overload + // that returns `Self`. let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let fileWrapper: TypeContextDescriptorWrapper = try TypeContextDescriptorWrapper.resolve(from: fileDescriptor.offset, in: machOFile) - let imageWrapper: TypeContextDescriptorWrapper = try TypeContextDescriptorWrapper.resolve(from: imageDescriptor.offset, in: machOImage) + let fileWrapper: TypeContextDescriptorWrapper = try TypeContextDescriptorWrapper.resolve(at: fileDescriptor.offset, in: fileContext) + let imageWrapper: TypeContextDescriptorWrapper = try TypeContextDescriptorWrapper.resolve(at: imageDescriptor.offset, in: imageContext) #expect(fileWrapper.isStruct == true) #expect(imageWrapper.isStruct == true) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift index 4d85822d4..ce3868c73 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeContextWrapperTests.swift @@ -27,8 +27,8 @@ final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let fileWrapperDescriptor = TypeContextDescriptorWrapper.struct(fileDescriptor) let imageWrapperDescriptor = TypeContextDescriptorWrapper.struct(imageDescriptor) - let file = try TypeContextWrapper.forTypeContextDescriptorWrapper(fileWrapperDescriptor, in: machOFile) - let image = try TypeContextWrapper.forTypeContextDescriptorWrapper(imageWrapperDescriptor, in: machOImage) + let file = try TypeContextWrapper.forTypeContextDescriptorWrapper(fileWrapperDescriptor, in: fileContext) + let image = try TypeContextWrapper.forTypeContextDescriptorWrapper(imageWrapperDescriptor, in: imageContext) return (file: file, image: image) } @@ -59,9 +59,9 @@ final class TypeContextWrapperTests: MachOSwiftSectionFixtureTests, FixtureSuite } /// `forTypeContextDescriptorWrapper(_:in:)` overloads (MachO + InProcess - /// + ReadingContext) collapse to one MethodKey. Exercise the MachO-based - /// overloads via the helper above; the additional ReadingContext - /// variant is exercised here. + /// + ReadingContext) collapse to one MethodKey. The helper above + /// exercises the ReadingContext overload over the file and image + /// contexts; the image-context variant is exercised here as well. @Test func forTypeContextDescriptorWrapper() async throws { let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let imageWrapperDescriptor = TypeContextDescriptorWrapper.struct(imageDescriptor) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift index 59c15e838..1b7d6dc4d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeMetadataRecordTests.swift @@ -46,7 +46,7 @@ final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite numberOfElements: section.size / recordSize ) for record in records { - guard let resolved = try? record.contextDescriptor(in: machO) else { continue } + guard let resolved = try? record.contextDescriptor(in: machO.context) else { continue } if resolved.contextDescriptor.offset == targetOffset { return record } @@ -75,7 +75,7 @@ final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite numberOfElements: section.size / recordSize ) for record in records { - guard let resolved = try? record.contextDescriptor(in: machO) else { continue } + guard let resolved = try? record.contextDescriptor(in: machO.context) else { continue } if resolved.contextDescriptor.offset == targetOffset { return record } @@ -125,14 +125,10 @@ final class TypeMetadataRecordTests: MachOSwiftSectionFixtureTests, FixtureSuite let (fileRecord, imageRecord) = try loadStructTestRecords() // `contextDescriptor(in:)` resolves to the wrapped descriptor; cross- // reader equality on the resolved descriptor's offset. - let result = try acrossAllReaders( - file: { try required(fileRecord.contextDescriptor(in: machOFile)).contextDescriptor.offset }, - image: { try required(imageRecord.contextDescriptor(in: machOImage)).contextDescriptor.offset } + let result = try acrossAllContexts( + file: { try required(fileRecord.contextDescriptor(in: fileContext)).contextDescriptor.offset }, + image: { try required(imageRecord.contextDescriptor(in: imageContext)).contextDescriptor.offset } ) #expect(result == TypeMetadataRecordBaseline.structTestRecord.contextDescriptorOffset) - - // ReadingContext-based overload also exercised. - let imageCtxOffset = try required(imageRecord.contextDescriptor(in: imageContext)).contextDescriptor.offset - #expect(imageCtxOffset == TypeMetadataRecordBaseline.structTestRecord.contextDescriptorOffset) } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift index 4c2691b86..d0771e01b 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/TypeReferenceTests.swift @@ -54,7 +54,7 @@ final class TypeReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un numberOfElements: section.size / recordSize ) for record in records { - guard let resolved = try? record.contextDescriptor(in: machO) else { continue } + guard let resolved = try? record.contextDescriptor(in: machO.context) else { continue } if resolved.contextDescriptor.offset == target { let fieldOffset = record.offset(of: \.nominalTypeDescriptor) let relativeOffset = record.layout.nominalTypeDescriptor.relativeOffset @@ -85,7 +85,7 @@ final class TypeReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un numberOfElements: section.size / recordSize ) for record in records { - guard let resolved = try? record.contextDescriptor(in: machO) else { continue } + guard let resolved = try? record.contextDescriptor(in: machO.context) else { continue } if resolved.contextDescriptor.offset == target { let fieldOffset = record.offset(of: \.nominalTypeDescriptor) let relativeOffset = record.layout.nominalTypeDescriptor.relativeOffset @@ -121,8 +121,8 @@ final class TypeReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un let fileRef = TypeReference.forKind(fileData.kind, at: fileData.relativeOffset) let imageRef = TypeReference.forKind(imageData.kind, at: imageData.relativeOffset) - let fileResolved = try fileRef.resolve(at: fileData.recordFieldOffset, in: machOFile) - let imageResolved = try imageRef.resolve(at: imageData.recordFieldOffset, in: machOImage) + let fileResolved = try fileRef.resolve(at: fileData.recordFieldOffset, in: fileContext) + let imageResolved = try imageRef.resolve(at: imageData.recordFieldOffset, in: imageContext) // The resolved `directTypeDescriptor` arm should round-trip to the // same descriptor we picked from the section. @@ -136,13 +136,5 @@ final class TypeReferenceTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un } else { Issue.record("expected resolved .directTypeDescriptor") } - - // ReadingContext-based overload also exercised. - let imageCtxResolved = try imageRef.resolve(at: imageData.recordFieldOffset, in: imageContext) - if case .directTypeDescriptor(let wrapper) = imageCtxResolved { - #expect(wrapper?.contextDescriptor.offset == TypeReferenceBaseline.structTestRecord.resolvedDescriptorOffset) - } else { - Issue.record("expected resolved .directTypeDescriptor") - } } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift index a9c728d91..90da965b5 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataProtocolTests.swift @@ -25,32 +25,28 @@ final class ValueMetadataProtocolTests: MachOSwiftSectionFixtureTests, FixtureSu /// (a `StructMetadata` for `Structs.StructTest`). private func loadStructTestStructMetadata() throws -> StructMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - return try required(try response.value.resolve(in: machOImage).struct) + return try required(try response.value.resolve(in: imageContext).struct) } - /// `descriptor(in:)` and `descriptor()` — the descriptor recovered - /// from the metadata's value-type-descriptor pointer must match the - /// one we picked from the MachOImage's type list. + /// `descriptor(in:)` — the descriptor recovered from the metadata's + /// value-type-descriptor pointer must match the one we picked from the + /// MachOImage's type list. @Test func descriptor() async throws { let metadata = try loadStructTestStructMetadata() let pickedDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let imageDescriptor = try metadata.descriptor(in: machOImage) - let imageCtxDescriptor = try metadata.descriptor(in: imageContext) - let inProcessDescriptor = try metadata.descriptor() + let imageDescriptor = try metadata.descriptor(in: imageContext) + let inProcessDescriptor = try metadata.descriptor(in: inProcessContext) // ValueTypeDescriptorWrapper isn't trivially Equatable; compare via - // the `.struct` payload's offset. The image and image-context paths - // share the same MachO and therefore the same offsets. + // the `.struct` payload's offset. let imageStructOffset = try required(imageDescriptor.struct).offset - let imageCtxStructOffset = try required(imageCtxDescriptor.struct).offset #expect(imageStructOffset == pickedDescriptor.offset) - #expect(imageCtxStructOffset == pickedDescriptor.offset) // The InProcess path returns the same descriptor; assert by name. let inProcessStruct = try required(inProcessDescriptor.struct) - #expect(try inProcessStruct.name() == "StructTest") + #expect(try inProcessStruct.name(in: inProcessContext) == "StructTest") } } diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift index 46f685185..21829e18d 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueMetadataTests.swift @@ -27,9 +27,9 @@ final class ValueMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un /// `kind`/`descriptor` prefix with `ValueMetadata`. private func loadStructTestValueMetadata() throws -> ValueMetadata { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let structMetadata = try required(try response.value.resolve(in: machOImage).struct) + let structMetadata = try required(try response.value.resolve(in: imageContext).struct) // ValueMetadata shares the (kind, descriptor) prefix with StructMetadata. return try machOImage.readWrapperElement(offset: structMetadata.offset) } @@ -44,7 +44,7 @@ final class ValueMetadataTests: MachOSwiftSectionFixtureTests, FixtureSuite, @un let metadata = try loadStructTestValueMetadata() // The descriptor pointer in the layout should resolve to the same // `ValueTypeDescriptorWrapper` we obtained from the picker. - let descriptorWrapper = try metadata.layout.descriptor.resolve(in: machOImage) + let descriptorWrapper = try metadata.layout.descriptor.resolve(in: imageContext) let pickerDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) let resolvedStructOffset = try required(descriptorWrapper.struct).offset #expect(resolvedStructOffset == pickerDescriptor.offset) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift index 765d5d3f9..daa539e12 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/Type/ValueTypeDescriptorWrapperTests.swift @@ -79,28 +79,20 @@ final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixt @Test func parent() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.parent(in: machOFile)) != nil }, - image: { (try wrappers.image.parent(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.parent(in: fileContext)) != nil }, + image: { (try wrappers.image.parent(in: imageContext)) != nil } ) #expect(presence == ValueTypeDescriptorWrapperBaseline.structTest.hasParent) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.parent(in: imageContext)) != nil - #expect(imageCtxPresence == ValueTypeDescriptorWrapperBaseline.structTest.hasParent) } @Test func genericContext() async throws { let wrappers = try loadStructTestWrappers() - let presence = try acrossAllReaders( - file: { (try wrappers.file.genericContext(in: machOFile)) != nil }, - image: { (try wrappers.image.genericContext(in: machOImage)) != nil } + let presence = try acrossAllContexts( + file: { (try wrappers.file.genericContext(in: fileContext)) != nil }, + image: { (try wrappers.image.genericContext(in: imageContext)) != nil } ) #expect(presence == ValueTypeDescriptorWrapperBaseline.structTest.hasGenericContext) - - // ReadingContext-based overload also exercised. - let imageCtxPresence = (try wrappers.image.genericContext(in: imageContext)) != nil - #expect(imageCtxPresence == ValueTypeDescriptorWrapperBaseline.structTest.hasGenericContext) } @Test func resolve() async throws { @@ -108,8 +100,8 @@ final class ValueTypeDescriptorWrapperTests: MachOSwiftSectionFixtureTests, Fixt let fileDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOFile) let imageDescriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let fileWrapper: ValueTypeDescriptorWrapper = try ValueTypeDescriptorWrapper.resolve(from: fileDescriptor.offset, in: machOFile) - let imageWrapper: ValueTypeDescriptorWrapper = try ValueTypeDescriptorWrapper.resolve(from: imageDescriptor.offset, in: machOImage) + let fileWrapper: ValueTypeDescriptorWrapper = try ValueTypeDescriptorWrapper.resolve(at: fileDescriptor.offset, in: fileContext) + let imageWrapper: ValueTypeDescriptorWrapper = try ValueTypeDescriptorWrapper.resolve(at: imageDescriptor.offset, in: imageContext) #expect(fileWrapper.isStruct == true) #expect(imageWrapper.isStruct == true) diff --git a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift index 2085633dd..32808a119 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/ValueWitnessTable/ValueWitnessTableTests.swift @@ -27,10 +27,10 @@ final class ValueWitnessTableTests: MachOSwiftSectionFixtureTests, FixtureSuite, private func loadStructTestValueWitnesses() throws -> ValueWitnessTable { let descriptor = try BaselineFixturePicker.struct_StructTest(in: machOImage) - let accessor = try required(try descriptor.metadataAccessorFunction(in: machOImage)) + let accessor = try required(try descriptor.metadataAccessorFunction(in: imageContext)) let response = try accessor(request: .init()) - let structMetadata = try required(try response.value.resolve(in: machOImage).struct) - return try structMetadata.valueWitnesses(in: machOImage) + let structMetadata = try required(try response.value.resolve(in: imageContext).struct) + return try structMetadata.valueWitnesses(in: imageContext) } @Test func offset() async throws { diff --git a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ResilientWitnessBaseline.swift b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ResilientWitnessBaseline.swift index b3d57d575..b3a7ed189 100644 --- a/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ResilientWitnessBaseline.swift +++ b/Tests/MachOSwiftSectionTests/Fixtures/__Baseline__/ResilientWitnessBaseline.swift @@ -3,7 +3,7 @@ // Source fixture: SymbolTestsCore.framework enum ResilientWitnessBaseline { - static let registeredTestMethodNames: Set = ["implementationAddress", "implementationOffset", "layout", "offset", "requirement"] + static let registeredTestMethodNames: Set = ["implementationAddress", "implementationAddressString", "implementationOffset", "layout", "offset", "requirement"] struct Entry { let offset: Int diff --git a/Tests/MachOSwiftSectionTests/OptionalAccessorReadTests.swift b/Tests/MachOSwiftSectionTests/OptionalAccessorReadTests.swift new file mode 100644 index 000000000..2a22a33b1 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/OptionalAccessorReadTests.swift @@ -0,0 +1,59 @@ +import Foundation +import Testing +@testable import MachOSwiftSection + +/// An accessor that answers an Optional must read its field at the field's +/// own width. Asked for the Optional directly, the generic `readElement` +/// is instantiated at `Optional` and reads the Optional's in-memory +/// shape — the field plus one tag byte — so a non-zero byte after the field +/// turns the answer into `nil`. The runtime leaves padding like that +/// unwritten, which is what made the live-metadata assertions of +/// `FunctionTypeMetadataTests` pass alone and fail in a full run. +/// +/// Each record here is laid out by hand with `0x01` — the Optional's "no +/// value" tag — right after the field, so the outcome does not depend on +/// what an allocator happens to leave behind. +@Suite +struct OptionalAccessorReadTests { + /// Runs `body` over zeroed, pointer-aligned memory of `byteCount` bytes. + private func withRecord(byteCount: Int, _ body: (UnsafeMutableRawPointer) throws -> Outcome) rethrows -> Outcome { + let record = UnsafeMutableRawPointer.allocate(byteCount: byteCount, alignment: 8) + defer { record.deallocate() } + record.initializeMemory(as: UInt8.self, repeating: 0, count: byteCount) + return try body(record) + } + + /// `() throws(E) -> ()` without a global actor: the extended flag word + /// directly follows the three-word header, and the four bytes after it + /// are the padding before the thrown error type. + @Test func extendedFlagsIgnoreTheByteAfterTheFlagWord() throws { + let extendedFlags = try withRecord(byteCount: 40) { record in + record.storeBytes(of: 0x302, toByteOffset: 0, as: UInt64.self) // kind: function + record.storeBytes(of: 0x8000_0000, toByteOffset: 8, as: UInt64.self) // has extended flags, no parameters + record.storeBytes(of: 0x0000_0001, toByteOffset: 24, as: UInt32.self) // typed throws + record.storeBytes(of: 0x01, toByteOffset: 28, as: UInt8.self) + let metadata = try FunctionTypeMetadata.resolve(at: UnsafeRawPointer(record), in: InProcessContext.shared) + return try metadata.extendedFlags(in: InProcessContext.shared) + } + #expect(extendedFlags?.rawValue == 0x0000_0001) + } + + /// A multi-payload enum whose metadata keeps its payload size in the + /// word after the descriptor pointer — the slot the descriptor's + /// `payloadSizeOffset` names for a generic multi-payload enum. + @Test func payloadSizeIgnoresTheByteAfterTheSizeWord() throws { + let payloadSize = try withRecord(byteCount: 28) { descriptorRecord in + // Two payload cases; the payload size is two words into the metadata. + descriptorRecord.storeBytes(of: 2 << 24 | 2, toByteOffset: 20, as: UInt32.self) + let descriptor = try EnumDescriptor.resolve(at: UnsafeRawPointer(descriptorRecord), in: InProcessContext.shared) + return try withRecord(byteCount: 32) { metadataRecord in + metadataRecord.storeBytes(of: 0x201, toByteOffset: 0, as: UInt64.self) // kind: enum + metadataRecord.storeBytes(of: 0x10, toByteOffset: 16, as: UInt64.self) + metadataRecord.storeBytes(of: 0x01, toByteOffset: 24, as: UInt8.self) + let metadata = try EnumMetadata.resolve(at: UnsafeRawPointer(metadataRecord), in: InProcessContext.shared) + return try metadata.payloadSize(descriptor: descriptor, in: InProcessContext.shared) + } + } + #expect(payloadSize == 0x10) + } +} diff --git a/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift new file mode 100644 index 000000000..675398895 --- /dev/null +++ b/Tests/MachOSwiftSectionTests/ReadingContextRelocationTests.swift @@ -0,0 +1,101 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// 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 +/// stores a chained-fixup encoding, a bound slot names a symbol in another +/// image. The Mach-O reading forms always consulted the fixup tables; the +/// context forms — now the only implementation — must too. +@Suite +final class ReadingContextRelocationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + /// Every rebased pointer slot in the fixture, paired with the target + /// dyld writes there. + private func rebasedSlots() throws -> [(offset: Int, target: UInt64)] { + let chainedFixups = try #require(machOFile.dyldChainedFixups) + let startsInImage = try #require(chainedFixups.startsInImage) + var slots: [(offset: Int, target: UInt64)] = [] + for startsInSegment in chainedFixups.startsInSegments(of: startsInImage) { + for fixupPointer in chainedFixups.pointers(of: startsInSegment, in: machOFile) where fixupPointer.fixupInfo.rebase != nil { + guard let target = machOFile.resolveRebase(fileOffset: fixupPointer.offset) else { continue } + slots.append((fixupPointer.offset, target)) + } + } + return slots + } + + @Test func aPointerReadFromAFileIsTheRebaseTarget() throws { + let slots = try rebasedSlots() + try #require(!slots.isEmpty) + // The stored bytes of a chained fixup carry the chain link and format + // bits; if they happened to equal the target everywhere, this test + // could not tell a rebase-aware read from a raw one. + let someSlotStoresAnEncoding = try slots.contains { slot in + let storedBytes: UInt64 = try machOFile.readElement(offset: slot.offset) + return storedBytes != slot.target + } + try #require(someSlotStoresAnEncoding) + + let misreadSlots = try slots.filter { slot in + try Pointer.resolve(at: slot.offset, in: fileContext).address != slot.target + } + #expect(misreadSlots.isEmpty, "\(misreadSlots.count) of \(slots.count) rebased slots read as their stored bytes") + } + + /// The runtime reads a stored address whose only set bits are tag bits + /// as a null pointer, and so do the Mach-O and pointer forms; the + /// in-process context used to follow it and throw. + @Test func aStoredAddressOfOnlyTagBitsIsANullElement() throws { + let pointer = SymbolOrElementPointer.address(0x8000_0000_0000_0000) + let resolved = try pointer.resolve(in: inProcessContext) + guard case .element(let element) = resolved else { + Issue.record("resolved to \(resolved) instead of an element") + return + } + #expect(element == nil) + } +} + +/// Where the standalone iOS 26.5 simulator runtime keeps +/// `libswiftSynchronization`: the last runtime whose libraries are separate +/// files, so a cross-image reference is a bind rather than a rebase. +enum StandaloneSimulatorRuntimeLibraries { + static let synchronizationPath: String = { + let swiftUIPath = MachOFileName.iOS_26_5_Simulator_SwiftUI.rawValue + let runtimeRoot = swiftUIPath.dropLast("/System/Library/Frameworks/SwiftUI.framework/SwiftUI".count) + return runtimeRoot + "/usr/lib/swift/libswiftSynchronization.dylib" + }() + + static var hasSynchronization: Bool { + FileManager.default.fileExists(atPath: synchronizationPath) + } +} + +@Suite(.enabled(if: StandaloneSimulatorRuntimeLibraries.hasSynchronization)) +struct BoundTypeMetadataRecordTests { + /// `libswiftSynchronization` registers a type record for `libswiftCore`'s + /// `Swift.Optional`. In a standalone file that record is indirect and its + /// slot is a bind: there is no descriptor in this image to read, so the + /// record resolves to none instead of reading the bind's encoding as an + /// address. + @Test func anIndirectRecordOfAStandaloneLibraryResolvesToNoDescriptor() throws { + guard case .machO(let library) = try File.loadFromFile(url: URL(fileURLWithPath: StandaloneSimulatorRuntimeLibraries.synchronizationPath)) else { + Issue.record("expected a thin dylib at \(StandaloneSimulatorRuntimeLibraries.synchronizationPath)") + return + } + let section = try library.section(for: MachOSwiftSectionName.__swift5_types) + let records: [TypeMetadataRecord] = try library.readWrapperElements( + offset: section.offset, + numberOfElements: section.size / TypeMetadataRecord.layoutSize + ) + let indirectRecords = records.filter { $0.typeKind == .indirectTypeDescriptor } + try #require(!indirectRecords.isEmpty) + for record in indirectRecords { + #expect(try record.contextDescriptor(in: library.context) == nil) + } + } +} diff --git a/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift b/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift index a10d0711e..a3f0537ae 100644 --- a/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift +++ b/Tests/MachOSwiftSectionTests/SpecializedDumperFieldTypeTests.swift @@ -42,7 +42,7 @@ struct SpecializedDumperFieldTypeTests { private func structDescriptor(named nameContains: String) throws -> StructDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.struct?.name(in: machO).contains(nameContains) == true + try $0.struct?.name(in: machO.context).contains(nameContains) == true }?.struct, "expected a struct descriptor whose name contains \"\(nameContains)\"" ) @@ -51,7 +51,7 @@ struct SpecializedDumperFieldTypeTests { private func enumDescriptor(named nameContains: String) throws -> EnumDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.enum?.name(in: machO).contains(nameContains) == true + try $0.enum?.name(in: machO.context).contains(nameContains) == true }?.enum, "expected an enum descriptor whose name contains \"\(nameContains)\"" ) @@ -60,7 +60,7 @@ struct SpecializedDumperFieldTypeTests { private func classDescriptor(named nameContains: String) throws -> ClassDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.class?.name(in: machO).contains(nameContains) == true + try $0.class?.name(in: machO.context).contains(nameContains) == true }?.class, "expected a class descriptor whose name contains \"\(nameContains)\"" ) @@ -73,7 +73,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.SingleParameterBox.self let descriptor = try structDescriptor(named: "SingleParameterBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.SingleParameterBox.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -92,7 +92,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.SingleParameterBox.self let descriptor = try structDescriptor(named: "SingleParameterBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let intMetadata = try StructMetadata.createInProcess(Fixtures.SingleParameterBox.self) let intContext = DumperMetadataContext(metadata: intMetadata, readingContext: InProcessContext.shared) @@ -118,7 +118,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.GenericArrayWrapper.self let descriptor = try structDescriptor(named: "GenericArrayWrapper") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.GenericArrayWrapper.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -139,7 +139,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.GenericResultEnum.self let descriptor = try enumDescriptor(named: "GenericResultEnum") - let enumValue = try Enum(descriptor: descriptor, in: machO) + let enumValue = try Enum(descriptor: descriptor, in: machO.context) let specializedMetadata = try EnumMetadata.createInProcess(Fixtures.GenericResultEnum.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -159,7 +159,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.GenericContainerClass.self let descriptor = try classDescriptor(named: "GenericContainerClass") - let classValue = try Class(descriptor: descriptor, in: machO) + let classValue = try Class(descriptor: descriptor, in: machO.context) let specializedMetadata = try ClassMetadataObjCInterop.createInProcess(Fixtures.GenericContainerClass.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -177,7 +177,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.SingleParameterBox.self let descriptor = try structDescriptor(named: "SingleParameterBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.SingleParameterBox.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -198,7 +198,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.SingleParameterBox.self let descriptor = try structDescriptor(named: "SingleParameterBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let intMetadata = try StructMetadata.createInProcess(Fixtures.SingleParameterBox.self) let intDumper = StructDumper( @@ -229,7 +229,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.GenericContainerClass.self let descriptor = try classDescriptor(named: "GenericContainerClass") - let classValue = try Class(descriptor: descriptor, in: machO) + let classValue = try Class(descriptor: descriptor, in: machO.context) let specializedMetadata = try ClassMetadataObjCInterop.createInProcess(Fixtures.GenericContainerClass.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -249,7 +249,7 @@ struct SpecializedDumperFieldTypeTests { @Test("specialized private struct declaration keeps its module") func specializedPrivateStructDeclarationKeepsItsModule() async throws { let descriptor = try structDescriptor(named: "RuntimeNamedDumpPrivateBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(RuntimeNamedDumpPrivateBox.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -266,7 +266,7 @@ struct SpecializedDumperFieldTypeTests { // fall back to the existing unbound path — the bound substitution // is gated on the in-process specialized metadata being present. let descriptor = try structDescriptor(named: "SingleParameterBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let dumper = StructDumper(structValue, using: configuration, in: machO) let renderedDeclaration = try await dumper.declaration.string @@ -284,7 +284,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.NestedStructHostingStruct.self let descriptor = try structDescriptor(named: "NestedStructHostingStruct") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.NestedStructHostingStruct.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -317,7 +317,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.NestedStructHostingStruct.self let descriptor = try structDescriptor(named: "NestedStructHostingStruct") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.NestedStructHostingStruct.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -342,7 +342,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.OptionalGenericFieldStruct>.self let descriptor = try structDescriptor(named: "OptionalGenericFieldStruct") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess( Fixtures.OptionalGenericFieldStruct>.self ) @@ -377,7 +377,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.SingleParameterBox.self let descriptor = try structDescriptor(named: "SingleParameterBox") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.SingleParameterBox.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) @@ -429,7 +429,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.OptionalGenericFieldStruct>.self let descriptor = try structDescriptor(named: "OptionalGenericFieldStruct") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess( Fixtures.OptionalGenericFieldStruct>.self ) @@ -467,7 +467,7 @@ struct SpecializedDumperFieldTypeTests { _ = Fixtures.StructHostingClassField.self let descriptor = try structDescriptor(named: "StructHostingClassField") - let structValue = try Struct(descriptor: descriptor, in: machO) + let structValue = try Struct(descriptor: descriptor, in: machO.context) let specializedMetadata = try StructMetadata.createInProcess(Fixtures.StructHostingClassField.self) let metadataContext = DumperMetadataContext(metadata: specializedMetadata, readingContext: InProcessContext.shared) diff --git a/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift b/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift index 9810110b1..1a0d2bb76 100644 --- a/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift +++ b/Tests/MachOSwiftSectionTests/SpecializedMangledNameResolutionTests.swift @@ -29,7 +29,7 @@ struct SpecializedMangledNameResolutionTests { private func structDescriptor(named nameContains: String) throws -> StructDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.struct?.name(in: machO).contains(nameContains) == true + try $0.struct?.name(in: machO.context).contains(nameContains) == true }?.struct, "expected a struct descriptor whose name contains \"\(nameContains)\"" ) @@ -39,7 +39,7 @@ struct SpecializedMangledNameResolutionTests { private func enumDescriptor(named nameContains: String) throws -> EnumDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.enum?.name(in: machO).contains(nameContains) == true + try $0.enum?.name(in: machO.context).contains(nameContains) == true }?.enum, "expected an enum descriptor whose name contains \"\(nameContains)\"" ) @@ -49,7 +49,7 @@ struct SpecializedMangledNameResolutionTests { private func classDescriptor(named nameContains: String) throws -> ClassDescriptor { try #require( try machO.swift.typeContextDescriptors.first { - try $0.class?.name(in: machO).contains(nameContains) == true + try $0.class?.name(in: machO.context).contains(nameContains) == true }?.class, "expected a class descriptor whose name contains \"\(nameContains)\"" ) @@ -63,13 +63,13 @@ struct SpecializedMangledNameResolutionTests { of descriptor: some TypeContextDescriptorProtocol, atFieldIndex fieldIndex: Int ) throws -> MangledName { - let fieldDescriptor = try descriptor.fieldDescriptor(in: machO) - let records = try fieldDescriptor.records(in: machO) + let fieldDescriptor = try descriptor.fieldDescriptor(in: machO.context) + let records = try fieldDescriptor.records(in: machO.context) try #require( fieldIndex < records.count, "expected at least \(fieldIndex + 1) field record(s); fixture had \(records.count)" ) - return try records[fieldIndex].mangledTypeName(in: machO) + return try records[fieldIndex].mangledTypeName(in: machO.context) } // MARK: - Single generic parameter diff --git a/Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift b/Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift new file mode 100644 index 000000000..d3b6805e6 --- /dev/null +++ b/Tests/MachOTestingSupportTests/DeclaredNameForTestingTests.swift @@ -0,0 +1,40 @@ +import Testing +import Demangling +import SwiftDeclaration +@testable import MachOTestingSupport + +/// `declaredNameForTesting` is what tests look definitions up by. It exists +/// because `currentName` misnames a function-local type — the case this suite +/// pins first, with the exact shape that made a specialization test pick a +/// local `MemberKey` enum as its `Int` (ReviewAdjudications A52). +@Suite +struct DeclaredNameForTestingTests { + private func typeName(mangled: String, kind: TypeKind) throws -> TypeName { + let global = try demangleAsNode(mangled) + let typeNode = try #require(global.first(of: .type), "\(mangled) demangles to a type") + return TypeName(node: NodeReference(interning: typeNode), kind: kind) + } + + @Test func aFunctionLocalTypeAnswersItsOwnName() throws { + // `MemberKey #1 in Main.foo() -> Swift.Int` + let local = try typeName(mangled: "$s4Main3fooSiyF9MemberKeyL_OD", kind: .enum) + + #expect(local.declaredNameForTesting == "MemberKey") + // The display name reads the tail of the enclosing function's + // signature — the reason tests must not look definitions up by it. + #expect(local.currentName == "Int") + } + + @Test func aNestedTypeAnswersItsOwnName() throws { + let nested = try typeName(mangled: "$s4Main5OuterV5InnerVD", kind: .struct) + + #expect(nested.declaredNameForTesting == "Inner") + } + + @Test func aPrivateTypeAnswersItsNameWithoutTheDiscriminator() throws { + // `Main.(Outer in _0123456789ABCDEF0123456789ABCDEF)` + let privateType = try typeName(mangled: "$s4Main5Outer33_0123456789ABCDEF0123456789ABCDEFLLVD", kind: .struct) + + #expect(privateType.declaredNameForTesting == "Outer") + } +} diff --git a/Tests/MachOTestingSupportTests/DyldSharedCachePathTests.swift b/Tests/MachOTestingSupportTests/DyldSharedCachePathTests.swift new file mode 100644 index 000000000..96f943961 --- /dev/null +++ b/Tests/MachOTestingSupportTests/DyldSharedCachePathTests.swift @@ -0,0 +1,35 @@ +import Testing +import MachOFixtureSupport + +/// `DyldSharedCachePath` builds an archived cache's path and label from its +/// version. The named macOS caches are built that way too, and only the +/// integration dumps — which nothing runs automatically — open them, so a +/// path or a label that came out wrong would go unnoticed until someone ran +/// one by hand. +@Suite +struct DyldSharedCachePathTests { + @Test("A version names the cache file in that version's directory on the volume, and labels it") + func versionSpellsTheArchivedPathAndLabel() { + let internalBuild = DyldSharedCachePath.macOS("14.0(Internal)") + #expect(internalBuild.rawValue == "/Volumes/DyldSharedCaches/macOS/14.0(Internal)/dyld_shared_cache_arm64e") + #expect(internalBuild.versionLabel == "14.0(Internal)") + + let device = DyldSharedCachePath.iOS("27.0") + #expect(device.rawValue == "/Volumes/DyldSharedCaches/iOS/27.0/dyld_shared_cache_arm64e") + #expect(device.versionLabel == "27.0") + } + + /// The paths these named caches spelled out before they were built from a + /// version, and the labels the evolution dumps used to write out for + /// them by hand. + @Test("The named macOS caches keep their paths and labels", arguments: [ + (DyldSharedCachePath.macOS_15_5, "/Volumes/DyldSharedCaches/macOS/15.5/dyld_shared_cache_arm64e", "15.5"), + (.macOS_26_5_1, "/Volumes/DyldSharedCaches/macOS/26.5.1/dyld_shared_cache_arm64e", "26.5.1"), + (.macOS_26_5_2, "/Volumes/DyldSharedCaches/macOS/26.5.2/dyld_shared_cache_arm64e", "26.5.2"), + (.macOS_27_0, "/Volumes/DyldSharedCaches/macOS/27.0/dyld_shared_cache_arm64e", "27.0"), + ]) + func namedCacheKeepsItsPathAndLabel(cachePath: DyldSharedCachePath, expectedPath: String, expectedVersionLabel: String) { + #expect(cachePath.rawValue == expectedPath) + #expect(cachePath.versionLabel == expectedVersionLabel) + } +} diff --git a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift index c57e84bae..36521652f 100644 --- a/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/FieldLayoutRendererReaderSpecializationTests.swift @@ -27,7 +27,7 @@ import MachOFixtureSupport final class FieldLayoutRendererReaderSpecializationTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { private func qualifiedName(of descriptorWrapper: TypeContextDescriptorWrapper, in machO: some MachOSwiftSectionRepresentableWithCache) -> String? { - guard let node = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machO) else { return nil } + guard let node = try? SymbolicDemangler.demangleContext(for: descriptorWrapper.asContextDescriptorWrapper, in: machO.context) else { return nil } return NodeTypeNaming.nominalQualifiedName(of: node) } @@ -110,9 +110,9 @@ final class FieldLayoutRendererReaderSpecializationTests: MachOSwiftSectionFixtu let renderer = FieldLayoutRenderer(type: type, metadata: nil, machO: machOFile, configuration: configuration, autoResolveAccessorMetadata: false) let offsets = renderer.fieldOffsets ?? [] guard !offsets.isEmpty else { continue } - let records = try structType.descriptor.fieldDescriptor(in: machOFile).records(in: machOFile) + let records = try structType.descriptor.fieldDescriptor(in: fileContext).records(in: fileContext) guard let firstRecord = records.first else { continue } - let mangledTypeName = try firstRecord.mangledTypeName(in: machOFile) + let mangledTypeName = try firstRecord.mangledTypeName(in: fileContext) let comments = try await renderer.storedFieldComments(forFieldAtIndex: 0, mangledTypeName: mangledTypeName, fieldOffsets: offsets).string #expect(comments.contains("Field offset"), "expected a Field offset comment, got: \(comments)") diff --git a/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift b/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift index 4111c5026..2d557bf8c 100644 --- a/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/InProcessAccessorFunctionResolutionTests.swift @@ -34,8 +34,8 @@ struct InProcessAccessorFunctionResolutionTests { var outcome = Outcome() for associatedType in try image.swift.associatedTypes { for record in associatedType.records { - let witnessMangledName = try record.substitutedTypeName(in: image) - guard let node = try? SymbolicDemangler.demangleType(for: witnessMangledName, in: image), + let witnessMangledName = try record.substitutedTypeName(in: image.context) + guard let node = try? SymbolicDemangler.demangleType(for: witnessMangledName, in: image.context), node.contains(Node.Kind.opaqueType), let offlineResolved = try? node.resolveOpaqueType(in: image), offlineResolved.contains(Node.Kind.accessorFunctionReference) @@ -86,8 +86,8 @@ struct InProcessAccessorFunctionResolutionTests { var comparedWitnesses = 0 for associatedType in try image.swift.associatedTypes { for record in associatedType.records { - let witnessMangledName = try record.substitutedTypeName(in: image) - guard let node = try? SymbolicDemangler.demangleType(for: witnessMangledName, in: image), + let witnessMangledName = try record.substitutedTypeName(in: image.context) + guard let node = try? SymbolicDemangler.demangleType(for: witnessMangledName, in: image.context), node.contains(Node.Kind.opaqueType), let offlineResolved = try? node.resolveOpaqueType(in: image), offlineResolved.contains(Node.Kind.accessorFunctionReference) diff --git a/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift b/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift index cda71d089..51f928567 100644 --- a/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/MultiPayloadEnumDescriptorCacheTests.swift @@ -32,8 +32,8 @@ final class MultiPayloadEnumDescriptorCacheTests: MachOSwiftSectionFixtureTests, try #require(!multiPayloadEnumDescriptors.isEmpty, "fixture must carry multi-payload enum descriptors for this test to be meaningful") for multiPayloadEnumDescriptor in multiPayloadEnumDescriptors { - let mangledTypeName = try multiPayloadEnumDescriptor.mangledTypeName(in: machOImage) - let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machOImage) + let mangledTypeName = try multiPayloadEnumDescriptor.mangledTypeName(in: imageContext) + let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: imageContext) let cached = MultiPayloadEnumDescriptorCache.shared.multiPayloadEnumDescriptor(for: node, in: machOImage) #expect(cached != nil, "cache missed a descriptor the build sweep should have indexed") } @@ -60,8 +60,8 @@ final class MultiPayloadEnumDescriptorCacheTests: MachOSwiftSectionFixtureTests, let indexedDescriptorByNode = MultiPayloadEnumDescriptorCache.indexDescriptors(splicedDescriptors, in: machOFile) for realDescriptor in realDescriptors { - let mangledTypeName = try realDescriptor.mangledTypeName(in: machOFile) - let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile) + let mangledTypeName = try realDescriptor.mangledTypeName(in: fileContext) + let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: fileContext) #expect( indexedDescriptorByNode[node] != nil, "a descriptor after the unreadable one was dropped — the catch is truncating the map instead of skipping one entry" @@ -124,7 +124,7 @@ final class MultiPayloadEnumDescriptorCacheTests: MachOSwiftSectionFixtureTests, let noncopyableEnumType = try #require(try machOImage.swift.types.first { type in guard case .enum(let enumType) = type else { return false } - return try enumType.descriptor.name(in: machOImage) == "NoncopyablePayloadEnumTest" + return try enumType.descriptor.name(in: imageContext) == "NoncopyablePayloadEnumTest" }, "fixture must contain AccessorFunctionReferences.NoncopyablePayloadEnumTest") let renderer = FieldLayoutRenderer(type: noncopyableEnumType, metadata: nil, machO: machOImage, configuration: configuration) let enumLayout = try #require(await renderer.enumLayout) diff --git a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift index b3e970bcf..7bfc6e12e 100644 --- a/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/OpaqueTypeOrdinalTests.swift @@ -148,8 +148,8 @@ struct OpaqueTypeOrdinalTests { @MainActor @Test func underlyingTypeArgumentsAreOrderedTypesFirstThenConformances() async throws { let machOFile = try loadFixtureMachOFile() - let descriptor = try OpaqueTypeDescriptor.resolve(from: opaqueTypeDescriptorOffset(in: machOFile), in: machOFile) - let opaqueType = try OpaqueType(descriptor: descriptor, in: machOFile) + let descriptor = try OpaqueTypeDescriptor.resolve(at: opaqueTypeDescriptorOffset(in: machOFile), in: machOFile.context) + let opaqueType = try OpaqueType(descriptor: descriptor, in: machOFile.context) #expect( descriptor.numUnderlyingTypeArguments == 4, @@ -158,7 +158,7 @@ struct OpaqueTypeOrdinalTests { var rendered: [String] = [] for mangledName in opaqueType.underlyingTypeArgumentMangledNames { - let node = try SymbolicDemangler.demangleType(for: mangledName, in: machOFile) + let node = try SymbolicDemangler.demangleType(for: mangledName, in: machOFile.context) rendered.append(await node.print(using: DemangleOptions.default)) } diff --git a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift index 2bb74edff..901322e83 100644 --- a/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RecursiveNestedFieldOffsetExpansionTests.swift @@ -88,12 +88,12 @@ final class RecursiveNestedFieldOffsetExpansionTests: MachOSwiftSectionFixtureTe return [] } - let records = try structType.descriptor.fieldDescriptor(in: machOImage).records(in: machOImage) + let records = try structType.descriptor.fieldDescriptor(in: imageContext).records(in: imageContext) let fieldIndex = try #require( - try records.firstIndex { (try? $0.fieldName(in: machOImage)) == targetFieldName }, + try records.firstIndex { (try? $0.fieldName(in: imageContext)) == targetFieldName }, "\(structTypeName) has no stored property named \(targetFieldName)" ) - let mangledTypeName = try records[fieldIndex].mangledTypeName(in: machOImage) + let mangledTypeName = try records[fieldIndex].mangledTypeName(in: imageContext) let renderer = FieldLayoutRenderer(type: type, metadata: nil, machO: machOImage, configuration: configuration) let rendered = try await renderer.storedFieldComments( @@ -107,7 +107,7 @@ final class RecursiveNestedFieldOffsetExpansionTests: MachOSwiftSectionFixtureTe private func findFixtureStruct(named typeName: String) throws -> TypeContextWrapper? { for type in try machOImage.swift.types { guard case .struct(let structType) = type, !structType.descriptor.isGeneric else { continue } - guard let node = try? SymbolicDemangler.demangleContext(for: .type(.struct(structType.descriptor)), in: machOImage) else { continue } + guard let node = try? SymbolicDemangler.demangleContext(for: .type(.struct(structType.descriptor)), in: imageContext) else { continue } if node.print(using: .default).hasSuffix(typeName) { return type } diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift index 2249f2e66..921fda12e 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeEnumLayoutRenderingTests.swift @@ -24,7 +24,7 @@ final class RuntimeEnumLayoutRenderingTests: MachOSwiftSectionFixtureTests, @unc private func findFixtureEnum(named typeName: String) throws -> TypeContextWrapper? { for type in try machOImage.swift.types { guard case .enum(let enumType) = type, !enumType.descriptor.isGeneric else { continue } - guard let node = try? SymbolicDemangler.demangleContext(for: .type(.enum(enumType.descriptor)), in: machOImage) else { continue } + guard let node = try? SymbolicDemangler.demangleContext(for: .type(.enum(enumType.descriptor)), in: imageContext) else { continue } if node.print(using: .default).contains(typeName) { return type } @@ -68,10 +68,10 @@ final class RuntimeEnumLayoutRenderingTests: MachOSwiftSectionFixtureTests, @unc let strategyComment = await renderer.enumPrefixComments(enumLayout: enumLayout).string #expect(strategyComment.contains("Single Payload"), "got: \(strategyComment)") - let records = try #require(try? type.contextDescriptorWrapper.typeContextDescriptor?.fieldDescriptor(in: machOImage).records(in: machOImage)) + let records = try #require(try? type.contextDescriptorWrapper.typeContextDescriptor?.fieldDescriptor(in: imageContext).records(in: imageContext)) let firstCaseComment = try await renderer.enumCaseComments( forCaseAtIndex: 1, - mangledTypeName: records[1].mangledTypeName(in: machOImage), + mangledTypeName: records[1].mangledTypeName(in: imageContext), enumLayout: enumLayout ).string #expect(firstCaseComment.contains("`first`"), "got: \(firstCaseComment)") @@ -79,7 +79,7 @@ final class RuntimeEnumLayoutRenderingTests: MachOSwiftSectionFixtureTests, @unc let secondCaseComment = try await renderer.enumCaseComments( forCaseAtIndex: 2, - mangledTypeName: records[2].mangledTypeName(in: machOImage), + mangledTypeName: records[2].mangledTypeName(in: imageContext), enumLayout: enumLayout ).string #expect(secondCaseComment.contains("bytes[0x0..<0x8] = 0x1"), "got: \(secondCaseComment)") diff --git a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift index 0f3da32cd..94c59408e 100644 --- a/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift +++ b/Tests/SwiftDeclarationRenderingTests/RuntimeTypeNamePrivateDiscriminatorTests.swift @@ -32,7 +32,7 @@ struct RuntimeTypeNamePrivateDiscriminatorTests { try #require(dlopen(Self.appKitPath, RTLD_LAZY) != nil, "AppKit could not be loaded into the test process") let machOImage = try #require(MachOImage(name: "AppKit")) let classDescriptor = try #require(try Self.classDescriptor(named: Self.privateClassName, in: machOImage)) - let descriptorBuiltNode = try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOImage) + let descriptorBuiltNode = try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOImage.context) let descriptorBuiltDiscriminator = try #require(Self.privateDiscriminator(ofNominal: descriptorBuiltNode)) let objcRuntimeName = try #require(Self.objcRuntimeName(in: machOImage)) let privateClass: AnyClass = try #require(NSClassFromString(objcRuntimeName)) @@ -48,7 +48,7 @@ struct RuntimeTypeNamePrivateDiscriminatorTests { private static func classDescriptor(named name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { for typeContextDescriptor in try machO.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor else { continue } - if try classDescriptor.name(in: machO) == name { + if try classDescriptor.name(in: machO.context) == name { return classDescriptor } } diff --git a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift index a0e15d7d9..f1e1ce9e5 100644 --- a/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift +++ b/Tests/SwiftDumpTests/CustomObjCClassNameDumpTests.swift @@ -20,8 +20,8 @@ struct CustomObjCClassNameDumpTests { ObjCAncestorResolverStore.shared.register(ObjCAncestorResolver(root: machOFile, searchPaths: try RenamedObjCClassFixture.dependencySearchPaths()), for: machOFile) defer { ObjCAncestorResolverStore.shared.remove(for: machOFile) } for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { - guard case .class(let classDescriptor) = typeContextDescriptor, try classDescriptor.name(in: machOFile) == name else { continue } - let classType = try Class(descriptor: classDescriptor, in: machOFile) + guard case .class(let classDescriptor) = typeContextDescriptor, try classDescriptor.name(in: machOFile.context) == name else { continue } + let classType = try Class(descriptor: classDescriptor, in: machOFile.context) return try await classType.dump(using: .demangleOptions(.test), in: machOFile).string } Issue.record("fixture is missing the class \(name)") diff --git a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift index 8a58d3567..9640b45c8 100644 --- a/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/ExportStatusDumpAnnotationTests.swift @@ -40,7 +40,7 @@ final class ExportStatusDumpAnnotationTests: MachOFileTests, SnapshotDumpableTes for typeContextDescriptor in typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor else { continue } guard (try? rootNamespace(of: typeContextDescriptor, in: unsafeMachOFile)) == namespace else { continue } - let classType = try Class(descriptor: classDescriptor, in: unsafeMachOFile) + let classType = try Class(descriptor: classDescriptor, in: unsafeMachOFile.context) results.append(try await classType.dump(using: configuration, in: unsafeMachOFile).string) } return results.joined(separator: "\n") diff --git a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift index 2f0acf5cc..0a44e5655 100644 --- a/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCImplementationClassDumpTests.swift @@ -27,13 +27,19 @@ struct ObjCImplementationClassDumpTests { @Test func fullFixtureDumpsBothSides() async throws { let output = try await dump(.full) #expect(output.contains("@objc @implementation extension Widget {")) - #expect(output.contains("// ObjC class Widget: NSObject, class_ro_t flags 0x184, instanceStart 8, instanceSize 40")) - #expect(output.contains("// Evidence: metadata accessor _$sSo6WidgetCMa, 3 field-offset globals, Swift symbols at 9 method implementations")) + #expect(output.contains("// ObjC class Widget: NSObject, class_ro_t flags 0x184, instanceStart 8, instanceSize 64")) + #expect(output.contains("// Evidence: metadata accessor _$sSo6WidgetCMa, 5 field-offset globals, Swift symbols at 9 method implementations")) #expect(output.contains("// Implemented in Swift module \(ObjCImplementationFixture.moduleName)")) #expect(output.contains("/* Stored properties (ObjC ivars) */")) #expect(output.contains("var title: Swift.String // offset 0x8, size 16, alignment 8, encoding \"?\", ")) // `.test` demangle options print sugared types. #expect(output.contains("var swiftOnlyCache: [Swift.Int] // offset 0x20, size 8, alignment 8, encoding \"\", ")) + // Field-offset symbols naming the variable through a `privateDeclName`: + // a `private` property, and a `lazy var`'s storage, which prints under + // the property's name with its storage type, as a Swift type's own + // lazy field does. + #expect(output.contains("var hiddenTally: Swift.Int // offset 0x28, size 8, alignment 8, encoding \"\", ")) + #expect(output.contains("lazy var summary: Swift.String? // offset 0x30, size 16, alignment 8, encoding \"\", ")) #expect(output.contains("not exposed to ObjC")) #expect(output.contains("/* ObjC instance methods */")) #expect(output.contains("-[Widget initWithTitle:] // types \"@24@0:8@16\", imp 0x")) @@ -58,8 +64,8 @@ struct ObjCImplementationClassDumpTests { @Test func fullyStrippedDumpIsHonestAboutWhatIsMissing() async throws { let output = try await dump(.strippedEverything) - #expect(output.hasPrefix("@objc @implementation /* inferred from ObjC class data: 2 ivars carry Swift-style type encodings */ extension Widget {")) - #expect(output.contains("// Evidence: inferred from ObjC class data: 2 ivars carry Swift-style type encodings")) + #expect(output.hasPrefix("@objc @implementation /* inferred from ObjC class data: 4 ivars carry Swift-style type encodings */ extension Widget {")) + #expect(output.contains("// Evidence: inferred from ObjC class data: 4 ivars carry Swift-style type encodings")) #expect(output.contains("title // offset 0x8, size 16, alignment 8, encoding \"?\", Swift type not recoverable")) // IMPs with no symbol print as addresses only. #expect(output.contains("-[Widget refresh] // types \"v16@0:8\", imp 0x")) diff --git a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift index 0013ee1ca..2c608f77d 100644 --- a/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift +++ b/Tests/SwiftDumpTests/ObjCMemberDumpTests.swift @@ -23,7 +23,7 @@ struct ObjCMemberDumpTests { 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) == name else { continue } + guard try classDescriptor.name(in: machOFile.context) == name else { continue } return classDescriptor } Issue.record("fixture is missing the class \(name)") @@ -41,7 +41,7 @@ struct ObjCMemberDumpTests { @Test func swiftClassDumpNamesTheAncestorChainAndTheOverriddenSelectors() async throws { let machOFile = try ObjCImplementationFixture.machOFile(.full) try await withFixtureWorld(for: machOFile) { - let classType = try Class(descriptor: try classDescriptor(named: "SwiftDerivedWidget", in: machOFile), in: machOFile) + let classType = try Class(descriptor: try classDescriptor(named: "SwiftDerivedWidget", in: machOFile), in: machOFile.context) let output = try await classType.dump(using: .demangleOptions(.test), in: machOFile).string let moduleName = ObjCImplementationFixture.moduleName // The chain — on its own line right under the header — runs through @@ -73,7 +73,7 @@ struct ObjCMemberDumpTests { @Test func swiftAncestorsPrintByTheirQualifiedName() async throws { let machOFile = try ObjCImplementationFixture.machOFile(.full) - let classType = try Class(descriptor: try classDescriptor(named: "SwiftGrandchildWidget", in: machOFile), in: machOFile) + let classType = try Class(descriptor: try classDescriptor(named: "SwiftGrandchildWidget", in: machOFile), in: machOFile.context) let output = try await classType.dump(using: .demangleOptions(.test), in: machOFile).string let moduleName = ObjCImplementationFixture.moduleName // The Swift ancestor's `class_ro_t` name is its mangled runtime name; @@ -90,7 +90,7 @@ struct ObjCMemberDumpTests { let machOFile = try ObjCImplementationFixture.machOFile(.full) ObjCAncestorResolverStore.shared.register(.empty, for: machOFile) defer { ObjCAncestorResolverStore.shared.remove(for: machOFile) } - let classType = try Class(descriptor: try classDescriptor(named: "SwiftGrandchildWidget", in: machOFile), in: machOFile) + let classType = try Class(descriptor: try classDescriptor(named: "SwiftGrandchildWidget", in: machOFile), in: machOFile.context) let output = try await classType.dump(using: .demangleOptions(.test), in: machOFile).string let moduleName = ObjCImplementationFixture.moduleName #expect(output.contains("// ObjC ancestor chain: \(moduleName).SwiftDerivedWidget → ClangWidget → NSObject (bound; chain not resolvable offline)")) @@ -125,10 +125,10 @@ struct ObjCMemberDumpTests { let machOImage = try #require(MachOImage(name: libraryURL.deletingPathExtension().lastPathComponent), "the fixture dylib did not load in-process") var descriptor: ClassDescriptor? for typeContextDescriptor in try machOImage.swift.typeContextDescriptors { - guard case .class(let classDescriptor) = typeContextDescriptor, try classDescriptor.name(in: machOImage) == "SwiftDerivedWidget" else { continue } + guard case .class(let classDescriptor) = typeContextDescriptor, try classDescriptor.name(in: machOImage.context) == "SwiftDerivedWidget" else { continue } descriptor = classDescriptor } - let classType = try Class(descriptor: try #require(descriptor), in: machOImage) + let classType = try Class(descriptor: try #require(descriptor), in: machOImage.context) let output = try await classType.dump(using: .demangleOptions(.test), in: machOImage).string let moduleName = ObjCImplementationFixture.moduleName #expect(output.contains("// ObjC ancestor chain: ClangWidget → NSObject\n")) @@ -147,7 +147,7 @@ struct ObjCMemberDumpTests { let machOFile = try ObjCImplementationFixture.machOFile(.optimizedStripped) let moduleName = ObjCImplementationFixture.moduleName try await withFixtureWorld(for: machOFile) { - let classType = try Class(descriptor: try classDescriptor(named: "SwiftDerivedWidget", in: machOFile), in: machOFile) + let classType = try Class(descriptor: try classDescriptor(named: "SwiftDerivedWidget", in: machOFile), in: machOFile.context) let implementationClass = try #require(ObjCImplementationClass.all(in: machOFile).first { $0.facts.className == "DerivedImplementationWidget" }) let inferred = try await classType.dump(using: .demangleOptions(.test), in: machOFile).string @@ -173,7 +173,7 @@ struct ObjCMemberDumpTests { /// Stripped thunks — the OS-framework shape — tie through the thunk's code. @Test func strippedThunksStillNameTheSelector() async throws { let machOFile = try ObjCImplementationFixture.machOFile(.strippedLocals) - let classType = try Class(descriptor: try classDescriptor(named: "SwiftDerivedWidget", in: machOFile), in: machOFile) + let classType = try Class(descriptor: try classDescriptor(named: "SwiftDerivedWidget", in: machOFile), in: machOFile.context) let output = try await classType.dump(using: .demangleOptions(.test), in: machOFile).string let moduleName = ObjCImplementationFixture.moduleName #expect(output.contains("notAnOverride() -> () // @objc -[\(moduleName).SwiftDerivedWidget notAnOverride] (the IMP's code references the implementation)")) diff --git a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift index d690b9f46..bceca48a5 100644 --- a/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift +++ b/Tests/SwiftDumpTests/OpaqueWitnessDumpAnnotationTests.swift @@ -140,8 +140,8 @@ struct OpaqueWitnessDumpAnnotationTests { private func dumpedConformances(in machOFile: MachOFile) async throws -> [String: String] { var dumps: [String: String] = [:] for associatedType in try machOFile.swift.associatedTypes { - let conformer = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machOFile)).print(using: DemangleOptions.default) - let protocolName = await (try SymbolicDemangler.demangleType(for: associatedType.protocolTypeName, in: machOFile)).print(using: DemangleOptions.default) + let conformer = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machOFile.context)).print(using: DemangleOptions.default) + let protocolName = await (try SymbolicDemangler.demangleType(for: associatedType.protocolTypeName, in: machOFile.context)).print(using: DemangleOptions.default) dumps["\(conformer): \(protocolName)"] = try await associatedType.dump(using: .demangleOptions(.default), in: machOFile).string } return dumps diff --git a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift index d128adf80..a6d80dc97 100644 --- a/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift +++ b/Tests/SwiftDumpTests/PrivateTypeMemberAttributionTests.swift @@ -23,9 +23,9 @@ final class PrivateTypeMemberAttributionTests: MachOFileTests, @unchecked Sendab for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { guard case .struct(let structDescriptor) = typeContextDescriptor, - try structDescriptor.name(in: machOFile) == "PrivateDoppelganger" + try structDescriptor.name(in: machOFile.context) == "PrivateDoppelganger" else { continue } - let structType = try Struct(descriptor: structDescriptor, in: machOFile) + let structType = try Struct(descriptor: structDescriptor, in: machOFile.context) let output = try await structType.dump(using: .demangleOptions(.test), in: machOFile).string if output.contains("alphaStorage") { dumpsByFieldMarker["alpha"] = output diff --git a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift index ccc67674d..4893afb76 100644 --- a/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift +++ b/Tests/SwiftDumpTests/VTableSlotAttributionTests.swift @@ -111,7 +111,7 @@ struct VTableSlotAttributionTests { 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) == name else { continue } + guard try classDescriptor.name(in: machOFile.context) == name else { continue } return classDescriptor } Issue.record("fixture is missing the class \(name)") @@ -123,7 +123,7 @@ struct VTableSlotAttributionTests { private func vtableSlots(inDumpOf classDescriptor: ClassDescriptor, in machOFile: MachOFile) async throws -> [(slot: Int, declaration: String)] { var configuration = DumperConfiguration.demangleOptions(.test) configuration.printVTableOffset = true - let classType = try Class(descriptor: classDescriptor, in: machOFile) + let classType = try Class(descriptor: classDescriptor, in: machOFile.context) let output = try await classType.dump(using: configuration, in: machOFile).string var slots: [(slot: Int, declaration: String)] = [] @@ -151,7 +151,7 @@ struct VTableSlotAttributionTests { /// — the premise the whole suite rests on. private func foldedImplementationAddress(in machOFile: MachOFile) throws -> Int { let hostDescriptor = try classDescriptor(named: "Host", in: machOFile) - let hostClass = try Class(descriptor: hostDescriptor, in: machOFile) + let hostClass = try Class(descriptor: hostDescriptor, in: machOFile.context) let methodImplementationOffsets = hostClass.methodDescriptors .filter { $0.flags.kind == .method } .compactMap(\.implementationOffset) @@ -300,10 +300,10 @@ struct GraphHostVTableAttributionTests { for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor, - try classDescriptor.name(in: machOFile) == "GraphHost" else { continue } + try classDescriptor.name(in: machOFile.context) == "GraphHost" else { continue } var configuration = DumperConfiguration.demangleOptions(.test) configuration.printVTableOffset = true - let classType = try Class(descriptor: classDescriptor, in: machOFile) + let classType = try Class(descriptor: classDescriptor, in: machOFile.context) return try await classType.dump(using: configuration, in: machOFile).string } Issue.record("SwiftUICore does not contain a GraphHost class") diff --git a/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift b/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift index 06fa14553..c88968517 100644 --- a/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift +++ b/Tests/SwiftIndexingTests/PerImageCacheEvictionTests.swift @@ -63,7 +63,7 @@ final class PerImageCacheEvictionTests: MachOFileTests, @unchecked Sendable { @discardableResult private func populateNonIndexerCaches(for machOFile: MachOFile) throws -> Bool { let typeDescriptor = try #require(try machOFile.swift.typeContextDescriptors.first) - let typeNode = try SymbolicDemangler.demangleContext(for: .type(typeDescriptor), in: machOFile) + let typeNode = try SymbolicDemangler.demangleContext(for: .type(typeDescriptor), in: machOFile.context) _ = InternedNodeReferenceCache.shared.reference(interning: typeNode, in: machOFile) return true } diff --git a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift index 89de48e5d..3244e29c8 100644 --- a/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift +++ b/Tests/SwiftIndexingTests/SymbolTestsCoreIntegrationTests.swift @@ -52,7 +52,7 @@ final class STCoreTests: MachOFileTests, @unchecked Sendable { extension STCoreTests { @Test func parsedTypeNames() async throws { let indexer = try await preparedIndexer() - let typeNames = Set(indexer.allTypeDefinitions.values.map { $0.typeName.currentName }) + let typeNames = Set(indexer.allTypeDefinitions.values.map { $0.typeName.declaredNameForTesting }) #expect(typeNames.contains("StructTest")) #expect(typeNames.contains("ClassTest")) @@ -85,7 +85,7 @@ extension STCoreTests { @Test func parsedProtocolNames() async throws { let indexer = try await preparedIndexer() - let protocolNames = Set(indexer.allProtocolDefinitions.values.map { $0.protocolName.currentName }) + let protocolNames = Set(indexer.allProtocolDefinitions.values.map { $0.protocolName.declaredNameForTesting }) #expect(protocolNames.contains("ProtocolTest")) #expect(protocolNames.contains("ProtocolWitnessTableTest")) @@ -192,7 +192,7 @@ extension STCoreTests { // RawRepresentableNestedStruct is defined inside a conditional extension, so its typeChildren // contain NestedStruct (which is defined in a direct extension of RawRepresentableNestedStruct). let rawRepresentableNested = try #require(findTypeDefinition(named: "RawRepresentableNestedStruct", in: indexer)) - let nestedChildren = rawRepresentableNested.typeChildren.map { $0.typeName.currentName } + let nestedChildren = rawRepresentableNested.typeChildren.map { $0.typeName.declaredNameForTesting } #expect(nestedChildren.contains("NestedStruct")) } @@ -614,7 +614,7 @@ extension STCoreTests { let opaqueReturnType = try #require(findTypeDefinition(named: "OpaqueReturnTypeTest", in: indexer)) // OpaqueReturnTypeTest has a nested type AnyProtocolTest - let childNames = opaqueReturnType.typeChildren.map { $0.typeName.currentName } + let childNames = opaqueReturnType.typeChildren.map { $0.typeName.declaredNameForTesting } #expect(childNames.contains("AnyProtocolTest")) } diff --git a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift index c42f8d9ac..a00c32bc2 100644 --- a/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift +++ b/Tests/SwiftInspectionTests/AnonymousContextPrivateDiscriminatorTests.swift @@ -38,7 +38,7 @@ struct AnonymousContextPrivateDiscriminatorTests { let classDescriptor = try #require(try Self.classDescriptor(named: Self.privateClassName, in: machOFile)) let expectedDiscriminator = try #require(try Self.discriminatorFromObjCRuntimeName(in: machOFile)) - let node = try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOFile) + let node = try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOFile.context) #expect(Self.privateDiscriminator(ofNominal: node) == expectedDiscriminator) } @@ -49,7 +49,7 @@ struct AnonymousContextPrivateDiscriminatorTests { let classDescriptor = try #require(try Self.classDescriptor(named: Self.privateClassName, in: machOImage)) let expectedDiscriminator = try #require(try Self.discriminatorFromObjCRuntimeName(in: machOImage)) - let node = try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOImage) + let node = try SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOImage.context) #expect(Self.privateDiscriminator(ofNominal: node) == expectedDiscriminator) } @@ -61,9 +61,9 @@ struct AnonymousContextPrivateDiscriminatorTests { let machOImage = try Self.loadedAppKitImage() let classDescriptor = try #require(try Self.classDescriptor(named: Self.privateClassName, in: machOImage)) let expectedDiscriminator = try #require(try Self.discriminatorFromObjCRuntimeName(in: machOImage)) - let inProcessDescriptor: ContextDescriptorWrapper = try .resolve(from: machOImage.ptr.advanced(by: classDescriptor.offset)) + let inProcessDescriptor: ContextDescriptorWrapper = try .resolve(at: machOImage.ptr.advanced(by: classDescriptor.offset), in: .inProcess) - let node = try SymbolicDemangler.demangleContext(for: inProcessDescriptor) + let node = try SymbolicDemangler.demangleContext(for: inProcessDescriptor, in: .inProcess) #expect(Self.privateDiscriminator(ofNominal: node) == expectedDiscriminator) } @@ -87,8 +87,8 @@ struct AnonymousContextPrivateDiscriminatorTests { runtimeName.hasPrefix("_Tt") else { continue } let metadata: ClassMetadataObjCInterop = try machOImage.readWrapperElement(offset: classObject.offset) - let classDescriptor = try #require(try metadata.descriptor(in: machOImage), "\(runtimeName) has no class descriptor") - let descriptorBuiltName = try Self.qualifiedName(ofNominal: SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOImage)) + let classDescriptor = try #require(try metadata.descriptor(in: machOImage.context), "\(runtimeName) has no class descriptor") + let descriptorBuiltName = try Self.qualifiedName(ofNominal: SymbolicDemangler.demangleContext(for: .type(.class(classDescriptor)), in: machOImage.context)) let runtimeNameBuiltName = try Self.qualifiedName(ofNominal: demangleAsNodeTransient(runtimeName)) comparedCount += 1 if runtimeName.contains("P33_") { @@ -125,7 +125,7 @@ struct AnonymousContextPrivateDiscriminatorTests { private static func classDescriptor(named name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { for typeContextDescriptor in try machO.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor else { continue } - if try classDescriptor.name(in: machO) == name { + if try classDescriptor.name(in: machO.context) == name { return classDescriptor } } diff --git a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift index a9c606cfe..1f2ccdf7a 100644 --- a/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift +++ b/Tests/SwiftInspectionTests/CImportedTypeIdentityTests.swift @@ -266,11 +266,11 @@ struct CImportedTypeIdentityFixtureTests { private func holderFieldMangledTypeNames(in machOFile: MachOFile) throws -> [String: MangledName] { for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { guard case .struct(let structDescriptor) = typeContextDescriptor else { continue } - guard try structDescriptor.name(in: machOFile) == "Holder" else { continue } - let fieldDescriptor = try #require(try structDescriptor.fieldDescriptor(in: machOFile)) + guard try structDescriptor.name(in: machOFile.context) == "Holder" else { continue } + let fieldDescriptor = try #require(try structDescriptor.fieldDescriptor(in: machOFile.context)) var mangledTypeNamesByFieldName: [String: MangledName] = [:] - for record in try fieldDescriptor.records(in: machOFile) { - mangledTypeNamesByFieldName[try record.fieldName(in: machOFile)] = try record.mangledTypeName(in: machOFile) + for record in try fieldDescriptor.records(in: machOFile.context) { + mangledTypeNamesByFieldName[try record.fieldName(in: machOFile.context)] = try record.mangledTypeName(in: machOFile.context) } return mangledTypeNamesByFieldName } @@ -310,7 +310,7 @@ struct CImportedTypeIdentityFixtureTests { let mangledTypeNames = try holderFieldMangledTypeNames(in: machOFile) for expectation in Self.expectations { let mangledTypeName = try #require(mangledTypeNames[expectation.fieldName], "Holder has no field \(expectation.fieldName)") - let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile) + let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context) #expect(try typeMangling(of: node) == expectation.mangling, Comment(rawValue: expectation.fieldName)) } } @@ -320,7 +320,7 @@ struct CImportedTypeIdentityFixtureTests { let mangledTypeNames = try holderFieldMangledTypeNames(in: machOFile) for expectation in Self.expectations { let mangledTypeName = try #require(mangledTypeNames[expectation.fieldName], "Holder has no field \(expectation.fieldName)") - let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile) + let node = try SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context) #expect(node.print(using: .default) == expectation.printedName, Comment(rawValue: expectation.fieldName)) } } @@ -332,9 +332,9 @@ struct CImportedTypeIdentityFixtureTests { var importInfosByUserFacingName: [String: TypeImportInfo?] = [:] for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { let descriptor = typeContextDescriptor.contextDescriptor - guard try descriptor.isCImportedContextDescriptor(in: machOFile) else { continue } + guard try descriptor.isCImportedContextDescriptor(in: machOFile.context) else { continue } let typeDescriptor = try #require(typeContextDescriptor.contextDescriptor as? any TypeContextDescriptorProtocol) - importInfosByUserFacingName[try typeDescriptor.name(in: machOFile)] = try typeDescriptor.typeImportInfo(in: machOFile) + importInfosByUserFacingName[try typeDescriptor.name(in: machOFile.context)] = try typeDescriptor.typeImportInfo(in: machOFile.context) } #expect(importInfosByUserFacingName["ProbeMode"] == .some(nil)) #expect(importInfosByUserFacingName["ProbePoint"] == TypeImportInfo(abiName: "ProbeOriginalPoint", symbolNamespace: nil, relatedEntityName: nil)) diff --git a/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift new file mode 100644 index 000000000..696af7161 --- /dev/null +++ b/Tests/SwiftInspectionTests/DyldCacheTwinImageTests.swift @@ -0,0 +1,69 @@ +import Foundation +import Testing +import MachOKit +import MachOObjCSection +@testable import SwiftInspection + +private enum TwinSwiftUICaches { + static let swiftUIPath = "/System/Library/Frameworks/SwiftUI.framework/Versions/A/SwiftUI" + static let joinedViewsRuntimeName = "_TtCV7SwiftUI12_ViewList_ID11JoinedViews" + + static func url(of version: String) -> URL { + URL(fileURLWithPath: "/Volumes/DyldSharedCaches/macOS/\(version)/dyld_shared_cache_arm64e") + } + + static var areAvailable: Bool { + ["13.5", "13.6"].allSatisfy { FileManager.default.fileExists(atPath: url(of: $0).path) } + } + + /// The offset of the class object the image's own class list names + /// `runtimeName` — the answer the index must give for this image. + static func ownClassObjectOffset(named runtimeName: String, in machOFile: MachOFile) -> Int? { + machOFile.objc.classes64?.first { $0.classROData(in: machOFile)?.name(in: machOFile) == runtimeName }?.offset + } +} + +/// The macOS 13.5 and 13.6 dyld caches carry the same SwiftUI build — the same +/// `LC_UUID` — at different addresses. Per-image caches keyed by the image +/// alone handed the copy read second the first one's class objects: reading +/// 13.6's `JoinedViews` in the 13.5 cache landed on a slot holding `0xa9`, and +/// decoding that as a pointer trapped in MachOKit. An evolution interface over +/// every archived macOS cache crashed this way. +@Suite(.enabled(if: TwinSwiftUICaches.areAvailable, "needs the archived macOS 13.5 and 13.6 dyld caches")) +struct DyldCacheTwinImageTests { + @Test func eachCacheIndexesItsOwnClassObjects() throws { + let newerCache = try DyldCache(url: TwinSwiftUICaches.url(of: "13.6")) + let olderCache = try DyldCache(url: TwinSwiftUICaches.url(of: "13.5")) + let newerImage = try #require(newerCache.machOFile(by: .path(TwinSwiftUICaches.swiftUIPath))) + let olderImage = try #require(olderCache.machOFile(by: .path(TwinSwiftUICaches.swiftUIPath))) + let runtimeName = TwinSwiftUICaches.joinedViewsRuntimeName + let newerOffset = try #require(TwinSwiftUICaches.ownClassObjectOffset(named: runtimeName, in: newerImage)) + let olderOffset = try #require(TwinSwiftUICaches.ownClassObjectOffset(named: runtimeName, in: olderImage)) + try #require(newerOffset != olderOffset, "the premise: the two caches place the class differently") + + // The newer cache first, the order the evolution's concurrent + // preparation happened to take. + _ = ObjCClassMethodIndex.shared.hierarchy(forRuntimeName: runtimeName, in: newerImage) + #expect(ObjCClassMethodIndex.shared.storage(in: olderImage)?.classObjectsByRuntimeName[runtimeName]?.offset == olderOffset) + #expect(ObjCClassMethodIndex.shared.storage(in: newerImage)?.classObjectsByRuntimeName[runtimeName]?.offset == newerOffset) + _ = ObjCClassMethodIndex.shared.hierarchy(forRuntimeName: runtimeName, in: olderImage) + + withExtendedLifetime((newerCache, olderCache)) {} + } + + /// The slot the newer cache's class data offset lands on in the older + /// cache: a small integer, which slide info decodes as a pointer below the + /// shared region. MachOKit subtracted the region start from it and trapped. + @Test func aSlotHoldingNoPointerResolvesToNoRebase() throws { + let url = TwinSwiftUICaches.url(of: "13.5") + let slotOffset: UInt64 = 0x59BE_A800 + let fileHandle = try FileHandle(forReadingFrom: url) + defer { try? fileHandle.close() } + try fileHandle.seek(toOffset: slotOffset) + let slotBytes = try #require(try fileHandle.read(upToCount: 8)) + let slotValue = slotBytes.withUnsafeBytes { $0.loadUnaligned(as: UInt64.self) } + try #require(slotValue == 0xa9, "the premise: the slot holds the integer, not a pointer") + + #expect(try DyldCache(url: url).resolveOptionalRebase(at: slotOffset) == nil) + } +} diff --git a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift index d8c4bca01..7d12f5e6b 100644 --- a/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift +++ b/Tests/SwiftInspectionTests/EnumLayoutVerificationTests.swift @@ -83,12 +83,12 @@ private func findMultiPayloadDescriptor( ) throws -> (spareBytes: [UInt8], spareBytesOffset: Int, usesSpare: Bool)? { for descriptor in try machO.swift.multiPayloadEnumDescriptors { let inProcess = descriptor.asPointerWrapper(in: machO) - let mangledName = try inProcess.mangledTypeName() - let name = try SymbolicDemangler.demangleType(for: mangledName).print(using: .default) + let mangledName = try inProcess.mangledTypeName(in: .inProcess) + let name = try SymbolicDemangler.demangleType(for: mangledName, in: .inProcess).print(using: .default) if name.contains(needle) { if inProcess.usesPayloadSpareBits { - let spareBytes = try inProcess.payloadSpareBits() - let offset = Int(try inProcess.payloadSpareBitMaskByteOffset()) + let spareBytes = try inProcess.payloadSpareBits(in: .inProcess) + let offset = Int(try inProcess.payloadSpareBitMaskByteOffset(in: .inProcess)) return (spareBytes, offset, true) } return ([], 0, false) @@ -252,7 +252,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U8_1E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U8_1E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U8_1E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 1, numExtraInhabitants: xi @@ -266,7 +266,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U8_3E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U8_3E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U8_3E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 3, numExtraInhabitants: xi @@ -282,7 +282,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U16_1E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U16_1E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U16_1E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 1, numExtraInhabitants: xi @@ -296,7 +296,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U16_3E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U16_3E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U16_3E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 3, numExtraInhabitants: xi @@ -312,7 +312,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U32_1E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U32_1E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U32_1E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 1, numExtraInhabitants: xi @@ -326,7 +326,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U32_5E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U32_5E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U32_5E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 5, numExtraInhabitants: xi @@ -342,7 +342,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U64_1E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U64_1E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U64_1E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 1, numExtraInhabitants: xi @@ -356,7 +356,7 @@ struct EnumLayoutVerificationTests { func singlePayload_U64_3E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_U64_3E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_U64_3E.self).typeLayout(in: .inProcess).extraInhabitantCount) let result = Calculator.calculateSinglePayload( payloadSize: payloadSize, numEmptyCases: 3, numExtraInhabitants: xi @@ -379,7 +379,7 @@ struct EnumLayoutVerificationTests { func singlePayload_Bool_1E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_Bool_1E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_Bool_1E.self).typeLayout(in: .inProcess).extraInhabitantCount) // Bool has 254 XI; 1 empty case fits entirely within XI #expect(xi + 1 >= 1, "Bool should have enough XI for 1 empty case") @@ -402,7 +402,7 @@ struct EnumLayoutVerificationTests { func singlePayload_Bool_3E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_Bool_3E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_Bool_3E.self).typeLayout(in: .inProcess).extraInhabitantCount) #expect(xi + 1 >= 3, "Bool should have enough XI for 3 empty cases") #expect(enumSize == payloadSize, "No extra tag bytes needed when XI suffice") @@ -427,7 +427,7 @@ struct EnumLayoutVerificationTests { func singlePayload_OptU8_1E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size // 2 - let payloadXI = try Int(Metadata.createInProcess(UInt8?.self).typeLayout().extraInhabitantCount) + let payloadXI = try Int(Metadata.createInProcess(UInt8?.self).typeLayout(in: .inProcess).extraInhabitantCount) #expect(payloadXI == 0, "Optional should have 0 XI") #expect(enumSize > payloadSize, "Overflow requires extra tag bytes") @@ -446,7 +446,7 @@ struct EnumLayoutVerificationTests { func singlePayload_OptU8_3E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size // 2 - let payloadXI = try Int(Metadata.createInProcess(UInt8?.self).typeLayout().extraInhabitantCount) + let payloadXI = try Int(Metadata.createInProcess(UInt8?.self).typeLayout(in: .inProcess).extraInhabitantCount) #expect(payloadXI == 0, "Optional should have 0 XI") @@ -465,7 +465,7 @@ struct EnumLayoutVerificationTests { func singlePayload_Ref_2E() throws { let enumSize = MemoryLayout.size let payloadSize = MemoryLayout.size - let xi = try Int(Metadata.createInProcess(SP_Ref_2E.self).typeLayout().extraInhabitantCount) + let xi = try Int(Metadata.createInProcess(SP_Ref_2E.self).typeLayout(in: .inProcess).extraInhabitantCount) // Class references have many XI (null pointer + aligned invalid pointers) #expect(xi >= 2, "Class reference should have XI for 2 empty cases") @@ -727,7 +727,7 @@ struct EnumLayoutVerificationTests { .impliedTotalSize(payloadAreaSize: 8) == MemoryLayout.size) // Single payload: overflow appends tag bytes, XI stays payload-sized. - let overflowXI = try Int(Metadata.createInProcess(SP_U8_3E.self).typeLayout().extraInhabitantCount) + let overflowXI = try Int(Metadata.createInProcess(SP_U8_3E.self).typeLayout(in: .inProcess).extraInhabitantCount) #expect(Calculator.calculateSinglePayload(payloadSize: 1, numEmptyCases: 3, numExtraInhabitants: overflowXI) .impliedTotalSize(payloadAreaSize: 1) == MemoryLayout.size) #expect(Calculator.calculateSinglePayload(payloadSize: 1, numEmptyCases: 3, numExtraInhabitants: 254) diff --git a/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift b/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift new file mode 100644 index 000000000..26eab6e2d --- /dev/null +++ b/Tests/SwiftInspectionTests/ReadingContextCacheScopeTests.swift @@ -0,0 +1,117 @@ +import Foundation +import Testing +import MachOKit +import Demangling +@_spi(Internals) import MachOCaches +@testable import MachOSwiftSection +@testable import MachOTestingSupport +import MachOFixtureSupport +@testable @_spi(Internals) import SwiftInspection + +/// A `ReadingContext` declares where memo caches may file what they compute +/// from it (evolution proposal `reading-context-migration`). These tests pin +/// the contract the demangle memo relies on: an image keys the same entries +/// whether it is reached through its reader or through a context over it — +/// so `removeCache(for:)` still drops them — and a context that declares no +/// identity is never memoized at all. +/// +/// Holds `ExclusiveImageAccess(.SymbolTestsHelper)` because it asserts on +/// that image's demangle memo, whole-process state that +/// `PerImageCacheEvictionTests` clears and rebuilds as well. +@Suite(.serialized, ExclusiveImageAccess(.SymbolTestsHelper)) +final class ReadingContextCacheScopeTests: MachOFileTests, @unchecked Sendable { + override class var fileName: MachOFileName { .SymbolTestsHelper } + + private func someTypeDescriptor() throws -> TypeContextDescriptorWrapper { + try #require(machOFile.swift.typeContextDescriptors.first) + } + + @Test func aMachOContextKeysItsImageTheWayItsReaderDoes() throws { + guard case .image(let identifier) = machOFile.context.cacheScope else { + Issue.record("a Mach-O context declared \(machOFile.context.cacheScope) instead of its image") + return + } + let keyThroughReader = SharedCacheKey(machOFile) + let keyThroughContext = SharedCacheKey(identifier: identifier) + #expect(keyThroughReader == keyThroughContext) + #expect(keyThroughReader.hashValue == keyThroughContext.hashValue) + } + + @Test func aDemangleThroughAMachOContextFillsTheImagesMemo() throws { + let descriptor = try someTypeDescriptor() + SymbolicDemangler.removeCache(for: machOFile) + try #require(!SymbolicDemangler.cacheExists(for: machOFile)) + + _ = try SymbolicDemangler.demangleContext(for: .type(descriptor), in: machOFile.context) + #expect(SymbolicDemangler.cacheExists(for: machOFile)) + + SymbolicDemangler.removeCache(for: machOFile) + #expect(!SymbolicDemangler.cacheExists(for: machOFile)) + } + + @Test func aContextWithoutIdentityIsNeverMemoized() throws { + let descriptor = try someTypeDescriptor() + SymbolicDemangler.removeCache(for: machOFile) + try #require(!SymbolicDemangler.cacheExists(for: machOFile)) + + let demangledThroughAnonymousContext = try SymbolicDemangler.demangleContext(for: .type(descriptor), in: ContextWithoutCacheScope(wrapped: machOFile.context)) + #expect(!SymbolicDemangler.cacheExists(for: machOFile)) + + let demangledThroughMachOContext = try SymbolicDemangler.demangleContext(for: .type(descriptor), in: machOFile.context) + #expect(demangledThroughAnonymousContext.print(using: .default) == demangledThroughMachOContext.print(using: .default)) + SymbolicDemangler.removeCache(for: machOFile) + } +} + +/// Reads exactly what a Mach-O context reads but declares no cache scope, the +/// way a third-party conformer that knows nothing of the caches would. +private struct ContextWithoutCacheScope: ReadingContext { + typealias Runtime = RuntimeTarget64 + typealias Address = Int + + let wrapped: MachOContext + + func readElement(at address: Int) throws -> T { + try wrapped.readElement(at: address) + } + + func readElements(at address: Int, numberOfElements: Int) throws -> [T] { + try wrapped.readElements(at: address, numberOfElements: numberOfElements) + } + + func readWrapperElement(at address: Int) throws -> T { + try wrapped.readWrapperElement(at: address) + } + + func readWrapperElements(at address: Int, numberOfElements: Int) throws -> [T] { + try wrapped.readWrapperElements(at: address, numberOfElements: numberOfElements) + } + + func readString(at address: Int) throws -> String { + try wrapped.readString(at: address) + } + + func advanceAddress(_ address: Int, by offset: Int) -> Int { + wrapped.advanceAddress(address, by: offset) + } + + func advanceAddress(_ address: Int, of type: T.Type) -> Int { + wrapped.advanceAddress(address, of: type) + } + + func addressFromOffset(_ offset: Int) throws -> Int { + wrapped.addressFromOffset(offset) + } + + func addressFromVirtualAddress(_ virtualAddress: UInt64) throws -> Int { + wrapped.addressFromVirtualAddress(virtualAddress) + } + + func offsetFromAddress(_ address: Int) throws -> Int { + wrapped.offsetFromAddress(address) + } + + var bindRebaseResolver: (any MachOBindRebaseResolving)? { + wrapped.bindRebaseResolver + } +} diff --git a/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift b/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift index 995d2d6ca..0ea234b4a 100644 --- a/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift +++ b/Tests/SwiftInspectionTests/RuntimeMetadataTypeBuilderTests.swift @@ -126,7 +126,7 @@ struct RuntimeMetadataTypeBuilderTests { break } guard let declarationName, let instantiation = knownInstantiations[declarationName] else { return nil } - guard let wrapper = try? Metadata.createInProcess(instantiation).typeContextDescriptorWrapper() else { return nil } + guard let wrapper = try? Metadata.createInProcess(instantiation).typeContextDescriptorWrapper(in: .inProcess) else { return nil } return try? wrapper.typeContextDescriptor.asPointer } diff --git a/Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift b/Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift index 4b6ec10ba..34f7f59ba 100644 --- a/Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift +++ b/Tests/SwiftInspectionTests/SwiftClassObjectIndexTests.swift @@ -3,6 +3,7 @@ import Testing import MachOKit import MachOFoundation @testable import MachOSwiftSection +import MachOObjCSection @testable import MachOTestingSupport import MachOFixtureSupport @_spi(Internals) @testable import SwiftInspection @@ -15,7 +16,7 @@ import MachOFixtureSupport struct SwiftClassObjectIndexTests { private static func classDescriptor(named name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor { for typeContextDescriptor in try machO.swift.typeContextDescriptors { - guard case .class(let classDescriptor) = typeContextDescriptor, try classDescriptor.name(in: machO) == name else { continue } + guard case .class(let classDescriptor) = typeContextDescriptor, try classDescriptor.name(in: machO.context) == name else { continue } return classDescriptor } Issue.record("no class named \(name)") @@ -66,6 +67,36 @@ struct SwiftClassObjectIndexTests { #expect(drifterInstanceStart == 8) #expect(resilientChildInstanceStart == nil) } + + /// The flag word is read at its own width. Read as an Optional, it took + /// the byte after it — `instanceAddressPoint`'s low byte — as the + /// Optional's tag, and a non-zero one dropped the class. The compiler + /// always writes zero there, so a patched copy of the library sets it. + @Test func renamedClassSurvivesANonZeroByteAfterTheFlagWord() throws { + let original = try RenamedObjCClassFixture.machOFile(.full) + let swiftClassObjectOffsets = (original.objcImplementationClassObjects() ?? []).filter(\.isSwift).map(\.offset) + try #require(!swiftClassObjectOffsets.isEmpty) + let byteAfterFlagWord = try #require(MemoryLayout.offset(of: \.instanceAddressPoint)) + let uuidCommand = try #require(original.loadCommands.info(of: LoadCommand.uuid)) + + var libraryBytes = try Data(contentsOf: RenamedObjCClassFixture.libraryURL(.full)) + for classObjectOffset in swiftClassObjectOffsets { + libraryBytes[original.headerStartOffset + classObjectOffset + byteAfterFlagWord] = 0x01 + } + // A copy with the original's UUID and install name is the same image + // to every per-image cache, which would answer from the original's + // index without reading the patched bytes. + libraryBytes[original.cmdsStartOffset + uuidCommand.offset + MemoryLayout.size] ^= 0xFF + let patchedLibraryURL = FileManager.default.temporaryDirectory + .appendingPathComponent("\(RenamedObjCClassFixture.moduleName)-byteAfterFlagWord-\(UUID().uuidString).dylib") + try libraryBytes.write(to: patchedLibraryURL) + defer { try? FileManager.default.removeItem(at: patchedLibraryURL) } + + let patched = try MachOFile(url: patchedLibraryURL, headerStartOffset: original.headerStartOffset) + try #require(patched.identifier != original.identifier) + let renamedWidgetName = try Self.customObjCClassName(ofClassNamed: "RenamedWidget", in: patched) + #expect(renamedWidgetName == CustomObjCClassName(name: "RCFRenamedWidget", attribute: .objc)) + } } /// The shared fixture's two `@objc(Name)` classes, through every reader. @@ -75,7 +106,7 @@ final class SwiftClassObjectIndexFixtureTests: MachOSwiftSectionFixtureTests, @u var namesByClassName: [String: CustomObjCClassName?] = [:] for typeContextDescriptor in try machO.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor else { continue } - let name = try classDescriptor.name(in: machO) + let name = try classDescriptor.name(in: machO.context) guard ["ObjCBridge", "ObjCBridgeWithProto", "ObjCAttributeClass"].contains(name) else { continue } namesByClassName[name] = SwiftClassObjectIndex.shared.customObjCClassName(forClassDescriptorOffset: classDescriptor.offset, in: machO) } diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift index 9083e5a5d..4700e05a2 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerFixedShapeExtractionTests.swift @@ -223,10 +223,10 @@ struct SymbolicDemanglerFixedShapeExtractionTests { private func holderFieldMangledTypeName(named fieldName: String, in machOFile: MachOFile) throws -> MangledName { for typeContextDescriptor in try machOFile.swift.typeContextDescriptors { guard case .struct(let structDescriptor) = typeContextDescriptor else { continue } - guard try structDescriptor.name(in: machOFile) == "Holder" else { continue } - let fieldDescriptor = try #require(try structDescriptor.fieldDescriptor(in: machOFile)) - for record in try fieldDescriptor.records(in: machOFile) where try record.fieldName(in: machOFile) == fieldName { - return try record.mangledTypeName(in: machOFile) + guard try structDescriptor.name(in: machOFile.context) == "Holder" else { continue } + let fieldDescriptor = try #require(try structDescriptor.fieldDescriptor(in: machOFile.context)) + for record in try fieldDescriptor.records(in: machOFile.context) where try record.fieldName(in: machOFile.context) == fieldName { + return try record.mangledTypeName(in: machOFile.context) } throw FixtureCompilationError(diagnostics: "Holder has no field \(fieldName)") } @@ -258,7 +258,7 @@ struct SymbolicDemanglerFixedShapeExtractionTests { let mangledName = try holderFieldMangledTypeName(named: "copyable", in: machOFile) try #require(objectiveCProtocolReferenceCount(in: mangledName) == 1, "the fixture must reference NSCopying through a \\x0C symbolic reference for this test to mean anything") - let node = try SymbolicDemangler.demangleType(for: mangledName, in: machOFile) + let node = try SymbolicDemangler.demangleType(for: mangledName, in: machOFile.context) #expect(node.print(using: .default) == "__C.NSCopying") let protocolTypes = try protocolTypes(inExistential: node) @@ -277,7 +277,7 @@ struct SymbolicDemanglerFixedShapeExtractionTests { let mangledName = try holderFieldMangledTypeName(named: "both", in: machOFile) try #require(objectiveCProtocolReferenceCount(in: mangledName) == 2, "the fixture must reference both protocols through \\x0C symbolic references for this test to mean anything") - let node = try SymbolicDemangler.demangleType(for: mangledName, in: machOFile) + let node = try SymbolicDemangler.demangleType(for: mangledName, in: machOFile.context) // The protocol Swift spells `NSObjectProtocol` is the ObjC protocol // `NSObject`; the reference record mangles the ObjC runtime name // (`So8NSObject_p`), and the Swift-side rename is APINotes' business diff --git a/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift b/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift index c4570c250..3d3154936 100644 --- a/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicDemanglerTests.swift @@ -74,7 +74,7 @@ final class SymbolicDemanglerImageTests: MachOImageTests, @unchecked Sendable { @Test func buildGenericSignatureReturnsNilForEmptyRequirements() async throws { // Empty requirements should return nil - let result = try SymbolicDemangler.buildGenericSignature(for: []) + let result = try SymbolicDemangler.buildGenericSignature(for: [], in: .inProcess) #expect(result == nil) } } @@ -91,7 +91,7 @@ final class SymbolicDemanglerFileTests: MachOFileTests, @unchecked Sendable { } @Test func buildGenericSignatureFromFileReturnsNilForEmpty() async throws { - let result = try SymbolicDemangler.buildGenericSignature(for: [] as [GenericRequirementDescriptor], in: machOFile) + let result = try SymbolicDemangler.buildGenericSignature(for: [] as [GenericRequirementDescriptor], in: machOFile.context) #expect(result == nil) } @@ -105,15 +105,15 @@ final class SymbolicDemanglerFileTests: MachOFileTests, @unchecked Sendable { processedCount += 1 do { if let structDescriptor = descriptor.struct { - let name = try structDescriptor.name(in: machOFile) + let name = try structDescriptor.name(in: machOFile.context) #expect(!name.isEmpty) successCount += 1 } else if let classDescriptor = descriptor.class { - let name = try classDescriptor.name(in: machOFile) + let name = try classDescriptor.name(in: machOFile.context) #expect(!name.isEmpty) successCount += 1 } else if let enumDescriptor = descriptor.enum { - let name = try enumDescriptor.name(in: machOFile) + let name = try enumDescriptor.name(in: machOFile.context) #expect(!name.isEmpty) successCount += 1 } @@ -134,7 +134,7 @@ final class SymbolicDemanglerFileTests: MachOFileTests, @unchecked Sendable { var successCount = 0 for descriptor in descriptors.prefix(20) { do { - let name = try descriptor.name(in: machOFile) + let name = try descriptor.name(in: machOFile.context) #expect(!name.isEmpty) successCount += 1 } catch { @@ -168,7 +168,7 @@ final class SymbolicDemanglerFileTests: MachOFileTests, @unchecked Sendable { for associatedType in associatedTypes.prefix(20) { for record in associatedType.records.prefix(5) { do { - let typeName = try record.substitutedTypeName(in: machOFile) + let typeName = try record.substitutedTypeName(in: machOFile.context) #expect(!typeName.isEmpty) successCount += 1 } catch { @@ -186,7 +186,7 @@ final class SymbolicDemanglerFileTests: MachOFileTests, @unchecked Sendable { @Suite struct BuildGenericSignatureTests { @Test func emptyRequirementsReturnsNil() throws { - let result = try SymbolicDemangler.buildGenericSignature(for: [] as [GenericRequirementDescriptor]) + let result = try SymbolicDemangler.buildGenericSignature(for: [] as [GenericRequirementDescriptor], in: .inProcess) #expect(result == nil) } diff --git a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift index c6de4dc3d..336b07f29 100644 --- a/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift +++ b/Tests/SwiftInspectionTests/SymbolicManglingIndexTests.swift @@ -131,7 +131,7 @@ struct SymbolicManglingIndexTests { var localTypeMismatches: [String] = [] for reference in SymbolicManglingIndex.shared.references(in: machOFile) where reference.kind == .directContextDescriptor { guard visitedReferencedOffsets.insert(reference.referencedOffset).inserted else { continue } - let context: ContextDescriptorWrapper = try .resolve(from: reference.referencedOffset, in: machOFile) + let context: ContextDescriptorWrapper = try .resolve(at: reference.referencedOffset, in: machOFile.context) switch context { case .type, .protocol: break @@ -143,7 +143,7 @@ struct SymbolicManglingIndexTests { "the referent of the reference at \(reference.referenceOffset) does not demangle" ) let compilerSpelledName = Self.printedName(of: referentNode) - let descriptorBuiltName = try Self.printedName(of: SymbolicDemangler.demangleContext(for: context, in: machOFile)) + let descriptorBuiltName = try Self.printedName(of: SymbolicDemangler.demangleContext(for: context, in: machOFile.context)) comparedCount += 1 if descriptorBuiltName != compilerSpelledName { let mismatch = "descriptor \(descriptorBuiltName), compiler \(compilerSpelledName)" @@ -238,7 +238,7 @@ struct SymbolicManglingIndexTests { private static func classDescriptor(named name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { for typeContextDescriptor in try machO.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor else { continue } - if try classDescriptor.name(in: machO) == name { + if try classDescriptor.name(in: machO.context) == name { return classDescriptor } } diff --git a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift index 607fa28df..fc519210c 100644 --- a/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift +++ b/Tests/SwiftInterfaceTests/CrossImageOpaqueReferenceTests.swift @@ -161,9 +161,9 @@ struct CrossImageOpaqueReferenceTests { private func resolvedWitnessTexts(in machOFile: MachOFile, spelling: OpaqueReferenceSpelling = .textualInterface) async throws -> [String: String] { var texts: [String: String] = [:] for associatedType in try machOFile.swift.associatedTypes { - let conformer = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machOFile)).print(using: DemangleOptions.default) - for record in associatedType.records where try record.name(in: machOFile) == "B" { - let node = try SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machOFile), in: machOFile) + let conformer = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machOFile.context)).print(using: DemangleOptions.default) + for record in associatedType.records where try record.name(in: machOFile.context) == "B" { + let node = try SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machOFile.context), in: machOFile.context) texts[conformer] = await node.resolveOpaqueTypeCollectingConditionalCandidates(in: machOFile, spelling: spelling).node.print(using: DemangleOptions.default) } } diff --git a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift index e966554d4..bb238bbf4 100644 --- a/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift +++ b/Tests/SwiftInterfaceTests/CustomObjCClassNameInterfaceTests.swift @@ -189,7 +189,7 @@ struct SystemFrameworkCustomObjCClassNameTests { private static func classDescriptor(named name: String, in machO: some MachOSwiftSectionRepresentableWithCache) throws -> ClassDescriptor? { for typeContextDescriptor in try machO.swift.typeContextDescriptors { guard case .class(let classDescriptor) = typeContextDescriptor else { continue } - if try classDescriptor.name(in: machO) == name { + if try classDescriptor.name(in: machO.context) == name { return classDescriptor } } diff --git a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift index dc7960843..593bdf33c 100644 --- a/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift +++ b/Tests/SwiftInterfaceTests/DiffRendererHeaderFailureTests.swift @@ -44,7 +44,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable named name: String, in builder: SwiftDiffableInterfaceBuilder ) -> TypeDefinition? { - builder.indexer.allTypeDefinitions.values.first { $0.typeName.currentName == name } + builder.indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == name } } /// Injecting a type whose header cannot be rendered must not add a single @@ -121,7 +121,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable // renderer sees on the side carrying the collector. let hostDefinition = try #require(findTypeDefinition(named: "Classes", in: newBuilder)) let replacedIndex = try #require( - hostDefinition.typeChildren.firstIndex { $0.typeName.currentName == "FinalClassTest" }, + hostDefinition.typeChildren.firstIndex { $0.typeName.declaredNameForTesting == "FinalClassTest" }, "fixture must nest FinalClassTest inside Classes for this injection to land on the matched entry" ) hostDefinition.typeChildren[replacedIndex] = try makeUnrenderableDefinition(borrowingNameFrom: "FinalClassTest", in: newBuilder) @@ -162,7 +162,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable // intact copy untouched. let oldHost = try #require(findTypeDefinition(named: "Classes", in: oldBuilder)) let replacedIndex = try #require( - oldHost.typeChildren.firstIndex { $0.typeName.currentName == "FinalClassTest" }, + oldHost.typeChildren.firstIndex { $0.typeName.declaredNameForTesting == "FinalClassTest" }, "fixture must nest FinalClassTest inside Classes for this test to exercise the two-sided path" ) oldHost.typeChildren[replacedIndex] = try makeUnrenderableDefinition(borrowingNameFrom: "FinalClassTest", in: oldBuilder) @@ -216,7 +216,7 @@ final class DiffRendererHeaderFailureTests: MachOFileTests, @unchecked Sendable /// Assert the premise rather than trust the fixture to hold still. private func requireAbsentFromHost(_ name: String, host: TypeDefinition) throws { try #require( - !host.typeChildren.contains { $0.typeName.currentName == name }, + !host.typeChildren.contains { $0.typeName.declaredNameForTesting == name }, "\(name) must not already be nested under the host, or this test silently stops covering the `.added` path" ) } diff --git a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift index 6e01cdbe1..4ee532e95 100644 --- a/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift +++ b/Tests/SwiftInterfaceTests/EvolutionMarkingTests.swift @@ -170,6 +170,110 @@ struct EvolutionMarkingTests { #expect(EvolutionMarking.renderBlock(block, versions: versionAxis).string == "struct Foo {\n\n}") } + // MARK: - Availability attributes + + /// The whole expressibility matrix: an attribute is emitted only when it + /// can tell the complete presence story — everything else stays with the + /// bitmap comment (evolution proposal + /// draft-evolution-interface-available-annotations). + @Test func introducedOnlyLifecycleRendersTheAttribute() { + let lifecycle = annotation([false, true, true], [LineageEvent(versionIndex: 1, status: .added)]) + #expect( + EvolutionMarking.availabilityAttributeText(for: lifecycle, versions: versionAxis, platform: "macOS") + == "@available(macOS, introduced: 2.0)" + ) + } + + @Test func obsoletedOnlyLifecycleRendersTheAttribute() { + let lifecycle = annotation([true, true, false], [LineageEvent(versionIndex: 2, status: .removed)]) + #expect( + EvolutionMarking.availabilityAttributeText(for: lifecycle, versions: versionAxis, platform: "macOS") + == "@available(macOS, obsoleted: 3.0)" + ) + } + + @Test func boundedLifecycleRendersBothClauses() { + let lifecycle = annotation( + [false, true, false], + [LineageEvent(versionIndex: 1, status: .added), LineageEvent(versionIndex: 2, status: .removed)] + ) + #expect( + EvolutionMarking.availabilityAttributeText(for: lifecycle, versions: versionAxis, platform: "iOS") + == "@available(iOS, introduced: 2.0, obsoleted: 3.0)" + ) + } + + /// Present from the first version = predates the axis: there is no + /// introduction fact, and a modified-only history has no `@available` + /// vocabulary at all. + @Test func presentThroughoutLifecycleCarriesNoAttribute() { + let lifecycle = annotation([true, true, true], [LineageEvent(versionIndex: 2, status: .modified)]) + #expect(EvolutionMarking.availabilityAttributeText(for: lifecycle, versions: versionAxis, platform: "macOS") == nil) + } + + /// A disappeared-and-returned shape (`●○●`) is two presence intervals — + /// no single attribute can carry it. + @Test func multiIntervalLifecycleIsNotExpressible() { + let lifecycle = annotation( + [true, false, true], + [LineageEvent(versionIndex: 1, status: .removed), LineageEvent(versionIndex: 2, status: .added)] + ) + #expect(EvolutionMarking.availabilityAttributeText(for: lifecycle, versions: versionAxis, platform: "macOS") == nil) + } + + /// An involved label that is not a dotted numeric version cannot become a + /// version literal — but an unparsable label at an UNINVOLVED axis + /// position must not block the attribute. + @Test func onlyInvolvedLabelsMustParseAsVersions() { + let mixedAxis = [ + ABIVersionDescriptor(label: "Baseline"), + ABIVersionDescriptor(label: "2.0"), + ABIVersionDescriptor(label: "beta3"), + ] + let introducedAtParsable = annotation([false, true, true], [LineageEvent(versionIndex: 1, status: .added)]) + #expect( + EvolutionMarking.availabilityAttributeText(for: introducedAtParsable, versions: mixedAxis, platform: "macOS") + == "@available(macOS, introduced: 2.0)" + ) + let removedAtUnparsable = annotation([true, true, false], [LineageEvent(versionIndex: 2, status: .removed)]) + #expect(EvolutionMarking.availabilityAttributeText(for: removedAtUnparsable, versions: mixedAxis, platform: "macOS") == nil) + } + + /// Defensive: a presence bitmap not aligned with the axis proves nothing. + @Test func misalignedPresenceBitmapCarriesNoAttribute() { + let lifecycle = annotation([false, true], [LineageEvent(versionIndex: 1, status: .added)]) + #expect(EvolutionMarking.availabilityAttributeText(for: lifecycle, versions: versionAxis, platform: "macOS") == nil) + } + + @Test func availabilityVersionAcceptsOneToThreeNumericComponents() { + #expect(EvolutionMarking.availabilityVersion(fromLabel: "26") == "26") + #expect(EvolutionMarking.availabilityVersion(fromLabel: "18.5") == "18.5") + #expect(EvolutionMarking.availabilityVersion(fromLabel: "18.5.1") == "18.5.1") + #expect(EvolutionMarking.availabilityVersion(fromLabel: "SwiftUI") == nil) + #expect(EvolutionMarking.availabilityVersion(fromLabel: "18.5.1.2") == nil) + #expect(EvolutionMarking.availabilityVersion(fromLabel: "18.") == nil) + #expect(EvolutionMarking.availabilityVersion(fromLabel: " 18.5") == nil) + } + + /// The attribute prepends as its own line at the unit's indent level, + /// carrying no annotation of its own; an empty unit stays empty. + @Test func attributePrependsAboveTheUnit() { + let declarationLine = EvolutionLine( + content: "func bar()", + indentLevel: 1, + annotation: annotation([false, true, true], [LineageEvent(versionIndex: 1, status: .added)]) + ) + let lines = EvolutionMarking.prependingAvailabilityAttribute("@available(macOS, introduced: 2.0)", to: [declarationLine], indentLevel: 1) + #expect(lines.count == 2) + #expect(lines[0].content.string == "@available(macOS, introduced: 2.0)") + #expect(lines[0].indentLevel == 1) + #expect(lines[0].annotation == nil) + #expect(lines[1].content.string == "func bar()") + + #expect(EvolutionMarking.prependingAvailabilityAttribute(nil, to: [declarationLine], indentLevel: 1).count == 1) + #expect(EvolutionMarking.prependingAvailabilityAttribute("@available(macOS, introduced: 2.0)", to: [], indentLevel: 1).isEmpty) + } + // MARK: - Legend & warnings @Test func legendNamesTheAxisAndMapsBitmapPositions() { @@ -181,6 +285,17 @@ struct EvolutionMarkingTests { """) } + /// The availability semantic-resolution note appears exactly when + /// attributes are enabled — the default legend stays byte-identical. + @Test func legendGainsTheAvailabilityNoteOnlyWhenEnabled() { + let evolution = ABIEvolution(versions: versionAxis) + let defaultLegend = EvolutionMarking.legendLines(for: evolution).string + #expect(!defaultLegend.contains("@available")) + let annotatedLegend = EvolutionMarking.legendLines(for: evolution, availabilityAnnotationPlatform: "iOS").string + #expect(annotatedLegend.hasPrefix(defaultLegend)) + #expect(annotatedLegend.contains("// @available(iOS, …) attributes are axis-resolution facts")) + } + @Test func warningsAreNilWithoutDiagnostics() { #expect(EvolutionMarking.warningsLines(for: ABIEvolution(versions: versionAxis)) == nil) } diff --git a/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift new file mode 100644 index 000000000..110c1d473 --- /dev/null +++ b/Tests/SwiftInterfaceTests/ExecutableImageSymbolOffsetTests.swift @@ -0,0 +1,322 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import MachOSwiftSection +import Demangling +import SwiftDeclarationRendering +import SwiftInterface +@testable import SwiftDump +@_spi(Internals) @testable import MachOSymbols +@testable import MachOTestingSupport +import MachOFixtureSupport + +/// 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 +/// 0 — the control. Both carry the linker's debug map (`-g`), so their symbol +/// tables also hold STABS entries. +/// +/// A symbol table entry's value is a virtual address, while every offset +/// `MachOSwiftSection` keys by is a file offset. In a dylib the two coincide, +/// which is why the gap went unnoticed; in an executable they differ by the +/// base address, so the index filed every symbol 0x100000000 too high. +enum ExecutableImageFixture { + enum Variant: String, CaseIterable, Sendable { + case executable + case library + } + + static let moduleName = "ExecutableImageFixture" + + /// `alpha` and `beta` own vtable slots. `sharedNames` and `hiddenNames` + /// are static stored properties, each with a STABS `N_GSYM` entry of the + /// value 0 under its storage symbol's name. `hiddenNames` is internal, so + /// its storage symbol is local, and the linker writes local symbols + /// BEFORE the debug map — the order in which the entry overwrote the + /// symbol. The class gives both builds a `__DATA` segment, as every + /// on-the-fly fixture in this repository needs. + static let librarySource = """ + open class OffsetHost { + public var storedValue: Int = 0 + public init() {} + open func alpha() -> Int { storedValue + 1 } + open func beta() -> Int { storedValue + 2 } + public static let sharedNames: [String] = ["first", "second"] + static let hiddenNames: [String] = ["third"] + public func hiddenCount() -> Int { Self.hiddenNames.count } + } + """ + + static let mainSource = """ + let host = OffsetHost() + print(host.alpha() + host.beta(), OffsetHost.sharedNames.count) + """ + + struct CompilationError: Swift.Error, CustomStringConvertible { + let step: String + let diagnostics: String + var description: String { "\(ExecutableImageFixture.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. + 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 librarySourceURL = workingDirectory.appendingPathComponent("OffsetHost.swift") + let mainSourceURL = workingDirectory.appendingPathComponent("main.swift") + try librarySource.write(to: librarySourceURL, atomically: true, encoding: .utf8) + try mainSource.write(to: mainSourceURL, atomically: true, encoding: .utf8) + let executableURL = workingDirectory.appendingPathComponent(moduleName) + let libraryURL = workingDirectory.appendingPathComponent("lib\(moduleName).dylib") + // The language mode pinned so CI's toolchain and a newer local one + // compile the same source the same way; `-g` leaves the debug map + // in the symbol table. + let commonArguments = ["swiftc", "-swift-version", "5", "-Onone", "-g", "-module-name", moduleName] + try run(step: "swiftc (executable)", commonArguments + [librarySourceURL.path, mainSourceURL.path, "-o", executableURL.path]) + try run(step: "swiftc (library)", commonArguments + ["-emit-library", librarySourceURL.path, "-o", libraryURL.path]) + return [.executable: executableURL, .library: libraryURL] + } + }() + + 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)) + } + } + + static func url(_ variant: Variant) throws -> URL { + let products = try compilationResult.get() + guard let url = products[variant] else { + throw CompilationError(step: "lookup", diagnostics: "no product for variant \(variant.rawValue)") + } + return url + } + + static func machOFile(_ variant: Variant) throws -> MachOFile { + switch try MachOKit.loadFromFile(url: try url(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 library loaded into the test process. The executable cannot be: + /// `dlopen` refuses an `MH_EXECUTE` image. + static func loadedLibraryImage() throws -> MachOImage { + let libraryURL = try url(.library) + _ = 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") + } +} + +extension MachOFile.Symbol { + /// A debug-map entry (`N_STAB`): it describes a symbol for the debugger + /// and is not one. An `N_GSYM` entry carries the value 0. + fileprivate var isDebuggingEntry: Bool { + nlist.flags?.stab != nil + } + + /// Defined in one of the image's sections — not an import, not an + /// absolute value, not a debug-map entry. + fileprivate var isDefinedInSection: Bool { + !isDebuggingEntry && nlist.sectionNumber != nil + } + + /// The entry's value, which is the symbol's virtual address. + fileprivate var address: UInt64 { + UInt64(bitPattern: Int64(offset)) + } +} + +/// Symbol offsets in a main executable, and STABS entries in any image. +@Suite(.serialized, ExclusiveImageAccess(ExecutableImageFixture.moduleName)) +struct ExecutableImageSymbolOffsetTests { + private func interface(of machO: some MachOFieldLayoutRenderable) async throws -> String { + var configuration = SwiftInterfaceBuilderConfiguration() + configuration.printConfiguration.printVTableOffset = true + configuration.printConfiguration.printMemberAddress = true + 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") + } + + private func hexadecimal(_ address: UInt64) -> String { + String(address, radix: 16, uppercase: true) + } + + private func definedSwiftSymbol(withSuffix suffix: String, in machOFile: MachOFile) throws -> MachOFile.Symbol { + let symbol = machOFile.symbols.first { $0.isDefinedInSection && $0.name.isSwiftSymbol && $0.name.hasSuffix(suffix) } + return try #require(symbol, "fixture is missing a defined symbol ending in \(suffix)") + } + + // MARK: - Symbol offsets + + /// Every defined Swift symbol is found at its file offset — the + /// accounting every descriptor-derived offset (a vtable slot's + /// implementation, a witness) uses to ask for it. + @Test(arguments: ExecutableImageFixture.Variant.allCases) + func everySymbolIsIndexedAtItsFileOffset(variant: ExecutableImageFixture.Variant) throws { + let machOFile = try ExecutableImageFixture.machOFile(variant) + var checkedCount = 0 + var missedNames: [String] = [] + for symbol in machOFile.symbols where symbol.isDefinedInSection && symbol.name.isSwiftSymbol { + let fileOffset = try #require(machOFile.fileOffset(of: symbol.address), "\(symbol.name) lies in no segment") + let namesAtOffset = machOFile.symbols(offset: Int(fileOffset))?.map(\.name) ?? [] + if !namesAtOffset.contains(symbol.name) { + missedNames.append(symbol.name) + } + checkedCount += 1 + } + #expect(checkedCount > 10, "the fixture should define more Swift symbols than that") + #expect(missedNames.isEmpty, "\(missedNames.count) of \(checkedCount) symbols not found at their file offset, e.g. \(missedNames.prefix(3))") + } + + /// `swiftSymbols` vends the same offsets as the index, and no debug-map + /// entry. + @Test(arguments: ExecutableImageFixture.Variant.allCases) + func swiftSymbolsCarryFileOffsets(variant: ExecutableImageFixture.Variant) throws { + let machOFile = try ExecutableImageFixture.machOFile(variant) + var expectedOffsetByName: [String: Int] = [:] + for symbol in machOFile.symbols where symbol.isDefinedInSection && symbol.name.isSwiftSymbol { + expectedOffsetByName[symbol.name] = Int(try #require(machOFile.fileOffset(of: symbol.address))) + } + var mismatchedNames: [String] = [] + for symbol in machOFile.swiftSymbols where expectedOffsetByName[symbol.name] != nil { + if symbol.offset != expectedOffsetByName[symbol.name] { + mismatchedNames.append(symbol.name) + } + } + #expect(mismatchedNames.isEmpty, "\(mismatchedNames.count) symbols at the wrong offset, e.g. \(mismatchedNames.prefix(3))") + let debuggingEntryNames = Set(machOFile.symbols.filter(\.isDebuggingEntry).map(\.name)) + let vendedNamesAtHeader = machOFile.swiftSymbols.filter { $0.offset == 0 && debuggingEntryNames.contains($0.name) }.map(\.name) + #expect(vendedNamesAtHeader.isEmpty, "\(vendedNamesAtHeader)") + } + + /// The symbolic-mangling table keys by the same accounting: its offsets + /// are where the mangled names are READ from. + @Test(arguments: ExecutableImageFixture.Variant.allCases) + func symbolicManglingSymbolsSitAtTheirFileOffsets(variant: ExecutableImageFixture.Variant) throws { + let machOFile = try ExecutableImageFixture.machOFile(variant) + var expectedOffsetByName: [String: Int] = [:] + for symbol in machOFile.symbols where symbol.isDefinedInSection && SymbolicManglingSymbolName.hasPrefix(symbol.name) { + 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)) + var collectedOffsetByName: [String: Int] = [:] + for symbol in collectedSymbols { + collectedOffsetByName[symbol.name] = symbol.offset + } + #expect(collectedOffsetByName == expectedOffsetByName) + } + + /// A member's address comment is the address its symbol is defined at — + /// what a disassembler opened on the same file shows. + @Test(arguments: ExecutableImageFixture.Variant.allCases) + func memberAddressesAreTheSymbolAddresses(variant: ExecutableImageFixture.Variant) async throws { + let machOFile = try ExecutableImageFixture.machOFile(variant) + let hostBlock = try #require(block(startingWith: "class OffsetHost", in: try await interface(of: machOFile))) + + let alphaSymbol = try definedSwiftSymbol(withSuffix: "5alphaSiyF", in: machOFile) + let sharedNamesStorageSymbol = try definedSwiftSymbol(withSuffix: "11sharedNamesSaySSGvpZ", in: machOFile) + let hiddenNamesStorageSymbol = try definedSwiftSymbol(withSuffix: "11hiddenNamesSaySSGvpZ", in: machOFile) + #expect(hostBlock.contains("// Address: 0x\(hexadecimal(alphaSymbol.address))\n"), "\(hostBlock)") + #expect(hostBlock.contains("// Address: 0x\(hexadecimal(sharedNamesStorageSymbol.address))\n"), "\(hostBlock)") + // The local storage symbol, which its debug-map entry overwrote + // with 0 — printed `Address: 0x0` before the fix. + #expect(hostBlock.contains("// Address: 0x\(hexadecimal(hiddenNamesStorageSymbol.address))\n"), "\(hostBlock)") + + // No address may point anywhere but at a defined symbol. + let symbolAddresses = Set(machOFile.symbols.filter(\.isDefinedInSection).map(\.address)) + let printedAddresses = hostBlock.matches(of: /Address[^:]*: 0x([0-9A-F]+)/).compactMap { UInt64($0.output.1, radix: 16) } + #expect(!printedAddresses.isEmpty, "\(hostBlock)") + let strayAddresses = printedAddresses.filter { !symbolAddresses.contains($0) } + #expect(strayAddresses.isEmpty, "addresses naming no symbol: \(strayAddresses.map(hexadecimal))\n\(hostBlock)") + } + + /// The vtable is joined to its symbols through the implementation + /// offsets: every slot is named and the members print in slot order. + @Test(arguments: ExecutableImageFixture.Variant.allCases) + func vtableSlotsAreNamed(variant: ExecutableImageFixture.Variant) async throws { + let machOFile = try ExecutableImageFixture.machOFile(variant) + let hostDescriptor = try #require(try machOFile.swift.typeContextDescriptors.compactMap { wrapper -> ClassDescriptor? in + guard case .class(let classDescriptor) = wrapper else { return nil } + return try classDescriptor.name(in: machOFile.context) == "OffsetHost" ? classDescriptor : nil + }.first) + var configuration = DumperConfiguration.demangleOptions(.test) + configuration.printVTableOffset = true + let dump = try await Class(descriptor: hostDescriptor, in: machOFile.context).dump(using: configuration, in: machOFile).string + #expect(!dump.contains("sub_"), "\(dump)") + #expect(!dump.contains("unnamed vtable slot"), "\(dump)") + + let hostBlock = try #require(block(startingWith: "class OffsetHost", in: try await interface(of: machOFile))) + let alphaRange = try #require(hostBlock.range(of: "func alpha()"), "\(hostBlock)") + let betaRange = try #require(hostBlock.range(of: "func beta()"), "\(hostBlock)") + #expect(alphaRange.lowerBound < betaRange.lowerBound, "members must print in slot order\n\(hostBlock)") + } + + // MARK: - STABS entries + + /// A debug-map entry never decides where a symbol is filed. `N_GSYM` + /// entries carry the value 0, so one indexed like a symbol was filed at + /// the mach header; and since the table keeps the LAST value it saw for + /// a name, every symbol listed before its debug-map entry — the local + /// ones — took the value 0 (`memberAddressesAreTheSymbolAddresses` shows + /// the printed result). The entry may still open its name's row, which + /// keeps members in the debug map's (source) order; the SymbolTestsCore + /// snapshot suites pin that order. + @Test(arguments: ExecutableImageFixture.Variant.allCases) + func debuggingEntriesNeverDecideAnOffset(variant: ExecutableImageFixture.Variant) throws { + let machOFile = try ExecutableImageFixture.machOFile(variant) + let debuggingEntryNames = Set(machOFile.symbols.filter { $0.isDebuggingEntry && $0.name.isSwiftSymbol && $0.offset == 0 }.map(\.name)) + try #require(!debuggingEntryNames.isEmpty, "premise: `-g` left `N_GSYM` entries in the symbol table") + let namesAtHeader = machOFile.symbols(offset: 0)?.map(\.name) ?? [] + #expect(namesAtHeader.isEmpty, "\(namesAtHeader)") + } + + /// RuntimeViewer's path: the image's own symbol table, read in-process. + @Test func debuggingEntriesNeverDecideAnInProcessOffset() throws { + let machOImage = try ExecutableImageFixture.loadedLibraryImage() + try #require(machOImage.symbols.contains { $0.nlist.flags?.stab != nil && $0.name.isSwiftSymbol }, "premise: the loaded image's symbol table keeps its debug map") + let namesAtHeader = machOImage.symbols(offset: 0)?.map(\.name) ?? [] + #expect(namesAtHeader.isEmpty, "\(namesAtHeader)") + } +} diff --git a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift index 6cef24465..bccb48392 100644 --- a/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCImplementationClassRecognitionTests.swift @@ -48,6 +48,15 @@ struct ObjCImplementationClassRecognitionTests { #expect(widget.contains("@objc func refresh()")) #expect(widget.contains("@objc func describe() -> Swift.String")) #expect(!widget.contains("@objc var swiftOnlyCache")) + // A `private` property and a `lazy var`'s storage: their field-offset + // symbols name the variable through a `privateDeclName`. Both render as + // storage as well — the lazy one folded onto its property with the + // getter's type, as a Swift type's own lazy field is. + #expect(widget.contains("var hiddenTally: Swift.Int\n")) + #expect(widget.contains("lazy var summary: Swift.String\n")) + #expect(!widget.contains("var summary: Swift.String {")) + #expect(!widget.contains("$__lazy_storage_$_")) + #expect(!widget.contains("stored property")) // Definitive: no inference marker. #expect(!widget.contains("inferred from ObjC class data")) } @@ -58,6 +67,8 @@ struct ObjCImplementationClassRecognitionTests { #expect(widget.contains("// Field offset: 0x8\n @objc var title: Swift.String")) #expect(widget.contains("// Field offset: 0x18\n @objc var count: Swift.Int")) #expect(widget.contains("// Field offset: 0x20\n var swiftOnlyCache: [Swift.Int]")) + #expect(widget.contains("// Field offset: 0x28\n var hiddenTally: Swift.Int")) + #expect(widget.contains("// Field offset: 0x30\n lazy var summary: Swift.String")) } @Test func negativeControlsStayPlainExtensionsOrClasses() async throws { @@ -84,6 +95,8 @@ struct ObjCImplementationClassRecognitionTests { #expect(widget.contains("// stored property title: Swift type not recoverable (ObjC ivar, offset 0x8, size 16, encoding \"?\")")) #expect(widget.contains("// stored property count: Swift type not recoverable (ObjC ivar, offset 0x18, size 8, encoding \"q\")")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable (ObjC ivar, offset 0x20, size 8, encoding \"\")")) + #expect(widget.contains("// stored property hiddenTally: Swift type not recoverable (ObjC ivar, offset 0x28, size 8, encoding \"\")")) + #expect(widget.contains("// stored property $__lazy_storage_$_summary: Swift type not recoverable (ObjC ivar, offset 0x30, size 16, encoding \"\")")) } // MARK: - Inferred tier: no Swift symbol at all @@ -92,7 +105,7 @@ struct ObjCImplementationClassRecognitionTests { let interface = try await interface(of: .strippedEverything) // The class has no member symbol left, so the extension is synthesized // from the ObjC side alone — and labelled as an inference. - let widget = try #require(block(named: "@objc @implementation /* inferred from ObjC class data: 2 ivars carry Swift-style type encodings */ extension __C.Widget {", in: interface)) + let widget = try #require(block(named: "@objc @implementation /* inferred from ObjC class data: 4 ivars carry Swift-style type encodings */ extension __C.Widget {", in: interface)) #expect(widget.contains("// stored property title: Swift type not recoverable")) #expect(widget.contains("// stored property swiftOnlyCache: Swift type not recoverable")) // The clang class has complete encodings and no Swift symbols: silent @@ -110,11 +123,11 @@ struct ObjCImplementationClassRecognitionTests { return } #expect(reasons.contains(.metadataAccessorSymbol(name: "_$sSo6WidgetCMa"))) - #expect(reasons.contains(.fieldOffsetSymbols(count: 3))) + #expect(reasons.contains(.fieldOffsetSymbols(count: 5))) #expect(reasons.contains { if case .swiftSymbolsAtMethodImplementations = $0 { return true } else { return false } }) #expect(facts.implementingModuleName == ObjCImplementationFixture.moduleName) #expect(facts.superclassName == "NSObject") - #expect(facts.instanceVariables.count == 3) + #expect(facts.instanceVariables.count == 5) // The header-declared property's ivar carries an EMPTY name in this // fixture; the join through the field-offset global's value still // pairs it with `title`. @@ -126,6 +139,21 @@ struct ObjCImplementationClassRecognitionTests { let swiftOnlyCache = try #require(facts.instanceVariable(forSwiftPropertyNamed: "swiftOnlyCache")) #expect(swiftOnlyCache.typeEncoding.isEmpty) #expect(!swiftOnlyCache.isObjCVisible) + // A `private` property's field-offset symbol names the variable through + // a `privateDeclName`, and so does a `lazy var`'s storage. + let hiddenTally = try #require(facts.instanceVariable(forSwiftPropertyNamed: "hiddenTally")) + #expect(hiddenTally.offset == 0x28) + #expect(hiddenTally.swiftTypeNode != nil) + #expect(hiddenTally.swiftFieldOffsetSymbolName?.contains("11hiddenTally33_") == true) + let summaryStorage = try #require(facts.instanceVariable(forSwiftPropertyNamed: "$__lazy_storage_$_summary")) + #expect(summaryStorage.offset == 0x30) + #expect(summaryStorage.size == 16) + #expect(summaryStorage.swiftTypeNode != nil) + // The storage answers for the `lazy var` it belongs to. + #expect(summaryStorage.lazyPropertyName == "summary") + #expect(hiddenTally.lazyPropertyName == nil) + #expect(facts.storageInstanceVariable(forPropertyNamed: "summary") === summaryStorage) + #expect(facts.storageInstanceVariable(forPropertyNamed: "title") === title) // The class's own method list is the Swift `To` thunks. let initWithTitle = try #require(facts.instanceMethods.first { $0.selector == "initWithTitle:" }) #expect(initWithTitle.implementationSymbolNames.contains { $0.hasSuffix("tcfcTo") }) @@ -158,7 +186,7 @@ struct ObjCImplementationClassRecognitionTests { @Test func fullyStrippedFactsAreInferred() throws { let machOFile = try ObjCImplementationFixture.machOFile(.strippedEverything) let facts = try #require(ObjCImplementationClasses.facts(forClassNamed: "Widget", in: machOFile)) - #expect(facts.evidence == .inferred(swiftStyleEncodedInstanceVariableCount: 2)) + #expect(facts.evidence == .inferred(swiftStyleEncodedInstanceVariableCount: 4)) #expect(facts.instanceVariables.allSatisfy { $0.swiftFieldOffsetSymbolName == nil }) #expect(ObjCImplementationClasses.facts(forClassNamed: "ClangWidget", in: machOFile) == nil) } @@ -175,7 +203,7 @@ struct ObjCImplementationClassRecognitionTests { #expect(Set(recognized.map(\.className)) == ["Widget", "DerivedImplementationWidget"]) let widget = try #require(recognized.first { $0.className == "Widget" }) #expect(widget.isInferred == false) - #expect(widget.instanceVariableCount == 3) + #expect(widget.instanceVariableCount == 5) // Informational, not a failure: it must not reach the zero-handler floor. #expect(SwiftIndexEvents.Payload.objcImplementationClassRecognized(context: recognized[0]).unhandledFailureDescription == nil) #expect(SwiftIndexEvents.Payload.objcImplementationClassSkipped(className: "X", reason: "unreadable").unhandledFailureDescription != nil) diff --git a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift index 39e649d8d..2ca9691ba 100644 --- a/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift +++ b/Tests/SwiftInterfaceTests/ObjCMemberRecoveryTests.swift @@ -628,6 +628,22 @@ struct ObjCMemberRecoveryTests { // MARK: - Shapes + /// A `private` / `fileprivate` member's name is the second child of a + /// `privateDeclName`, not an `identifier`; the first version of the shape + /// reader saw no name there and gave such a member no shape at all. + @Test func privateMembersHaveShapes() throws { + let getter = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo17NSGlassEffectViewC6AppKitE11hiddenTally33_0123456789ABCDEF0123456789ABCDEFLLSivg"))) + #expect(getter.kind == .getter(propertyName: "hiddenTally")) + #expect(getter.ownerQualifiedName == "__C.NSGlassEffectView") + #expect(getter.isConsistent(withSelector: "hiddenTally", isClassMethod: false)) + + let method = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo17NSGlassEffectViewC6AppKitE9recompute33_0123456789ABCDEF0123456789ABCDEFLLyyF"))) + #expect(method.kind == .method(baseName: "recompute", labels: [], arity: 0)) + #expect(method.isConsistent(withSelector: "recompute", isClassMethod: false)) + let methodThunk = try #require(ObjCMemberShape(demangledSymbol: try demangleAsNode("$sSo17NSGlassEffectViewC6AppKitE9recompute33_0123456789ABCDEF0123456789ABCDEFLLyyFTo"))) + #expect(methodThunk == method) + } + @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/PrintFailureEventTests.swift b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift index 774876f69..ec9e21571 100644 --- a/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift +++ b/Tests/SwiftInterfaceTests/PrintFailureEventTests.swift @@ -66,7 +66,7 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { } private func findTypeDefinition(named name: String, in indexer: SwiftDeclarationIndexer) -> TypeDefinition? { - indexer.allTypeDefinitions.values.first { $0.typeName.currentName == name } + indexer.allTypeDefinitions.values.first { $0.typeName.declaredNameForTesting == name } } /// A real struct descriptor re-wrapped at an offset far past the fixture's @@ -170,14 +170,10 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { // Stream writes that predate this rule, in paths evolution 0005 did not // touch. Listed rather than ignored: the set may shrink, never grow — - // a new offender in any other file fails this test. Paying these down is - // its own change (they are debug tracing and error prints in the - // descriptor-wrapper and layout-analysis layers, not the degradation - // reporting this proposal restructured). + // a new offender in any other file fails this test. What is left is + // debug output by design: the spare-bit analyzer's table printer and a + // fixture-support dump helper. let knownBaselineDebt: Set = [ - "ContextDescriptorWrapper.swift", - "TypeContextDescriptorWrapper.swift", - "SubstitutionMap.swift", "SpareBitAnalyzer.swift", "DumpableTests.swift", ] @@ -272,9 +268,10 @@ final class PrintFailureEventTests: MachOFileTests, @unchecked Sendable { 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" { + // `Sources///…`: the module is two levels below `Sources`. let moduleName = fileURL.pathComponents .drop(while: { $0 != "Sources" }) - .dropFirst() + .dropFirst(2) .first if let moduleName, hostModules.contains(moduleName) { continue } files.append(fileURL) diff --git a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift index 4e090bfcc..1be05d8c5 100644 --- a/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift +++ b/Tests/SwiftInterfaceTests/ProjectedOpaqueMemberWitnessTests.swift @@ -179,9 +179,9 @@ struct ProjectedOpaqueMemberWitnessTests { /// indexer both obtain it. private func elementResolution(in machOFile: MachOFile) throws -> Node.OpaqueTypeResolution? { for associatedType in try machOFile.swift.associatedTypes { - for record in associatedType.records where try record.name(in: machOFile) == "Element" { - let witnessMangledName = try record.substitutedTypeName(in: machOFile) - let node = try SymbolicDemangler.demangleType(for: witnessMangledName, in: machOFile) + for record in associatedType.records where try record.name(in: machOFile.context) == "Element" { + let witnessMangledName = try record.substitutedTypeName(in: machOFile.context) + let node = try SymbolicDemangler.demangleType(for: witnessMangledName, in: machOFile.context) return node.resolveOpaqueTypeCollectingConditionalCandidates(witnessMangledName: witnessMangledName, conformingTypeName: associatedType.conformingTypeName, in: machOFile) } } diff --git a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift index f4b73e2dd..725dabe4d 100644 --- a/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift +++ b/Tests/SwiftInterfaceTests/SwiftEvolutionInterfaceBuilderTests.swift @@ -304,6 +304,65 @@ struct SwiftEvolutionInterfaceBuilderTests { #expect(directionPosition.lowerBound < legacyPosition.lowerBound) } + /// With `availabilityAnnotationPlatform` set, every fully-expressible + /// lifecycle gains a genuine `@available` attribute line directly above + /// its declaration (at the declaration's own indentation), while the + /// bitmap comment stays untouched; inexpressible lifecycles (modified-only + /// histories) and never-changed declarations stay attribute-free, and the + /// default configuration emits no attribute anywhere. + @Test func availabilityAttributesRenderWhenConfigured() async throws { + let builder = try AnySwiftEvolutionInterfaceBuilder( + versions: try loadFixtureMachOFiles(), + labels: ["1.0", "2.0", "3.0"], + availabilityAnnotationPlatform: "macOS" + ) + try await builder.prepare() + let interface = try await builder.printAnnotatedInterface().string + let lines = interface.split(separator: "\n", omittingEmptySubsequences: false).map(String.init) + func lineIndex(containing needles: String...) throws -> Int { + try #require( + lines.firstIndex { line in needles.allSatisfy(line.contains) }, + "no line containing \(needles) in:\n\(interface)" + ) + } + func attributeLine(above declarationIndex: Int) -> String { + lines[declarationIndex - 1].trimmingCharacters(in: .whitespaces) + } + func indentation(of line: String) -> Substring { + line.prefix { $0 == " " } + } + + // Legend carries the semantic-resolution note. + #expect(lines[2].contains("// @available(macOS, …) attributes are axis-resolution facts")) + + // Added member: introduced-only attribute, same indentation as the + // declaration, bitmap comment still on the declaration line. + let addedIndex = try lineIndex(containing: "func bar(id:") + #expect(attributeLine(above: addedIndex) == "@available(macOS, introduced: 2.0)") + #expect(indentation(of: lines[addedIndex - 1]) == indentation(of: lines[addedIndex])) + #expect(lines[addedIndex].contains("// [○●●] added in 2.0")) + + // Removed member: obsoleted-only attribute. + let removedIndex = try lineIndex(containing: "func bar()", "->") + #expect(attributeLine(above: removedIndex) == "@available(macOS, obsoleted: 3.0)") + + // Removed container: the attribute sits above the whole header. + let removedClassIndex = try lineIndex(containing: "Legacy", "{") + #expect(attributeLine(above: removedClassIndex) == "@available(macOS, obsoleted: 2.0)") + + // Modified-only field: no @available vocabulary — bitmap comment only. + let modifiedIndex = try lineIndex(containing: "modified in 3.0") + #expect(!lines[modifiedIndex - 1].contains("@available")) + + // Never-changed declaration: bare. + let unchangedIndex = try lineIndex(containing: "var title") + #expect(!lines[unchangedIndex - 1].contains("@available")) + + // The default configuration emits no attribute anywhere. + let defaultInterface = try await preparedBuilder().printAnnotatedInterface().string + #expect(!defaultInterface.contains("@available(")) + } + // MARK: - Structured stream & evolution reuse @Test func structuredStreamAlignsWithTheVersionAxis() async throws { diff --git a/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift new file mode 100644 index 000000000..ebadd090d --- /dev/null +++ b/Tests/SwiftInterfaceTests/VisibilityRegionProjectionTests.swift @@ -0,0 +1,138 @@ +@_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 MachOTestingSupport +import MachOFixtureSupport + +/// A marked print (`SwiftDeclarationPrintConfiguration.marksOptionalContent`), +/// projected to a configuration, reads byte for byte as printing with that +/// configuration — for every root type, root protocol and extension of the +/// SymbolTestsCore fixture, printed in process (the runtime layout path, +/// which RuntimeViewer takes) and from the file (the static layout path). +/// +/// RuntimeViewer's Find searches one marked print per declaration under +/// whatever options the user displays with (evolution proposal +/// `visibility-regions`); this is the contract that stands on. A new output +/// point an option controls that is not marked shows up here: the +/// projection keeps it where the plain print drops it. +@Suite(.serialized) +final class VisibilityRegionProjectionTests: MachOSwiftSectionFixtureTests, @unchecked Sendable { + /// Everything off, everything on, and each of `varied` alone and left + /// out. + private static func optionCombinations(varying varied: [SwiftVisibilityOption]) -> [Set] { + let allOptions = Set(SwiftVisibilityOption.allCases) + var combinations: [Set] = [[], allOptions] + for option in varied { + combinations.append([option]) + combinations.append(allOptions.subtracting([option])) + } + return combinations + } + + /// The options whose output the file path works out differently from + /// the in-process path: the layout comments. Everything else prints the + /// same way from either, and the in-process test varies all of it. + private static let layoutOptions: [SwiftVisibilityOption] = [.printFieldOffset, .printExpandedFieldOffsets, .printTypeLayout, .printEnumLayout] + + private static func configuration(enabling options: Set) -> SwiftDeclarationPrintConfiguration { + var configuration = SwiftDeclarationPrintConfiguration() + configuration.printStrippedSymbolicItem = options.contains(.printStrippedSymbolicItem) + configuration.printFieldOffset = options.contains(.printFieldOffset) + configuration.printExpandedFieldOffsets = options.contains(.printExpandedFieldOffsets) + configuration.printMemberAddress = options.contains(.printMemberAddress) + configuration.printVTableOffset = options.contains(.printVTableOffset) + configuration.printPWTOffset = options.contains(.printPWTOffset) + configuration.printTypeLayout = options.contains(.printTypeLayout) + configuration.printEnumLayout = options.contains(.printEnumLayout) + configuration.infersObjCOverridesFromSelectorNames = options.contains(.infersObjCOverridesFromSelectorNames) + return configuration + } + + private static func makePrinter( + _ configuration: SwiftDeclarationPrintConfiguration, + resolvesOpaqueTypes: Bool, + in machO: MachO + ) -> SwiftDeclarationPrinter where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + let printer = SwiftDeclarationPrinter(configuration: configuration, in: machO) + if resolvesOpaqueTypes { + printer.addTypeNameResolver(SwiftInterfaceBuilderOpaqueTypeProvider(machO: machO)) + } + return printer + } + + /// Prints every declaration marked and plainly under every combination, + /// and describes the first few whose projection differs. + private static func mismatches( + in machO: MachO, + optionCombinations: [Set] + ) async throws -> (checkedDeclarationCount: Int, mismatches: [String]) where MachO: MachOFieldLayoutRenderable & MachOSwiftSectionRepresentableWithCache & Sendable { + let indexer = SwiftDeclarationIndexer(in: machO) + try await indexer.prepare() + + var markedConfiguration = SwiftDeclarationPrintConfiguration() + markedConfiguration.marksOptionalContent = true + let markedPrinter = makePrinter(markedConfiguration, resolvesOpaqueTypes: true, in: machO) + let plainPrinters = optionCombinations.map { options in + (options, configuration(enabling: options), makePrinter(configuration(enabling: options), resolvesOpaqueTypes: options.contains(.opaqueTypeResolution), in: machO)) + } + + typealias Printing = (SwiftDeclarationPrinter) async throws -> SemanticString + var printings: [(label: String, print: Printing)] = [] + // Definitions are classes the printers index in place; the printings + // run one after another, as the fixture tests always do. + for (name, definition) in indexer.rootTypeDefinitions { + nonisolated(unsafe) let unsafeDefinition = definition + printings.append(("type \(name)", { try await $0.printTypeDefinition(unsafeDefinition) })) + } + for (name, definition) in indexer.rootProtocolDefinitions { + nonisolated(unsafe) let unsafeDefinition = definition + printings.append(("protocol \(name)", { try await $0.printProtocolDefinition(unsafeDefinition) })) + } + let extensionGroups = [indexer.typeExtensionDefinitions, indexer.protocolExtensionDefinitions, indexer.typeAliasExtensionDefinitions, indexer.conformanceExtensionDefinitions] + for extensionGroup in extensionGroups { + for (name, definitions) in extensionGroup { + for definition in definitions { + nonisolated(unsafe) let unsafeDefinition = definition + printings.append(("extension \(name)", { try await $0.printExtensionDefinition(unsafeDefinition) })) + } + } + } + + var mismatches: [String] = [] + for printing in printings { + let separated = try await printing.print(markedPrinter).frozen().separatingVisibilityRegions() + for (options, configuration, printer) in plainPrinters { + let expected = try await printing.print(printer).frozen() + let projected = separated.regions.projection(of: separated.text) { + configuration.isVisibilityOptionEnabled($0, resolvesOpaqueTypes: options.contains(.opaqueTypeResolution)) + }.text + if projected != expected { + let enabled = SwiftVisibilityOption.allCases.filter(options.contains).map(\.rawValue) + mismatches.append("\(printing.label) with \(enabled):\n\(projected.string)\n--- expected ---\n\(expected.string)") + break + } + } + if mismatches.count >= 5 { break } + } + return (printings.count, mismatches) + } + + @Test func inProcessPrintsProjectToEveryConfiguration() async throws { + let result = try await Self.mismatches(in: machOImage, optionCombinations: Self.optionCombinations(varying: SwiftVisibilityOption.allCases)) + #expect(result.checkedDeclarationCount > 100) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } + + @Test func filePrintsProjectToEveryConfiguration() async throws { + let result = try await Self.mismatches(in: machOFile, optionCombinations: Self.optionCombinations(varying: Self.layoutOptions)) + #expect(result.checkedDeclarationCount > 100) + #expect(result.mismatches.isEmpty, "\(result.mismatches.joined(separator: "\n\n"))") + } +} diff --git a/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift b/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift index 791bdbccd..48f82f1c8 100644 --- a/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift +++ b/Tests/SwiftLayoutTests/BuiltinTypeLayoutTests.swift @@ -70,7 +70,7 @@ final class BuiltinTypeLayoutTests: MachOSwiftSectionFixtureTests, @unchecked Se var resolved: StaticTypeLayout? for contextDescriptor in try machO.swift.contextDescriptors { guard - let node = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO), + let node = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext), NodeTypeNaming.nominalQualifiedName(of: node) == targetName else { continue } resolved = try resolver.layout(forTypeNode: node, in: universe.rootImage) diff --git a/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift new file mode 100644 index 000000000..573abd833 --- /dev/null +++ b/Tests/SwiftLayoutTests/CacheRootDependencyLayoutTests.swift @@ -0,0 +1,44 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +import Demangling +@testable import MachOSwiftSection +@testable import SwiftLayout +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 ArchivedMacOS15LayoutFixtures { + static let cachePath = DyldSharedCachePath.macOS_15_5 + static var hasCache: Bool { FileManager.default.fileExists(atPath: cachePath.rawValue) } + + static func swiftUICore() throws -> MachOFile { + let cache = try FullDyldCache(path: cachePath) + return try #require( + cache.machOFile(by: .path("/System/Library/Frameworks/SwiftUICore.framework/Versions/A/SwiftUICore")), + "the macOS 15.5 cache has no SwiftUICore" + ) + } +} + +/// `Foundation.URL` is resilient, so SwiftUICore's `LinkDestination.Configuration` +/// takes its `url` field's size from whichever Foundation the closure finds. +/// In macOS 15.5 that is Foundation's own field records: `_url: NSURL`, +/// `_parseInfo: URLParseInfo?` and `_baseParseInfo: URLParseInfo?`, 24 bytes. +/// macOS 26 rebuilt `URL` around a single `any _URLProtocol & AnyObject`, 16 +/// bytes, and that is what an archived cache's image read when its closure +/// fell through to the host's cache. +@Suite(.enabled(if: ArchivedMacOS15LayoutFixtures.hasCache)) +struct CacheRootDependencyLayoutTests { + @Test("A cache image lays out another module's type against its own cache") + func resilientTypeFromAnotherModuleTakesTheRootCachesLayout() throws { + let root = try ArchivedMacOS15LayoutFixtures.swiftUICore() + let universe = try ImageUniverse.dependencyClosure(root: root) + let resolver = StaticTypeLayoutResolver(imageUniverse: universe) + let urlNode = try demangleAsNode("10Foundation3URLV", isType: true) + let urlLayout = try resolver.layout(forTypeNode: urlNode, in: universe.rootImage) + #expect(urlLayout.size == 24) + } +} diff --git a/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift b/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift index 27a470f0f..e2cea3526 100644 --- a/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ClassBoundParameterLayoutTests.swift @@ -246,18 +246,18 @@ final class ClassBoundParameterLayoutTests: MachOSwiftSectionFixtureTests, @unch for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName, - let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) + let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context) else { continue } let response = try accessor(request: .init(), metatypes: firstArgumentMetatype, secondArgumentMetatype) - let metadata = try response.value.resolve(in: machO) + let metadata = try response.value.resolve(in: machO.context) switch metadata { case .struct(let structMetadata): - return try structMetadata.fieldOffsets(in: machO).map { Int($0) } + return try structMetadata.fieldOffsets(in: machO.context).map { Int($0) } case .class(let classMetadata): - return try classMetadata.fieldOffsets(in: machO).map { Int($0) } + return try classMetadata.fieldOffsets(in: machO.context).map { Int($0) } default: return nil } diff --git a/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift b/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift index ae53f1029..d459b505d 100644 --- a/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ExistentialLayoutTests.swift @@ -50,7 +50,7 @@ final class ExistentialLayoutTests: MachOSwiftSectionFixtureTests, @unchecked Se guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard descriptor.isStruct || descriptor.isClass else { continue } guard - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), let expectedOffsets = Self.expectedFieldOffsets[qualifiedTypeName] else { continue } diff --git a/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift b/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift index 851ab24cd..684a14b1d 100644 --- a/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ForeignStructTopLevelLayoutTests.swift @@ -30,7 +30,7 @@ final class ForeignStructTopLevelLayoutTests: MachOSwiftSectionFixtureTests, @un guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isStruct, - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), qualifiedTypeName == "__C.NSDecimal" else { continue } @@ -77,7 +77,7 @@ final class ForeignStructTopLevelLayoutTests: MachOSwiftSectionFixtureTests, @un guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isStruct, - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), qualifiedTypeName == "__C.CMTime" else { continue } diff --git a/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift b/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift index 484a0bcd6..ae5e420c9 100644 --- a/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift +++ b/Tests/SwiftLayoutTests/GenericSpareBitsEnumLayoutTests.swift @@ -61,7 +61,7 @@ final class GenericSpareBitsEnumLayoutTests: MachOSwiftSectionFixtureTests, @unc for contextDescriptor in try machOFile.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, - (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machOFile)) + (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: fileContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)) == holderName else { continue } let fileLayout = try fileCalculator.typeLayout(forDescriptor: descriptor) @@ -124,7 +124,7 @@ final class GenericSpareBitsEnumLayoutTests: MachOSwiftSectionFixtureTests, @unc let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isStruct, !descriptor.typeContextDescriptor.layout.flags.isGeneric, - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: rootFile)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: rootFile.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), targetNameSuffixes.contains(where: { qualifiedTypeName.hasSuffix($0) }) else { continue } @@ -158,7 +158,7 @@ final class GenericSpareBitsEnumLayoutTests: MachOSwiftSectionFixtureTests, @unc for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)) == qualifiedTypeName else { continue } return descriptor @@ -174,10 +174,9 @@ final class GenericSpareBitsEnumLayoutTests: MachOSwiftSectionFixtureTests, @unc _ staticLayout: StaticTypeLayout, for descriptor: TypeContextDescriptorWrapper ) throws { - let machO = machOImage - guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) else { return } + guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: imageContext) else { return } let response = try accessor(request: .init()) - let valueWitnessTable = try response.value.resolve(in: machO).valueWitnessTable(in: machO) + let valueWitnessTable = try response.value.resolve(in: imageContext).valueWitnessTable(in: imageContext) #expect(Int(valueWitnessTable.layout.size) == staticLayout.size) #expect(Int(valueWitnessTable.layout.stride) == staticLayout.stride) #expect(Int(valueWitnessTable.layout.flags.alignment) == staticLayout.alignment) @@ -194,12 +193,12 @@ final class GenericSpareBitsEnumLayoutTests: MachOSwiftSectionFixtureTests, @unc for contextDescriptor in (try? machO.swift.contextDescriptors) ?? [] { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, - (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)) == qualifiedTypeName, - let accessor = try? descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO), + let accessor = try? descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context), let response = try? accessor(request: .init()), - let metadata = try? response.value.resolve(in: machO), - let valueWitnessTable = try? metadata.valueWitnessTable(in: machO) + let metadata = try? response.value.resolve(in: machO.context), + let valueWitnessTable = try? metadata.valueWitnessTable(in: machO.context) else { continue } return ( size: Int(valueWitnessTable.layout.size), diff --git a/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift b/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift index 1d07c2441..ce9a90280 100644 --- a/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift +++ b/Tests/SwiftLayoutTests/MetatypeAndGenericEnumProjectionLayoutTests.swift @@ -144,7 +144,7 @@ final class MetatypeAndGenericEnumProjectionLayoutTests: MachOSwiftSectionFixtur for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isEnum else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName else { continue } diff --git a/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift b/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift index 8ef60b14c..85dd63a35 100644 --- a/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift +++ b/Tests/SwiftLayoutTests/MultiPayloadEnumStructuralTests.swift @@ -43,7 +43,7 @@ final class MultiPayloadEnumStructuralTests: MachOSwiftSectionFixtureTests, @unc !descriptor.typeContextDescriptor.layout.flags.isGeneric else { continue } guard - let node = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO), + let node = try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext), let qualifiedTypeName = NodeTypeNaming.nominalQualifiedName(of: node), qualifiedTypeName.hasPrefix("SymbolTests") else { continue } diff --git a/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift b/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift index a393a065b..4c981e940 100644 --- a/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift +++ b/Tests/SwiftLayoutTests/NestedFieldExtentTests.swift @@ -74,11 +74,11 @@ struct NestedFieldExtentTests { let calculator = try StaticLayoutCalculator(machO: machOFile) for typeContext in try machOFile.swift.types { guard case .struct(let structType) = typeContext, - try structType.descriptor.name(in: machOFile) == structName else { continue } - let records = try structType.descriptor.fieldDescriptor(in: machOFile).records(in: machOFile) - let record = try #require(records.first { (try? $0.fieldName(in: machOFile)) == fieldName }) + try structType.descriptor.name(in: machOFile.context) == structName else { continue } + let records = try structType.descriptor.fieldDescriptor(in: machOFile.context).records(in: machOFile.context) + let record = try #require(records.first { (try? $0.fieldName(in: machOFile.context)) == fieldName }) return calculator.nestedFieldOffsetTree( - forMangledTypeName: try record.mangledTypeName(in: machOFile), + forMangledTypeName: try record.mangledTypeName(in: machOFile.context), baseOffset: 32, depthLimit: 8 ) } @@ -176,11 +176,11 @@ struct NestedFieldExtentTests { let rootFile = try MachOFile(url: directory.appendingPathComponent("libExtentRoot.dylib")) let rootType = try #require(try rootFile.swift.types.first { typeContext in guard case .struct(let structType) = typeContext else { return false } - return (try? structType.descriptor.name(in: rootFile)) == "Envelope" + return (try? structType.descriptor.name(in: rootFile.context)) == "Envelope" }) guard case .struct(let envelope) = rootType else { return } - let record = try #require(try envelope.descriptor.fieldDescriptor(in: rootFile).records(in: rootFile).first) - let typeName = try record.mangledTypeName(in: rootFile) + let record = try #require(try envelope.descriptor.fieldDescriptor(in: rootFile.context).records(in: rootFile.context).first) + let typeName = try record.mangledTypeName(in: rootFile.context) let unavailableUniverse = try ImageUniverse.dependencyClosure(root: rootFile, searchPaths: []) #expect(StaticLayoutCalculator(imageUniverse: unavailableUniverse).nestedFieldOffsetTree( forMangledTypeName: typeName, baseOffset: 32, depthLimit: 4 diff --git a/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift b/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift index ca9768ca8..1f141ee07 100644 --- a/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift +++ b/Tests/SwiftLayoutTests/ObjCAncestorSlideLayoutTests.swift @@ -64,7 +64,7 @@ final class ObjCAncestorSlideLayoutTests: MachOSwiftSectionFixtureTests, @unchec let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isClass, !descriptor.typeContextDescriptor.layout.flags.isGeneric, - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: rootFile)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: rootFile.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), targetNameSuffixes.contains(where: { qualifiedTypeName.contains($0) }) else { continue } @@ -100,10 +100,10 @@ final class ObjCAncestorSlideLayoutTests: MachOSwiftSectionFixtureTests, @unchec guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isClass, - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName, - let accessor = try? descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO), + let accessor = try? descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context), let response = try? accessor(request: .init()) else { continue } let anyClass = unsafeBitCast(UInt(response.value.address), to: AnyClass.self) diff --git a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift index ea3951a14..92e3c043f 100644 --- a/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift +++ b/Tests/SwiftLayoutTests/RawLayoutBuiltinDescriptorLayoutTests.swift @@ -166,7 +166,7 @@ struct RawLayoutBuiltinDescriptorFieldOffsetTests { var holderDescriptor: TypeContextDescriptorWrapper? for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)).flatMap(NodeTypeNaming.nominalQualifiedName(of:)), + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)).flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName else { continue } holderDescriptor = descriptor diff --git a/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift b/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift index 230e80012..23bda9c40 100644 --- a/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift +++ b/Tests/SwiftLayoutTests/RecursiveNestedFieldOffsetTreeTests.swift @@ -31,17 +31,17 @@ final class RecursiveNestedFieldOffsetTreeTests: MachOSwiftSectionFixtureTests, for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isStruct else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: fileContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName else { continue } - let records = try descriptor.typeContextDescriptor.fieldDescriptor(in: machO).records(in: machO) + let records = try descriptor.typeContextDescriptor.fieldDescriptor(in: fileContext).records(in: fileContext) let record = try #require( - records.first { (try? $0.fieldName(in: machO)) == targetFieldName }, + records.first { (try? $0.fieldName(in: fileContext)) == targetFieldName }, "\(qualifiedTypeName) has no stored property named \(targetFieldName)" ) - let mangledTypeName = try record.mangledTypeName(in: machO) + let mangledTypeName = try record.mangledTypeName(in: fileContext) return calculator.nestedFieldOffsetTree( forMangledTypeName: mangledTypeName, baseOffset: 0, diff --git a/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift b/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift new file mode 100644 index 000000000..fafdd3c56 --- /dev/null +++ b/Tests/SwiftLayoutTests/SimulatorRuntimeObjCAncestorLayoutTests.swift @@ -0,0 +1,56 @@ +import Foundation +import Testing +import MachOKit +import MachOFoundation +@testable import MachOSwiftSection +@testable import SwiftLayout + +/// Where the simulator-runtime-gated suite below finds its runtime. 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 IOS18SimulatorRuntimeFixtures { + /// The iOS 18.5 simulator runtime's `RuntimeRoot`, on whichever volume + /// CoreSimulator mounted it. + static let runtimeRootPath: String? = { + let volumesDirectory = "/Library/Developer/CoreSimulator/Volumes" + let runtimeSuffix = "Library/Developer/CoreSimulator/Profiles/Runtimes/iOS 18.5.simruntime/Contents/Resources/RuntimeRoot" + let volumeNames = (try? FileManager.default.contentsOfDirectory(atPath: volumesDirectory)) ?? [] + return volumeNames.sorted() + .map { "\(volumesDirectory)/\($0)/\(runtimeSuffix)" } + .first { FileManager.default.fileExists(atPath: "\($0)/System/Library/Frameworks/SwiftUI.framework/SwiftUI") } + }() + + static func swiftUI(underRuntimeRoot runtimeRootPath: String) throws -> MachOFile { + let url = URL(fileURLWithPath: "\(runtimeRootPath)/System/Library/Frameworks/SwiftUI.framework/SwiftUI") + switch try MachOKit.loadFromFile(url: url) { + case .machO(let thinFile): + return thinFile + case .fat(let fatFile): + return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }, "the runtime's SwiftUI has no arm64 slice") + } + } +} + +/// A simulator runtime's frameworks are linked `-interposable`, so UIKitCore +/// reaches every class it exports through a bind to itself — its class list +/// entry included. Reading only rebases, the ObjC reader lost 1,586 of +/// UIKitCore's 5,017 classes, `UIDocument` among them, and a Swift class +/// deriving from one could not place its own fields: +/// `// Field offset: unknown (Objective-C ancestor UIDocument unresolved)`. +@Suite(.enabled(if: IOS18SimulatorRuntimeFixtures.runtimeRootPath != nil)) +struct SimulatorRuntimeObjCAncestorLayoutTests { + @Test("A Swift class places its fields after an ObjC ancestor its dependency binds to itself") + func fieldsStartAfterASelfBoundObjCAncestor() throws { + let runtimeRootPath = try #require(IOS18SimulatorRuntimeFixtures.runtimeRootPath) + let swiftUI = try IOS18SimulatorRuntimeFixtures.swiftUI(underRuntimeRoot: runtimeRootPath) + let universe = try ImageUniverse.dependencyClosure(root: swiftUI, searchPaths: [.systemRoot(path: runtimeRootPath)]) + let calculator = StaticLayoutCalculator(imageUniverse: universe) + // The universe indexes the root's types up front; scanning SwiftUI's + // descriptors again by name would demangle every one of them. + let platformDocumentDescriptor = try #require(universe.resolveType(byQualifiedTypeName: "SwiftUI.PlatformDocument")?.descriptor) + let platformDocument = try calculator.fieldLayout(of: platformDocumentDescriptor) + // `UIDocument`'s `class_ro_t.instanceSize` in the runtime's UIKitCore + // is 0xc4 (read with xxd); its subclass's first field is 8-aligned. + #expect(platformDocument.computedFieldOffsets.first == 0xc8) + } +} diff --git a/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift b/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift index 5f99ce180..3b5cfd7fd 100644 --- a/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift +++ b/Tests/SwiftLayoutTests/StaticLayoutVsRuntimeTests.swift @@ -50,23 +50,23 @@ final class StaticLayoutVsRuntimeTests: MachOSwiftSectionFixtureTests, @unchecke // C bitfield layout is not reflected in Swift field records) are out // of scope until the dependency-closure phase. guard - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), qualifiedTypeName.hasPrefix("SymbolTests") else { continue } // Ground truth: the runtime field-offset vector via the metadata // accessor. - guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) else { continue } + guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: imageContext) else { continue } let runtimeOffsets: [Int] do { let response = try accessor(request: .init()) - let metadata = try response.value.resolve(in: machO) + let metadata = try response.value.resolve(in: imageContext) switch metadata { case .struct(let structMetadata): - runtimeOffsets = try structMetadata.fieldOffsets(in: machO).map { Int($0) } + runtimeOffsets = try structMetadata.fieldOffsets(in: imageContext).map { Int($0) } case .class(let classMetadata): - runtimeOffsets = try classMetadata.fieldOffsets(in: machO).map { Int($0) } + runtimeOffsets = try classMetadata.fieldOffsets(in: imageContext).map { Int($0) } default: continue } @@ -92,7 +92,7 @@ final class StaticLayoutVsRuntimeTests: MachOSwiftSectionFixtureTests, @unchecke // The computed prefix must always equal the runtime prefix. let runtimePrefix = Array(runtimeOffsets.prefix(staticOffsets.count)) if staticOffsets != runtimePrefix { - let typeName = (try? descriptor.typeContextDescriptor.name(in: machO)) ?? qualifiedTypeName + let typeName = (try? descriptor.typeContextDescriptor.name(in: imageContext)) ?? qualifiedTypeName mismatches.append(Mismatch( typeName: typeName, runtimeOffsets: runtimeOffsets, diff --git a/Tests/SwiftLayoutTests/Support/StaticLayoutTestSupport.swift b/Tests/SwiftLayoutTests/Support/StaticLayoutTestSupport.swift index 273b999a9..9ed726aaf 100644 --- a/Tests/SwiftLayoutTests/Support/StaticLayoutTestSupport.swift +++ b/Tests/SwiftLayoutTests/Support/StaticLayoutTestSupport.swift @@ -25,7 +25,7 @@ func fieldLayout( guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard descriptor.isStruct || descriptor.isClass else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName else { continue } @@ -50,7 +50,7 @@ func fieldLayout( guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard descriptor.isStruct || descriptor.isClass else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName else { continue } @@ -74,18 +74,18 @@ func runtimeFieldOffsets( for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName, - let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) + let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context) else { continue } let response = try accessor(request: .init(), metatypes: argumentMetatype) - let metadata = try response.value.resolve(in: machO) + let metadata = try response.value.resolve(in: machO.context) switch metadata { case .struct(let structMetadata): - return try structMetadata.fieldOffsets(in: machO).map { Int($0) } + return try structMetadata.fieldOffsets(in: machO.context).map { Int($0) } case .class(let classMetadata): - return try classMetadata.fieldOffsets(in: machO).map { Int($0) } + return try classMetadata.fieldOffsets(in: machO.context).map { Int($0) } default: return nil } @@ -100,18 +100,18 @@ func runtimeFieldOffsets(ofQualifiedTypeName qualifiedTypeName: String, in machO for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName, - let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) + let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context) else { continue } let response = try accessor(request: .init()) - let metadata = try response.value.resolve(in: machO) + let metadata = try response.value.resolve(in: machO.context) switch metadata { case .struct(let structMetadata): - return try structMetadata.fieldOffsets(in: machO).map { Int($0) } + return try structMetadata.fieldOffsets(in: machO.context).map { Int($0) } case .class(let classMetadata): - return try classMetadata.fieldOffsets(in: machO).map { Int($0) } + return try classMetadata.fieldOffsets(in: machO.context).map { Int($0) } default: return nil } @@ -131,14 +131,14 @@ func runtimeValueWitnessLayout( for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName, - let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) + let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context) else { continue } let response = try accessor(request: .init()) - let metadata = try response.value.resolve(in: machO) - let valueWitnessTable = try metadata.valueWitnessTable(in: machO) + let metadata = try response.value.resolve(in: machO.context) + let valueWitnessTable = try metadata.valueWitnessTable(in: machO.context) return ( Int(valueWitnessTable.layout.size), Int(valueWitnessTable.layout.stride), @@ -156,10 +156,10 @@ func runtimeMetatype(ofQualifiedTypeName qualifiedTypeName: String, in machO: Ma for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName, - let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) + let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO.context) else { continue } let response = try accessor(request: .init()) return unsafeBitCast(UInt(response.value.address), to: Any.Type.self) diff --git a/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift b/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift index 9bb7480e0..a0f528e75 100644 --- a/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift +++ b/Tests/SwiftLayoutTests/TopLevelGenericInstantiationLayoutTests.swift @@ -133,13 +133,13 @@ final class TopLevelGenericInstantiationLayoutTests: MachOSwiftSectionFixtureTes for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper, descriptor.isStruct || descriptor.isClass else { continue } guard - let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let name = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO.context)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), name == qualifiedTypeName else { continue } - let records = try descriptor.typeContextDescriptor.fieldDescriptor(in: machO).records(in: machO) - for record in records where (try? record.fieldName(in: machO)) == fieldName { - return try record.mangledTypeName(in: machO) + let records = try descriptor.typeContextDescriptor.fieldDescriptor(in: machO.context).records(in: machO.context) + for record in records where (try? record.fieldName(in: machO.context)) == fieldName { + return try record.mangledTypeName(in: machO.context) } } return nil diff --git a/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift b/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift index 9c8f9cbe0..9fb3d8abc 100644 --- a/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift +++ b/Tests/SwiftLayoutTests/WholeTypeLayoutVsRuntimeTests.swift @@ -86,18 +86,18 @@ final class WholeTypeLayoutVsRuntimeTests: MachOSwiftSectionFixtureTests, @unche // its instance layout is validated field-by-field by the offset suite. guard descriptor.isStruct || descriptor.isEnum else { continue } guard - let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + let qualifiedTypeName = (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)), qualifiedTypeName.hasPrefix("SymbolTests") else { continue } // Ground truth: the runtime value-witness table. - guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) else { continue } + guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: imageContext) else { continue } let runtime: WitnessedLayout do { let response = try accessor(request: .init()) - let metadata = try response.value.resolve(in: machO) - let valueWitnessTable = try metadata.valueWitnessTable(in: machO) + let metadata = try response.value.resolve(in: imageContext) + let valueWitnessTable = try metadata.valueWitnessTable(in: imageContext) runtime = WitnessedLayout( size: Int(valueWitnessTable.layout.size), stride: Int(valueWitnessTable.layout.stride), @@ -119,7 +119,7 @@ final class WholeTypeLayoutVsRuntimeTests: MachOSwiftSectionFixtureTests, @unche let witnessed = Self.witnessedLayout(of: staticLayout) if witnessed != runtime { - let typeName = (try? descriptor.typeContextDescriptor.name(in: machO)) ?? qualifiedTypeName + let typeName = (try? descriptor.typeContextDescriptor.name(in: imageContext)) ?? qualifiedTypeName mismatches.append(Mismatch(typeName: typeName, runtime: runtime, staticLayout: witnessed)) } } @@ -145,7 +145,7 @@ final class WholeTypeLayoutVsRuntimeTests: MachOSwiftSectionFixtureTests, @unche for contextDescriptor in try machO.swift.contextDescriptors { guard let descriptor = contextDescriptor.typeContextDescriptorWrapper else { continue } guard - (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: machO)) + (try? SymbolicDemangler.demangleContext(for: contextDescriptor, in: imageContext)) .flatMap(NodeTypeNaming.nominalQualifiedName(of:)) == qualifiedTypeName else { continue } return descriptor @@ -161,10 +161,9 @@ final class WholeTypeLayoutVsRuntimeTests: MachOSwiftSectionFixtureTests, @unche _ staticLayout: StaticTypeLayout, for descriptor: TypeContextDescriptorWrapper ) throws { - let machO = machOImage - guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: machO) else { return } + guard let accessor = try descriptor.typeContextDescriptor.metadataAccessorFunction(in: imageContext) else { return } let response = try accessor(request: .init()) - let valueWitnessTable = try response.value.resolve(in: machO).valueWitnessTable(in: machO) + let valueWitnessTable = try response.value.resolve(in: imageContext).valueWitnessTable(in: imageContext) #expect(Int(valueWitnessTable.layout.size) == staticLayout.size) #expect(Int(valueWitnessTable.layout.stride) == staticLayout.stride) #expect(Int(valueWitnessTable.layout.flags.alignment) == staticLayout.alignment) diff --git a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift index d0497894c..c4e956e27 100644 --- a/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift +++ b/Tests/SwiftPrintingTests/EnumCaseRenderingParityTests.swift @@ -79,8 +79,8 @@ struct EnumCaseRenderingParityTests: GenericSpecializationTestingEnvironment { var dumpOutput: String? = nil for typeContextDescriptor in try machO.swift.typeContextDescriptors { guard case .enum(let enumDescriptor) = typeContextDescriptor, - try enumDescriptor.name(in: machO) == "VoidPayloadRenderingFixtureEnum" else { continue } - let enumType = try Enum(descriptor: enumDescriptor, in: machO) + try enumDescriptor.name(in: machO.context) == "VoidPayloadRenderingFixtureEnum" else { continue } + let enumType = try Enum(descriptor: enumDescriptor, in: machO.context) dumpOutput = try await enumType.dump(using: .demangleOptions(.interface), in: machO).string break } diff --git a/Tests/SwiftPrintingTests/NodeKindParityTests.swift b/Tests/SwiftPrintingTests/NodeKindParityTests.swift index 51c702ccf..5b6efad22 100644 --- a/Tests/SwiftPrintingTests/NodeKindParityTests.swift +++ b/Tests/SwiftPrintingTests/NodeKindParityTests.swift @@ -114,10 +114,10 @@ enum NodeKindParitySurvey { for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) else { continue } - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile) + guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile.context) else { continue } + for record in try fieldDescriptor.records(in: machOFile.context) { + guard let mangledTypeName = try? record.mangledTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context) else { continue } trees.append(typeNode) } @@ -125,8 +125,8 @@ enum NodeKindParitySurvey { for associatedType in try machOFile.swift.associatedTypes { for record in associatedType.records { - guard let substituted = try? record.substitutedTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: substituted, in: machOFile) + guard let substituted = try? record.substitutedTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: substituted, in: machOFile.context) else { continue } trees.append(typeNode) } diff --git a/Tests/SwiftPrintingTests/NodePrinterTests.swift b/Tests/SwiftPrintingTests/NodePrinterTests.swift index 79b834b3b..f4737653a 100644 --- a/Tests/SwiftPrintingTests/NodePrinterTests.swift +++ b/Tests/SwiftPrintingTests/NodePrinterTests.swift @@ -316,8 +316,8 @@ final class NodePrinterIntegrationTests: DyldCacheTests, @unchecked Sendable { for associatedType in associatedTypes.prefix(10) { for record in associatedType.records.prefix(5) { do { - let substitutedTypeNameMangledName = try record.substitutedTypeName(in: machO) - let node = try SymbolicDemangler.demangleType(for: substitutedTypeNameMangledName, in: machO) + let substitutedTypeNameMangledName = try record.substitutedTypeName(in: machO.context) + let node = try SymbolicDemangler.demangleType(for: substitutedTypeNameMangledName, in: machO.context) var printer = SemanticTypeNodePrinter() let result = try await printer.printRoot(node).string #expect(!result.isEmpty) diff --git a/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift new file mode 100644 index 000000000..782cbdb45 --- /dev/null +++ b/Tests/SwiftSectionCommandTests/CommandLineErrorTranslationTests.swift @@ -0,0 +1,60 @@ +import Foundation +import Testing +import ArgumentParser +import SwiftSectionKit +@testable import swift_section + +/// The library words its errors without naming options; the command line has +/// always named them, and reported a usage mistake as a `ValidationError` +/// (usage text, exit code 64) rather than a plain failure (exit code 1). The +/// translation keeps every message and exit code as it was. +@Suite +struct CommandLineErrorTranslationTests { + @Test("A fat binary without -a names the option, and the slices") + func fatBinary() { + let translated = CommandLineErrorTranslation.translated(MachOSourceError.fatBinaryRequiresArchitecture(availableArchitectures: ["arm64", "x86_64"])) + #expect((translated as? LocalizedError)?.errorDescription == "The file is a fat (universal) binary. You must specify an architecture using --architecture (-a). Available architectures: arm64, x86_64") + } + + @Test("The other loading errors keep their historical wording", arguments: [ + (MachOSourceError.architectureNotFound(.arm64e), "The specified architecture is not found or supported."), + (.dyldSharedCacheImageNotFound(.name("Foundation")), "The specified image was not found in the dyld shared cache."), + ]) + func loadingErrors(error: MachOSourceError, expectedDescription: String) { + #expect((CommandLineErrorTranslation.translated(error) as? LocalizedError)?.errorDescription == expectedDescription) + } + + @Test("A snapshot document given to diff --interface is a usage error in diff's words") + func diffAnnotatedInterface() { + let translated = CommandLineErrorTranslation.translated(SnapshotSourceError.binaryRequired(path: "old.json"), annotatedInterfaceRequiresBinaries: { _ in + "--interface needs two binaries; snapshot JSON inputs only support the change-list report." + }) + #expect((translated as? ValidationError)?.message == "--interface needs two binaries; snapshot JSON inputs only support the change-list report.") + } + + @Test("Without a wording for it, the snapshot-document error passes through") + func snapshotErrorWithoutWording() { + let translated = CommandLineErrorTranslation.translated(SnapshotSourceError.binaryRequired(path: "old.json")) + #expect(translated as? SnapshotSourceError == .binaryRequired(path: "old.json")) + } + + @Test("A platform --emit-available cannot infer is a usage error that points at --platform", arguments: [ + ( + AvailabilityPlatformInferenceError.noPlatform(path: "driver.dylib"), + "--emit-available could not infer an @available platform from driver.dylib (no LC_BUILD_VERSION, or a platform with no @available spelling); pass --platform explicitly." + ), + ( + .conflictingPlatforms(["iOS", "macOS"]), + "--emit-available found conflicting platforms across the inputs (iOS, macOS); pass --platform explicitly." + ), + ]) + func availabilityPlatformInference(error: AvailabilityPlatformInferenceError, 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")) + #expect(translated as? ObjCDeclarationLookupError == .declarationNotFound("NSString")) + } +} diff --git a/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift new file mode 100644 index 000000000..d62696bfa --- /dev/null +++ b/Tests/SwiftSectionCommandTests/CommandRequestMappingTests.swift @@ -0,0 +1,215 @@ +import Foundation +import Testing +import ArgumentParser +import MachOFoundation +import SwiftSectionKit +@testable import swift_section + +/// The wrapper's one job besides wording and streams: turning flags into the +/// library request. A flag that stops reaching its field produces a +/// plausible-looking but wrong product, so each mapping is pinned from the +/// parsed command to the request it makes. +@Suite +struct CommandRequestMappingTests { + // MARK: - Input options + + @Test("A path alone is a file, with the architecture for a fat binary's slice") + func fileInput() throws { + let request = try DumpCommand.parse(["/tmp/Sample", "-a", "arm64e"]).makeRequest() + #expect(request.source == .file(path: "/tmp/Sample", architecture: .arm64e)) + } + + @Test("--dyld-shared-cache extracts the named image from the cache at the path") + func cacheInput() throws { + let request = try DumpCommand.parse(["/tmp/dyld_shared_cache_arm64e", "--dyld-shared-cache", "-n", "SwiftUICore"]).makeRequest() + #expect(request.source == .dyldSharedCache(cachePath: "/tmp/dyld_shared_cache_arm64e", image: .name("SwiftUICore"))) + } + + @Test("--uses-system-dyld-shared-cache needs no path") + func systemCacheInput() throws { + let request = try InterfaceCommand.parse(["--uses-system-dyld-shared-cache", "-p", "/usr/lib/libobjc.A.dylib"]).makeRequest() + #expect(request.source == .systemDyldSharedCache(image: .path("/usr/lib/libobjc.A.dylib"))) + } + + /// These combinations have no `MachOSource`; they keep the wording the + /// command line has always printed for them. + @Test("Input combinations a source cannot express keep their historical errors", arguments: [ + (["--dyld-shared-cache", "-n", "Foundation"], "The filePath is required"), + (["/tmp/cache", "--dyld-shared-cache", "-n", "Foundation", "-p", "/usr/lib/libobjc.A.dylib"], "Both cacheImageName and cacheImagePath are provided"), + (["/tmp/cache", "--dyld-shared-cache"], "Either cacheImageName or cacheImagePath must be provided"), + ([], "The filePath is required"), + ]) + func impossibleInputCombinations(arguments: [String], messagePrefix: String) throws { + let command = try DumpCommand.parse(arguments) + #expect(performing: { _ = try command.makeRequest() }, throws: { error in + (error as? SwiftSectionCommandError)?.errorDescription?.hasPrefix(messagePrefix) == true + }) + } + + @Test("--dependency-search-path is classified into search paths") + func dependencySearchPaths() throws { + let directoryPath = FileManager.default.temporaryDirectory.path + let request = try DumpCommand.parse(["/tmp/Sample", "--dependency-search-path", directoryPath]).makeRequest() + #expect(request.dependencySearchPaths == [DependencySearchPath(classifyingPath: directoryPath)]) + } + + // MARK: - dump + + @Test("dump defaults: every section, section order, no comments, to the output") + func dumpDefaults() throws { + let request = try DumpCommand.parse(["/tmp/Sample"]).makeRequest() + #expect(request == DumpRequest(source: .file(path: "/tmp/Sample", architecture: nil))) + } + + @Test("dump flags reach their fields") + func dumpFlags() throws { + let request = try DumpCommand.parse([ + "/tmp/Sample", + "--sections", "protocols", "types", + "--preferred-binary-order", + "--emit-expanded-field-offsets", + "--emit-member-addresses", "--emit-vtable-offsets", "--emit-pwt-addresses", + "--emit-type-layout", "--emit-enum-layout", "--emit-export-status", "--emit-header", + "--output-path", "out.txt", + ]).makeRequest() + #expect(request.sections == .only([.protocols, .types])) + #expect(request.ordering == .binaryOrder) + #expect(request.fieldOffsetComments == .expanded) + #expect(request.emitsMemberAddresses) + #expect(request.emitsVTableOffsets) + #expect(request.emitsProtocolWitnessTableAddresses) + #expect(request.emitsTypeLayout) + #expect(request.emitsEnumLayout) + #expect(request.emitsExportStatus) + #expect(request.emitsHeader) + #expect(request.destination == .file(path: "out.txt")) + } + + @Test("--emit-field-offsets alone is the flat form") + func dumpFlatFieldOffsets() throws { + #expect(try DumpCommand.parse(["/tmp/Sample", "--emit-field-offsets"]).makeRequest().fieldOffsetComments == .flat) + } + + @Test("A comment template reaches the request as a configuration") + func dumpCommentTemplates() throws { + let request = try DumpCommand.parse(["/tmp/Sample", "--member-address-template", "${offset}"]).makeRequest() + #expect(request.commentTransformers?.swiftMemberAddress.isEnabled == true) + #expect(request.commentTransformers?.swiftMemberAddress.template == "${offset}") + } + + // MARK: - interface + + @Test("interface flags reach their fields") + func interfaceFlags() throws { + let request = try InterfaceCommand.parse([ + "/tmp/Sample", + "--show-c-imported-types", "--parse-opaque-return-type", + "--resolve-c-module-names", "--supplementary-apinotes", "/tmp/Extra.apinotes", + "--emit-offset-comments", "--sort-members-by-offset", "--exported-only", + "--infer-objc-overrides", "--emit-header", + ]).makeRequest() + #expect(request.showsCImportedTypes) + #expect(request.parsesOpaqueReturnTypes) + #expect(request.cModuleNameResolution == .enabled(supplementaryAPINotesPaths: ["/tmp/Extra.apinotes"])) + #expect(request.fieldOffsetComments == .flat) + #expect(request.memberSortOrder == .byOffset) + #expect(request.printsExportedDeclarationsOnly) + #expect(request.infersObjCOverridesFromSelectorNames) + #expect(request.emitsHeader) + } + + @Test("--emit-expanded-field-offsets implies the offset comments") + func interfaceExpandedFieldOffsets() throws { + #expect(try InterfaceCommand.parse(["/tmp/Sample", "--emit-expanded-field-offsets"]).makeRequest().fieldOffsetComments == .expanded) + } + + // MARK: - snapshot / diff / evolution + + @Test("snapshot without a path is a usage error") + func snapshotRequiresAPath() throws { + let command = try SnapshotCommand.parse([]) + #expect(throws: ValidationError.self) { try command.makeRequest() } + } + + @Test("snapshot with --dyld-shared-cache extracts the named image from each binary input") + func snapshotCacheInput() throws { + let request = try SnapshotCommand.parse(["/tmp/cache", "--dyld-shared-cache", "-p", "/usr/lib/libobjc.A.dylib", "--label", "26.0"]).makeRequest() + #expect(request == ABISnapshotRequest( + source: .path("/tmp/cache"), + binaryLoading: BinaryLoadingOptions(dyldSharedCacheImage: .path("/usr/lib/libobjc.A.dylib")), + label: "26.0" + )) + } + + @Test("diff's output flags become one report", arguments: [ + ([String](), ABIDiffRequest.Report.changeList), + (["--summary-only"], .summary), + (["--json"], .json), + (["--interface"], .annotatedInterface(format: .inline, includesBreakingChangeVerdict: false)), + (["--interface", "--format", "unified", "--fail-on-breaking"], .annotatedInterface(format: .unified, includesBreakingChangeVerdict: true)), + (["--interface", "--format", "markdown"], .annotatedInterface(format: .markdownFenced, includesBreakingChangeVerdict: false)), + ]) + func diffReport(flags: [String], expectedReport: ABIDiffRequest.Report) throws { + #expect(try DiffCommand.parse(flags + ["old.dylib", "new.dylib"]).makeRequest().report == expectedReport) + } + + @Test("diff over two caches extracts the same image from each") + func diffCacheInputs() throws { + let request = try DiffCommand.parse(["--dyld-shared-cache", "-n", "SwiftUICore", "--jobs", "1", "old", "new"]).makeRequest() + #expect(request == ABIDiffRequest( + old: .path("old"), + new: .path("new"), + binaryLoading: BinaryLoadingOptions(dyldSharedCacheImage: .name("SwiftUICore")), + maximumConcurrentPreparations: 1 + )) + } + + /// Empty labels are kept, so that a stray comma fails the one-label-per- + /// input check instead of shifting every later label. + @Test("evolution's --labels splits on commas, trims, and keeps empty labels") + func evolutionLabels() throws { + let request = try EvolutionCommand.parse(["--labels", " 17.0 ,,26.0", "a", "b", "c"]).makeRequest() + #expect(request.labels == ["17.0", "", "26.0"]) + #expect(request.inputs == [.path("a"), .path("b"), .path("c")]) + #expect(request.report == .lineage) + } + + @Test("evolution's output flags become one report", arguments: [ + ([String](), ABIEvolutionRequest.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 evolutionReport(flags: [String], expectedReport: ABIEvolutionRequest.Report) throws { + #expect(try EvolutionCommand.parse(flags + ["old.dylib", "new.dylib"]).makeRequest().report == expectedReport) + } + + // MARK: - objc + + @Test("objc dump passes the image description the caller typed") + func objcDumpImageDescription() throws { + let request = try ObjCDumpCommand.parse(["/tmp/cache", "--dyld-shared-cache", "-n", "AppKit", "--sections", "classes,protocols", "--verbose"]).makeRequest() + #expect(request.source == .dyldSharedCache(cachePath: "/tmp/cache", image: .name("AppKit"))) + #expect(request.imageDescription == "AppKit") + #expect(request.kinds == [.classes, .protocols]) + #expect(request.reportsIndexingProgress) + } + + @Test("objc diff's output flags become one report", arguments: [ + ([String](), ObjCAPIDiffRequest.Report.changeList), + (["--summary-only"], .summary), + (["--json"], .json), + ]) + func objcDiffReport(flags: [String], expectedReport: ObjCAPIDiffRequest.Report) throws { + #expect(try ObjCDiffCommand.parse(flags + ["old.dylib", "new.dylib"]).makeRequest().report == expectedReport) + } + + @Test("objc evolution splits --labels the way evolution does") + func objcEvolutionLabels() throws { + let request = try ObjCEvolutionCommand.parse(["--labels", "a, b", "--json", "one", "two"]).makeRequest() + #expect(request.labels == ["a", "b"]) + #expect(request.report == .json) + } +} diff --git a/Tests/SwiftSectionCommandTests/DumpSectionsOptionTests.swift b/Tests/SwiftSectionCommandTests/DumpSectionsOptionTests.swift index f7ece9ead..fca6288d2 100644 --- a/Tests/SwiftSectionCommandTests/DumpSectionsOptionTests.swift +++ b/Tests/SwiftSectionCommandTests/DumpSectionsOptionTests.swift @@ -1,5 +1,6 @@ import Testing import ArgumentParser +import SwiftSectionKit @testable import swift_section /// `dump --sections` accepts the `objcImplementationClasses` section @@ -9,6 +10,6 @@ struct DumpSectionsOptionTests { @Test func objcImplementationClassesIsASection() throws { let command = try DumpCommand.parse(["/tmp/example", "--sections", "types", "objcImplementationClasses"]) #expect(command.sections == [.types, .objcImplementationClasses]) - #expect(SwiftSection.allCases.contains(.objcImplementationClasses)) + #expect(DumpSection.allCases.contains(.objcImplementationClasses)) } } diff --git a/Tests/SwiftSectionCommandTests/EvolutionCommandValidationTests.swift b/Tests/SwiftSectionCommandTests/EvolutionCommandValidationTests.swift index 88b937d29..731b4b529 100644 --- a/Tests/SwiftSectionCommandTests/EvolutionCommandValidationTests.swift +++ b/Tests/SwiftSectionCommandTests/EvolutionCommandValidationTests.swift @@ -65,4 +65,20 @@ struct EvolutionCommandValidationTests { #expect(command.failOnBreaking) #expect(command.inputPaths == ["old.dylib", "new.dylib"]) } + + // MARK: - Availability attributes (--emit-available / --platform) + + @Test func emitAvailableRequiresInterface() { + expectValidationFailure( + ["--emit-available", "old.dylib", "new.dylib"], + messagePart: "--emit-available requires --interface" + ) + } + + @Test func platformRequiresEmitAvailable() { + expectValidationFailure( + ["--interface", "--platform", "iOS", "old.dylib", "new.dylib"], + messagePart: "--platform requires --emit-available" + ) + } } diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift index 82c989b1c..9bdc35af1 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift +++ b/Tests/SwiftSectionCommandTests/ObjC/ObjCSectionCommandTests.swift @@ -201,31 +201,33 @@ struct ObjCSectionCommandTests { // MARK: - Ivar Offset Template @Test("No template option leaves the renderer's own wording in place") - func noTemplateMeansNoBuilder() throws { + func noTemplateMeansNoModule() throws { let command = try ObjCDumpCommand.parse(["/tmp/Sample"]) - #expect(command.transformerOptions.buildIvarOffsetCommentBuilder() == nil) - #expect(command.transformerOptions.impliesIvarOffsetComments == false) + #expect(command.transformerOptions.buildIvarOffsetComment() == nil) + #expect(try command.makeRequest().ivarOffsetComment == nil) } - @Test("A template is applied, and switches ivar offset comments on") - func templateIsAppliedAndImpliesComments() throws { + /// A module in the request is what switches ivar offset comments on in + /// the library, so a template on its own is not inert. + @Test("A template is applied, and reaches the request") + func templateIsAppliedAndReachesTheRequest() throws { let command = try ObjCDumpCommand.parse([ "/tmp/Sample", "--ivar-offset-template", "ivar @ ${offset}", ]) - let builder = try #require(command.transformerOptions.buildIvarOffsetCommentBuilder()) + let module = try #require(command.transformerOptions.buildIvarOffsetComment()) - #expect(builder(16) == "ivar @ 0x10") - #expect(command.transformerOptions.impliesIvarOffsetComments) + #expect(module.transform(.init(offset: 16)) == "ivar @ 0x10") + #expect(try command.makeRequest().ivarOffsetComment == module) } @Test("Decimal formatting is a customization on its own") - func decimalFlagAloneBuildsABuilder() throws { + func decimalFlagAloneBuildsAModule() throws { let command = try ObjCDumpCommand.parse(["/tmp/Sample", "--ivar-offset-decimal"]) - let builder = try #require(command.transformerOptions.buildIvarOffsetCommentBuilder()) + let module = try #require(command.transformerOptions.buildIvarOffsetComment()) - #expect(builder(16) == "offset: 16") - #expect(command.transformerOptions.impliesIvarOffsetComments) + #expect(module.transform(.init(offset: 16)) == "offset: 16") + #expect(try command.makeRequest().ivarOffsetComment == module) } // MARK: - Interface Subcommand diff --git a/Tests/SwiftSectionCommandTests/StandardStreamOutputTests.swift b/Tests/SwiftSectionCommandTests/StandardStreamOutputTests.swift new file mode 100644 index 000000000..a3b361a8e --- /dev/null +++ b/Tests/SwiftSectionCommandTests/StandardStreamOutputTests.swift @@ -0,0 +1,166 @@ +import Foundation +import Testing +@preconcurrency import Rainbow +import Semantic +import SwiftSectionKit +@testable import swift_section + +/// Where the command line puts a request's output, and in which bytes. The +/// streams are memory streams here, so the tests read back exactly what a +/// terminal or a redirect would have received. +/// +/// Serialized because `Rainbow.enabled` is process-wide: the tests pin colors +/// off (or on) for their own duration. +@Suite(.serialized) +struct StandardStreamOutputTests { + /// Runs `body` against two memory streams and returns what each received. + private func capture( + standardOutputSeverities: Set = [], + colorsEnabled: Bool = false, + _ body: (StandardStreamOutput) -> Void + ) -> (standardOutput: String, standardError: String) { + // Rainbow colors only when enabled AND writing to a console; a test + // process's stdout is usually neither, so both are pinned. + let previousColorsEnabled = Rainbow.enabled + let previousOutputTarget = Rainbow.outputTarget + Rainbow.enabled = colorsEnabled + Rainbow.outputTarget = .console + defer { + Rainbow.enabled = previousColorsEnabled + Rainbow.outputTarget = previousOutputTarget + } + + var standardOutputBuffer: UnsafeMutablePointer? + var standardOutputSize = 0 + var standardErrorBuffer: UnsafeMutablePointer? + var standardErrorSize = 0 + guard let standardOutputStream = open_memstream(&standardOutputBuffer, &standardOutputSize), + let standardErrorStream = open_memstream(&standardErrorBuffer, &standardErrorSize) + else { + Issue.record("open_memstream failed") + return ("", "") + } + body(StandardStreamOutput( + standardOutputSeverities: standardOutputSeverities, + standardOutput: standardOutputStream, + standardError: standardErrorStream + )) + fclose(standardOutputStream) + fclose(standardErrorStream) + defer { + free(standardOutputBuffer) + free(standardErrorBuffer) + } + return ( + standardOutputBuffer.map { String(cString: $0) } ?? "", + standardErrorBuffer.map { String(cString: $0) } ?? "" + ) + } + + @Test("Every piece of the product goes to stdout followed by a newline") + func productPieces() { + let captured = capture { output in + output.write(.text("report")) + output.write(.data(Data("{}".utf8))) + output.write(.annotatedInterface("+added\n-removed", style: .diff(isUnifiedDiff: false))) + output.write(.declarations("struct Declaration {}")) + output.write(.text("")) + } + #expect(captured.standardOutput == "report\n{}\n+added\n-removed\nstruct Declaration {}\n\n") + #expect(captured.standardError.isEmpty) + } + + @Test("Diagnostics go to stderr unless the command routes their severity to stdout") + func diagnosticRouting() { + let captured = capture(standardOutputSeverities: [.progress]) { output in + output.report(SwiftSectionDiagnostic(severity: .progress, message: "Building Swift interface...")) + output.report(SwiftSectionDiagnostic(severity: .warning, message: "warning: something degraded")) + output.report(SwiftSectionDiagnostic(severity: .note, message: "no unions found in Sample")) + } + #expect(captured.standardOutput == "Building Swift interface...\n") + #expect(captured.standardError == "warning: something degraded\nno unions found in Sample\n") + } + + /// `dump` has always printed a declaration's failure in red, in line with + /// the declarations around it. + @Test("An error routed to stdout is red when colors are on") + func errorOnStandardOutputIsRed() { + let captured = capture(standardOutputSeverities: [.error], colorsEnabled: true) { output in + output.report(SwiftSectionDiagnostic(severity: .error, message: "failed")) + } + #expect(captured.standardOutput.hasPrefix("\u{1B}[31m")) + #expect(captured.standardOutput.contains("failed")) + } + + @Test("Annotated lines are colored by their kind when colors are on") + func annotatedLinesAreColored() { + let captured = capture(colorsEnabled: true) { output in + output.write(.annotatedInterface("+added\n kept", style: .diff(isUnifiedDiff: false))) + } + let lines = captured.standardOutput.split(separator: "\n") + #expect(lines.first?.hasPrefix("\u{1B}[32m") == true) + #expect(lines.last == " kept") + } +} + +/// Every byte the command line writes goes through `StandardStreamOutput`, +/// which writes with `fwrite`. The `objc` subcommands used to write through +/// `FileHandle.standardOutput/standardError.write(_:)`, whose Objective-C +/// bridge raises an exception Swift cannot catch on a closed stream and aborts +/// the process; the Swift side had already been fixed for `snapshot`. A source +/// scan keeps the whole class out, not just the instances that were found. +@Suite +struct CommandLineStreamWriteScanTests { + private static let commandLineSourcesDirectory = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // SwiftSectionCommandTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root + .appendingPathComponent("Sources/Executables/swift-section") + + @Test("No command-line source writes to a process stream except StandardStreamOutput") + func streamWritesGoThroughTheOutput() throws { + let enumerator = try #require(FileManager.default.enumerator(at: Self.commandLineSourcesDirectory, includingPropertiesForKeys: nil)) + var scannedFileCount = 0 + var offendingLines: [String] = [] + for case let fileURL as URL in enumerator where fileURL.pathExtension == "swift" { + scannedFileCount += 1 + let isTheOutput = fileURL.lastPathComponent == "StandardStreamOutput.swift" + let contents = try String(contentsOf: fileURL, encoding: .utf8) + for (lineIndex, line) in contents.components(separatedBy: .newlines).enumerated() { + let code = line.trimmingCharacters(in: .whitespaces) + guard !code.hasPrefix("//") else { continue } + let writesThroughFileHandle = code.contains("FileHandle.standardOutput") || code.contains("FileHandle.standardError") + let writesDirectly = Self.containsBareCall(to: "print", in: code) + || Self.containsBareCall(to: "fputs", in: code) + || Self.containsBareCall(to: "fwrite", in: code) + if writesThroughFileHandle || (writesDirectly && !isTheOutput) { + offendingLines.append("\(fileURL.lastPathComponent):\(lineIndex + 1): \(code)") + } + } + } + #expect(scannedFileCount > 20, "the premise: the scan sees the command-line sources") + #expect(offendingLines.isEmpty, "\(offendingLines.joined(separator: "\n"))") + } + + @Test("The scan's call detector discriminates") + func callDetectorDiscriminates() { + #expect(Self.containsBareCall(to: "print", in: "print(text)")) + #expect(Self.containsBareCall(to: "fputs", in: "_ = fputs(line, stderr)")) + #expect(!Self.containsBareCall(to: "print", in: "builder.printRoot()")) + #expect(!Self.containsBareCall(to: "print", in: "node.print(using: options)")) + } + + /// Is `name(` called as a function, rather than as a member of something? + private static func containsBareCall(to name: String, in code: String) -> Bool { + var searchRange = code.startIndex ..< code.endIndex + while let found = code.range(of: name + "(", range: searchRange) { + if found.lowerBound == code.startIndex { return true } + let preceding = code[code.index(before: found.lowerBound)] + if !preceding.isLetter, !preceding.isNumber, preceding != ".", preceding != "_" { + return true + } + searchRange = found.upperBound ..< code.endIndex + } + return false + } +} diff --git a/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift b/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift index 37f6f7ba7..3cefea1fd 100644 --- a/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift +++ b/Tests/SwiftSectionCommandTests/TransformerOptionGroupTests.swift @@ -5,6 +5,7 @@ import OutputTransformer import SwiftOutputTransformer import SwiftDeclarationRendering import SwiftPrinting +import SwiftSectionKit @testable import swift_section /// Unit tests for the `swift-section` comment-template command-line surface: diff --git a/Tests/SwiftSectionKitTests/ABIRequestTests.swift b/Tests/SwiftSectionKitTests/ABIRequestTests.swift new file mode 100644 index 000000000..c1ff6f303 --- /dev/null +++ b/Tests/SwiftSectionKitTests/ABIRequestTests.swift @@ -0,0 +1,308 @@ +import Foundation +import Testing +import MachO +import SwiftDiffing +import SwiftSectionKit + +/// `snapshot`, `diff` and `evolution` against the SymbolTestsCore fixture: +/// what each produces, how a snapshot document and a binary mix as inputs, +/// and the verdict a CI gate reads. +@Suite +struct ABIRequestTests { + private static let fixture = SnapshotSource.path(FixtureFiles.symbolTestsCore) + + /// The fixture indexed once for the whole suite: every test that only + /// needs a snapshot document starts from this one instead of indexing the + /// fixture again. + private static let fixtureDocument = Task { + try await ABISnapshotRequest(source: fixture).run(output: RecordingOutput(), environment: .testing) + } + + /// Writes the fixture's snapshot document, labeled `label`, into + /// `directoryURL`. + private func writeFixtureSnapshot(named fileName: String, label: String?, in directoryURL: URL) async throws -> String { + var document = try await Self.fixtureDocument.value + document.provenance?.label = label + let path = directoryURL.appendingPathComponent(fileName).path + try document.encoded().write(to: URL(fileURLWithPath: path)) + return path + } + + // MARK: - snapshot + + @Test("A snapshot's provenance is stamped from the request and the environment") + func snapshotProvenance() async throws { + let output = RecordingOutput() + let document = try await ABISnapshotRequest(source: Self.fixture, label: "1.0").run(output: output, environment: .testing) + + let provenance = try #require(document.provenance) + #expect(provenance.label == "1.0") + #expect(provenance.binaryPath == FixtureFiles.symbolTestsCore) + #expect(provenance.generatorVersion == "9.9.9") + #expect(provenance.createdAt == Date(timeIntervalSince1970: 1_800_000_000)) + #expect(output.messages(of: .progress) == ["Indexing \(FixtureFiles.symbolTestsCore)…"]) + #expect(output.indexingLabels == ["1.0"]) + } + + @Test("The product is the document's JSON, which reads back as the document") + func snapshotProductIsTheDocument() async throws { + let output = RecordingOutput() + let document = try await ABISnapshotRequest(source: Self.fixture).run(output: output, environment: .testing) + + guard case .data(let data)? = output.products.first, output.products.count == 1 else { + Issue.record("expected one data product, got \(output.products)") + return + } + #expect(try ABISnapshotDocument.decode(from: data) == document) + } + + @Test("A snapshot document as input is relabeled, not re-indexed") + func snapshotRelabelsADocument() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: "before", in: directoryURL) + + let output = RecordingOutput() + let relabeled = try await ABISnapshotRequest(source: .path(documentPath), label: "after").run(output: output, environment: .testing) + + #expect(relabeled.provenance?.label == "after") + #expect(output.messages(of: .progress) == ["Reading snapshot \(documentPath)…"]) + #expect(output.indexingLabels.isEmpty) + } + + @Test("A file destination says where the snapshot went") + func snapshotFileDestination() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let path = directoryURL.appendingPathComponent("snapshot.json").path + + let output = RecordingOutput() + let document = try await ABISnapshotRequest(source: Self.fixture, destination: .file(path: path)).run(output: output, environment: .testing) + + #expect(output.products.isEmpty) + #expect(output.messages(of: .progress).last == "Snapshot written to \(path)") + #expect(try ABISnapshotDocument.decode(from: Data(contentsOf: URL(fileURLWithPath: path))) == document) + } + + // MARK: - diff + + @Test("A binary diffed against its own snapshot has no change") + func diffAgainstOwnSnapshot() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: nil, in: directoryURL) + + let output = RecordingOutput() + let outcome = try await ABIDiffRequest(old: .path(documentPath), new: Self.fixture, report: .summary) + .run(output: output, environment: .testing) + + #expect(outcome.hasBreakingChange == false) + #expect(output.printedProduct == "ABI-breaking: false · backward-compatible: true\n") + #expect(output.indexingLabels == ["new"]) + } + + /// The summary line has always gone to stdout even with `-o`. + @Test("The summary reaches the output even with a file destination") + func diffSummaryIgnoresTheFileDestination() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: nil, in: directoryURL) + let reportPath = directoryURL.appendingPathComponent("report.txt").path + + let output = RecordingOutput() + _ = try await ABIDiffRequest(old: .path(documentPath), new: .path(documentPath), report: .summary, destination: .file(path: reportPath)) + .run(output: output, environment: .testing) + + #expect(output.printedProduct == "ABI-breaking: false · backward-compatible: true\n") + #expect(!FileManager.default.fileExists(atPath: reportPath)) + } + + @Test("The change list ends with the verdict, and a file gets it without the trailing newline") + func diffChangeListFileDestination() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: nil, in: directoryURL) + let reportPath = directoryURL.appendingPathComponent("report.txt").path + + let printed = RecordingOutput() + _ = try await ABIDiffRequest(old: .path(documentPath), new: .path(documentPath)).run(output: printed, environment: .testing) + let written = RecordingOutput() + _ = try await ABIDiffRequest(old: .path(documentPath), new: .path(documentPath), destination: .file(path: reportPath)) + .run(output: written, environment: .testing) + + #expect(printed.printedProduct.hasSuffix("\n\nABI-breaking: false · backward-compatible: true\n")) + #expect(try String(contentsOfFile: reportPath, encoding: .utf8) + "\n" == printed.printedProduct) + #expect(written.messages(of: .progress).last == "Report written to \(reportPath)") + } + + @Test("An annotated interface refuses a snapshot document before indexing anything") + func annotatedDiffRejectsADocument() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: nil, in: directoryURL) + + let output = RecordingOutput() + await #expect(throws: SnapshotSourceError.binaryRequired(path: documentPath)) { + _ = try await ABIDiffRequest( + old: Self.fixture, + new: .path(documentPath), + report: .annotatedInterface(format: .inline, includesBreakingChangeVerdict: false) + ).run(output: output, environment: .testing) + } + #expect(output.events.isEmpty) + } + + @Test("An annotated interface computes the verdict only when asked") + func annotatedDiffVerdictIsOptional() async throws { + let withoutVerdict = try await ABIDiffRequest( + old: Self.fixture, + new: Self.fixture, + report: .annotatedInterface(format: .unified, includesBreakingChangeVerdict: false), + maximumConcurrentPreparations: 1 + ).run(output: RecordingOutput(), environment: .testing) + #expect(withoutVerdict.diff == nil) + + let output = RecordingOutput() + let withVerdict = try await ABIDiffRequest( + old: Self.fixture, + new: Self.fixture, + report: .annotatedInterface(format: .unified, includesBreakingChangeVerdict: true), + maximumConcurrentPreparations: 1 + ).run(output: output, environment: .testing) + #expect(withVerdict.hasBreakingChange == false) + #expect(output.messages(of: .progress) == ["Indexing old binary, then new binary…", "Rendering annotated interface…"]) + #expect(output.indexingLabels == ["old", "new"]) + guard case .annotatedInterface(_, let style)? = output.products.first, output.products.count == 1 else { + Issue.record("expected one annotated interface, got \(output.products)") + return + } + #expect(style == .diff(isUnifiedDiff: true)) + } + + // MARK: - evolution + + @Test("A label per input is required, and checked before anything is loaded") + func evolutionLabelCountIsCheckedFirst() async throws { + await #expect(throws: ABIEvolutionError.labelCountMismatch(labelCount: 1, versionCount: 2)) { + _ = try await ABIEvolutionRequest(inputs: [.path("/nonexistent/one"), .path("/nonexistent/two")], labels: ["1.0"]) + .run(output: RecordingOutput(), environment: .testing) + } + } + + @Test("A lineage of identical versions breaks nothing, labeled by stored label or file name") + func evolutionLineage() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let firstPath = try await writeFixtureSnapshot(named: "first.json", label: "1.0", in: directoryURL) + let secondPath = try await writeFixtureSnapshot(named: "second.json", label: nil, in: directoryURL) + + let output = RecordingOutput() + let outcome = try await ABIEvolutionRequest(inputs: [.path(firstPath), .path(secondPath)], report: .json) + .run(output: output, environment: .testing) + + let evolution = try #require(outcome.evolution) + #expect(!outcome.hasBreakingChange) + #expect(evolution.versions.map(\.label) == ["1.0", "second.json"]) + #expect(output.messages(of: .progress).last == "Tracking evolution…") + } + + @Test("The lineage report holds the same bytes printed and in a file") + func evolutionFileDestination() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: nil, in: directoryURL) + let reportPath = directoryURL.appendingPathComponent("lineage.txt").path + let inputs: [SnapshotSource] = [.path(documentPath), .path(documentPath)] + + let printed = RecordingOutput() + _ = try await ABIEvolutionRequest(inputs: inputs, labels: ["a", "b"]).run(output: printed, environment: .testing) + _ = try await ABIEvolutionRequest(inputs: inputs, labels: ["a", "b"], destination: .file(path: reportPath)) + .run(output: RecordingOutput(), environment: .testing) + + #expect(try String(contentsOfFile: reportPath, encoding: .utf8) == printed.printedProduct) + } + + @Test("An annotated evolution refuses a snapshot document") + func annotatedEvolutionRejectsADocument() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = try await writeFixtureSnapshot(named: "baseline.json", label: nil, in: directoryURL) + + await #expect(throws: SnapshotSourceError.binaryRequired(path: documentPath)) { + _ = try await ABIEvolutionRequest( + inputs: [Self.fixture, .path(documentPath)], + report: .annotatedInterface(availabilityAttributes: .none) + ).run(output: RecordingOutput(), environment: .testing) + } + } + + /// Two copies of one binary add and remove nothing, so no declaration + /// gets an attribute; what tells the platform is the legend line that + /// explains the attributes, present exactly when they are on. + @Test("An annotated evolution spells @available for the platform it is given, or the one its inputs name", arguments: [ + (ABIEvolutionRequest.AvailabilityAttributes.none, nil), + (.inferredPlatform, "macOS"), + (.platform("visionOS"), "visionOS"), + ] as [(ABIEvolutionRequest.AvailabilityAttributes, String?)]) + func annotatedEvolutionAvailabilityPlatform(availabilityAttributes: ABIEvolutionRequest.AvailabilityAttributes, expectedPlatform: String?) async throws { + let output = RecordingOutput() + _ = try await ABIEvolutionRequest( + inputs: [Self.fixture, Self.fixture], + labels: ["1.0", "2.0"], + report: .annotatedInterface(availabilityAttributes: availabilityAttributes) + ).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 interface, got \(output.products)") + return + } + #expect(style == .evolution) + let availabilityLegendLines = text.split(separator: "\n").filter { $0.hasPrefix("// @available(") } + if let expectedPlatform { + #expect(availabilityLegendLines.count == 1) + #expect(availabilityLegendLines.first?.hasPrefix("// @available(\(expectedPlatform), …)") == true) + } else { + #expect(availabilityLegendLines.isEmpty) + } + } + + /// The copy names another platform than the fixture's macOS; a simulator + /// counts as its device. Thrown after loading and before any indexing. + @Test("Inputs naming different platforms leave nothing to infer", arguments: [ + (PLATFORM_IOSSIMULATOR, ["iOS", "macOS"]), + (PLATFORM_TVOS, ["macOS", "tvOS"]), + (PLATFORM_WATCHOSSIMULATOR, ["macOS", "watchOS"]), + (PLATFORM_VISIONOSSIMULATOR, ["macOS", "visionOS"]), + (PLATFORM_MACCATALYST, ["macCatalyst", "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: AvailabilityPlatformInferenceError.conflictingPlatforms(expectedPlatforms)) { + _ = try await ABIEvolutionRequest( + inputs: [Self.fixture, .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 @available 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_DRIVERKIT, in: directoryURL) + + let output = RecordingOutput() + await #expect(throws: AvailabilityPlatformInferenceError.noPlatform(path: copyPath)) { + _ = try await ABIEvolutionRequest( + inputs: [Self.fixture, .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/DumpAndInterfaceRequestTests.swift b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift new file mode 100644 index 000000000..de8b1a96a --- /dev/null +++ b/Tests/SwiftSectionKitTests/DumpAndInterfaceRequestTests.swift @@ -0,0 +1,254 @@ +import Foundation +import Testing +import OutputTransformer +import SwiftOutputTransformer +import SwiftSectionKit + +/// `dump` and `interface` against the SymbolTestsCore fixture: which sections +/// are read and how a failure surfaces, where the product goes, and the +/// progress a host hears. What the rendered declarations say is pinned by the +/// snapshot suites; these pin what the requests add around them. +@Suite +struct DumpAndInterfaceRequestTests { + private static let fixture = MachOSource.file(path: FixtureFiles.symbolTestsCore, architecture: nil) + + /// A plain C tool: a Mach-O with no Swift section at all. + private static let nonSwiftBinaryPath = "/usr/bin/true" + + // MARK: - dump + + @Test("Every section of the fixture is dumped as it is read, and a file holds exactly what was printed") + func dumpToOutputAndToFile() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let dumpPath = directoryURL.appendingPathComponent("dump.txt").path + + let printed = RecordingOutput() + try await DumpRequest(source: Self.fixture).run(output: printed, environment: .testing) + let written = RecordingOutput() + try await DumpRequest(source: Self.fixture, destination: .file(path: dumpPath)).run(output: written, environment: .testing) + + #expect(printed.printedProduct.contains("@objc(SymbolTestsCoreObjCBridgeClass)")) + #expect(printed.diagnostics.isEmpty) + #expect(written.events.isEmpty) + #expect(try String(contentsOfFile: dumpPath, encoding: .utf8) == printed.printedProduct) + } + + @Test("A section asked for by name reports what it cannot read; the default selection stays silent", .enabled(if: FileManager.default.fileExists(atPath: nonSwiftBinaryPath))) + func explicitSectionsReportFailures() async throws { + let source = MachOSource.file(path: Self.nonSwiftBinaryPath, architecture: .arm64e) + + let explicit = RecordingOutput() + try await DumpRequest(source: source, sections: .only([.types, .protocols])).run(output: explicit, environment: .testing) + let errors = explicit.messages(of: .error) + #expect(errors.count == 2) + #expect(errors.first?.hasPrefix("Swift section __swift5_types not found") == true) + #expect(errors.last?.hasPrefix("Swift section __swift5_protos not found") == true) + + let defaulted = RecordingOutput() + try await DumpRequest(source: source).run(output: defaulted, environment: .testing) + #expect(defaulted.events.isEmpty) + } + + @Test("An empty section asked for by name says so in the product") + func explicitEmptyObjCImplementationSection() async throws { + let output = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.objcImplementationClasses])).run(output: output, environment: .testing) + #expect(output.printedProduct == "// No @objc @implementation classes recognized in this image.\n") + } + + @Test("Binary order reorders the declarations, never adds or drops one") + func binaryOrderKeepsEveryDeclaration() async throws { + let bySection = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types, .protocols])).run(output: bySection, environment: .testing) + let inBinaryOrder = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types, .protocols]), ordering: .binaryOrder).run(output: inBinaryOrder, environment: .testing) + + let declarationsBySection = bySection.products.compactMap(Self.declarationText) + let declarationsInBinaryOrder = inBinaryOrder.products.compactMap(Self.declarationText) + #expect(!declarationsBySection.isEmpty) + #expect(declarationsBySection.sorted() == declarationsInBinaryOrder.sorted()) + } + + @Test("The header names the environment's generator") + func dumpHeaderNamesTheGenerator() async throws { + let output = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.protocols]), emitsHeader: true).run(output: output, environment: .testing) + #expect(output.printedProduct.hasPrefix("// Generated by swift-section-kit-tests 9.9.9\n")) + } + + /// Passing a template is enough to see its output; no separate switch for + /// the comment kind it renders. + @Test("A comment template turns its comment kind on") + func commentTemplateEnablesItsCommentKind() async throws { + var transformers = Transformer.SwiftConfiguration() + transformers.swiftMemberAddress.isEnabled = true + transformers.swiftMemberAddress.template = "ADDRESS[${offset}]" + + let withTemplate = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.protocolConformances]), commentTransformers: transformers) + .run(output: withTemplate, environment: .testing) + let withoutTemplate = RecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.protocolConformances])).run(output: withoutTemplate, environment: .testing) + + #expect(withTemplate.printedProduct.contains("ADDRESS[")) + #expect(!withoutTemplate.printedProduct.contains("ADDRESS[")) + } + + private static func declarationText(_ product: SwiftSectionProduct) -> String? { + if case .declarations(let semanticString) = product { semanticString.string } else { nil } + } + + // MARK: - dump: what each piece declares + + @Test("Every declaration a dump prints comes with what it declares, and the pieces are those a plain output gets") + func everyDeclarationIsNamed() async throws { + let plain = RecordingOutput() + try await DumpRequest(source: Self.fixture).run(output: plain, environment: .testing) + let named = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture).run(output: named, environment: .testing) + + let namedPieces = named.declarationPieces + #expect(!namedPieces.isEmpty) + #expect(namedPieces.allSatisfy { $0.declaration != nil }) + #expect(namedPieces.map(\.declarationText) == plain.products.compactMap(Self.declarationText)) + } + + struct TypeAndConformance: Sendable, CustomTestStringConvertible { + let typeName: String + let typeLinePrefix: String + let conformanceLinePrefix: String + + var testDescription: String { typeName } + } + + /// What a host files one type's pieces together by. + @Test("A type and its conformances share one name", arguments: [ + TypeAndConformance( + typeName: "SymbolTestsCore.Enums.NoPayloadEnumTest", + typeLinePrefix: "enum SymbolTestsCore.Enums.NoPayloadEnumTest {", + conformanceLinePrefix: "extension SymbolTestsCore.Enums.NoPayloadEnumTest: Swift.Equatable" + ), + TypeAndConformance( + typeName: "SymbolTestsCore.Generics.GenericRequirementTest", + typeLinePrefix: "struct SymbolTestsCore.Generics.GenericRequirementTest<", + conformanceLinePrefix: "extension SymbolTestsCore.Generics.GenericRequirementTest: Swift.Equatable" + ), + ]) + func typeAndConformancesShareName(_ typeAndConformance: TypeAndConformance) async throws { + let output = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types, .protocolConformances])).run(output: output, environment: .testing) + + #expect(output.declaration(ofPieceStartingWith: typeAndConformance.typeLinePrefix) == .swift(.types, name: typeAndConformance.typeName)) + #expect(output.declaration(ofPieceStartingWith: typeAndConformance.conformanceLinePrefix) == .swift(.protocolConformances, name: typeAndConformance.typeName)) + } + + /// A file-scope private type's name carries the file's discriminator; + /// its conformance has to be named with it, or a host files the two apart. + @Test("A file-private type and its conformance share one name") + func filePrivateTypeAndConformanceShareName() async throws { + let output = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types, .protocolConformances])).run(output: output, environment: .testing) + + let typeNames = output.declarationPieces.compactMap { piece -> String? in + guard case .swift(.types, let name)? = piece.declaration, name?.contains("AlphaProtocolWitness") == true else { return nil } + return name + } + let conformanceNames = output.declarationPieces.compactMap { piece -> String? in + guard case .swift(.protocolConformances, let name)? = piece.declaration, + piece.declarationText?.contains("PrivateDoppelgangerProtocol") == true, + name?.contains("AlphaProtocolWitness") == true + else { return nil } + return name + } + #expect(typeNames.count == 1) + #expect(conformanceNames.count == 1) + #expect(conformanceNames == typeNames) + } + + @Test("A protocol is named as declared") + func protocolIsNamed() async throws { + let output = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.protocols])).run(output: output, environment: .testing) + + #expect(output.declaration(ofPieceStartingWith: "protocol SymbolTestsCore.Protocols.ProtocolTest ") == .swift(.protocols, name: "SymbolTestsCore.Protocols.ProtocolTest")) + } + + @Test("An associated type is named after the type that witnesses it") + func associatedTypeIsNamedAfterItsType() async throws { + let output = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.associatedTypes])).run(output: output, environment: .testing) + + #expect( + output.declaration(ofPieceStartingWith: "extension SymbolTestsCore.Generics.GenericRequirementTest: SymbolTestsCore.Protocols.ProtocolTest") + == .swift(.associatedTypes, name: "SymbolTestsCore.Generics.GenericRequirementTest") + ) + } + + @Test("Binary order names the same declarations") + func binaryOrderNamesTheSameDeclarations() async throws { + let bySection = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types, .protocols])).run(output: bySection, environment: .testing) + let inBinaryOrder = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.types, .protocols]), ordering: .binaryOrder).run(output: inBinaryOrder, environment: .testing) + + let bySectionDeclarations = Set(bySection.declarationPieces.compactMap(\.declaration)) + #expect(!bySectionDeclarations.isEmpty) + #expect(Set(inBinaryOrder.declarationPieces.compactMap(\.declaration)) == bySectionDeclarations) + #expect(inBinaryOrder.declarationPieces.allSatisfy { $0.declaration != nil }) + } + + @Test("The header is no declaration") + func headerIsNoDeclaration() async throws { + let output = DeclarationRecordingOutput() + try await DumpRequest(source: Self.fixture, sections: .only([.protocols]), emitsHeader: true).run(output: output, environment: .testing) + + let firstPiece = try #require(output.declarationPieces.first) + #expect(firstPiece.declarationText?.hasPrefix("// Generated by swift-section-kit-tests 9.9.9\n") == true) + #expect(firstPiece.declaration == nil) + #expect(output.declarationPieces.dropFirst().allSatisfy { $0.declaration != nil }) + } + + // MARK: - interface + + @Test("Interface progress is three steps, and the interface is one piece") + func interfaceProgressWithoutHeader() async throws { + let output = RecordingOutput() + try await InterfaceRequest(source: Self.fixture).run(output: output, environment: .testing) + + #expect(output.messages(of: .progress) == [ + "Preparing to build Swift interface...", + "Building Swift interface...", + "Swift interface built successfully.", + ]) + #expect(output.products.count == 1) + #expect(output.indexingLabels == [nil]) + } + + /// With a header, "Preparing…" is announced before the header's symbol + /// index build rather than after it, so nothing is heard for the whole + /// build otherwise. + @Test("With a header and a file, the file holds what would have been printed, minus the final newline") + func interfaceWithHeaderToFile() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let interfacePath = directoryURL.appendingPathComponent("SymbolTestsCore.swiftinterface").path + + let printed = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, emitsHeader: true).run(output: printed, environment: .testing) + let written = RecordingOutput() + try await InterfaceRequest(source: Self.fixture, emitsHeader: true, destination: .file(path: interfacePath)) + .run(output: written, environment: .testing) + + #expect(written.products.isEmpty) + #expect(written.messages(of: .progress) == [ + "Preparing to build Swift interface...", + "Building Swift interface...", + "Swift interface built successfully.", + "Writing Swift interface to \(interfacePath)...", + ]) + let fileContents = try String(contentsOfFile: interfacePath, encoding: .utf8) + #expect(fileContents + "\n" == printed.printedProduct) + #expect(fileContents.hasPrefix("// Generated by swift-section-kit-tests 9.9.9\n")) + } +} diff --git a/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift b/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift new file mode 100644 index 000000000..09212831e --- /dev/null +++ b/Tests/SwiftSectionKitTests/InterfaceAnnotationStyleTests.swift @@ -0,0 +1,75 @@ +import Testing +import SwiftSectionKit + +/// The rule a host colors an annotated interface by. `swift-section` used to +/// keep it private to two `emit` functions; it is public now so that every +/// host colors alike, and so it can be pinned here. +@Suite +struct InterfaceAnnotationStyleTests { + @Test("An inline diff reads its lines by their +/- prefix") + func inlineDiff() { + let text = """ + struct Kept { + + var added: Int + - var removed: Int + """ + #expect(InterfaceAnnotationStyle.diff(isUnifiedDiff: false).lineKinds(of: text) == [.plain, .added, .removed]) + } + + /// In a unified diff the first two lines are `--- old` / `+++ new` file + /// headers. Told apart by position, a content line that happens to begin + /// with `++` or `--` is never mistaken for one. + @Test("A unified diff's headers are told apart by position, not prefix") + func unifiedDiffHeaders() { + let text = """ + --- old.dylib + +++ new.dylib + @@ -1,2 +1,2 @@ + ++counter + --counter + """ + #expect(InterfaceAnnotationStyle.diff(isUnifiedDiff: true).lineKinds(of: text) == [.header, .header, .header, .added, .removed]) + } + + @Test("An inline diff has no headers, whatever its first lines say") + func inlineDiffHasNoHeaders() { + #expect(InterfaceAnnotationStyle.diff(isUnifiedDiff: false).lineKinds(of: "--- old\n@@ hunk") == [.removed, .plain]) + } + + @Test("An evolution interface reads each line by its lifecycle annotation") + func evolutionAnnotations() { + let text = """ + // Legend: [added in v2] … + public struct Removed {} // [removed in 2.0] + public struct Modified {} // [modified in 2.0] + public struct Added {} // [added in 2.0] + public struct Unchanged {} + """ + #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: text) == [.header, .removed, .modified, .added, .plain]) + } + + /// `ABIEvolutionRequest.AvailabilityAttributes`: the legend gains a line, + /// and an attribute line above a declaration carries no annotation of its + /// own, so the declaration line below it is the one colored. + @Test("@available attribute lines stay plain; their legend line is a header") + func evolutionAvailabilityAttributes() { + let text = """ + // @available(iOS, …) attributes are axis-resolution facts: … + @available(iOS, introduced: 18.0) + public struct Added {} // [○●] added in 18.0 + @available(iOS, introduced: 17.0, obsoleted: 18.0) + public var removed: Int // [●○] removed in 18.0 + """ + #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: text) == [.header, .plain, .added, .plain, .removed]) + } + + @Test("A declaration whose name mentions a lifecycle word stays plain") + func evolutionClassifiesByAnnotationOnly() { + #expect(InterfaceAnnotationStyle.evolution.lineKinds(of: "public func removedInLegacyMode()") == [.plain]) + } + + @Test("Empty lines are kept, one kind per line") + func emptyLinesAreKept() { + #expect(InterfaceAnnotationStyle.diff(isUnifiedDiff: false).lineKinds(of: "+a\n\n-b\n") == [.added, .plain, .removed, .plain]) + } +} diff --git a/Tests/SwiftSectionKitTests/MachOSourceTests.swift b/Tests/SwiftSectionKitTests/MachOSourceTests.swift new file mode 100644 index 000000000..7eb82dfb3 --- /dev/null +++ b/Tests/SwiftSectionKitTests/MachOSourceTests.swift @@ -0,0 +1,58 @@ +import Foundation +import Testing +import SwiftSectionKit + +/// `MachOSource.load()` is the one loader every request shares; these pin the +/// fat-binary affordance and the cache-image lookup it centralizes. +@Suite +struct MachOSourceTests { + @Test("A thin file loads, whatever architecture is asked for") + func thinFileIgnoresTheArchitecture() throws { + let machOFile = try MachOSource.file(path: FixtureFiles.symbolTestsCore, architecture: .x86_64).load() + #expect(machOFile.imagePath.hasSuffix("SymbolTestsCore")) + } + + @Test("A fat file without an architecture names the slices it has") + func fatFileRequiresAnArchitecture() throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let fatPath = try FixtureFiles.makeSingleSliceFatFile(wrapping: FixtureFiles.symbolTestsCore, in: directoryURL) + + #expect(throws: MachOSourceError.fatBinaryRequiresArchitecture(availableArchitectures: ["arm64"])) { + try MachOSource.file(path: fatPath, architecture: nil).load() + } + } + + @Test("A fat file yields the slice asked for, and rejects one it lacks") + func fatFileSliceSelection() throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let fatPath = try FixtureFiles.makeSingleSliceFatFile(wrapping: FixtureFiles.symbolTestsCore, in: directoryURL) + + let machOFile = try MachOSource.file(path: fatPath, architecture: .arm64).load() + #expect(machOFile.imagePath.hasSuffix("SymbolTestsCore")) + #expect(throws: MachOSourceError.architectureNotFound(.arm64e)) { + try MachOSource.file(path: fatPath, architecture: .arm64e).load() + } + } + + @Test("An image the system cache does not have is reported by the name asked for") + func missingCacheImage() throws { + #expect(throws: MachOSourceError.dyldSharedCacheImageNotFound(.name("NoSuchImageInAnyCache"))) { + try MachOSource.systemDyldSharedCache(image: .name("NoSuchImageInAnyCache")).load() + } + } + + @Test("The library's loading errors name no command-line option", arguments: [ + MachOSourceError.fatBinaryRequiresArchitecture(availableArchitectures: ["arm64", "x86_64"]), + .architectureNotFound(.arm64e), + .dyldSharedCacheImageNotFound(.name("Foundation")), + .dyldSharedCacheImageNotFound(.path("/usr/lib/libobjc.A.dylib")), + .systemDyldSharedCacheUnavailable, + ]) + func errorDescriptionIsOptionFree(error: MachOSourceError) throws { + let description = try #require(error.errorDescription) + #expect(!description.isEmpty) + #expect(!description.contains("--")) + } +} diff --git a/Tests/SwiftSectionCommandTests/ObjC/ObjCDumpDiagnosticsTests.swift b/Tests/SwiftSectionKitTests/ObjCDumpDiagnosticsTests.swift similarity index 94% rename from Tests/SwiftSectionCommandTests/ObjC/ObjCDumpDiagnosticsTests.swift rename to Tests/SwiftSectionKitTests/ObjCDumpDiagnosticsTests.swift index 152d13e68..5b34766ac 100644 --- a/Tests/SwiftSectionCommandTests/ObjC/ObjCDumpDiagnosticsTests.swift +++ b/Tests/SwiftSectionKitTests/ObjCDumpDiagnosticsTests.swift @@ -1,5 +1,5 @@ import Testing -@testable import swift_section +import SwiftSectionKit /// `dump` used to answer three unrelated situations with the same silence: /// empty stdout, empty stderr, exit code 0. A binary carrying no Objective-C at @@ -9,19 +9,19 @@ import Testing /// /// The note wording is pinned here rather than by capturing a process's stderr: /// `diagnosticNotes` is pure precisely so these cases can be enumerated cheaply. -@Suite("swift-section objc dump diagnostics") +@Suite("objc dump diagnostics") struct ObjCDumpDiagnosticsTests { private static let imageDescription = "/tmp/Sample" private func notes( - nameCountByKind: [ObjCSectionKind: Int], + nameCountByKind: [ObjCDeclarationKind: Int], emittedCount: Int, - explicitKinds: [ObjCSectionKind]? = nil, + explicitKinds: [ObjCDeclarationKind]? = nil, isEntireIndexEmpty: Bool = false, filter: String? = nil ) -> [String] { - ObjCDumpCommand.diagnosticNotes( - for: ObjCDumpCommand.Outcome( + ObjCDumpRequest.diagnosticNotes( + for: ObjCDumpRequest.Outcome( imageDescription: Self.imageDescription, explicitKinds: explicitKinds, nameCountByKind: nameCountByKind, @@ -35,7 +35,7 @@ struct ObjCDumpDiagnosticsTests { @Test("A binary with no Objective-C at all says so") func reportsAnIndexWithNothingInIt() { let reported = notes( - nameCountByKind: Dictionary(uniqueKeysWithValues: ObjCSectionKind.allCases.map { ($0, 0) }), + nameCountByKind: Dictionary(uniqueKeysWithValues: ObjCDeclarationKind.allCases.map { ($0, 0) }), emittedCount: 0, isEntireIndexEmpty: true ) diff --git a/Tests/SwiftSectionKitTests/ObjCRequestTests.swift b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift new file mode 100644 index 000000000..a1a7c1852 --- /dev/null +++ b/Tests/SwiftSectionKitTests/ObjCRequestTests.swift @@ -0,0 +1,102 @@ +import Foundation +import Testing +import ObjCDiffing +import ObjCOutputTransformer +import OutputTransformer +import SwiftSectionKit + +/// The `objc` requests against the SymbolTestsCore fixture, whose +/// `@objc`-exposed classes give it a small Objective-C side. +@Suite +struct ObjCRequestTests { + private static let fixture = MachOSource.file(path: FixtureFiles.symbolTestsCore, architecture: nil) + private static let bridgeClassName = "SymbolTestsCoreObjCBridgeClass" + + @Test("A filtered dump prints the matching declaration, each followed by an empty line") + func filteredDump() async throws { + let output = RecordingOutput() + let outcome = try await ObjCDumpRequest(source: Self.fixture, kinds: [.classes], nameFilter: Self.bridgeClassName) + .run(output: output) + + #expect(outcome.emittedCount == 1) + #expect(output.printedProduct.hasPrefix("@interface SymbolTestsCoreObjCBridgeClass : NSObject {\n")) + #expect(output.printedProduct.hasSuffix("@end\n\n")) + #expect(output.diagnostics.isEmpty) + } + + /// What lets a host write each declaration into a file of its own; the + /// empty line after the piece is no declaration. + @Test("A dump hands each declaration over with its kind and name") + func dumpNamesEachDeclaration() async throws { + let output = DeclarationRecordingOutput() + try await ObjCDumpRequest(source: Self.fixture, kinds: [.classes], nameFilter: Self.bridgeClassName) + .run(output: output) + + let declarationPieces = output.declarationPieces + #expect(declarationPieces.map(\.declaration) == [.objc(.classes, name: Self.bridgeClassName)]) + #expect(declarationPieces.first?.declarationText?.hasPrefix("@interface SymbolTestsCoreObjCBridgeClass : NSObject {\n") == true) + #expect(output.pieces.count == 2) + #expect(output.pieces.last?.declaration == nil) + } + + @Test("A kind asked for by name that is empty is noted, under the image description given") + func emptyRequestedKindIsNoted() async throws { + let derived = RecordingOutput() + try await ObjCDumpRequest(source: Self.fixture, kinds: [.unions]).run(output: derived) + #expect(derived.messages(of: .note) == ["no unions found in \(FixtureFiles.symbolTestsCore)"]) + + let described = RecordingOutput() + try await ObjCDumpRequest(source: Self.fixture, kinds: [.unions], imageDescription: "SymbolTestsCore").run(output: described) + #expect(described.messages(of: .note) == ["no unions found in SymbolTestsCore"]) + } + + /// A custom ivar-offset wording on its own would otherwise be silently + /// inert, since ivar offset comments are off by default. + @Test("A custom ivar-offset comment turns ivar offset comments on") + func ivarOffsetCommentImpliesTheComments() async throws { + let withComment = RecordingOutput() + try await ObjCInterfaceRequest( + declarationName: Self.bridgeClassName, + source: Self.fixture, + ivarOffsetComment: Transformer.ObjCIvarOffset(isEnabled: true, template: "IVAR@${offset}", useHexadecimal: true) + ).run(output: withComment) + let withoutComment = RecordingOutput() + try await ObjCInterfaceRequest(declarationName: Self.bridgeClassName, source: Self.fixture).run(output: withoutComment) + + #expect(withComment.printedProduct.contains("// IVAR@0x")) + #expect(!withoutComment.printedProduct.contains("IVAR@")) + } + + @Test("A declaration the binary does not have is an error naming it") + func missingDeclaration() async throws { + await #expect(throws: ObjCDeclarationLookupError.declarationNotFound("NoSuchDeclaration")) { + try await ObjCInterfaceRequest(declarationName: "NoSuchDeclaration", source: Self.fixture).run(output: RecordingOutput()) + } + } + + @Test("A binary diffed against its own snapshot breaks no API") + func diffAgainstOwnSnapshot() async throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let documentPath = directoryURL.appendingPathComponent("baseline.json").path + let snapshotOutput = RecordingOutput() + let document = try await ObjCAPISnapshotRequest(source: .path(FixtureFiles.symbolTestsCore), label: "1.0", destination: .file(path: documentPath)) + .run(output: snapshotOutput, environment: .testing) + #expect(document.provenance?.generatorVersion == "9.9.9") + #expect(snapshotOutput.messages(of: .progress).last == "Snapshot written to \(documentPath)") + + let output = RecordingOutput() + let outcome = try await ObjCAPIDiffRequest(old: .path(documentPath), new: .path(FixtureFiles.symbolTestsCore), report: .summary) + .run(output: output, environment: .testing) + #expect(!outcome.hasBreakingChange) + #expect(output.printedProduct == "API-breaking: false · backward-compatible: true\n") + } + + @Test("An ObjC evolution needs a label per input, checked before anything is loaded") + func evolutionLabelCountIsCheckedFirst() async throws { + await #expect(throws: ObjCAPIEvolutionError.labelCountMismatch(labelCount: 3, versionCount: 2)) { + _ = try await ObjCAPIEvolutionRequest(inputs: [.path("/nonexistent/one"), .path("/nonexistent/two")], labels: ["a", "b", "c"]) + .run(output: RecordingOutput(), environment: .testing) + } + } +} diff --git a/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift b/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift new file mode 100644 index 000000000..ff130f8ec --- /dev/null +++ b/Tests/SwiftSectionKitTests/Support/DeclarationRecordingOutput.swift @@ -0,0 +1,58 @@ +import Foundation +import SwiftSectionKit + +/// A `SwiftSectionOutput` that also takes the declarations `dump` and +/// `objc dump` name, keeping every product piece beside the declaration it +/// came with, in order. +/// +/// `RecordingOutput` stays the output that only implements `write(_:)`, so +/// the suites using it go on exercising the default `write(_:declaring:)`. +/// +/// `@unchecked Sendable`: every access goes through `lock`. +final class DeclarationRecordingOutput: SwiftSectionOutput, @unchecked Sendable { + struct Piece { + var product: SwiftSectionProduct + /// `nil` for a piece handed over through `write(_:)`. + var declaration: DumpedDeclaration? + + /// The rendered text of a `.declarations` piece, `nil` for any other. + var declarationText: String? { + if case .declarations(let semanticString) = product { semanticString.string } else { nil } + } + } + + private let lock = NSLock() + private var recordedPieces: [Piece] = [] + private var recordedDiagnostics: [SwiftSectionDiagnostic] = [] + + func write(_ product: SwiftSectionProduct) { + lock.withLock { recordedPieces.append(Piece(product: product, declaration: nil)) } + } + + func write(_ product: SwiftSectionProduct, declaring declaration: DumpedDeclaration) { + lock.withLock { recordedPieces.append(Piece(product: product, declaration: declaration)) } + } + + func report(_ diagnostic: SwiftSectionDiagnostic) { + lock.withLock { recordedDiagnostics.append(diagnostic) } + } + + var pieces: [Piece] { + lock.withLock { recordedPieces } + } + + /// The `.declarations` pieces, in order. + var declarationPieces: [Piece] { + pieces.filter { $0.declarationText != nil } + } + + var diagnostics: [SwiftSectionDiagnostic] { + lock.withLock { recordedDiagnostics } + } + + /// The declaration the first `.declarations` piece starting with `prefix` + /// came with — `nil` when no piece starts so, or the piece came without one. + func declaration(ofPieceStartingWith prefix: String) -> DumpedDeclaration? { + declarationPieces.first { $0.declarationText?.hasPrefix(prefix) == true }?.declaration + } +} diff --git a/Tests/SwiftSectionKitTests/Support/FixtureFiles.swift b/Tests/SwiftSectionKitTests/Support/FixtureFiles.swift new file mode 100644 index 000000000..f29dc7d6f --- /dev/null +++ b/Tests/SwiftSectionKitTests/Support/FixtureFiles.swift @@ -0,0 +1,78 @@ +import Foundation +import MachO + +/// Paths the request tests hand to `MachOSource` / `SnapshotSource`, which take +/// paths rather than loaded images. +enum FixtureFiles { + private static let packageRoot = URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() // Support + .deletingLastPathComponent() // SwiftSectionKitTests + .deletingLastPathComponent() // Tests + .deletingLastPathComponent() // package root + + /// The SymbolTestsCore fixture framework binary (thin arm64). A gitignored + /// per-machine build product; see FixtureTestingAndContinuousIntegration.md. + static let symbolTestsCore = packageRoot + .appendingPathComponent("Tests/Projects/SymbolTests/DerivedData/SymbolTests/Build/Products/Release/SymbolTestsCore.framework/Versions/A/SymbolTestsCore") + .path + + /// A fresh directory for one test's files. + static func makeTemporaryDirectory() throws -> URL { + let directoryURL = FileManager.default.temporaryDirectory + .appendingPathComponent("SwiftSectionKitTests-\(UUID().uuidString)", isDirectory: true) + try FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true) + return directoryURL + } + + /// A fat file whose one slice is the thin arm64 binary at `thinPath`. + /// + /// Built by hand rather than taken from the host: whether a system binary + /// is fat, and with which slices, changes between OS releases. + static func makeSingleSliceFatFile(wrapping thinPath: String, in directoryURL: URL) throws -> String { + let thinData = try Data(contentsOf: URL(fileURLWithPath: thinPath)) + let sliceAlignmentPower: UInt32 = 14 + let sliceOffset: UInt32 = 1 << sliceAlignmentPower + var fatData = Data() + func appendBigEndian(_ value: UInt32) { + withUnsafeBytes(of: value.bigEndian) { fatData.append(contentsOf: $0) } + } + appendBigEndian(0xCAFE_BABE) // FAT_MAGIC + appendBigEndian(1) // nfat_arch + appendBigEndian(0x0100_000C) // CPU_TYPE_ARM64 + appendBigEndian(0) // CPU_SUBTYPE_ARM64_ALL + appendBigEndian(sliceOffset) + appendBigEndian(UInt32(thinData.count)) + appendBigEndian(sliceAlignmentPower) + fatData.append(Data(count: Int(sliceOffset) - fatData.count)) + fatData.append(thinData) + let fatURL = directoryURL.appendingPathComponent("SingleSliceFat") + try fatData.write(to: fatURL) + return fatURL.path + } + + /// A copy of the thin binary at `thinPath` whose `LC_BUILD_VERSION` names + /// `buildPlatform`, a `PLATFORM_*` value of ``. + /// + /// Nothing else changes, the UUID included, so every per-image cache + /// takes the copy for the original: hand it only to code that stops + /// before indexing. + static func makeCopy(of thinPath: String, buildPlatform: Int32, in directoryURL: URL) throws -> String { + var bytes = try Data(contentsOf: URL(fileURLWithPath: thinPath)) + let header = bytes.withUnsafeBytes { $0.loadUnaligned(as: mach_header_64.self) } + var commandOffset = MemoryLayout.size + for _ in 0 ..< header.ncmds { + let command = bytes.withUnsafeBytes { $0.loadUnaligned(fromByteOffset: commandOffset, as: load_command.self) } + if command.cmd == UInt32(LC_BUILD_VERSION) { + let platformOffset = commandOffset + MemoryLayout.offset(of: \.platform)! + withUnsafeBytes(of: UInt32(buildPlatform).littleEndian) { platformBytes in + bytes.replaceSubrange(platformOffset ..< platformOffset + platformBytes.count, with: platformBytes) + } + let copyURL = directoryURL.appendingPathComponent("SymbolTestsCore-platform-\(buildPlatform)") + try bytes.write(to: copyURL) + return copyURL.path + } + commandOffset += Int(command.cmdsize) + } + throw CocoaError(.fileReadCorruptFile, userInfo: [NSFilePathErrorKey: thinPath]) + } +} diff --git a/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift b/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift new file mode 100644 index 000000000..dd39701ad --- /dev/null +++ b/Tests/SwiftSectionKitTests/Support/RecordingOutput.swift @@ -0,0 +1,81 @@ +import Foundation +import SwiftDeclaration +import SwiftSectionKit + +/// A `SwiftSectionOutput` that keeps everything it is handed, in order. +/// +/// `@unchecked Sendable`: every access goes through `lock`. +final class RecordingOutput: SwiftSectionOutput, @unchecked Sendable { + enum Event { + case product(SwiftSectionProduct) + case diagnostic(SwiftSectionDiagnostic) + } + + private let lock = NSLock() + private var recordedEvents: [Event] = [] + private var recordedIndexingLabels: [String?] = [] + + func write(_ product: SwiftSectionProduct) { + lock.withLock { recordedEvents.append(.product(product)) } + } + + func report(_ diagnostic: SwiftSectionDiagnostic) { + lock.withLock { recordedEvents.append(.diagnostic(diagnostic)) } + } + + func indexEventHandlers(forInputLabeled label: String?) -> [any SwiftIndexEvents.Handler] { + lock.withLock { recordedIndexingLabels.append(label) } + return [] + } + + var events: [Event] { + lock.withLock { recordedEvents } + } + + var products: [SwiftSectionProduct] { + events.compactMap { event in + if case .product(let product) = event { product } else { nil } + } + } + + var diagnostics: [SwiftSectionDiagnostic] { + events.compactMap { event in + if case .diagnostic(let diagnostic) = event { diagnostic } else { nil } + } + } + + func messages(of severity: SwiftSectionDiagnostic.Severity) -> [String] { + diagnostics.filter { $0.severity == severity }.map(\.message) + } + + /// The labels the request asked indexing-event handlers for, in order. + var indexingLabels: [String?] { + lock.withLock { recordedIndexingLabels } + } + + /// The product as a terminal without colors shows it: every piece + /// followed by a newline. + var printedProduct: String { + products.map { product in + switch product { + case .declarations(let semanticString): + semanticString.string + "\n" + case .text(let text): + text + "\n" + case .annotatedInterface(let text, _): + text + "\n" + case .data(let data): + String(decoding: data, as: UTF8.self) + "\n" + } + }.joined() + } +} + +extension SwiftSectionEnvironment { + /// A fixed generator and a fixed date, so that two runs stamp the same + /// bytes. + static let testing = SwiftSectionEnvironment( + generator: GeneratorIdentity(name: "swift-section-kit-tests", version: "9.9.9"), + currentDate: { Date(timeIntervalSince1970: 1_800_000_000) } + ) +} diff --git a/Tests/SwiftSectionKitTests/TransformerRequestTests.swift b/Tests/SwiftSectionKitTests/TransformerRequestTests.swift new file mode 100644 index 000000000..5743a07c7 --- /dev/null +++ b/Tests/SwiftSectionKitTests/TransformerRequestTests.swift @@ -0,0 +1,67 @@ +import Foundation +import Testing +import OutputTransformer +import SwiftOutputTransformer +import SwiftSectionKit + +@Suite +struct TransformerRequestTests { + @Test("The tokens listing of one module names its placeholders, aligned") + func tokensOfOneModule() { + let output = RecordingOutput() + TransformerTokensRequest(module: .fieldOffset).run(output: output) + #expect(output.printedProduct == """ + Swift Field Offset Comment (field-offset) + Tokens — --field-offset-template + ${startOffset} Start Offset + ${endOffset} End Offset + + """) + } + + @Test("Listing every module lists each once, in order, an empty line apart") + func everyModuleIsListed() { + let output = RecordingOutput() + TransformerTemplatesRequest().run(output: output) + let lines = output.printedProduct.split(separator: "\n", omittingEmptySubsequences: false) + let moduleNames = lines + .filter { !$0.isEmpty && !$0.hasPrefix(" ") } + .compactMap { line in line.split(separator: "(").last.map { String($0.dropLast()) } } + #expect(moduleNames == ["field-offset", "vtable-offset", "member-address", "type-layout", "enum-layout"]) + // Four separators between five modules, plus the final newline. + #expect(lines.filter(\.isEmpty).count == 5) + } + + @Test("The configuration JSON reads back as the configuration it was made from") + func configurationRoundTrips() throws { + var configuration = Transformer.SwiftConfiguration() + configuration.swiftFieldOffset.isEnabled = true + configuration.swiftFieldOffset.template = "${startOffset}" + let output = RecordingOutput() + try TransformerConfigurationRequest(configuration: configuration).run(output: output) + + guard case .text(let json)? = output.products.first else { + Issue.record("expected one text product, got \(output.products)") + return + } + let decoded = try JSONDecoder().decode(Transformer.SwiftConfiguration.self, from: Data(json.utf8)) + #expect(decoded == configuration) + } + + /// A file holds the JSON as is; printed, the same JSON is followed by a + /// newline — the one `print` always added. + @Test("A file destination holds the printed JSON minus its newline") + func configurationFileDestination() throws { + let directoryURL = try FixtureFiles.makeTemporaryDirectory() + defer { try? FileManager.default.removeItem(at: directoryURL) } + let filePath = directoryURL.appendingPathComponent("transformers.json").path + + let printed = RecordingOutput() + try TransformerConfigurationRequest().run(output: printed) + let written = RecordingOutput() + try TransformerConfigurationRequest(destination: .file(path: filePath)).run(output: written) + + #expect(written.events.isEmpty) + #expect(try String(contentsOfFile: filePath, encoding: .utf8) + "\n" == printed.printedProduct) + } +} diff --git a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift index 12e62df7b..6ddefd89f 100644 --- a/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift +++ b/Tests/SwiftSpecializationTests/GenericSpecializationTests.swift @@ -373,7 +373,7 @@ struct GenericSpecializationTests { // the metadata accessor should succeed. let result = try specializer.specialize(request, with: ["A": .metatype(Int.self)]) let structMetadata = try #require(result.resolveMetadata().struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func invertedEscapableExposed() async throws { @@ -482,15 +482,15 @@ struct GenericSpecializationTests { // genuinely describe constraints on the same dependent member type. @Test func dualProtocolSameNamedAssociatedTypeIsCanonicalized() throws { let descriptor = try structDescriptor(named: "DualElementStruct") - let genericContext = try #require(try descriptor.genericContext(in: machO)) + let genericContext = try #require(try descriptor.genericContext(in: machO.context)) // Walk every requirement's LHS, collecting the declaring protocol // identity for any `A.Element`-rooted dependent member type. var protocolIdentities: Set = [] var elementRequirementCount = 0 for req in genericContext.requirements { - let mangled = try req.paramMangledName(in: machO) - let node = try SymbolicDemangler.demangleType(for: mangled, in: machO) + let mangled = try req.paramMangledName(in: machO.context) + let node = try SymbolicDemangler.demangleType(for: mangled, in: machO.context) guard let path = GenericSpecializer.extractAssociatedPath(of: node), !path.steps.isEmpty, path.baseParamName == "A", @@ -572,7 +572,7 @@ struct GenericSpecializationTests { @Test func manualAccessorMatchesSpecializerWitnessOrder() async throws { let descriptor = try inProcessStructDescriptor(named: "TestGenericStruct") - let genericContext = try #require(try descriptor.genericContext()) + let genericContext = try #require(try descriptor.genericContext(in: .inProcess)) #expect(genericContext.header.numKeyArguments == 9) @@ -597,7 +597,7 @@ struct GenericSpecializationTests { "C": CMetadata, ]) - let metadataAccessorFunction = try #require(try descriptor.metadataAccessorFunction()) + let metadataAccessorFunction = try #require(try descriptor.metadataAccessorFunction(in: .inProcess)) let metadata = try metadataAccessorFunction( request: .completeAndBlocking, metadatas: [ AMetadata, @@ -609,7 +609,7 @@ struct GenericSpecializationTests { #require(try RuntimeFunctions.conformsToProtocol(metatype: CMetatype, protocolType: CProtocol)), ] + associatedTypeWitnesses ) - try #expect(#require(metadata.value.resolve().struct).fieldOffsets() == [0, 8, 16]) + try #expect(#require(metadata.value.resolve(in: .inProcess).struct).fieldOffsets(in: .inProcess) == [0, 8, 16]) } @Test func threeParameter() async throws { @@ -642,7 +642,7 @@ struct GenericSpecializationTests { // Verify we can resolve metadata let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) - let fieldOffsets = try structMetadata.fieldOffsets() + let fieldOffsets = try structMetadata.fieldOffsets(in: .inProcess) #expect(fieldOffsets == [0, 8, 16]) } @@ -666,7 +666,7 @@ struct GenericSpecializationTests { let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func singleProtocolParameter() async throws { @@ -689,7 +689,7 @@ struct GenericSpecializationTests { let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func multiProtocolParameter() async throws { @@ -710,7 +710,7 @@ struct GenericSpecializationTests { let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func classConstraint() async throws { @@ -736,7 +736,7 @@ struct GenericSpecializationTests { let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func nestedAssociatedType() async throws { @@ -752,7 +752,7 @@ struct GenericSpecializationTests { let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) // Single field of type [[Int]] occupies one pointer slot - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func dualAssociated() async throws { @@ -786,7 +786,7 @@ struct GenericSpecializationTests { let metadata = try result.resolveMetadata() let structMetadata = try #require(metadata.struct) // [Int] occupies 8 bytes, [String] occupies 8 bytes (Array storage pointer) - #expect(try structMetadata.fieldOffsets() == [0, 8]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0, 8]) } @Test func mixedConstraints() async throws { @@ -818,7 +818,7 @@ struct GenericSpecializationTests { let structMetadata = try #require(metadata.struct) // [Int] is one pointer (8 bytes), String is 16 bytes // a at offset 0, b at offset 8 - #expect(try structMetadata.fieldOffsets() == [0, 8]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0, 8]) } @Test func configurableMetadataRequest() async throws { @@ -835,7 +835,7 @@ struct GenericSpecializationTests { // Default request (existing behaviour) let defaultResult = try specializer.specialize(request, with: selection) - let defaultOffsets = try #require(defaultResult.resolveMetadata().struct).fieldOffsets() + let defaultOffsets = try #require(defaultResult.resolveMetadata().struct).fieldOffsets(in: .inProcess) // Explicit non-blocking complete request let nonBlocking = MetadataRequest(state: .complete, isBlocking: false) @@ -844,7 +844,7 @@ struct GenericSpecializationTests { with: selection, metadataRequest: nonBlocking ) - let explicitOffsets = try #require(explicitResult.resolveMetadata().struct).fieldOffsets() + let explicitOffsets = try #require(explicitResult.resolveMetadata().struct).fieldOffsets(in: .inProcess) #expect(defaultOffsets == [0, 8, 16]) #expect(explicitOffsets == defaultOffsets) @@ -925,17 +925,21 @@ struct GenericSpecializationTests { // Use `.excludeGenerics` so the parameter's candidate list only // surfaces directly-specializable types. Pin the candidate to - // `Swift.Int` (matched via `currentName`) so the assertion below - // can compare against the equivalent `.metatype(Int.self)` path — - // an order-dependent `first { !$0.isGeneric }` would silently - // degrade if the indexer's iteration shifted. + // `Swift.Int` by its full name so the assertion below can compare + // against the equivalent `.metatype(Int.self)` path — an + // order-dependent `first { !$0.isGeneric }` would silently degrade + // if the indexer's iteration shifted. Matching the short name + // `Int` did exactly that: a `Hashable` enum declared in a function + // returning `Int` has `Int` as its `currentName`, and the candidate + // order decided which of the two the test specialized + // (ReviewAdjudications A52). let request = try specializer.makeRequest( for: TypeContextDescriptorWrapper.struct(descriptor), candidateOptions: .excludeGenerics ) let intCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Int" && !$0.isGeneric + $0.typeName.name == "Swift.Int" && !$0.isGeneric }, "expected Swift.Int candidate after .excludeGenerics" ) @@ -948,21 +952,15 @@ struct GenericSpecializationTests { // accessor that `.metatype` already exercises. let candidateMetadata = try viaCandidate.metadata() let metatypeMetadata = try viaMetatype.metadata() - // In some processes the two paths come back with two different - // `TestSingleProtocolStruct` metadata instances; the cause is - // not yet known. Tracked as ReviewAdjudications A52 — remove this - // wrapper once it is fixed. - withKnownIssue("the candidate path sometimes reaches a second metadata instance for the same type", isIntermittent: true) { - #expect( - candidateMetadata == metatypeMetadata, - "Argument.candidate path must reach the same metadata pointer as Argument.metatype for the same concrete type" - ) - } + #expect( + candidateMetadata == metatypeMetadata, + "Argument.candidate path must reach the same metadata pointer as Argument.metatype for the same concrete type" + ) #expect(viaCandidate.resolvedArguments.count == 1) #expect(viaCandidate.resolvedArguments[0].hasWitnessTables) let structMetadata = try #require(viaCandidate.resolveMetadata().struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func argumentSpecializedPathFeedsNestedSpecialization() async throws { @@ -991,7 +989,7 @@ struct GenericSpecializationTests { // (8 bytes), so the outer field is at offset 0 and occupies one // pointer-sized slot. let structMetadata = try #require(outer.resolveMetadata().struct) - #expect(try structMetadata.fieldOffsets() == [0]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0]) } @Test func genericCandidateFailFast() async throws { @@ -1004,13 +1002,13 @@ struct GenericSpecializationTests { // the fail-fast logic (test body) or a fixture shift (#require message), // rather than the generic "no isGeneric candidate" mode the original // first-matching-any-candidate form would silently degrade into. - // `currentName` strips the module prefix (e.g. "Swift.Int" → "Int"). + // Matched by full name: see `argumentCandidatePathSpecializesNonGenericCandidate`. let genericCandidate = try #require( - request.parameters[0].candidates.first { $0.typeName.currentName == "Array" && $0.isGeneric }, + request.parameters[0].candidates.first { $0.typeName.name == "Swift.Array" && $0.isGeneric }, "expected Swift.Array candidate flagged isGeneric" ) let nonGenericCandidate = try #require( - request.parameters[0].candidates.first { $0.typeName.currentName == "Int" && !$0.isGeneric }, + request.parameters[0].candidates.first { $0.typeName.name == "Swift.Int" && !$0.isGeneric }, "expected Swift.Int candidate flagged non-generic" ) @@ -1041,7 +1039,7 @@ struct GenericSpecializationTests { let request = try specializer.makeRequest(for: TypeContextDescriptorWrapper.struct(descriptor)) let genericCandidate = try #require( - request.parameters[0].candidates.first { $0.typeName.currentName == "Array" && $0.isGeneric }, + request.parameters[0].candidates.first { $0.typeName.name == "Swift.Array" && $0.isGeneric }, "expected Swift.Array candidate flagged isGeneric" ) @@ -1076,7 +1074,7 @@ struct GenericSpecializationTests { struct NestedGenerics: GenericSpecializationTestingEnvironment { @Test func twoLevelBaseline() throws { let descriptor = try structDescriptor(named: "NestedGenericTwoLevelInner") - let genericContext = try #require(try descriptor.genericContext(in: machO)) + let genericContext = try #require(try descriptor.genericContext(in: machO.context)) // Inner sees both A (inherited from Outer) and B (its own), stored // cumulatively. @@ -1103,7 +1101,7 @@ struct GenericSpecializationTests { @Test func threeLevelCurrentRequirementsKeepsInnerRequirement() throws { let descriptor = try structDescriptor(named: "NestedGenericThreeLevelInner") - let genericContext = try #require(try descriptor.genericContext(in: machO)) + let genericContext = try #require(try descriptor.genericContext(in: machO.context)) // Sanity — the binary stores parameters and requirements cumulatively. #expect(genericContext.parameters.count == 3) // [A, B, C] @@ -1195,7 +1193,7 @@ struct GenericSpecializationTests { #expect(result.resolvedArguments.allSatisfy { $0.witnessTables.count == 1 }) let structMetadata = try #require(result.resolveMetadata().struct) - let fieldOffsets = try structMetadata.fieldOffsets() + let fieldOffsets = try structMetadata.fieldOffsets(in: .inProcess) // Layout: a(Int) at 0, b(Double) at 8, c(String) at 16. String // occupies 16 bytes but the field offset is the start address. #expect(fieldOffsets == [0, 8, 16]) @@ -1214,10 +1212,10 @@ struct GenericSpecializationTests { // `` to match the demangler's canonical naming. @Test func threeLevelDumpAllLevelsHasNoDuplicates() async throws { let descriptor = try structDescriptor(named: "NestedGenericThreeLevelInner") - let genericContext = try #require(try descriptor.genericContext(in: machO)) + let genericContext = try #require(try descriptor.genericContext(in: machO.context)) let dumped = try await genericContext.dumpGenericParameters( - in: machO, + in: machO.context, isDumpCurrentLevel: false ).string @@ -1323,7 +1321,7 @@ struct GenericSpecializationTests { // Layout matches the non-inverted three-level fixture: // a(Int) at 0, b(Double) at 8, c(String) at 16. let structMetadata = try #require(result.resolveMetadata().struct) - #expect(try structMetadata.fieldOffsets() == [0, 8, 16]) + #expect(try structMetadata.fieldOffsets(in: .inProcess) == [0, 8, 16]) } } @@ -1791,7 +1789,7 @@ struct GenericSpecializationTests { "subclasses(of: \(baseClassTypeName.name)) returned empty — narrowing falls back to 'do not narrow'" ) - let candidateNames = Set(parameter.candidates.map { $0.typeName.currentName }) + let candidateNames = Set(parameter.candidates.map { $0.typeName.declaredNameForTesting }) // Must include the base class itself plus the two known // subclasses (the BFS over the parent → child map walks @@ -2077,8 +2075,8 @@ struct GenericSpecializationTests { // witness routing is wrong). // // Note: `makeRequest` resolves the descriptor via the *file-context* - // `genericContext(in: machO)` overload, while - // `metadataAccessorFunction()` (no-arg) reads in-process — so we + // `genericContext(in: machO.context)` overload, while + // `metadataAccessorFunction(in: .inProcess)` reads in-process — so we // need a file-form descriptor for `makeRequest` and an // in-process pointer wrapper for the manual accessor call. let descriptor = try structDescriptor(named: "TestTriAssociatedSameLeafStruct") @@ -2120,7 +2118,7 @@ struct GenericSpecializationTests { // Associated block: A.Element:Hashable, B.Element:Hashable, // C.Element:Hashable. let accessor = try #require( - try inProcessDescriptor.metadataAccessorFunction(), + try inProcessDescriptor.metadataAccessorFunction(in: .inProcess), "TestTriAssociatedSameLeafStruct must have a metadata accessor function" ) let manualResponse = try accessor( @@ -2135,7 +2133,7 @@ struct GenericSpecializationTests { intHashablePWT, // C.Element ] ) - let manualMetadata = try manualResponse.value.resolve().metadata + let manualMetadata = try manualResponse.value.resolve(in: .inProcess).anyMetadata.asMetadata(in: .inProcess) // API call. let apiResult = try specializer.specialize(request, with: [ @@ -2280,7 +2278,7 @@ struct GenericSpecializationTests { ) let intCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Int" && !$0.isGeneric + $0.typeName.name == "Swift.Int" && !$0.isGeneric }, "expected Swift.Int candidate after .excludeGenerics" ) @@ -2364,7 +2362,7 @@ struct GenericSpecializationTests { ) let candidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Int" && !$0.isGeneric + $0.typeName.name == "Swift.Int" && !$0.isGeneric }, "expected Swift.Int candidate after .excludeGenerics" ) @@ -2628,7 +2626,7 @@ struct GenericSpecializationTests { ) let arrayCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Array" && $0.isGeneric + $0.typeName.name == "Swift.Array" && $0.isGeneric }, "expected Swift.Array candidate flagged isGeneric in TestSingleProtocolStruct's candidate list" ) @@ -2683,13 +2681,13 @@ struct GenericSpecializationTests { ) let dictionaryCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Dictionary" && $0.isGeneric + $0.typeName.name == "Swift.Dictionary" && $0.isGeneric }, "expected Swift.Dictionary candidate flagged isGeneric" ) let arrayCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Array" && $0.isGeneric + $0.typeName.name == "Swift.Array" && $0.isGeneric }, "expected Swift.Array candidate flagged isGeneric" ) @@ -2801,7 +2799,7 @@ struct GenericSpecializationTests { ) let arrayCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Array" && $0.isGeneric + $0.typeName.name == "Swift.Array" && $0.isGeneric }, "expected Swift.Array candidate flagged isGeneric on A's candidate list" ) @@ -2870,7 +2868,7 @@ struct GenericSpecializationTests { // typed cause. let intCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Int" && !$0.isGeneric + $0.typeName.name == "Swift.Int" && !$0.isGeneric }, "expected Swift.Int non-generic candidate" ) @@ -2943,7 +2941,7 @@ struct GenericSpecializationTests { // request, so the tree terminates here. let intCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Int" && !$0.isGeneric + $0.typeName.name == "Swift.Int" && !$0.isGeneric } ) let candidateResult = try specializer.specialize(request, with: [ @@ -3008,12 +3006,12 @@ struct GenericSpecializationTests { ) let dictionaryCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Dictionary" && $0.isGeneric + $0.typeName.name == "Swift.Dictionary" && $0.isGeneric } ) let arrayCandidate = try #require( request.parameters[0].candidates.first { - $0.typeName.currentName == "Array" && $0.isGeneric + $0.typeName.name == "Swift.Array" && $0.isGeneric } ) diff --git a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift index cbd00d4de..9faab1405 100644 --- a/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift +++ b/Tests/SwiftSpecializationTests/GenericTypeNameSubstitutionTests.swift @@ -291,7 +291,7 @@ struct GenericTypeNameSubstitutionEndToEndTests: GenericSpecializationTestingEnv // `mangleAsString` produces a *type-mangled* body with no global // symbol prefix (`$s…` / `_T…`). Pass `isType: true` so the demangler // skips the symbol-prefix check and parses the body directly as a - // type — mirrors what `SymbolicDemangler.demangleType(for:)` does + // type — mirrors what `SymbolicDemangler.demangleType(for:in:)` does // internally when handed a `MangledName`. let reconstructed = try await demangleAsNode(mangled, isType: true) let reconstructedBound = try #require(reconstructed.first(of: .boundGenericStructure)) @@ -391,7 +391,7 @@ struct GenericTypeNameSubstitutionEndToEndTests: GenericSpecializationTestingEnv let resolvedIndexer = try await indexer let baseDefinition = try #require( resolvedIndexer.allTypeDefinitions.first(where: { entry in - entry.value.typeName.currentName == "NestedGenericInheritedOnlyOuter" + entry.value.typeName.declaredNameForTesting == "NestedGenericInheritedOnlyOuter" })?.value, "expected indexer to have the root outer fixture definition" ) @@ -472,7 +472,7 @@ struct GenericTypeNameSubstitutionEndToEndTests: GenericSpecializationTestingEnv let resolvedIndexer = try await indexer let baseDefinition = try #require( resolvedIndexer.allTypeDefinitions.first(where: { entry in - entry.value.typeName.currentName == "NestedGenericInheritedOnlyOuter" + entry.value.typeName.declaredNameForTesting == "NestedGenericInheritedOnlyOuter" })?.value, "expected indexer to surface the root outer fixture definition" ) diff --git a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift index d31ca849a..651a9128b 100644 --- a/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift +++ b/Tests/SwiftSpecializationTests/SubclassMapMaterializationFailureTests.swift @@ -38,7 +38,7 @@ final class SubclassMapMaterializationFailureTests: MachOFileTests, @unchecked S } private func typeName(named leafName: String, in indexer: SwiftDeclarationIndexer) throws -> TypeName { - try #require(indexer.allTypeDefinitions.keys.first { $0.currentName == leafName }) + try #require(indexer.allTypeDefinitions.keys.first { $0.declaredNameForTesting == leafName }) } /// A class whose wrapper cannot be materialized is reported as an event, and diff --git a/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift b/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift index c6701879d..be10f1883 100644 --- a/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift +++ b/Tests/SwiftThunkAnalysisTests/AccessorThunkReaderTests.swift @@ -26,20 +26,20 @@ struct AccessorThunkReaderTests { private func firstAccessorThunk(in machO: MachOFile) throws -> (offset: Int, ownerLayout: AccessorThunkOwnerLayout)? { for associatedType in try machO.swift.associatedTypes { for record in associatedType.records { - guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO), in: machO), + guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO.context), in: machO.context), let opaqueTypeNode = node.first(of: Node.Kind.opaqueType), let descriptorReference = opaqueTypeNode.firstChild, descriptorReference.isKind(of: .opaqueTypeDescriptorSymbolicReference), let descriptorOffset: Int = descriptorReference.index?.cast(), - let descriptor = try? OpaqueTypeDescriptor.resolve(from: descriptorOffset, in: machO), - let opaqueType = try? OpaqueType(descriptor: descriptor, in: machO) + let descriptor = try? OpaqueTypeDescriptor.resolve(at: descriptorOffset, in: machO.context), + let opaqueType = try? OpaqueType(descriptor: descriptor, in: machO.context) else { continue } let ordinal: Int = opaqueTypeNode[safeChild: 1]?.index?.cast() ?? 0 guard ordinal < opaqueType.underlyingTypeArgumentMangledNames.count, let underlyingNode = try? SymbolicDemangler.demangleType( for: opaqueType.underlyingTypeArgumentMangledNames[ordinal], - in: machO + in: machO.context ), let accessorReference = underlyingNode.first(of: Node.Kind.accessorFunctionReference), let thunkOffset: Int = accessorReference.index?.cast() diff --git a/Tests/SwiftThunkAnalysisTests/ArchivedIOSCacheThunkTests.swift b/Tests/SwiftThunkAnalysisTests/ArchivedIOSCacheThunkTests.swift index 6a98d09ab..3dc19b5e7 100644 --- a/Tests/SwiftThunkAnalysisTests/ArchivedIOSCacheThunkTests.swift +++ b/Tests/SwiftThunkAnalysisTests/ArchivedIOSCacheThunkTests.swift @@ -35,17 +35,17 @@ struct ArchivedIOSCacheThunkTests { var texts: [String: String] = [:] for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let name = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile).print(using: .default), + guard let name = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile.context).print(using: .default), name == typeName, - let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) + let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile.context) else { continue } - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile)) - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile), + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile.context)) + for record in try fieldDescriptor.records(in: machOFile.context) { + guard let mangledTypeName = try? record.mangledTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context), typeNode.contains(Node.Kind.accessorFunctionReference) else { continue } - texts[try record.fieldName(in: machOFile)] = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout).print(using: .default) + texts[try record.fieldName(in: machOFile.context)] = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout).print(using: .default) } } return texts @@ -76,8 +76,8 @@ struct ArchivedIOSCacheThunkTests { var conditionalWitnessCount = 0 for associatedType in try swiftUI.swift.associatedTypes { for record in associatedType.records { - guard let mangledName = try? record.substitutedTypeName(in: swiftUI), - let node = try? SymbolicDemangler.demangleType(for: mangledName, in: swiftUI), + guard let mangledName = try? record.substitutedTypeName(in: swiftUI.context), + let node = try? SymbolicDemangler.demangleType(for: mangledName, in: swiftUI.context), node.contains(Node.Kind.opaqueType) else { continue } let resolution = node.resolveOpaqueTypeCollectingConditionalCandidates(in: swiftUI) diff --git a/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift b/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift index d3c9b13bd..b52c73e66 100644 --- a/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift +++ b/Tests/SwiftThunkAnalysisTests/ConstructedThunkOracleTests.swift @@ -53,12 +53,12 @@ struct ConstructedThunkOracleTests { var mismatches: [String] = [] for (fileAssociatedType, imageAssociatedType) in zip(fileAssociatedTypes, imageAssociatedTypes) { for (fileRecord, imageRecord) in zip(fileAssociatedType.records, imageAssociatedType.records) { - let fileMangledName = try fileRecord.substitutedTypeName(in: machOFile) - guard let fileNode = try? SymbolicDemangler.demangleType(for: fileMangledName, in: machOFile), + let fileMangledName = try fileRecord.substitutedTypeName(in: machOFile.context) + guard let fileNode = try? SymbolicDemangler.demangleType(for: fileMangledName, in: machOFile.context), fileNode.contains(Node.Kind.opaqueType) else { continue } - let imageMangledName = try imageRecord.substitutedTypeName(in: machOImage) - guard let imageNode = try? SymbolicDemangler.demangleType(for: imageMangledName, in: machOImage), + let imageMangledName = try imageRecord.substitutedTypeName(in: machOImage.context) + guard let imageNode = try? SymbolicDemangler.demangleType(for: imageMangledName, in: machOImage.context), let offlineUnresolved = try? imageNode.resolveOpaqueType(in: machOImage), offlineUnresolved.contains(Node.Kind.accessorFunctionReference) else { continue } diff --git a/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift index 0d290437d..7c8398498 100644 --- a/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/FieldRecordThunkResolutionTests.swift @@ -28,16 +28,16 @@ final class FieldRecordThunkResolutionTests: MachOSwiftSectionFixtureTests, @unc var resolved: [ResolvedField] = [] for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) else { continue } - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile)) - let ownerName = try SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile).print(using: .default) - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile), + guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: fileContext) else { continue } + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: fileContext)) + let ownerName = try SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: fileContext).print(using: .default) + for record in try fieldDescriptor.records(in: fileContext) { + guard let mangledTypeName = try? record.mangledTypeName(in: fileContext), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: fileContext), typeNode.contains(Node.Kind.accessorFunctionReference) else { continue } let resolvedNode = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout) - resolved.append(ResolvedField(owner: ownerName, name: try record.fieldName(in: machOFile), text: resolvedNode.print(using: .default))) + resolved.append(ResolvedField(owner: ownerName, name: try record.fieldName(in: fileContext), text: resolvedNode.print(using: .default))) } } return resolved diff --git a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift index f84824773..94ce47b0a 100644 --- a/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift +++ b/Tests/SwiftThunkAnalysisTests/MergedAccessorFixtureTests.swift @@ -137,16 +137,16 @@ struct MergedAccessorFixtureTests { var texts: [String: String] = [:] for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) else { continue } - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile)) - let ownerName = try SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile).print(using: .default) - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile), + guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile.context) else { continue } + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile.context)) + let ownerName = try SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile.context).print(using: .default) + for record in try fieldDescriptor.records(in: machOFile.context) { + guard let mangledTypeName = try? record.mangledTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context), typeNode.contains(Node.Kind.accessorFunctionReference) else { continue } let resolvedNode = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout) - texts["\(ownerName).\(try record.fieldName(in: machOFile))"] = resolvedNode.print(using: .default) + texts["\(ownerName).\(try record.fieldName(in: machOFile.context))"] = resolvedNode.print(using: .default) } } return texts diff --git a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift index b0a3c14f0..3739ab4e4 100644 --- a/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift +++ b/Tests/SwiftThunkAnalysisTests/OpaqueTypeRenderingIntegrationTests.swift @@ -30,7 +30,7 @@ struct OpaqueTypeRenderingIntegrationTests { var rendered: [String] = [] for associatedType in try machO.swift.associatedTypes { for record in associatedType.records { - guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO), in: machO), + guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO.context), in: machO.context), node.contains(Node.Kind.opaqueType), let resolved = try? node.resolveOpaqueType(in: machO) else { continue } @@ -118,8 +118,8 @@ struct OpaqueTypeRenderingIntegrationTests { var dumpsWithBranches: [String] = [] for associatedType in try machO.swift.associatedTypes { let hasConditionalWitness = associatedType.records.contains { record in - guard let mangledName = try? record.substitutedTypeName(in: machO), - let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machO), + guard let mangledName = try? record.substitutedTypeName(in: machO.context), + let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machO.context), node.contains(Node.Kind.opaqueType) else { return false } return node.resolveOpaqueTypeCollectingConditionalCandidates(in: machO).conditionalCandidates.count >= 2 @@ -155,7 +155,7 @@ struct OpaqueTypeRenderingIntegrationTests { do { for associatedType in (try? machO.swift.associatedTypes) ?? [] { for record in associatedType.records { - guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO), in: machO), + guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO.context), in: machO.context), node.contains(Node.Kind.opaqueType) else { continue } let resolution = node.resolveOpaqueTypeCollectingConditionalCandidates(in: machO) diff --git a/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift b/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift index ded66271d..16c6c3771 100644 --- a/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift +++ b/Tests/SwiftThunkAnalysisTests/RealThunkShapeProbe.swift @@ -29,9 +29,9 @@ struct RealThunkShapeProbe { guard printedThunkOffsets.insert(thunkOffset).inserted else { continue } let conformingTypeName = await (try SymbolicDemangler - .demangleType(for: associatedType.conformingTypeName, in: machO)) + .demangleType(for: associatedType.conformingTypeName, in: machO.context)) .print(using: DemangleOptions.default) - var description = "######## \(conformingTypeName).\(try record.name(in: machO)) — thunk at file offset \(thunkOffset)" + var description = "######## \(conformingTypeName).\(try record.name(in: machO.context)) — thunk at file offset \(thunkOffset)" if let virtualAddress = virtualAddress(ofFileOffset: thunkOffset, in: machO) { description += " / VM 0x\(String(virtualAddress, radix: 16))" @@ -54,7 +54,7 @@ struct RealThunkShapeProbe { /// Walks an associated-type record to the accessor thunk its opaque /// underlying type points at, if it has one. private func accessorThunkOffset(ofRecord record: AssociatedTypeRecord, in machO: MachOFile) throws -> Int? { - let substitutedTypeNode = try SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO), in: machO) + let substitutedTypeNode = try SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO.context), in: machO.context) guard let opaqueTypeNode = substitutedTypeNode.first(of: Node.Kind.opaqueType), let descriptorReference = opaqueTypeNode.firstChild, descriptorReference.isKind(of: .opaqueTypeDescriptorSymbolicReference), @@ -62,12 +62,12 @@ struct RealThunkShapeProbe { else { return nil } let ordinal: Int = opaqueTypeNode[safeChild: 1]?.index?.cast() ?? 0 - let descriptor = try OpaqueTypeDescriptor.resolve(from: descriptorOffset, in: machO) - let opaqueType = try OpaqueType(descriptor: descriptor, in: machO) + let descriptor = try OpaqueTypeDescriptor.resolve(at: descriptorOffset, in: machO.context) + let opaqueType = try OpaqueType(descriptor: descriptor, in: machO.context) guard ordinal < opaqueType.underlyingTypeArgumentMangledNames.count else { return nil } let underlyingTypeNode = try SymbolicDemangler.demangleType( for: opaqueType.underlyingTypeArgumentMangledNames[ordinal], - in: machO + in: machO.context ) guard let accessorReference = underlyingTypeNode.first(of: Node.Kind.accessorFunctionReference), let offset: Int = accessorReference.index?.cast() diff --git a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift index 2f3d02fc0..83d504ee4 100644 --- a/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/SimulatorRuntimeThunkResolutionTests.swift @@ -56,17 +56,17 @@ struct SimulatorStandaloneSwiftUIThunkTests { var texts: [String: String] = [:] for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let name = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile).print(using: .default), + guard let name = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile.context).print(using: .default), name == typeName, - let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) + let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile.context) else { continue } - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile)) - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile) + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile.context)) + for record in try fieldDescriptor.records(in: machOFile.context) { + guard let mangledTypeName = try? record.mangledTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context) else { continue } let resolvedNode = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout) - texts[try record.fieldName(in: machOFile)] = resolvedNode.print(using: .default) + texts[try record.fieldName(in: machOFile.context)] = resolvedNode.print(using: .default) } } return texts @@ -84,7 +84,7 @@ struct SimulatorStandaloneSwiftUIThunkTests { return } let typeNames = try library.swift.typeContextDescriptors.compactMap { wrapper in - try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: library).print(using: .default) + try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: library.context).print(using: .default) } #expect(typeNames.contains("Synchronization.Mutex"), "\(typeNames)") #expect(typeNames.count >= 10, "\(typeNames)") @@ -132,15 +132,15 @@ struct SimulatorStandaloneSwiftUIThunkTests { var collectionViewBodyWitness: String? var byNameLeftovers: [String] = [] for associatedType in try machOFile.swift.associatedTypes { - let conformingTypeName = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machOFile)).print(using: DemangleOptions.default) + let conformingTypeName = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machOFile.context)).print(using: DemangleOptions.default) for record in associatedType.records { - guard let mangledName = try? record.substitutedTypeName(in: machOFile), - let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machOFile), + guard let mangledName = try? record.substitutedTypeName(in: machOFile.context), + let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machOFile.context), node.contains(Node.Kind.opaqueType) else { continue } let resolved = node.resolveOpaqueTypeCollectingConditionalCandidates(in: machOFile).node if resolved.contains(Node.Kind.opaqueReturnTypeOf) { byNameLeftovers.append(conformingTypeName) } - if conformingTypeName.hasPrefix("SwiftUI.SidebarListBody.(CollectionViewBody in "), try record.name(in: machOFile) == "Body" { + if conformingTypeName.hasPrefix("SwiftUI.SidebarListBody.(CollectionViewBody in "), try record.name(in: machOFile.context) == "Body" { collectionViewBodyWitness = await resolved.print(using: DemangleOptions.default) } } @@ -159,8 +159,8 @@ struct SimulatorStandaloneSwiftUIThunkTests { for associatedType in try machOFile.swift.associatedTypes { var hasConditionalWitness = false for record in associatedType.records { - guard let mangledName = try? record.substitutedTypeName(in: machOFile), - let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machOFile), + guard let mangledName = try? record.substitutedTypeName(in: machOFile.context), + let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machOFile.context), node.contains(Node.Kind.opaqueType) else { continue } let resolution = node.resolveOpaqueTypeCollectingConditionalCandidates(in: machOFile) @@ -201,8 +201,8 @@ struct SimulatorCacheSwiftUIThunkTests { var conditionalWitnessCount = 0 for associatedType in try machO.swift.associatedTypes { for record in associatedType.records { - guard let mangledName = try? record.substitutedTypeName(in: machO), - let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machO), + guard let mangledName = try? record.substitutedTypeName(in: machO.context), + let node = try? SymbolicDemangler.demangleType(for: mangledName, in: machO.context), node.contains(Node.Kind.opaqueType) else { continue } let resolution = node.resolveOpaqueTypeCollectingConditionalCandidates(in: machO) @@ -245,17 +245,17 @@ struct ArchivedMacOSCacheSwiftUICoreMergedAccessorTests { var texts: [String: String] = [:] for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let name = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile).print(using: .default), + guard let name = try? SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile.context).print(using: .default), name == "SwiftUI.PlatformAccessibilitySettingsDefinition" || name == "SwiftUI.NamedImage.Cache", - let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) + let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile.context) else { continue } - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile)) - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile), + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile.context)) + for record in try fieldDescriptor.records(in: machOFile.context) { + guard let mangledTypeName = try? record.mangledTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context), typeNode.contains(Node.Kind.accessorFunctionReference) else { continue } - texts["\(name).\(try record.fieldName(in: machOFile))"] = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout).print(using: .default) + texts["\(name).\(try record.fieldName(in: machOFile.context))"] = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout).print(using: .default) } } try #require(texts.count == 2, "the premise: this cache's SwiftUICore names both fields through accessor-function references") diff --git a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift index bf84eab65..fcc10e2c1 100644 --- a/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift +++ b/Tests/SwiftThunkAnalysisTests/StandaloneFileThunkResolutionTests.swift @@ -102,6 +102,60 @@ struct StandaloneFileThunkResolutionTests { } """ + /// The same source linked into a main executable, whose `__TEXT` sits at + /// 0x100000000. Its kind-9 thunks call the image's own copy of + /// `__swift_instantiateConcreteTypeFromMangledNameV2`, found by its local + /// symbol — whose value is an address, which a dylib's `__TEXT` at 0 had + /// let pass for a file offset. + private static let executableCompilationResult: Result = { + Result { + let workingDirectory = FileManager.default.temporaryDirectory + .appendingPathComponent("ThunkProbeExecutableFixture-\(UUID().uuidString)") + try FileManager.default.createDirectory(at: workingDirectory, withIntermediateDirectories: true) + _ = FixtureWorkingDirectoryCleanup.registration + FixtureWorkingDirectoryCleanup.directories.append(workingDirectory) + + let sourceURL = workingDirectory.appendingPathComponent("ThunkProbe.swift") + let mainSourceURL = workingDirectory.appendingPathComponent("main.swift") + let executableURL = workingDirectory.appendingPathComponent("ThunkProbe") + try fixtureSource.write(to: sourceURL, atomically: true, encoding: .utf8) + try executableMainSource.write(to: mainSourceURL, atomically: true, encoding: .utf8) + + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcrun") + process.arguments = [ + "swiftc", "-O", "-module-name", "ThunkProbe", + "-target", "arm64-apple-macosx15.0", + sourceURL.path, mainSourceURL.path, "-o", executableURL.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 executableURL + } + }() + + private static let executableMainSource = """ + let holder = ProbeHolder() + print(holder.counter.withLock { $0 }) + """ + + private func loadExecutableFixture() throws -> MachOFile { + let executableURL = try Self.executableCompilationResult.get() + switch try File.loadFromFile(url: executableURL) { + case .machO(let machOFile): + return machOFile + case .fat(let fatFile): + return try #require(try fatFile.machOFiles().first { $0.header.cpuType == .arm64 }) + } + } + private func loadFixture() throws -> MachOFile { let libraryURL = try Self.fixtureCompilationResult.get() switch try File.loadFromFile(url: libraryURL) { @@ -126,19 +180,19 @@ struct StandaloneFileThunkResolutionTests { var resolved: [ResolvedField] = [] for wrapper in try machOFile.swift.typeContextDescriptors { let descriptor = wrapper.typeContextDescriptor - guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile) else { continue } - let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile)) - let ownerName = try SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile).print(using: .default) - for record in try fieldDescriptor.records(in: machOFile) { - guard let mangledTypeName = try? record.mangledTypeName(in: machOFile), - let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile), + guard let fieldDescriptor = try? descriptor.fieldDescriptor(in: machOFile.context) else { continue } + let ownerLayout = AccessorThunkOwnerLayout(genericContext: try descriptor.genericContext(in: machOFile.context)) + let ownerName = try SymbolicDemangler.demangleContext(for: wrapper.asContextDescriptorWrapper, in: machOFile.context).print(using: .default) + for record in try fieldDescriptor.records(in: machOFile.context) { + guard let mangledTypeName = try? record.mangledTypeName(in: machOFile.context), + let typeNode = try? SymbolicDemangler.demangleType(for: mangledTypeName, in: machOFile.context), let reference = typeNode.first(of: Node.Kind.accessorFunctionReference), let thunkOffset = reference.index else { continue } let resolvedNode = typeNode.resolvingAccessorFunctionReferences(in: machOFile, ownerLayout: ownerLayout) resolved.append(ResolvedField( owner: ownerName, - name: try record.fieldName(in: machOFile), + name: try record.fieldName(in: machOFile.context), text: resolvedNode.print(using: .default), thunkOffset: Int(thunkOffset), ownerLayout: ownerLayout @@ -163,6 +217,20 @@ struct StandaloneFileThunkResolutionTests { #expect(text(of: "counter") == "Synchronization.Mutex") } + /// In a main executable the concrete fields' thunks reach the image's own + /// runtime helper, named by a local symbol whose value is its address. + /// Before the fix that value was read as a file offset, so the helper + /// went unrecognized and both fields printed as `accessor function at …`. + @Test func theImageLocalRuntimeHelperResolvesInAnExecutable() throws { + let machOFile = try loadExecutableFixture() + // The premise: the helper is the image's own, under a local symbol. + try #require(machOFile.symbols.contains { $0.name == "___swift_instantiateConcreteTypeFromMangledNameV2" && $0.nlist.sectionNumber != nil }) + let fields = try resolvedAccessorFields(in: machOFile) + func text(of name: String) -> String? { fields.first { $0.name == name }?.text } + #expect(text(of: "observed") == "Synchronization.Mutex>", "\(fields.map(\.text))") + #expect(text(of: "counter") == "Synchronization.Mutex", "\(fields.map(\.text))") + } + /// Without any search path the binds have nowhere to resolve, and the /// honest answer is the placeholder — never a partial or wrong type. @Test func withoutSearchPathsTheBindsStayUnreadAndAreNamed() throws { diff --git a/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift b/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift index cf532c5bb..586a24087 100644 --- a/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift +++ b/Tests/SwiftThunkAnalysisTests/ThunkResolutionSurveyProbe.swift @@ -29,17 +29,17 @@ struct ThunkResolutionSurveyProbe { for associatedType in try machO.swift.associatedTypes { for record in associatedType.records { - guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO), in: machO), + guard let node = try? SymbolicDemangler.demangleType(for: record.substitutedTypeName(in: machO.context), in: machO.context), let opaqueTypeNode = node.first(of: Node.Kind.opaqueType), let descriptorReference = opaqueTypeNode.firstChild, descriptorReference.isKind(of: .opaqueTypeDescriptorSymbolicReference), let descriptorOffset: Int = descriptorReference.index?.cast(), - let descriptor = try? OpaqueTypeDescriptor.resolve(from: descriptorOffset, in: machO), - let opaqueType = try? OpaqueType(descriptor: descriptor, in: machO) + let descriptor = try? OpaqueTypeDescriptor.resolve(at: descriptorOffset, in: machO.context), + let opaqueType = try? OpaqueType(descriptor: descriptor, in: machO.context) else { continue } let ordinal: Int = opaqueTypeNode[safeChild: 1]?.index?.cast() ?? 0 guard ordinal < opaqueType.underlyingTypeArgumentMangledNames.count, - let underlyingNode = try? SymbolicDemangler.demangleType(for: opaqueType.underlyingTypeArgumentMangledNames[ordinal], in: machO), + let underlyingNode = try? SymbolicDemangler.demangleType(for: opaqueType.underlyingTypeArgumentMangledNames[ordinal], in: machO.context), let accessorReference = underlyingNode.first(of: Node.Kind.accessorFunctionReference), let thunkOffset: Int = accessorReference.index?.cast() else { continue } @@ -47,10 +47,10 @@ struct ThunkResolutionSurveyProbe { recordCount += 1 guard seenThunkOffsets.insert(thunkOffset).inserted else { continue } - let conformingTypeName = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machO)) + let conformingTypeName = await (try SymbolicDemangler.demangleType(for: associatedType.conformingTypeName, in: machO.context)) .print(using: DemangleOptions.default) let resolved = try AccessorThunkReader.read(thunkAtOffset: thunkOffset, in: machO) - print("######## \(conformingTypeName).\(try record.name(in: machO))") + print("######## \(conformingTypeName).\(try record.name(in: machO.context))") if let check = resolved.availabilityCheck { print(" if #available(platform \(check.platform), \(check.major).\(check.minor).\(check.patch))") } diff --git a/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift b/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift index 35e2b69bf..08036a70a 100644 --- a/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift +++ b/Tests/TypeIndexingTests/SupplementaryAPINotesTests.swift @@ -41,12 +41,17 @@ struct SupplementaryAPINotesTests { """ /// The end-to-end data flow for a user-supplied AttributeGraph mapping, - /// in all three mangling shapes a CF-bridged type reaches Swift metadata - /// as: the typedef name (`AGGraphRef`, a typealias node → `.other`), the + /// in both mangling shapes a CF-bridged type reaches Swift metadata as: + /// the typedef name (`AGGraphRef`, a typealias node → `.other`) and the /// storage/tag name (`AGGraphStorage`, a foreign *class* descriptor the - /// consuming binary emits → `.objcClass`), and the imported Swift name - /// itself (`__C.Graph`, a foreign descriptor recording the post-rename - /// spelling — attribution-only, no rewrite needed or possible). + /// consuming binary emits → `.objcClass`). + /// + /// The imported Swift spelling (`Graph`) is attributed as well, though + /// no printed name carries it any more: a foreign descriptor records it, + /// but the demangler names the descriptor by the ABI name in its import + /// info (evolution proposal `type-import-info-identity`). Why the + /// spellings are still registered: + /// `TypeDatabaseMergePriorityTests.renamingEntryKeepsItsModuleAgainstLaterListings`. @Test func userSuppliedMappingsResolveInAllManglingShapes() async throws { let directoryURL = try Self.makeTemporaryDirectory() diff --git a/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift b/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift index 15add2a5e..de0f8b943 100644 --- a/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift +++ b/Tests/TypeIndexingTests/TypeDatabaseMergePriorityTests.swift @@ -11,11 +11,24 @@ import Testing @Suite struct TypeDatabaseMergePriorityTests { private static func makeAPINotesIndex(yaml apiNotesYAML: String) throws -> APINotesIndex { - let temporaryFileURL = FileManager.default.temporaryDirectory - .appending(component: "TypeDatabaseMergePriorityTests-\(UUID().uuidString).apinotes") - try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) - defer { try? FileManager.default.removeItem(at: temporaryFileURL) } - return try APINotesIndex(files: [APINotesFile(path: temporaryFileURL.path(percentEncoded: false))]) + try makeAPINotesIndex(yamls: [apiNotesYAML]) + } + + /// One index over several files, registered in the order given. + private static func makeAPINotesIndex(yamls apiNotesYAMLs: [String]) throws -> APINotesIndex { + var temporaryFileURLs: [URL] = [] + defer { + for temporaryFileURL in temporaryFileURLs { + try? FileManager.default.removeItem(at: temporaryFileURL) + } + } + for apiNotesYAML in apiNotesYAMLs { + let temporaryFileURL = FileManager.default.temporaryDirectory + .appending(component: "TypeDatabaseMergePriorityTests-\(UUID().uuidString).apinotes") + try apiNotesYAML.write(to: temporaryFileURL, atomically: true, encoding: .utf8) + temporaryFileURLs.append(temporaryFileURL) + } + return try APINotesIndex(files: temporaryFileURLs.map { try APINotesFile(path: $0.path(percentEncoded: false)) }) } @Test @@ -49,6 +62,33 @@ struct TypeDatabaseMergePriorityTests { #expect(await typeDatabase.moduleName(forTypeName: "TSTThing") == "RightModule") } + /// A C name several modules' APINotes list keeps the module whose entry + /// renames it. Foundation's and AppKit's APINotes list `NSObject` only to + /// annotate category methods, and among C-name entries the last file + /// wins; ObjectiveC's entry renames `NSObject` to itself, and that + /// spelling, registered after the C names, keeps the class in + /// ObjectiveC. Without it AppKit's resolved interface printed + /// `Foundation.NSObject`. + @Test + func renamingEntryKeepsItsModuleAgainstLaterListings() async throws { + let typeDatabase = TypeDatabase(platform: .macOS) + let apiNotesIndex = try Self.makeAPINotesIndex(yamls: [ + """ + Name: DeclaringModule + Classes: + - Name: TSTBase + SwiftName: TSTBase + """, + """ + Name: AnnotatingModule + Classes: + - Name: TSTBase + """, + ]) + await typeDatabase.register(apiNotesIndex: apiNotesIndex) + #expect(await typeDatabase.moduleName(forTypeName: "TSTBase") == "DeclaringModule") + } + @Test func swiftNameForCNameComesFromAPINotes() async throws { let typeDatabase = TypeDatabase(platform: .macOS) diff --git a/build-executable-product.sh b/build-executable-product.sh index ada66135a..6e5c23ead 100755 --- a/build-executable-product.sh +++ b/build-executable-product.sh @@ -4,35 +4,75 @@ set -e # Exit on any error # Builds a universal `swift-section` (x86_64 + arm64) and signs it ad hoc. # -# SwiftPM 6.4 made the Swift Build engine the default. Its products land in -# `/out/Products/` — one directory shared by every -# architecture — instead of the native engine's `.build//`. -# Each architecture therefore gets its own scratch path, and the binary -# location is asked from SwiftPM (`--show-bin-path`) rather than assumed, so -# the script works under both engines and with either toolchain. +# How the two slices get built depends on SwiftPM's default build engine, and +# the two engines fail in opposite ways once macro plugins (MemberwiseInit, +# FrameworkToolbox) are in the graph: +# +# - Swift Build, the default from SwiftPM 6.4: a separate `--arch x86_64` build +# on an arm64 Mac never builds the macro plugins for the host ("Build input +# file cannot be found: …/MemberwiseInitMacros"). One build with both +# `--arch` flags does, and links the universal binary itself. +# - The native engine, SwiftPM 6.3 and earlier: a build with both `--arch` +# flags goes through XCBuild, which drops the macro plugin targets ("missing +# target with GUID 'PACKAGE-TARGET:MemberwiseInitMacros'"). Separate builds +# work, and lipo joins them. +# +# Each build gets its own scratch path, and the binary location is asked from +# SwiftPM (`--show-bin-path`) rather than assumed: the engines put it in +# different places. PRODUCT_NAME="swift-section" -ARCHITECTURES=("x86_64" "arm64") -SLICE_PATHS=() - -for ARCHITECTURE in "${ARCHITECTURES[@]}"; do - SCRATCH_PATH=".build/universal-${ARCHITECTURE}" - echo "Building ${ARCHITECTURE} architecture..." - swift build -c release --arch "${ARCHITECTURE}" --product "${PRODUCT_NAME}" --scratch-path "${SCRATCH_PATH}" - - BINARY_DIRECTORY="$(swift build -c release --arch "${ARCHITECTURE}" --product "${PRODUCT_NAME}" --scratch-path "${SCRATCH_PATH}" --show-bin-path)" - SLICE_PATH="${BINARY_DIRECTORY}/${PRODUCT_NAME}" - if [ ! -f "${SLICE_PATH}" ]; then - echo "Error: ${ARCHITECTURE} binary not found at ${SLICE_PATH}" - exit 1 - fi - SLICE_PATHS+=("${SLICE_PATH}") -done +SWIFT_VERSION_NUMBERS="$(swift --version 2>&1 | sed -nE 's/.*Swift version ([0-9]+)\.([0-9]+).*/\1 \2/p' | head -n 1)" +read -r SWIFT_MAJOR_VERSION SWIFT_MINOR_VERSION <<< "${SWIFT_VERSION_NUMBERS}" +if [ -z "${SWIFT_MAJOR_VERSION}" ] || [ -z "${SWIFT_MINOR_VERSION}" ]; then + echo "Error: could not read the Swift version from 'swift --version'" + exit 1 +fi + +swift package update + +# Builds with the given arguments and prints the path of the resulting binary. +# The build's own output goes to stderr so that only the path is captured. +build_product() { + local binary_directory + swift build -c release --product "${PRODUCT_NAME}" "$@" >&2 || return 1 + binary_directory="$(swift build -c release --product "${PRODUCT_NAME}" "$@" --show-bin-path)" || return 1 + echo "${binary_directory}/${PRODUCT_NAME}" +} -# Create Products directory mkdir -p Products -echo "Creating universal binary..." -lipo -create "${SLICE_PATHS[@]}" -output "./Products/${PRODUCT_NAME}" +if [ "${SWIFT_MAJOR_VERSION}" -gt 6 ] || { [ "${SWIFT_MAJOR_VERSION}" -eq 6 ] && [ "${SWIFT_MINOR_VERSION}" -ge 4 ]; }; then + echo "Building arm64 + x86_64 in one Swift Build invocation..." + UNIVERSAL_BINARY_PATH="$(build_product --arch arm64 --arch x86_64 --scratch-path .build/universal)" + if [ ! -f "${UNIVERSAL_BINARY_PATH}" ]; then + echo "Error: universal binary not found at ${UNIVERSAL_BINARY_PATH}" + exit 1 + fi + cp "${UNIVERSAL_BINARY_PATH}" "./Products/${PRODUCT_NAME}" +else + SLICE_PATHS=() + for ARCHITECTURE in x86_64 arm64; do + echo "Building ${ARCHITECTURE} architecture..." + SLICE_PATH="$(build_product --arch "${ARCHITECTURE}" --scratch-path ".build/universal-${ARCHITECTURE}")" + if [ ! -f "${SLICE_PATH}" ]; then + echo "Error: ${ARCHITECTURE} binary not found at ${SLICE_PATH}" + exit 1 + fi + SLICE_PATHS+=("${SLICE_PATH}") + done + echo "Creating universal binary..." + lipo -create "${SLICE_PATHS[@]}" -output "./Products/${PRODUCT_NAME}" +fi + +# One architecture per `-verify_arch`: Xcode 27's lipo takes a second +# architecture name for a second input file and refuses the command. +for ARCHITECTURE in arm64 x86_64; do + if ! lipo "./Products/${PRODUCT_NAME}" -verify_arch "${ARCHITECTURE}"; then + echo "Error: ./Products/${PRODUCT_NAME} lacks ${ARCHITECTURE}:" + lipo -info "./Products/${PRODUCT_NAME}" + exit 1 + fi +done echo "Signing universal binary..." codesign --force --sign - "./Products/${PRODUCT_NAME}" diff --git a/install.sh b/install.sh new file mode 100755 index 000000000..00bcc57ce --- /dev/null +++ b/install.sh @@ -0,0 +1,57 @@ +#!/bin/bash + +set -e # Exit on any error + +# Builds `swift-section` with build-executable-product.sh and installs the +# resulting binary on this machine. +# +# ./install.sh [install-directory] +# +# The install directory defaults to /usr/local/bin, which macOS puts on PATH +# through /etc/paths. sudo is used only when that directory is not writable. +PRODUCT_NAME="swift-section" +PACKAGE_DIRECTORY="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +INSTALL_DIRECTORY="${1:-/usr/local/bin}" + +# A relative install directory means relative to where the script was invoked, +# so it is made absolute before the build changes the working directory. +case "${INSTALL_DIRECTORY}" in + /*) ;; + *) INSTALL_DIRECTORY="${PWD}/${INSTALL_DIRECTORY}" ;; +esac +INSTALL_DIRECTORY="${INSTALL_DIRECTORY%/}" +INSTALL_PATH="${INSTALL_DIRECTORY}/${PRODUCT_NAME}" + +# build-executable-product.sh works relative to the current directory. +cd "${PACKAGE_DIRECTORY}" +./build-executable-product.sh + +PRODUCT_PATH="${PACKAGE_DIRECTORY}/Products/${PRODUCT_NAME}" +if [ ! -f "${PRODUCT_PATH}" ]; then + echo "Error: ${PRODUCT_PATH} not found after the build" + exit 1 +fi + +PRIVILEGE_COMMAND=() +if ! mkdir -p "${INSTALL_DIRECTORY}" 2>/dev/null || [ ! -w "${INSTALL_DIRECTORY}" ]; then + echo "${INSTALL_DIRECTORY} is not writable; installing with sudo..." + PRIVILEGE_COMMAND=(sudo) +fi + +# `install` writes a temporary file and renames it over the target, so an +# existing binary is replaced by a new file rather than overwritten in place: +# overwriting a signed binary in place gets the new one killed on launch. +"${PRIVILEGE_COMMAND[@]}" mkdir -p "${INSTALL_DIRECTORY}" +"${PRIVILEGE_COMMAND[@]}" install -m 0755 "${PRODUCT_PATH}" "${INSTALL_PATH}" + +echo "Installed ${INSTALL_PATH}, version $("${INSTALL_PATH}" --version)" + +# Another `swift-section` earlier on PATH — typically Homebrew's in +# /opt/homebrew/bin — would keep running instead of the one just installed. +RESOLVED_PATH="$(command -v "${PRODUCT_NAME}" || true)" +if [ -z "${RESOLVED_PATH}" ]; then + echo "Warning: ${INSTALL_DIRECTORY} is not on PATH; run ${INSTALL_PATH} directly or add the directory to PATH." +elif [ "${RESOLVED_PATH}" != "${INSTALL_PATH}" ]; then + echo "Warning: '${PRODUCT_NAME}' on PATH resolves to ${RESOLVED_PATH}, which shadows ${INSTALL_PATH}." + echo " Remove that copy (for Homebrew: brew uninstall ${PRODUCT_NAME}) or put ${INSTALL_DIRECTORY} earlier on PATH." +fi