Modern Apps git

xtool.git

Public
git clone https://git.maproj.org/xtool.git
appstore-distribution ▾

xtool.git / Sources / XToolSupport / SDKBuilder.swift

SDKBuilder.swift883 lines · 33.4 KiBRaw
1import Foundation
2import Dependencies
3import libunxip
4import Subprocess
5import XKit // HTTPClient, stdoutSafe
6import XUtils // System.File{Path,Descriptor}
7
8// swiftlint:disable:next type_body_length
9struct SDKBuilder {
10 enum Arch: String {
11 case x86_64
12 case aarch64
13 }
14
15 enum Input {
16 case xip(String)
17 case app(String)
18
19 init(path: String) throws {
20 var isDir: ObjCBool = false
21 guard FileManager.default.fileExists(atPath: path, isDirectory: &isDir) else {
22 throw Console.Error("""
23 Could not read file or directory at path '\(path)'.
24 See 'xtool help sdk' for usage.
25 """)
26 }
27
28 let url = URL(fileURLWithPath: path)
29
30 if isDir.boolValue {
31 self = .app(path)
32 let devDir = url.appendingPathComponent("Contents/Developer")
33 guard devDir.dirExists else {
34 throw Console.Error("""
35 The provided directory at '\(path)' does not appear to be a version of Xcode: \
36 could not read '\(devDir.path)'.
37 """)
38 }
39 } else {
40 self = .xip(path)
41 let handle = try FileHandle(forReadingFrom: url)
42 defer { try? handle.close() }
43
44 let expectedMagic = "xar!".utf8
45 let actualMagic = try handle.read(upToCount: expectedMagic.count) ?? Data()
46
47 guard actualMagic.elementsEqual(expectedMagic) else {
48 throw Console.Error("""
49 The file at '\(path)' does not appear to be a valid XIP file.
50 """)
51 }
52 }
53 }
54 }
55
56 enum Mode {
57 /// Create a slim SDK with just the files that this version of xtool uses
58 case buildSlim
59 /// Create an SDK that retains a full copy of Xcode.app/Contents/Developer.
60 /// Larger but allows in-place updates.
61 case buildNormal
62 /// Update a normal SDK in-place.
63 case update
64
65 var usesHardLinks: Bool {
66 switch self {
67 case .buildSlim: false
68 case .buildNormal, .update: true
69 }
70 }
71 }
72
73 let input: Input
74 let output: URL
75 let arch: Arch
76 let mode: Mode
77
78 // bump this when the sdk builder logic changes
79 static let sdkEpoch = 4
80
81 // tag from https://github.com/xtool-org/darwin-tools-linux-llvm
82 static let darwinToolsVersion = "1.1.0"
83 // tag from https://github.com/xtool-org/OpenAppleMacros
84 static let oamVersion = "1.4.1"
85
86 static var currentSDKVersion: String {
87 """
88 epoch=\(sdkEpoch),darwinTools=\(darwinToolsVersion),oam=\(oamVersion)
89 """
90 }
91
92 // swiftlint:disable:next function_body_length
93 func buildSDK() async throws {
94 let sdkVersion = Self.currentSDKVersion
95
96 try? FileManager.default.removeItem(at: output)
97 try FileManager.default.createDirectory(
98 at: output,
99 withIntermediateDirectories: true
100 )
101
102 // TODO: parallelize these three steps
103 // we need to synchronize progress reporting though
104
105 try await installMacros(in: output)
106
107 try await installToolset(in: output)
108
109 let dev = try await installDeveloper(in: output)
110
111 func sdk(platform: String, prefix: String) throws -> String {
112 let regex = try NSRegularExpression(pattern: #"^\#(prefix)\d+\.\d+\.sdk$"#)
113 let dir = dev.appendingPathComponent("Platforms/\(platform).platform/Developer/SDKs")
114 let names = try dir.contents().map(\.lastPathComponent)
115 guard let name = names.first(where: {
116 regex.firstMatch(in: $0, range: NSRange($0.startIndex..., in: $0)) != nil
117 }) else {
118 throw Console.Error("Could not find SDK for \(platform)/\(prefix)")
119 }
120 return name
121 }
122
123 func triple(platform: String, sdk: String) -> SDKDefinition.Triple {
124 SDKDefinition.Triple(
125 sdkRootPath: "Developer/Platforms/\(platform).platform/Developer/SDKs/\(sdk)",
126 includeSearchPaths: ["Developer/Platforms/\(platform).platform/Developer/usr/lib"],
127 librarySearchPaths: ["Developer/Platforms/\(platform).platform/Developer/usr/lib"],
128 swiftResourcesPath: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift",
129 swiftStaticResourcesPath: "Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift_static",
130 toolsetPaths: ["toolset.json"]
131 )
132 }
133
134 let iPhoneOSSDK = try sdk(platform: "iPhoneOS", prefix: "iPhoneOS")
135 let iPhoneSimSDK = try sdk(platform: "iPhoneSimulator", prefix: "iPhoneSimulator")
136 let macOSSDK = try sdk(platform: "MacOSX", prefix: "MacOSX")
137
138 print("""
139 - \(iPhoneOSSDK)
140 - \(iPhoneSimSDK)
141 - \(macOSSDK)
142 """)
143
144 print("[Writing metadata]")
145 try """
146 {
147 "schemaVersion": "1.0",
148 "artifacts": {
149 "darwin": {
150 "type": "swiftSDK",
151 "version": "0.0.1",
152 "variants": [
153 {
154 "path": ".",
155 "supportedTriples": ["aarch64-unknown-linux-gnu", "x86_64-unknown-linux-gnu"]
156 }
157 ]
158 }
159 }
160 }
161 """.write(
162 to: output.appendingPathComponent("info.json"),
163 atomically: false,
164 encoding: .utf8
165 )
166
167 try """
168 {
169 "schemaVersion": "1.0",
170 "rootPath": "toolset/bin",
171 "linker": {
172 "path": "ld64.lld"
173 },
174 "librarian": {
175 "path": "llvm-lib"
176 },
177 "swiftCompiler": {
178 "extraCLIOptions": [
179 "-Xfrontend", "-enable-cross-import-overlays",
180 "-use-ld=lld"
181 ]
182 }
183 }
184 """.write(
185 to: output.appendingPathComponent("toolset.json"),
186 atomically: false,
187 encoding: .utf8
188 )
189
190 // this toolset works with the swiftbuild system on Linux
191 // note that we need Swift 6.4+ because 6.3 has bugs in
192 // resolving the librarian and linker paths.
193 try """
194 {
195 "schemaVersion": "1.0",
196 "rootPath": "toolset/bin",
197 "linker": {
198 "path": "ld64.lld"
199 },
200 "librarian": {
201 "path": "llvm-lib"
202 },
203 "swiftCompiler": {
204 "extraCLIOptions": [
205 "-Xfrontend", "-enable-cross-import-overlays"
206 ]
207 }
208 }
209 """.write(
210 to: output.appendingPathComponent("toolset-swb.json"),
211 atomically: false,
212 encoding: .utf8
213 )
214
215 let sdkDefinition = SDKDefinition(
216 schemaVersion: "4.0",
217 targetTriples: [
218 "arm64-apple-ios": triple(platform: "iPhoneOS", sdk: iPhoneOSSDK),
219 "arm64-apple-ios-simulator": triple(platform: "iPhoneSimulator", sdk: iPhoneSimSDK),
220 "x86_64-apple-ios-simulator": triple(platform: "iPhoneSimulator", sdk: iPhoneSimSDK),
221 "arm64-apple-macosx": triple(platform: "MacOSX", sdk: macOSSDK),
222 "x86_64-apple-macosx": triple(platform: "MacOSX", sdk: macOSSDK),
223 ]
224 )
225
226 let encoder = JSONEncoder()
227 try encoder
228 .encode(sdkDefinition)
229 .write(to: output.appendingPathComponent("swift-sdk.json"))
230
231 try Data("\(sdkVersion)\n".utf8)
232 .write(to: output.appendingPathComponent("darwin-sdk-version.txt"))
233 }
234
235 private func fetchTarball(
236 url: URL,
237 destination directory: URL,
238 displayName: String,
239 envOverride: String? = nil,
240 ) async throws {
241 try FileManager.default.createDirectory(
242 at: directory,
243 withIntermediateDirectories: false
244 )
245
246 if let envOverride, let path = ProcessInfo.processInfo.environment[envOverride] {
247 let source = URL(fileURLWithPath: path)
248 if source.dirExists {
249 print("[Copying \(displayName)] \(source.path)")
250 try await Subprocess.run(
251 .name("cp"),
252 arguments: ["-RL", "\(source.path)/.", "."],
253 workingDirectory: FilePath(directory),
254 output: .discarded,
255 error: .discarded,
256 )
257 .checkSuccess()
258 // later steps write into the copy
259 try await Subprocess.run(
260 .name("chmod"),
261 arguments: ["-R", "u+w", "."],
262 workingDirectory: FilePath(directory),
263 output: .discarded,
264 error: .discarded,
265 )
266 .checkSuccess()
267 return
268 }
269
270 print("[Extracting \(displayName)] \(source.path)")
271 try await Subprocess.run(
272 .name("tar"),
273 arguments: ["xzf", source.path],
274 workingDirectory: FilePath(directory),
275 output: .discarded,
276 error: .discarded,
277 )
278 .checkSuccess()
279 return
280 }
281
282 @Dependency(\.httpClient) var httpClient
283 let (response, body) = try await httpClient.send(HTTPRequest(url: url))
284 guard response.status == 200, let body else {
285 throw Console.Error("Could not fetch tarball at \(url)")
286 }
287 let length: Int64? = switch body.length {
288 case .known(let known): known
289 case .unknown: nil
290 }
291
292 defer { print() }
293 try await Subprocess.run(
294 .name("tar"),
295 arguments: ["xzf", "-"],
296 workingDirectory: FilePath(directory),
297 input: .inputWriter,
298 output: .discarded,
299 error: .discarded,
300 ) { execution in
301 var totalWritten: Int64 = 0
302 for try await chunk in body {
303 var remaining = chunk
304 while !remaining.isEmpty {
305 let written = try await execution.standardInputWriter.write(Array(remaining))
306 remaining = remaining.dropFirst(written)
307 totalWritten += Int64(written)
308
309 guard let length else { continue }
310 let progress = Int(Double(totalWritten) / Double(length) * 100)
311 print("\r[Downloading \(displayName)] \(progress)%", terminator: "")
312 fflush(stdoutSafe)
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 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 print("\r[Installing SDKs] \(progress)%", terminator: "")
563 fflush(stdoutSafe)
564 }
565 if count % 100 == 0 {
566 if wanted == nil {
567 print("\r[Installing SDKs] Installed \(count) files", terminator: "")
568 fflush(stdoutSafe)
569 }
570 await Task.yield()
571 }
572
573 let insideDeveloper = path.dropFirst("Contents/Developer/".count)
574 guard !insideDeveloper.isEmpty else { continue }
575 let dest = dev.appendingPathComponent(String(insideDeveloper))
576
577 if try child.resourceValues(forKeys: [.isDirectoryKey]).isDirectory == true {
578 toDoDirs.append(path)
579 try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: false)
580 } else if mode.usesHardLinks {
581 // Installed SDKs retain Xcode.app developer dir, so avoid storing their developer files twice.
582 try FileManager.default.linkItem(at: child, to: dest)
583 } else {
584 // Slim SDKs omit Xcode.app and contain independent copies.
585 try FileManager.default.copyItem(at: child, to: dest)
586 }
587 }
588 }
589
590 if wanted != nil {
591 // otherwise the last log might say 99%
592 print("\r[Installing SDKs] 100%", terminator: "")
593 }
594 print()
595
596 if let cleanupStageDir {
597 print("[Cleaning up]")
598 try FileManager.default.removeItem(at: cleanupStageDir)
599 }
600
601 print("[Finalizing SDKs]")
602
603 for platform in ["iPhoneOS", "MacOSX", "iPhoneSimulator"] {
604 let lib = "../../../../../Library"
605 let platformDir = dev.appending(path: "Platforms/\(platform).platform")
606
607 try patchPlatformManifest(path: platformDir.appending(path: "Info.plist"))
608
609 /*
610 XCTest and Testing.framework are located in *.platform/Developer/{Library/Frameworks,usr/lib} rather than inside
611 the SDK. These search paths are explicitly included when building tests, which presumably ensures that normal
612 applications don't accidentally link against them in production.
613
614 SwiftPM makes no such affordances outside of macOS, so we add the usr/lib path as include/library search paths
615 in the SDK config, and symlink the frameworks into the SDKs (since there's no frameworkSearchPaths option).
616 While this drops a safeguard it's better than not having the testing libs at all.
617 */
618
619 let fwk = platformDir.appending(path: "Developer/SDKs/\(platform).sdk/System/Library/Frameworks").path
620
621 try FileManager.default.createSymbolicLink(
622 atPath: "\(fwk)/Testing.framework",
623 withDestinationPath: "\(lib)/Frameworks/Testing.framework"
624 )
625
626 try FileManager.default.createSymbolicLink(
627 atPath: "\(fwk)/XCTest.framework",
628 withDestinationPath: "\(lib)/Frameworks/XCTest.framework"
629 )
630
631 try FileManager.default.createSymbolicLink(
632 atPath: "\(fwk)/XCUIAutomation.framework",
633 withDestinationPath: "\(lib)/Frameworks/XCUIAutomation.framework"
634 )
635
636 try FileManager.default.createSymbolicLink(
637 atPath: "\(fwk)/XCTestCore.framework",
638 withDestinationPath: "\(lib)/PrivateFrameworks/XCTestCore.framework"
639 )
640
641 /*
642 Apply patches to load OpenAppleMacros as the swift-plugin-server
643 */
644
645 let bin = platformDir.appendingPathComponent("Developer/usr/bin")
646 let pluginServer = bin.appendingPathComponent("swift-plugin-server")
647 try? FileManager.default.createDirectory(at: bin, withIntermediateDirectories: true)
648 try? FileManager.default.removeItem(at: pluginServer)
649 try FileManager.default.createSymbolicLink(
650 atPath: pluginServer.path,
651 withDestinationPath: "../../../../../../OpenAppleMacrosServer"
652 )
653
654 let hostDir = platformDir.appendingPathComponent("Developer/usr/lib/swift/host")
655 let pluginsDir = hostDir.appendingPathComponent("plugins")
656
657 try FileManager.default.createDirectory(at: hostDir, withIntermediateDirectories: true)
658 try? FileManager.default.removeItem(at: pluginsDir)
659 try FileManager.default.createSymbolicLink(
660 atPath: pluginsDir.path,
661 withDestinationPath: "../../../../../../../../OpenAppleMacrosPlugins"
662 )
663 }
664
665 // we copy over the host's clang resorurce dir during install, because intrinsics can differ
666 // by LLVM version
667 try FileManager.default.removeItem(
668 at: dev.appending(path: "Toolchains/XcodeDefault.xctoolchain/usr/lib/swift/clang/include")
669 )
670
671 return dev
672 }
673
674 /// Removes unneeded files from a copy of Xcode.app that's owned by xtool.
675 ///
676 /// This is conservative: we keep anything that we expect _might_ be necessary
677 /// even in a future update of xtool, so that SDK self-updates work. We only
678 /// delete files that we're relatively confident won't be needed.
679 ///
680 /// - Important: ONLY call this if we own appDir, lest we delete files from the user's Xcode.
681 private func cleanUpXcode(_ appDir: URL) throws {
682 let contentsDir = appDir.appendingPathComponent("Contents")
683 let contents = try FileManager.default.contentsOfDirectory(
684 at: contentsDir,
685 includingPropertiesForKeys: nil
686 )
687 let expectedChildren = Set(Self.expectedXcodeChildren)
688 let missingChildren = expectedChildren.subtracting(contents.map(\.lastPathComponent))
689 guard missingChildren.isEmpty else {
690 let missing = missingChildren.sorted().joined(separator: ", ")
691 throw Console.Error("Unrecognized xip layout: missing \(missing)")
692 }
693 for child in contents where !expectedChildren.contains(child.lastPathComponent) {
694 try FileManager.default.removeItem(at: child)
695 }
696 }
697
698 private func extractXIP(inputPath: String, outDir: String) async throws -> Int {
699 // unxip doesn't like cooperative cancellation atm so shield it.
700 // if the user does a ^C during unxip, we'll just wait until extraction
701 // is over before bailing
702 try await Task {
703 try await _extractXIP(inputPath: inputPath, outDir: outDir)
704 }.value
705 }
706
707 private func patchPlatformManifest(path: URL) throws {
708 let data = try Data(contentsOf: path)
709 guard var plist = try PropertyListSerialization.propertyList(from: data, options: [], format: nil) as? [String: Any] else {
710 throw Console.Error("Could not read '\(path.path)'")
711 }
712
713 var defaultProperties = (plist["DefaultProperties"] as? [String: Any]) ?? [:]
714 defaultProperties["SWIFT_RESOURCE_DIR"] = "$(PLATFORM_DIR)/../../Toolchains/XcodeDefault.xctoolchain/usr/lib/swift"
715 defaultProperties["CLANG_RESOURCE_DIR"] = "$(SWIFT_RESOURCE_DIR)/clang"
716 defaultProperties["ALTERNATE_LINKER"] = "lld"
717 // stub out codesign as /bin/true (SwiftBuild often emits CodeSign tasks, e.g. when
718 // building for sim). we sign post-build.
719 defaultProperties["CODESIGN"] = "true"
720 plist["DefaultProperties"] = defaultProperties
721
722 let newData = try PropertyListSerialization.data(fromPropertyList: plist, format: .xml, options: 0)
723 // a non-atomic write would modify the shared inode that's hard-linked from Xcode.app
724 try newData.write(to: path, options: .atomic)
725 }
726
727 // returns the number of files we actually want to keep,
728 // useful for computing progress % during fs traversal
729 private func _extractXIP(inputPath: String, outDir: String) async throws -> Int {
730 let fd = try FileDescriptor.open(inputPath, .readOnly)
731 defer { try? fd.close() }
732
733 let length = try fd.seek(offset: 0, from: .end)
734 try fd.seek(offset: 0, from: .start)
735
736 // global state, ah well
737 let oldDirectory = FileManager.default.currentDirectoryPath
738 guard FileManager.default.changeCurrentDirectoryPath(outDir) else {
739 throw Console.Error("Could not change directory to '\(outDir)'")
740 }
741 defer { _ = FileManager.default.changeCurrentDirectoryPath(oldDirectory) }
742
743 let inputStream = DataReader.data(readingFrom: fd.rawValue)
744
745 let (observer, source) = inputStream.lockstepSplit()
746
747 async let readTask: Void = {
748 var read = 0
749 for try await chunk in observer {
750 read += chunk.count
751 let progress = Int(Double(read) / Double(length) * 100)
752 print("\r[Extracting XIP] \(progress)%", terminator: "")
753 fflush(stdoutSafe)
754 if read == length { break }
755 }
756 }()
757
758 let xipToChunks = XIP.transform(
759 DataReader(data: source),
760 options: nil
761 )
762
763 // ideally we would filter out the files we don't want at this stage,
764 // speeding up extraction AND entirely avoiding the "Installing SDKs"
765 // post-processing step. However, files in xip archives may be hardlinks
766 // to one another and so we need to handle the case where a file inside
767 // our filter() points to a file outside of it. We might be able to do this
768 // with a double-pass system.
769
770 let chunksToFiles = Chunks.transform(
771 xipToChunks,
772 options: nil
773 )
774
775 let filesToDisk = Files.transform(
776 chunksToFiles,
777 options: .init(
778 compress: false,
779 dryRun: false
780 )
781 )
782
783 var wanted = 0
784 for try await file in filesToDisk {
785 wanted += Self.isWanted(file.name[...]) ? 1 : 0
786 }
787 _ = try await readTask
788
789 print()
790
791 return wanted
792 }
793
794 private static func isWanted(_ path: Substring) -> Bool {
795 var components = path.split(separator: "/")[...]
796 if components.first == "." {
797 components.removeFirst()
798 }
799 if components.first?.hasSuffix(".app") == true {
800 components.removeFirst()
801 }
802 guard SDKEntry.wanted.matches(components) else { return false }
803
804 // TODO: see if we can exclude most dylibs. Seems we need the XCTest ones though.
805
806 if components.count >= 10 && components[components.startIndex + 9] == "prebuilt-modules" && components.starts(
807 with: "Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/lib/swift"
808 .split(separator: "/")
809 ) {
810 return false
811 }
812
813 return true
814 }
815}
816
817struct SDKDefinition: Encodable {
818 struct Triple: Encodable {
819 var sdkRootPath: String
820 var includeSearchPaths: [String]
821 var librarySearchPaths: [String]
822 var swiftResourcesPath: String
823 var swiftStaticResourcesPath: String
824 var toolsetPaths: [String]
825 }
826 var schemaVersion: String
827 var targetTriples: [String: Triple]
828}
829
830struct SDKEntry {
831 var names: Set<Substring>
832 var values: [SDKEntry] = []
833
834 // empty = wildcard
835 init(_ names: Set<Substring>, _ values: [SDKEntry] = []) {
836 self.names = names
837 self.values = values
838 }
839
840 init(_ name: Substring, _ values: [SDKEntry] = []) {
841 self.init([name], values)
842 }
843
844 func matches(_ path: ArraySlice<Substring>) -> Bool {
845 guard let first = path.first else { return true }
846 guard names.isEmpty || names.contains(first) else { return false }
847 if values.isEmpty { return true } // leaf, everything after is good
848 let afterName = path.dropFirst()
849 for value in values {
850 if value.matches(afterName) {
851 return true
852 }
853 }
854 return false
855 }
856
857 static func E(_ name: Substring?, _ values: [SDKEntry] = []) -> SDKEntry {
858 guard let name else { return SDKEntry([], values) }
859 let parts = name.split(separator: "/").reversed()
860 return parts.dropFirst().reduce(SDKEntry(parts.first!, values)) { SDKEntry($1, [$0]) }
861 }
862
863 static let wanted = E("Contents/Developer", [
864 E("Toolchains/XcodeDefault.xctoolchain/usr/lib", [
865 E("swift"),
866 E("swift_static"),
867 E("clang"),
868 ]),
869 E("Platforms", ["iPhoneOS", "MacOSX", "iPhoneSimulator"].map {
870 E("\($0).platform", [
871 E("Info.plist"),
872 E("Developer", [
873 E("SDKs"),
874 E("Library", [
875 E("Frameworks"),
876 E("PrivateFrameworks"),
877 ]),
878 E("usr/lib"),
879 ])
880 ])
881 }),
882 ])
883}