xtool.git
Publicgit clone https://git.maproj.org/xtool.gitxtool.git / Sources / XToolSupport / SDKBuilder.swift
SDKBuilder.swift880 lines · 33.4 KiBRaw
| 1 | import XCLIUtils |
| 2 | import Foundation |
| 3 | import Dependencies |
| 4 | import libunxip |
| 5 | import Subprocess |
| 6 | import XKit // HTTPClient, stdoutSafe |
| 7 | import XUtils // System.File{Path,Descriptor} |
| 8 | |
| 9 | // swiftlint:disable:next type_body_length |
| 10 | struct SDKBuilder { |
| 11 | enum Arch: String { |
| 12 | case x86_64 |
| 13 | case aarch64 |
| 14 | } |
| 15 | |
| 16 | enum Input { |
| 17 | case xip(String) |
| 18 | case app(String) |
| 19 | |
| 20 | init(path: String) throws { |
| 21 | var isDir: ObjCBool = false |
| 22 | guard FileManager.default.fileExists(atPath: path, isDirectory: &isDir) else { |
| 23 | throw Console.Error(""" |
| 24 | Could not read file or directory at path '\(path)'. |
| 25 | See 'xtool help sdk' for usage. |
| 26 | """) |
| 27 | } |
| 28 | |
| 29 | let url = URL(fileURLWithPath: path) |
| 30 | |
| 31 | if isDir.boolValue { |
| 32 | self = .app(path) |
| 33 | let devDir = url.appendingPathComponent("Contents/Developer") |
| 34 | guard devDir.dirExists else { |
| 35 | throw Console.Error(""" |
| 36 | The provided directory at '\(path)' does not appear to be a version of Xcode: \ |
| 37 | could not read '\(devDir.path)'. |
| 38 | """) |
| 39 | } |
| 40 | } else { |
| 41 | self = .xip(path) |
| 42 | let handle = try FileHandle(forReadingFrom: url) |
| 43 | defer { try? handle.close() } |
| 44 | |
| 45 | let expectedMagic = "xar!".utf8 |
| 46 | let actualMagic = try handle.read(upToCount: expectedMagic.count) ?? Data() |
| 47 | |
| 48 | guard actualMagic.elementsEqual(expectedMagic) else { |
| 49 | throw Console.Error(""" |
| 50 | The file at '\(path)' does not appear to be a valid XIP file. |
| 51 | """) |
| 52 | } |
| 53 | } |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | enum Mode { |
| 58 | /// Create a slim SDK with just the files that this version of xtool uses |
| 59 | case buildSlim |
| 60 | /// Create an SDK that retains a full copy of Xcode.app/Contents/Developer. |
| 61 | /// Larger but allows in-place updates. |
| 62 | case buildNormal |
| 63 | /// Update a normal SDK in-place. |
| 64 | case update |
| 65 | |
| 66 | var usesHardLinks: Bool { |
| 67 | switch self { |
| 68 | case .buildSlim: false |
| 69 | case .buildNormal, .update: true |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | let input: Input |
| 75 | let output: URL |
| 76 | let arch: Arch |
| 77 | let mode: Mode |
| 78 | |
| 79 | // bump this when the sdk builder logic changes |
| 80 | static let sdkEpoch = 4 |
| 81 | |
| 82 | // tag from https://github.com/xtool-org/darwin-tools-linux-llvm |
| 83 | static let darwinToolsVersion = "1.1.0" |
| 84 | // tag from https://github.com/xtool-org/OpenAppleMacros |
| 85 | static let oamVersion = "1.4.1" |
| 86 | |
| 87 | static var currentSDKVersion: String { |
| 88 | """ |
| 89 | epoch=\(sdkEpoch),darwinTools=\(darwinToolsVersion),oam=\(oamVersion) |
| 90 | """ |
| 91 | } |
| 92 | |
| 93 | // swiftlint:disable:next function_body_length |
| 94 | func buildSDK() async throws { |
| 95 | let sdkVersion = Self.currentSDKVersion |
| 96 | |
| 97 | try? FileManager.default.removeItem(at: output) |
| 98 | try FileManager.default.createDirectory( |
| 99 | at: output, |
| 100 | withIntermediateDirectories: true |
| 101 | ) |
| 102 | |
| 103 | // TODO: parallelize these three steps |
| 104 | // we need to synchronize progress reporting though |
| 105 | |
| 106 | try await installMacros(in: output) |
| 107 | |
| 108 | try await installToolset(in: output) |
| 109 | |
| 110 | let dev = try await installDeveloper(in: output) |
| 111 | |
| 112 | func sdk(platform: String, prefix: String) throws -> String { |
| 113 | let regex = try NSRegularExpression(pattern: #"^\#(prefix)\d+\.\d+\.sdk$"#) |
| 114 | let dir = dev.appendingPathComponent("Platforms/\(platform).platform/Developer/SDKs") |
| 115 | let names = try dir.contents().map(\.lastPathComponent) |
| 116 | guard let name = names.first(where: { |
| 117 | regex.firstMatch(in: $0, range: NSRange($0.startIndex..., in: $0)) != nil |
| 118 | }) else { |
| 119 | throw Console.Error("Could not find SDK for \(platform)/\(prefix)") |
| 120 | } |
| 121 | return name |
| 122 | } |
| 123 | |
| 124 | func triple(platform: String, sdk: String) -> SDKDefinition.Triple { |
| 125 | SDKDefinition.Triple( |
| 126 | sdkRootPath: "Developer/Platforms/\(platform).platform/Developer/SDKs/\(sdk)", |
| 127 | includeSearchPaths: ["Developer/Platforms/\(platform).platform/Developer/usr/lib"], |
| 128 | librarySearchPaths: ["Developer/Platforms/\(platform).platform/Developer/usr/lib"], |
| 129 | swiftResourcesPath: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift", |
| 130 | swiftStaticResourcesPath: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift_static", |
| 131 | toolsetPaths: ["toolset.json"] |
| 132 | ) |
| 133 | } |
| 134 | |
| 135 | let iPhoneOSSDK = try sdk(platform: "iPhoneOS", prefix: "iPhoneOS") |
| 136 | let iPhoneSimSDK = try sdk(platform: "iPhoneSimulator", prefix: "iPhoneSimulator") |
| 137 | let macOSSDK = try sdk(platform: "MacOSX", prefix: "MacOSX") |
| 138 | |
| 139 | d.out.print(""" |
| 140 | - \(iPhoneOSSDK) |
| 141 | - \(iPhoneSimSDK) |
| 142 | - \(macOSSDK) |
| 143 | """) |
| 144 | |
| 145 | d.out.print("[Writing metadata]") |
| 146 | try """ |
| 147 | { |
| 148 | "schemaVersion": "1.0", |
| 149 | "artifacts": { |
| 150 | "darwin": { |
| 151 | "type": "swiftSDK", |
| 152 | "version": "0.0.1", |
| 153 | "variants": [ |
| 154 | { |
| 155 | "path": ".", |
| 156 | "supportedTriples": ["aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"] |
| 157 | } |
| 158 | ] |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | """.write( |
| 163 | to: output.appendingPathComponent("info.json"), |
| 164 | atomically: false, |
| 165 | encoding: .utf8 |
| 166 | ) |
| 167 | |
| 168 | try """ |
| 169 | { |
| 170 | "schemaVersion": "1.0", |
| 171 | "rootPath": "toolset/bin", |
| 172 | "linker": { |
| 173 | "path": "ld64.lld" |
| 174 | }, |
| 175 | "librarian": { |
| 176 | "path": "llvm-lib" |
| 177 | }, |
| 178 | "swiftCompiler": { |
| 179 | "extraCLIOptions": [ |
| 180 | "-Xfrontend", "-enable-cross-import-overlays", |
| 181 | "-use-ld=lld" |
| 182 | ] |
| 183 | } |
| 184 | } |
| 185 | """.write( |
| 186 | to: output.appendingPathComponent("toolset.json"), |
| 187 | atomically: false, |
| 188 | encoding: .utf8 |
| 189 | ) |
| 190 | |
| 191 | // this toolset works with the swiftbuild system on Linux |
| 192 | // note that we need Swift 6.4+ because 6.3 has bugs in |
| 193 | // resolving the librarian and linker paths. |
| 194 | try """ |
| 195 | { |
| 196 | "schemaVersion": "1.0", |
| 197 | "rootPath": "toolset/bin", |
| 198 | "linker": { |
| 199 | "path": "ld64.lld" |
| 200 | }, |
| 201 | "librarian": { |
| 202 | "path": "llvm-lib" |
| 203 | }, |
| 204 | "swiftCompiler": { |
| 205 | "extraCLIOptions": [ |
| 206 | "-Xfrontend", "-enable-cross-import-overlays" |
| 207 | ] |
| 208 | } |
| 209 | } |
| 210 | """.write( |
| 211 | to: output.appendingPathComponent("toolset-swb.json"), |
| 212 | atomically: false, |
| 213 | encoding: .utf8 |
| 214 | ) |
| 215 | |
| 216 | let sdkDefinition = SDKDefinition( |
| 217 | schemaVersion: "4.0", |
| 218 | targetTriples: [ |
| 219 | "arm64-apple-ios": triple(platform: "iPhoneOS", sdk: iPhoneOSSDK), |
| 220 | "arm64-apple-ios-simulator": triple(platform: "iPhoneSimulator", sdk: iPhoneSimSDK), |
| 221 | "x86_64-apple-ios-simulator": triple(platform: "iPhoneSimulator", sdk: iPhoneSimSDK), |
| 222 | "arm64-apple-macosx": triple(platform: "MacOSX", sdk: macOSSDK), |
| 223 | "x86_64-apple-macosx": triple(platform: "MacOSX", sdk: macOSSDK), |
| 224 | ] |
| 225 | ) |
| 226 | |
| 227 | let encoder = JSONEncoder() |
| 228 | try encoder |
| 229 | .encode(sdkDefinition) |
| 230 | .write(to: output.appendingPathComponent("swift-sdk.json")) |
| 231 | |
| 232 | try Data("\(sdkVersion)\n".utf8) |
| 233 | .write(to: output.appendingPathComponent("darwin-sdk-version.txt")) |
| 234 | } |
| 235 | |
| 236 | private func fetchTarball( |
| 237 | url: URL, |
| 238 | destination directory: URL, |
| 239 | displayName: String, |
| 240 | envOverride: String? = nil, |
| 241 | ) async throws { |
| 242 | try FileManager.default.createDirectory( |
| 243 | at: directory, |
| 244 | withIntermediateDirectories: false |
| 245 | ) |
| 246 | |
| 247 | if let envOverride, let path = ProcessInfo.processInfo.environment[envOverride] { |
| 248 | let source = URL(fileURLWithPath: path) |
| 249 | if source.dirExists { |
| 250 | d.out.print("[Copying \(displayName)] \(source.path)") |
| 251 | try await Subprocess.run( |
| 252 | .name("cp"), |
| 253 | arguments: ["-RL", "\(source.path)/.", "."], |
| 254 | workingDirectory: FilePath(directory), |
| 255 | output: .discarded, |
| 256 | error: .discarded, |
| 257 | ) |
| 258 | .checkSuccess() |
| 259 | // later steps write into the copy |
| 260 | try await Subprocess.run( |
| 261 | .name("chmod"), |
| 262 | arguments: ["-R", "u+w", "."], |
| 263 | workingDirectory: FilePath(directory), |
| 264 | output: .discarded, |
| 265 | error: .discarded, |
| 266 | ) |
| 267 | .checkSuccess() |
| 268 | return |
| 269 | } |
| 270 | |
| 271 | d.out.print("[Extracting \(displayName)] \(source.path)") |
| 272 | try await Subprocess.run( |
| 273 | .name("tar"), |
| 274 | arguments: ["xzf", source.path], |
| 275 | workingDirectory: FilePath(directory), |
| 276 | output: .discarded, |
| 277 | error: .discarded, |
| 278 | ) |
| 279 | .checkSuccess() |
| 280 | return |
| 281 | } |
| 282 | |
| 283 | @Dependency(\.httpClient) var httpClient |
| 284 | let (response, body) = try await httpClient.send(HTTPRequest(url: url)) |
| 285 | guard response.status == 200, let body else { |
| 286 | throw Console.Error("Could not fetch tarball at \(url)") |
| 287 | } |
| 288 | let length: Int64? = switch body.length { |
| 289 | case .known(let known): known |
| 290 | case .unknown: nil |
| 291 | } |
| 292 | |
| 293 | defer { d.out.print() } |
| 294 | try await Subprocess.run( |
| 295 | .name("tar"), |
| 296 | arguments: ["xzf", "-"], |
| 297 | workingDirectory: FilePath(directory), |
| 298 | input: .inputWriter, |
| 299 | output: .discarded, |
| 300 | error: .discarded, |
| 301 | ) { execution in |
| 302 | var totalWritten: Int64 = 0 |
| 303 | for try await chunk in body { |
| 304 | var remaining = chunk |
| 305 | while !remaining.isEmpty { |
| 306 | let written = try await execution.standardInputWriter.write(Array(remaining)) |
| 307 | remaining = remaining.dropFirst(written) |
| 308 | totalWritten += Int64(written) |
| 309 | |
| 310 | guard let length else { continue } |
| 311 | let progress = Int(Double(totalWritten) / Double(length) * 100) |
| 312 | d.out.print("\r[Downloading \(displayName)] \(progress)%", terminator: "", flush: true) |
| 313 | } |
| 314 | } |
| 315 | try await execution.standardInputWriter.finish() |
| 316 | } |
| 317 | .checkSuccess() |
| 318 | } |
| 319 | |
| 320 | // swiftlint:disable:next function_body_length |
| 321 | private func installToolset(in output: URL) async throws { |
| 322 | let toolsetDir = output.appendingPathComponent("toolset") |
| 323 | let url = URL(string: """ |
| 324 | https://github.com/xtool-org/darwin-tools-linux-llvm/releases/download/\ |
| 325 | v\(Self.darwinToolsVersion)/toolset-\(arch.rawValue).tar.gz |
| 326 | """)! |
| 327 | try await fetchTarball( |
| 328 | url: url, |
| 329 | destination: toolsetDir, |
| 330 | displayName: "toolset", |
| 331 | envOverride: "XTL_TOOLSET_TARBALL", |
| 332 | ) |
| 333 | |
| 334 | // swift-build assumes we have an Apple-flavored librarian for Apple platforms |
| 335 | // (https://github.com/swiftlang/swift-build/blob/b2433e74e/Sources/SWBCore/SpecImplementations/Tools/LinkerTools.swift#L1735) |
| 336 | // but allows us to override this assumption if we explicitly provide the name llvm-lib (look a few lines above in that file) |
| 337 | try FileManager.default.moveItem( |
| 338 | at: toolsetDir.appending(path: "bin/libtool"), |
| 339 | to: toolsetDir.appending(path: "bin/llvm-lib") |
| 340 | ) |
| 341 | |
| 342 | let ld64 = toolsetDir.appending(path: "bin/ld64.lld") |
| 343 | let origBins = toolsetDir.appending(path: "bin/orig") |
| 344 | let origLD64 = origBins.appending(path: "ld64.lld") |
| 345 | try FileManager.default.createDirectory(at: origBins, withIntermediateDirectories: false) |
| 346 | try FileManager.default.moveItem(at: ld64, to: origLD64) |
| 347 | |
| 348 | // this terrible hack works around the fact that lld doesn't support the -r option, |
| 349 | // which merges multiple object files into one (used by SPM's SWB backend to combine |
| 350 | // per-file MachOs into a single one for the module, on Darwin). |
| 351 | // |
| 352 | // so instead, we write a trampoline that intercepts `ld64.lld -r` and instead runs |
| 353 | // libtool to build a static archive. |
| 354 | try """ |
| 355 | #!/bin/sh |
| 356 | |
| 357 | set -eu |
| 358 | |
| 359 | case "$0" in |
| 360 | */*) script_path="$0" ;; |
| 361 | *) script_path="$(command -v "$0")" ;; |
| 362 | esac |
| 363 | case "$script_path" in |
| 364 | /*) script_dir="${script_path%/*}"; [ -n "$script_dir" ] || script_dir="/" ;; |
| 365 | */*) script_dir="${script_path%/*}" ;; |
| 366 | *) script_dir="." ;; |
| 367 | esac |
| 368 | bin_dir="$(CDPATH= cd -P "$script_dir" && pwd -P)" |
| 369 | |
| 370 | find_argument_value() { |
| 371 | argument_name="$1" |
| 372 | shift |
| 373 | |
| 374 | while [ "$#" -gt 0 ]; do |
| 375 | if [ "$1" = "$argument_name" ]; then |
| 376 | shift |
| 377 | if [ "$#" -gt 0 ]; then |
| 378 | argument_value="$1" |
| 379 | return 0 |
| 380 | fi |
| 381 | return 1 |
| 382 | fi |
| 383 | shift |
| 384 | done |
| 385 | |
| 386 | return 1 |
| 387 | } |
| 388 | |
| 389 | relocatable= |
| 390 | for argument do |
| 391 | if [ "$argument" = "-r" ]; then |
| 392 | relocatable=1 |
| 393 | fi |
| 394 | done |
| 395 | |
| 396 | if [ -n "$relocatable" ]; then |
| 397 | missing_argument= |
| 398 | |
| 399 | if find_argument_value -filelist "$@"; then |
| 400 | filelist="$argument_value" |
| 401 | else |
| 402 | missing_argument=1 |
| 403 | fi |
| 404 | if find_argument_value -dependency_info "$@"; then |
| 405 | dependency_info="$argument_value" |
| 406 | else |
| 407 | missing_argument=1 |
| 408 | fi |
| 409 | if find_argument_value -o "$@"; then |
| 410 | output="$argument_value" |
| 411 | else |
| 412 | missing_argument=1 |
| 413 | fi |
| 414 | |
| 415 | if [ -n "$missing_argument" ]; then |
| 416 | echo "ld64.lld trampoline could not process arguments." >&2 |
| 417 | echo "Please file an issue at https://github.com/xtool-org/xtool/issues" >&2 |
| 418 | echo " Arguments: $@" >&2 |
| 419 | exit 2 |
| 420 | fi |
| 421 | |
| 422 | exec "$bin_dir/llvm-lib" -static \ |
| 423 | -filelist "$filelist" \ |
| 424 | -dependency_info "$dependency_info" \ |
| 425 | -o "$output" |
| 426 | fi |
| 427 | |
| 428 | exec "$bin_dir/orig/ld64.lld" "$@" |
| 429 | """.write( |
| 430 | to: ld64, |
| 431 | atomically: false, |
| 432 | encoding: .utf8 |
| 433 | ) |
| 434 | // set -x |
| 435 | try FileManager.default.setAttributes([.posixPermissions: 0o755], ofItemAtPath: ld64.path) |
| 436 | } |
| 437 | |
| 438 | private func installMacros(in output: URL) async throws { |
| 439 | let url = URL(string: """ |
| 440 | https://github.com/xtool-org/OpenAppleMacros/releases/download/\ |
| 441 | v\(Self.oamVersion)/OpenAppleMacrosServer-\(arch.rawValue).tar.gz |
| 442 | """)! |
| 443 | let macrosDir = output.appendingPathComponent("OpenAppleMacros") |
| 444 | try await fetchTarball( |
| 445 | url: url, |
| 446 | destination: macrosDir, |
| 447 | displayName: "OpenAppleMacros", |
| 448 | envOverride: "XTL_OAM_TARBALL", |
| 449 | ) |
| 450 | |
| 451 | struct MacrosInfo: Decodable { |
| 452 | var plugins: [String] |
| 453 | } |
| 454 | let macrosInfo = try JSONDecoder().decode( |
| 455 | MacrosInfo.self, |
| 456 | from: Data(contentsOf: macrosDir.appendingPathComponent("info.json")) |
| 457 | ) |
| 458 | try FileManager.default.moveItem( |
| 459 | at: macrosDir.appendingPathComponent("OpenAppleMacrosServer"), |
| 460 | to: output.appendingPathComponent("OpenAppleMacrosServer") |
| 461 | ) |
| 462 | try FileManager.default.removeItem(at: macrosDir) |
| 463 | |
| 464 | let pluginsDir = output.appendingPathComponent("OpenAppleMacrosPlugins") |
| 465 | try FileManager.default.createDirectory(at: pluginsDir, withIntermediateDirectories: false) |
| 466 | // create a lib*.so file for each macro 'library' that we support. |
| 467 | // the files are stubs (empty) because we just need them to convince swiftc that |
| 468 | // yes we can handle said modules. the actual logic lives in the OpenAppleMacros |
| 469 | // server. |
| 470 | for library in macrosInfo.plugins { |
| 471 | let target = pluginsDir.appendingPathComponent("lib\(library).so") |
| 472 | try Data().write(to: target) |
| 473 | } |
| 474 | } |
| 475 | |
| 476 | private static let expectedXcodeChildren = ["Info.plist", "version.plist", "Developer"] |
| 477 | |
| 478 | // swiftlint:disable:next cyclomatic_complexity function_body_length |
| 479 | private func installDeveloper(in output: URL) async throws -> URL { |
| 480 | let dev = output.appendingPathComponent("Developer") |
| 481 | |
| 482 | let expectedAppDir = output.appendingPathComponent("Xcode.app") |
| 483 | let appDir: URL |
| 484 | let cleanupStageDir: URL? |
| 485 | let wanted: Int? |
| 486 | |
| 487 | switch (input, mode) { |
| 488 | case (.xip(let inputPath), .buildSlim): |
| 489 | let stage = output.appendingPathComponent("DeveloperStage") |
| 490 | try FileManager.default.createDirectory(at: stage, withIntermediateDirectories: false) |
| 491 | wanted = try await extractXIP(inputPath: inputPath, outDir: stage.path) |
| 492 | try Task.checkCancellation() |
| 493 | let contents = try FileManager.default.contentsOfDirectory( |
| 494 | at: stage, |
| 495 | includingPropertiesForKeys: nil |
| 496 | ) |
| 497 | let apps = contents.filter { $0.pathExtension == "app" } |
| 498 | switch apps.count { |
| 499 | case 0: |
| 500 | throw Console.Error("Unrecognized xip layout (Xcode.app not found)") |
| 501 | case 1: |
| 502 | appDir = apps[0] |
| 503 | default: |
| 504 | throw Console.Error("Unrecognized xip layout (multiple apps found)") |
| 505 | } |
| 506 | cleanupStageDir = stage |
| 507 | case (.xip(let inputPath), .buildNormal): |
| 508 | wanted = try await extractXIP(inputPath: inputPath, outDir: output.path) |
| 509 | appDir = expectedAppDir |
| 510 | cleanupStageDir = nil |
| 511 | try cleanUpXcode(appDir) |
| 512 | case (.xip, .update): |
| 513 | throw Console.Error("Can't update with xip input") |
| 514 | case (.app(let appPath), .buildSlim): |
| 515 | appDir = URL(fileURLWithPath: appPath) |
| 516 | wanted = nil |
| 517 | cleanupStageDir = nil |
| 518 | case (.app(let appPath), .update): |
| 519 | appDir = URL(fileURLWithPath: appPath) |
| 520 | wanted = nil |
| 521 | cleanupStageDir = nil |
| 522 | try cleanUpXcode(appDir) |
| 523 | case (.app(let appPath), .buildNormal): |
| 524 | let source = URL(fileURLWithPath: appPath) |
| 525 | let sourceContentsDir = source.appendingPathComponent("Contents") |
| 526 | let expectedContentsDir = expectedAppDir.appendingPathComponent("Contents") |
| 527 | try FileManager.default.createDirectory(at: expectedContentsDir, withIntermediateDirectories: true) |
| 528 | d.out.print("[Copying Xcode.app] This might take a minute...") |
| 529 | for child in Self.expectedXcodeChildren { |
| 530 | let expectedFile = expectedContentsDir.appendingPathComponent(child) |
| 531 | let sourceFile = sourceContentsDir.appendingPathComponent(child) |
| 532 | guard FileManager.default.fileExists(atPath: sourceFile.path) else { |
| 533 | throw Console.Error(""" |
| 534 | The provided directory at '\(appPath)' does not appear to be a known version of Xcode: \ |
| 535 | could not read '\(sourceFile.path)' |
| 536 | """) |
| 537 | } |
| 538 | try await FileManager.default.copyItem(at: sourceFile, to: expectedFile, preserveOwner: false) |
| 539 | } |
| 540 | appDir = expectedAppDir |
| 541 | wanted = nil |
| 542 | cleanupStageDir = nil |
| 543 | } |
| 544 | try Task.checkCancellation() |
| 545 | |
| 546 | try FileManager.default.createDirectory(at: dev, withIntermediateDirectories: false) |
| 547 | |
| 548 | var toDoDirs: [String] = ["Contents/Developer"] |
| 549 | var count = 0 |
| 550 | while let next = toDoDirs.popLast() { |
| 551 | try Task.checkCancellation() |
| 552 | |
| 553 | let url = appDir.appendingPathComponent(next) |
| 554 | let contents = try FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: [.isDirectoryKey]) |
| 555 | for child in contents { |
| 556 | let path = "\(next)/\(child.lastPathComponent)" |
| 557 | guard Self.isWanted(path[...]) else { continue } |
| 558 | |
| 559 | count += 1 |
| 560 | if let wanted { |
| 561 | let progress = Int(Double(count) / Double(wanted) * 100) |
| 562 | d.out.print("\r[Installing SDKs] \(progress)%", terminator: "", flush: true) |
| 563 | } |
| 564 | if count % 100 == 0 { |
| 565 | if wanted == nil { |
| 566 | d.out.print("\r[Installing SDKs] Installed \(count) files", terminator: "", flush: true) |
| 567 | } |
| 568 | await Task.yield() |
| 569 | } |
| 570 | |
| 571 | let insideDeveloper = path.dropFirst("Contents/Developer/".count) |
| 572 | guard !insideDeveloper.isEmpty else { continue } |
| 573 | let dest = dev.appendingPathComponent(String(insideDeveloper)) |
| 574 | |
| 575 | if try child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true { |
| 576 | toDoDirs.append(path) |
| 577 | try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: false) |
| 578 | } else if mode.usesHardLinks { |
| 579 | // Installed SDKs retain Xcode.app developer dir, so avoid storing their developer files twice. |
| 580 | try FileManager.default.linkItem(at: child, to: dest) |
| 581 | } else { |
| 582 | // Slim SDKs omit Xcode.app and contain independent copies. |
| 583 | try FileManager.default.copyItem(at: child, to: dest) |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | if wanted != nil { |
| 589 | // otherwise the last log might say 99% |
| 590 | d.out.print("\r[Installing SDKs] 100%", terminator: "") |
| 591 | } |
| 592 | d.out.print() |
| 593 | |
| 594 | if let cleanupStageDir { |
| 595 | d.out.print("[Cleaning up]") |
| 596 | try FileManager.default.removeItem(at: cleanupStageDir) |
| 597 | } |
| 598 | |
| 599 | d.out.print("[Finalizing SDKs]") |
| 600 | |
| 601 | for platform in ["iPhoneOS", "MacOSX", "iPhoneSimulator"] { |
| 602 | let lib = "../../../../../Library" |
| 603 | let platformDir = dev.appending(path: "Platforms/\(platform).platform") |
| 604 | |
| 605 | try patchPlatformManifest(path: platformDir.appending(path: "Info.plist")) |
| 606 | |
| 607 | /* |
| 608 | XCTest and Testing.framework are located in *.platform/Developer/{Library/Frameworks,usr/lib} rather than inside |
| 609 | the SDK. These search paths are explicitly included when building tests, which presumably ensures that normal |
| 610 | applications don't accidentally link against them in production. |
| 611 | |
| 612 | SwiftPM makes no such affordances outside of macOS, so we add the usr/lib path as include/library search paths |
| 613 | in the SDK config, and symlink the frameworks into the SDKs (since there's no frameworkSearchPaths option). |
| 614 | While this drops a safeguard it's better than not having the testing libs at all. |
| 615 | */ |
| 616 | |
| 617 | let fwk = platformDir.appending(path: "Developer/SDKs/\(platform).sdk/System/Library/Frameworks").path |
| 618 | |
| 619 | try FileManager.default.createSymbolicLink( |
| 620 | atPath: "\(fwk)/Testing.framework", |
| 621 | withDestinationPath: "\(lib)/Frameworks/Testing.framework" |
| 622 | ) |
| 623 | |
| 624 | try FileManager.default.createSymbolicLink( |
| 625 | atPath: "\(fwk)/XCTest.framework", |
| 626 | withDestinationPath: "\(lib)/Frameworks/XCTest.framework" |
| 627 | ) |
| 628 | |
| 629 | try FileManager.default.createSymbolicLink( |
| 630 | atPath: "\(fwk)/XCUIAutomation.framework", |
| 631 | withDestinationPath: "\(lib)/Frameworks/XCUIAutomation.framework" |
| 632 | ) |
| 633 | |
| 634 | try FileManager.default.createSymbolicLink( |
| 635 | atPath: "\(fwk)/XCTestCore.framework", |
| 636 | withDestinationPath: "\(lib)/PrivateFrameworks/XCTestCore.framework" |
| 637 | ) |
| 638 | |
| 639 | /* |
| 640 | Apply patches to load OpenAppleMacros as the swift-plugin-server |
| 641 | */ |
| 642 | |
| 643 | let bin = platformDir.appendingPathComponent("Developer/usr/bin") |
| 644 | let pluginServer = bin.appendingPathComponent("swift-plugin-server") |
| 645 | try? FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true) |
| 646 | try? FileManager.default.removeItem(at: pluginServer) |
| 647 | try FileManager.default.createSymbolicLink( |
| 648 | atPath: pluginServer.path, |
| 649 | withDestinationPath: "../../../../../../OpenAppleMacrosServer" |
| 650 | ) |
| 651 | |
| 652 | let hostDir = platformDir.appendingPathComponent("Developer/usr/lib/swift/host") |
| 653 | let pluginsDir = hostDir.appendingPathComponent("plugins") |
| 654 | |
| 655 | try FileManager.default.createDirectory(at: hostDir, withIntermediateDirectories: true) |
| 656 | try? FileManager.default.removeItem(at: pluginsDir) |
| 657 | try FileManager.default.createSymbolicLink( |
| 658 | atPath: pluginsDir.path, |
| 659 | withDestinationPath: "../../../../../../../../OpenAppleMacrosPlugins" |
| 660 | ) |
| 661 | } |
| 662 | |
| 663 | // we copy over the host's clang resorurce dir during install, because intrinsics can differ |
| 664 | // by LLVM version |
| 665 | try FileManager.default.removeItem( |
| 666 | at: dev.appending(path: "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/include") |
| 667 | ) |
| 668 | |
| 669 | return dev |
| 670 | } |
| 671 | |
| 672 | /// Removes unneeded files from a copy of Xcode.app that's owned by xtool. |
| 673 | /// |
| 674 | /// This is conservative: we keep anything that we expect _might_ be necessary |
| 675 | /// even in a future update of xtool, so that SDK self-updates work. We only |
| 676 | /// delete files that we're relatively confident won't be needed. |
| 677 | /// |
| 678 | /// - Important: ONLY call this if we own appDir, lest we delete files from the user's Xcode. |
| 679 | private func cleanUpXcode(_ appDir: URL) throws { |
| 680 | let contentsDir = appDir.appendingPathComponent("Contents") |
| 681 | let contents = try FileManager.default.contentsOfDirectory( |
| 682 | at: contentsDir, |
| 683 | includingPropertiesForKeys: nil |
| 684 | ) |
| 685 | let expectedChildren = Set(Self.expectedXcodeChildren) |
| 686 | let missingChildren = expectedChildren.subtracting(contents.map(\.lastPathComponent)) |
| 687 | guard missingChildren.isEmpty else { |
| 688 | let missing = missingChildren.sorted().joined(separator: ", ") |
| 689 | throw Console.Error("Unrecognized xip layout: missing \(missing)") |
| 690 | } |
| 691 | for child in contents where !expectedChildren.contains(child.lastPathComponent) { |
| 692 | try FileManager.default.removeItem(at: child) |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | private func extractXIP(inputPath: String, outDir: String) async throws -> Int { |
| 697 | // unxip doesn't like cooperative cancellation atm so shield it. |
| 698 | // if the user does a ^C during unxip, we'll just wait until extraction |
| 699 | // is over before bailing |
| 700 | try await Task { |
| 701 | try await _extractXIP(inputPath: inputPath, outDir: outDir) |
| 702 | }.value |
| 703 | } |
| 704 | |
| 705 | private func patchPlatformManifest(path: URL) throws { |
| 706 | let data = try Data(contentsOf: path) |
| 707 | guard var plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else { |
| 708 | throw Console.Error("Could not read '\(path.path)'") |
| 709 | } |
| 710 | |
| 711 | var defaultProperties = (plist["DefaultProperties"] as? [String: Any]) ?? [:] |
| 712 | defaultProperties["SWIFT_RESOURCE_DIR"] = "$(PLATFORM_DIR)/../../Toolchains/XcodeDefault.xctoolchain/usr/lib/swift" |
| 713 | defaultProperties["CLANG_RESOURCE_DIR"] = "$(SWIFT_RESOURCE_DIR)/clang" |
| 714 | defaultProperties["ALTERNATE_LINKER"] = "lld" |
| 715 | // stub out codesign as /bin/true (SwiftBuild often emits CodeSign tasks, e.g. when |
| 716 | // building for sim). we sign post-build. |
| 717 | defaultProperties["CODESIGN"] = "true" |
| 718 | plist["DefaultProperties"] = defaultProperties |
| 719 | |
| 720 | let newData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0) |
| 721 | // a non-atomic write would modify the shared inode that's hard-linked from Xcode.app |
| 722 | try newData.write(to: path, options: .atomic) |
| 723 | } |
| 724 | |
| 725 | // returns the number of files we actually want to keep, |
| 726 | // useful for computing progress % during fs traversal |
| 727 | private func _extractXIP(inputPath: String, outDir: String) async throws -> Int { |
| 728 | let fd = try FileDescriptor.open(inputPath, .readOnly) |
| 729 | defer { try? fd.close() } |
| 730 | |
| 731 | let length = try fd.seek(offset: 0, from: .end) |
| 732 | try fd.seek(offset: 0, from: .start) |
| 733 | |
| 734 | // global state, ah well |
| 735 | let oldDirectory = FileManager.default.currentDirectoryPath |
| 736 | guard FileManager.default.changeCurrentDirectoryPath(outDir) else { |
| 737 | throw Console.Error("Could not change directory to '\(outDir)'") |
| 738 | } |
| 739 | defer { _ = FileManager.default.changeCurrentDirectoryPath(oldDirectory) } |
| 740 | |
| 741 | let inputStream = DataReader.data(readingFrom: fd.rawValue) |
| 742 | |
| 743 | let (observer, source) = inputStream.lockstepSplit() |
| 744 | |
| 745 | async let readTask: Void = { |
| 746 | var read = 0 |
| 747 | for try await chunk in observer { |
| 748 | read += chunk.count |
| 749 | let progress = Int(Double(read) / Double(length) * 100) |
| 750 | d.out.print("\r[Extracting XIP] \(progress)%", terminator: "", flush: true) |
| 751 | if read == length { break } |
| 752 | } |
| 753 | }() |
| 754 | |
| 755 | let xipToChunks = XIP.transform( |
| 756 | DataReader(data: source), |
| 757 | options: nil |
| 758 | ) |
| 759 | |
| 760 | // ideally we would filter out the files we don't want at this stage, |
| 761 | // speeding up extraction AND entirely avoiding the "Installing SDKs" |
| 762 | // post-processing step. However, files in xip archives may be hardlinks |
| 763 | // to one another and so we need to handle the case where a file inside |
| 764 | // our filter() points to a file outside of it. We might be able to do this |
| 765 | // with a double-pass system. |
| 766 | |
| 767 | let chunksToFiles = Chunks.transform( |
| 768 | xipToChunks, |
| 769 | options: nil |
| 770 | ) |
| 771 | |
| 772 | let filesToDisk = Files.transform( |
| 773 | chunksToFiles, |
| 774 | options: .init( |
| 775 | compress: false, |
| 776 | dryRun: false |
| 777 | ) |
| 778 | ) |
| 779 | |
| 780 | var wanted = 0 |
| 781 | for try await file in filesToDisk { |
| 782 | wanted += Self.isWanted(file.name[...]) ? 1 : 0 |
| 783 | } |
| 784 | _ = try await readTask |
| 785 | |
| 786 | d.out.print() |
| 787 | |
| 788 | return wanted |
| 789 | } |
| 790 | |
| 791 | private static func isWanted(_ path: Substring) -> Bool { |
| 792 | var components = path.split(separator: "/")[...] |
| 793 | if components.first == "." { |
| 794 | components.removeFirst() |
| 795 | } |
| 796 | if components.first?.hasSuffix(".app") == true { |
| 797 | components.removeFirst() |
| 798 | } |
| 799 | guard SDKEntry.wanted.matches(components) else { return false } |
| 800 | |
| 801 | // TODO: see if we can exclude most dylibs. Seems we need the XCTest ones though. |
| 802 | |
| 803 | if components.count >= 10 && components[components.startIndex + 9] == "prebuilt-modules" && components.starts( |
| 804 | with: "Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift" |
| 805 | .split(separator: "/") |
| 806 | ) { |
| 807 | return false |
| 808 | } |
| 809 | |
| 810 | return true |
| 811 | } |
| 812 | } |
| 813 | |
| 814 | struct SDKDefinition: Encodable { |
| 815 | struct Triple: Encodable { |
| 816 | var sdkRootPath: String |
| 817 | var includeSearchPaths: [String] |
| 818 | var librarySearchPaths: [String] |
| 819 | var swiftResourcesPath: String |
| 820 | var swiftStaticResourcesPath: String |
| 821 | var toolsetPaths: [String] |
| 822 | } |
| 823 | var schemaVersion: String |
| 824 | var targetTriples: [String: Triple] |
| 825 | } |
| 826 | |
| 827 | struct SDKEntry { |
| 828 | var names: Set<Substring> |
| 829 | var values: [SDKEntry] = [] |
| 830 | |
| 831 | // empty = wildcard |
| 832 | init(_ names: Set<Substring>, _ values: [SDKEntry] = []) { |
| 833 | self.names = names |
| 834 | self.values = values |
| 835 | } |
| 836 | |
| 837 | init(_ name: Substring, _ values: [SDKEntry] = []) { |
| 838 | self.init([name], values) |
| 839 | } |
| 840 | |
| 841 | func matches(_ path: ArraySlice<Substring>) -> Bool { |
| 842 | guard let first = path.first else { return true } |
| 843 | guard names.isEmpty || names.contains(first) else { return false } |
| 844 | if values.isEmpty { return true } // leaf, everything after is good |
| 845 | let afterName = path.dropFirst() |
| 846 | for value in values { |
| 847 | if value.matches(afterName) { |
| 848 | return true |
| 849 | } |
| 850 | } |
| 851 | return false |
| 852 | } |
| 853 | |
| 854 | static func E(_ name: Substring?, _ values: [SDKEntry] = []) -> SDKEntry { |
| 855 | guard let name else { return SDKEntry([], values) } |
| 856 | let parts = name.split(separator: "/").reversed() |
| 857 | return parts.dropFirst().reduce(SDKEntry(parts.first!, values)) { SDKEntry($1, [$0]) } |
| 858 | } |
| 859 | |
| 860 | static let wanted = E("Contents/Developer", [ |
| 861 | E("Toolchains/XcodeDefault.xctoolchain/usr/lib", [ |
| 862 | E("swift"), |
| 863 | E("swift_static"), |
| 864 | E("clang"), |
| 865 | ]), |
| 866 | E("Platforms", ["iPhoneOS", "MacOSX", "iPhoneSimulator"].map { |
| 867 | E("\($0).platform", [ |
| 868 | E("Info.plist"), |
| 869 | E("Developer", [ |
| 870 | E("SDKs"), |
| 871 | E("Library", [ |
| 872 | E("Frameworks"), |
| 873 | E("PrivateFrameworks"), |
| 874 | ]), |
| 875 | E("usr/lib"), |
| 876 | ]) |
| 877 | ]) |
| 878 | }), |
| 879 | ]) |
| 880 | } |