Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
290 changes: 189 additions & 101 deletions Sources/XToolSupport/SDKBuilder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ struct SDKBuilder {
"""
}

// swiftlint:disable:next function_body_length
func buildSDK() async throws {
let sdkVersion = Self.currentSDKVersion

Expand All @@ -107,40 +106,7 @@ struct SDKBuilder {

try await installToolset(in: output)

let dev = try await installDeveloper(in: output)

func sdk(platform: String, prefix: String) throws -> String {
let regex = try NSRegularExpression(pattern: #"^\#(prefix)\d+\.\d+\.sdk$"#)
let dir = dev.appendingPathComponent("Platforms/\(platform).platform/Developer/SDKs")
let names = try dir.contents().map(\.lastPathComponent)
guard let name = names.first(where: {
regex.firstMatch(in: $0, range: NSRange($0.startIndex..., in: $0)) != nil
}) else {
throw Console.Error("Could not find SDK for \(platform)/\(prefix)")
}
return name
}

func triple(platform: String, sdk: String) -> SDKDefinition.Triple {
SDKDefinition.Triple(
sdkRootPath: "Developer/Platforms/\(platform).platform/Developer/SDKs/\(sdk)",
includeSearchPaths: ["Developer/Platforms/\(platform).platform/Developer/usr/lib"],
librarySearchPaths: ["Developer/Platforms/\(platform).platform/Developer/usr/lib"],
swiftResourcesPath: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift",
swiftStaticResourcesPath: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift_static",
toolsetPaths: ["toolset.json"]
)
}

let iPhoneOSSDK = try sdk(platform: "iPhoneOS", prefix: "iPhoneOS")
let iPhoneSimSDK = try sdk(platform: "iPhoneSimulator", prefix: "iPhoneSimulator")
let macOSSDK = try sdk(platform: "MacOSX", prefix: "MacOSX")

d.out.print("""
- \(iPhoneOSSDK)
- \(iPhoneSimSDK)
- \(macOSSDK)
""")
let sdkDefinition = try await installDeveloper(in: output)

d.out.print("[Writing metadata]")
try """
Expand Down Expand Up @@ -213,17 +179,6 @@ struct SDKBuilder {
encoding: .utf8
)

let sdkDefinition = SDKDefinition(
schemaVersion: "4.0",
targetTriples: [
"arm64-apple-ios": triple(platform: "iPhoneOS", sdk: iPhoneOSSDK),
"arm64-apple-ios-simulator": triple(platform: "iPhoneSimulator", sdk: iPhoneSimSDK),
"x86_64-apple-ios-simulator": triple(platform: "iPhoneSimulator", sdk: iPhoneSimSDK),
"arm64-apple-macosx": triple(platform: "MacOSX", sdk: macOSSDK),
"x86_64-apple-macosx": triple(platform: "MacOSX", sdk: macOSSDK),
]
)

let encoder = JSONEncoder()
try encoder
.encode(sdkDefinition)
Expand Down Expand Up @@ -476,7 +431,7 @@ struct SDKBuilder {
private static let expectedXcodeChildren = ["Info.plist", "version.plist", "Developer"]

// swiftlint:disable:next cyclomatic_complexity function_body_length
private func installDeveloper(in output: URL) async throws -> URL {
func installDeveloper(in output: URL) async throws -> SDKDefinition {
let dev = output.appendingPathComponent("Developer")

let expectedAppDir = output.appendingPathComponent("Xcode.app")
Expand Down Expand Up @@ -596,77 +551,210 @@ struct SDKBuilder {
try FileManager.default.removeItem(at: cleanupStageDir)
}

d.out.print("[Finalizing SDKs]")
return try finalizeDeveloper(in: dev)
}

for platform in ["iPhoneOS", "MacOSX", "iPhoneSimulator"] {
let lib = "../../../../../Library"
let platformDir = dev.appending(path: "Platforms/\(platform).platform")
private enum Platform: String, CaseIterable {
case iPhoneOS
case iPhoneSimulator
case macOS = "MacOSX"

try patchPlatformManifest(path: platformDir.appending(path: "Info.plist"))
var triples: [String] {
switch self {
case .iPhoneOS: ["arm64-apple-ios"]
case .iPhoneSimulator: ["arm64-apple-ios-simulator", "x86_64-apple-ios-simulator"]
case .macOS: ["arm64-apple-macosx", "x86_64-apple-macosx"]
}
}

/*
XCTest and Testing.framework are located in *.platform/Developer/{Library/Frameworks,usr/lib} rather than inside
the SDK. These search paths are explicitly included when building tests, which presumably ensures that normal
applications don't accidentally link against them in production.
func directory(in developer: URL) -> URL {
developer.appending(path: "Platforms/\(rawValue).platform")
}
}

SwiftPM makes no such affordances outside of macOS, so we add the usr/lib path as include/library search paths
in the SDK config, and symlink the frameworks into the SDKs (since there's no frameworkSearchPaths option).
While this drops a safeguard it's better than not having the testing libs at all.
*/
private var allowsIOSOnly: Bool {
if case (.app, .buildSlim) = (input, mode) { return true }
return false
}

let fwk = platformDir.appending(path: "Developer/SDKs/\(platform).sdk/System/Library/Frameworks").path
private func findSDK(for platform: Platform, in developer: URL, required: Bool) throws -> URL? {
let dir = platform.directory(in: developer).appending(path: "Developer/SDKs")
let entries: [URL]
do {
entries = try FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)
} catch let error as CocoaError where !required &&
(error.code == .fileReadNoSuchFile || error.code == .fileNoSuchFile) {
return nil
}

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/Testing.framework",
withDestinationPath: "\(lib)/Frameworks/Testing.framework"
)
let name = platform.rawValue
let regex = try NSRegularExpression(pattern: #"^\#(name)\d+\.\d+\.sdk$"#)
let root = entries.first { entry in
let candidate = entry.lastPathComponent
return regex.firstMatch(in: candidate, range: NSRange(candidate.startIndex..., in: candidate)) != nil
}
if !required && root == nil && !entries.contains(where: { $0.pathExtension == "sdk" }) {
return nil
}
guard let root, root.dirExists else {
throw Console.Error("Could not find a valid SDK for \(name) in '\(dir.path)'")
}
return root
}

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/XCTest.framework",
withDestinationPath: "\(lib)/Frameworks/XCTest.framework"
)
private func validateStagedSDK(_ root: URL, for platform: Platform) throws {
struct Settings: Decodable {
let canonicalName: String

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/XCUIAutomation.framework",
withDestinationPath: "\(lib)/Frameworks/XCUIAutomation.framework"
)
enum CodingKeys: String, CodingKey {
case canonicalName = "CanonicalName"
}
}

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/XCTestCore.framework",
withDestinationPath: "\(lib)/PrivateFrameworks/XCTestCore.framework"
)
let manifest = root.appending(path: "SDKSettings.json")
let expected = platform.rawValue.lowercased()
let versioned = root.deletingPathExtension().lastPathComponent.lowercased()
guard let data = try? Data(contentsOf: manifest),
let settings = try? JSONDecoder().decode(Settings.self, from: data),
[expected, versioned].contains(settings.canonicalName.lowercased()) else {
throw Console.Error("Invalid SDK settings for \(platform.rawValue) at '\(manifest.path)'")
}

/*
Apply patches to load OpenAppleMacros as the swift-plugin-server
*/

let bin = platformDir.appendingPathComponent("Developer/usr/bin")
let pluginServer = bin.appendingPathComponent("swift-plugin-server")
try? FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
try? FileManager.default.removeItem(at: pluginServer)
try FileManager.default.createSymbolicLink(
atPath: pluginServer.path,
withDestinationPath: "../../../../../../OpenAppleMacrosServer"
)
let plistURL = root.appending(path: "SDKSettings.plist")
if FileManager.default.fileExists(atPath: plistURL.path) {
guard let plistData = try? Data(contentsOf: plistURL),
let raw = try? PropertyListSerialization.propertyList(from: plistData, format: nil) as? [String: Any],
let plistName = raw["CanonicalName"] as? String,
[expected, versioned].contains(plistName.lowercased()) else {
throw Console.Error("Invalid SDK settings plist for \(platform.rawValue) at '\(plistURL.path)'")
}
}

let libSystem = root.appending(path: "usr/lib/libSystem.tbd")
let resolvedLibSystem = libSystem.resolvingSymlinksInPath()
var isDir: ObjCBool = false
guard FileManager.default.fileExists(atPath: resolvedLibSystem.path, isDirectory: &isDir),
!isDir.boolValue,
(try? resolvedLibSystem.resourceValues(forKeys: [.isRegularFileKey]))?.isRegularFile == true,
let payload = try? Data(contentsOf: resolvedLibSystem),
!payload.isEmpty else {
throw Console.Error("Missing essential SDK payload for \(platform.rawValue) at '\(libSystem.path)'")
}
}

private func finalizeDeveloper(in dev: URL) throws -> SDKDefinition {
d.out.print("[Finalizing SDKs]")

var roots: [Platform: URL] = [:]
for platform in Platform.allCases {
roots[platform] = try findSDK(for: platform, in: dev, required: platform != .macOS || !allowsIOSOnly)
}

let hostDir = platformDir.appendingPathComponent("Developer/usr/lib/swift/host")
let pluginsDir = hostDir.appendingPathComponent("plugins")
let isIOSOnly = roots[.macOS] == nil
let swiftResources = "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift"
guard dev.appending(path: swiftResources).dirExists else {
throw Console.Error("Could not find Swift resources in XcodeDefault.xctoolchain")
}

try FileManager.default.createDirectory(at: hostDir, withIntermediateDirectories: true)
try? FileManager.default.removeItem(at: pluginsDir)
try FileManager.default.createSymbolicLink(
atPath: pluginsDir.path,
withDestinationPath: "../../../../../../../../OpenAppleMacrosPlugins"
var triples: [String: SDKDefinition.Triple] = [:]
for platform in Platform.allCases {
guard let root = roots[platform] else { continue }
let platformDir = platform.directory(in: dev)
if isIOSOnly {
try validateStagedSDK(root, for: platform)
}
let alias = platformDir.appending(path: "Developer/SDKs/\(platform.rawValue).sdk")
try finalizePlatform(at: platformDir, sdkRoot: isIOSOnly ? root : alias, allowMissingManifest: isIOSOnly)

let platformPath = "Developer/Platforms/\(platform.rawValue).platform/Developer"
let definition = SDKDefinition.Triple(
sdkRootPath: "\(platformPath)/SDKs/\(root.lastPathComponent)",
includeSearchPaths: ["\(platformPath)/usr/lib"],
librarySearchPaths: ["\(platformPath)/usr/lib"],
swiftResourcesPath: "Developer/\(swiftResources)",
swiftStaticResourcesPath: "Developer/\(swiftResources)_static",
toolsetPaths: ["toolset.json"]
)
for triple in platform.triples {
triples[triple] = definition
}
}

// we copy over the host's clang resorurce dir during install, because intrinsics can differ
// by LLVM version
try FileManager.default.removeItem(
at: dev.appending(path: "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/include")
// Install replaces the Xcode clang headers with those from the host Swift toolchain.
try FileManager.default.removeItem(at: dev.appending(path: "\(swiftResources)/clang/include"))

for platform in Platform.allCases {
if let root = roots[platform] {
d.out.print("- \(root.lastPathComponent)")
}
}
return SDKDefinition(schemaVersion: "4.0", targetTriples: triples)
}

private func finalizePlatform(at platformDir: URL, sdkRoot: URL, allowMissingManifest: Bool) throws {
// SDK-only archives can omit platform manifests. Patch any that are supplied.
let hasManifest = try !allowMissingManifest || platformDir.contents().contains {
$0.lastPathComponent == "Info.plist"
}
if hasManifest {
try patchPlatformManifest(path: platformDir.appending(path: "Info.plist"))
}

/*
XCTest and Testing.framework are located in *.platform/Developer/{Library/Frameworks,usr/lib} rather than inside
the SDK. These search paths are explicitly included when building tests, which presumably ensures that normal
applications don't accidentally link against them in production.

SwiftPM makes no such affordances outside of macOS, so we add the usr/lib path as include/library search paths
in the SDK config, and symlink the frameworks into the SDKs (since there's no frameworkSearchPaths option).
While this drops a safeguard it's better than not having the testing libs at all.
*/

let lib = "../../../../../Library"
let fwk = sdkRoot.appending(path: "System/Library/Frameworks").path

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/Testing.framework",
withDestinationPath: "\(lib)/Frameworks/Testing.framework"
)

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/XCTest.framework",
withDestinationPath: "\(lib)/Frameworks/XCTest.framework"
)

return dev
try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/XCUIAutomation.framework",
withDestinationPath: "\(lib)/Frameworks/XCUIAutomation.framework"
)

try FileManager.default.createSymbolicLink(
atPath: "\(fwk)/XCTestCore.framework",
withDestinationPath: "\(lib)/PrivateFrameworks/XCTestCore.framework"
)

/*
Apply patches to load OpenAppleMacros as the swift-plugin-server
*/

let bin = platformDir.appendingPathComponent("Developer/usr/bin")
let pluginServer = bin.appendingPathComponent("swift-plugin-server")
try? FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
try? FileManager.default.removeItem(at: pluginServer)
try FileManager.default.createSymbolicLink(
atPath: pluginServer.path,
withDestinationPath: "../../../../../../OpenAppleMacrosServer"
)

let hostDir = platformDir.appendingPathComponent("Developer/usr/lib/swift/host")
let pluginsDir = hostDir.appendingPathComponent("plugins")

try FileManager.default.createDirectory(at: hostDir, withIntermediateDirectories: true)
try? FileManager.default.removeItem(at: pluginsDir)
try FileManager.default.createSymbolicLink(
atPath: pluginsDir.path,
withDestinationPath: "../../../../../../../../OpenAppleMacrosPlugins"
)
}

/// Removes unneeded files from a copy of Xcode.app that's owned by xtool.
Expand Down
Loading