diff --git a/Sources/PackLib/Packer.swift b/Sources/PackLib/Packer.swift index 6506fe7d..cd7933e0 100644 --- a/Sources/PackLib/Packer.swift +++ b/Sources/PackLib/Packer.swift @@ -59,7 +59,8 @@ public struct Packer: Sendable { for product in plan.allProducts { let sources: URL = packageDir.appendingPathComponent("Sources/\(product.targetName)", isDirectory: true) try FileManager.default.createDirectory(at: sources, withIntermediateDirectories: true) - try Data().write(to: sources.appendingPathComponent("stub.c", isDirectory: false)) + let stub = Self.stubSource(for: product.type) + try Data(stub.utf8).write(to: sources.appendingPathComponent("stub.c", isDirectory: false)) } let buildConfig = try await buildSettings @@ -75,6 +76,12 @@ public struct Packer: Sendable { // in order to dump the plan, so we can skip resolution here to skirt // the issue. "--disable-automatic-resolution", + // Dependency scanning does not enable cross-import overlays + // by default, so modules like `_PhotosUI_SwiftUI` never make + // it into the explicit module map and types such as + // `PhotosPickerItem` become unresolvable. Opt in explicitly. + "-Xswiftc", "-Xfrontend", + "-Xswiftc", "-enable-cross-import-overlays", ], ) try await Subprocess.run( @@ -218,6 +225,24 @@ public struct Packer: Sendable { } } + /// The `stub.c` source written into the builder package's target for a product. + static func stubSource(for productType: Plan.ProductType) -> String { + switch productType { + case .application: + return "" + case .appExtension: + // The extension links with -e _NSExtensionMain, so nothing + // references the user's `main` at link time. Under + // -dead_strip that strips the entire extension. A weak + // reference anchors `main` when it exists and compiles to + // NULL when the extension has none. + return """ + extern int main(void) __attribute__((weak_import)); + __attribute__((used)) static void * const xtool_main_anchor = (void * const)&main; + """ + } + } + static func cfBundleSupportedPlatforms(for triple: String) -> [String] { let components = triple.split(separator: "-").map(String.init) guard let appleIndex = components.firstIndex(of: "apple"), diff --git a/Tests/XToolTests/PackerTests.swift b/Tests/XToolTests/PackerTests.swift index 5aabda83..ef128b16 100644 --- a/Tests/XToolTests/PackerTests.swift +++ b/Tests/XToolTests/PackerTests.swift @@ -13,3 +13,15 @@ import Testing #expect(Packer.cfBundleSupportedPlatforms(for: "unknown-triple") == ["iPhoneOS"]) } + +@Test func extensionStubAnchorsMainAgainstDeadStripping() { + #expect(Packer.stubSource(for: .application) == "") + + let stub = Packer.stubSource(for: .appExtension) + // Extensions link with `-e _NSExtensionMain`, so nothing references + // the product's `main`; `-dead_strip` then strips all of its code. + // The stub must weakly anchor `main` without requiring it to exist. + #expect(stub.contains("weak_import")) + #expect(stub.contains("&main")) + #expect(stub.contains("used")) +}