forked from swiftlang/swift-package-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwiftBuildSystem.swift
More file actions
1366 lines (1204 loc) · 61.2 KB
/
SwiftBuildSystem.swift
File metadata and controls
1366 lines (1204 loc) · 61.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2025 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_spi(SwiftPMInternal)
import Basics
import Dispatch
import class Foundation.FileManager
import class Foundation.JSONEncoder
import class Foundation.NSArray
import class Foundation.NSDictionary
import PackageGraph
import PackageModel
import PackageLoading
@_spi(SwiftPMInternal)
import SPMBuildCore
import class Basics.AsyncProcess
import func TSCBasic.memoize
import protocol TSCBasic.OutputByteStream
import func TSCBasic.withTemporaryFile
import enum TSCUtility.Diagnostics
import var TSCBasic.stdoutStream
import Foundation
import SWBBuildService
import SwiftBuild
import enum SWBCore.SwiftAPIDigesterMode
import struct SWBUtil.XcodeVersionInfo
import struct SWBUtil.Path
struct SessionFailedError: Error {
var error: Error
var diagnostics: [SwiftBuild.SwiftBuildMessage.DiagnosticInfo]
}
package func withService<T>(
connectionMode: SWBBuildServiceConnectionMode = .default,
variant: SWBBuildServiceVariant = .default,
serviceBundleURL: URL? = nil,
body: @escaping (_ service: SWBBuildService) async throws -> T
) async throws -> T {
let service = try await SWBBuildService(connectionMode: connectionMode, variant: variant, serviceBundleURL: serviceBundleURL)
let result: T
do {
result = try await body(service)
} catch {
await service.close()
throw error
}
await service.close()
return result
}
/// Determines the effective toolchain path and whether it is embedded in an Xcode installation.
///
/// On Windows, the "developer dir" is two levels up from the toolchain dir, unlike Swift.org
/// toolchains on other platforms where they are both the same.
///
/// Users often rename Xcode.app, and in Swift.org CI on macOS we construct the toolchain under
/// a nonfunctioning shell of Xcode.app. Instead of just checking the app name, see if we can
/// find the app's version.plist at the expected location.
func toolchainDeveloperPathInfo(toolchain: Toolchain) throws -> (toolchainPath: Basics.AbsolutePath, isEmbeddedInXcode: Bool) {
let toolchainPath = try toolchain.toolchainDir
// On Windows, the "developer dir" is two levels up from the toolchain dir,
// unlike Swift.org toolchains on other platforms where they are both the same.
if ProcessInfo.hostOperatingSystem == .windows {
return (toolchainPath.parentDirectory.parentDirectory, false)
}
let xcodeVersionPlistPath = toolchainPath
.parentDirectory // Remove 'XcodeDefault.xctoolchain'
.parentDirectory // Remove 'Toolchains'
.parentDirectory // Remove 'Developer'
.appending(component: "version.plist")
let isEmbeddedInXcode = (try? XcodeVersionInfo.versionInfo(versionPath: SWBUtil.Path(xcodeVersionPlistPath.pathString))) != nil
return (toolchainPath, isEmbeddedInXcode)
}
public func createSession(
service: SWBBuildService,
name: String,
toolchain: Toolchain,
packageManagerResourcesDirectory: Basics.AbsolutePath?
) async throws-> (SWBBuildServiceSession, [SwiftBuildMessage.DiagnosticInfo]) {
var buildSessionEnv: [String: String]? = nil
if let metalToolchainPath = toolchain.metalToolchainPath {
buildSessionEnv = ["EXTERNAL_TOOLCHAINS_DIR": metalToolchainPath.pathString]
}
let (toolchainPath, toolchainIsEmbeddedInXcode) = try toolchainDeveloperPathInfo(toolchain: toolchain)
// SWIFT_EXEC and SWIFT_EXEC_MANIFEST may need to be overridden in debug scenarios in order to pick up Open Source toolchains
let sessionResult = if toolchainIsEmbeddedInXcode {
// If this toolchain is bundled with Xcode.app, let the build service handle toolchain registration.
await service.createSession(name: name, developerPath: nil, resourceSearchPaths: packageManagerResourcesDirectory.map { [$0.pathString] } ?? [], cachePath: nil, inferiorProductsPath: nil, environment: buildSessionEnv)
} else {
// Otherwise, treat this toolchain as standalone when initializing the build service.
await service.createSession(name: name, swiftToolchainPath: toolchainPath.pathString, resourceSearchPaths: packageManagerResourcesDirectory.map { [$0.pathString] } ?? [], cachePath: nil, inferiorProductsPath: nil, environment: buildSessionEnv)
}
switch sessionResult {
case (.success(let session), let diagnostics):
return (session, diagnostics)
case (.failure(let error), let diagnostics):
throw SessionFailedError(error: error, diagnostics: diagnostics)
}
}
func withSession(
service: SWBBuildService,
name: String,
toolchain: Toolchain,
packageManagerResourcesDirectory: Basics.AbsolutePath?,
body: @escaping (
_ session: SWBBuildServiceSession,
_ diagnostics: [SwiftBuild.SwiftBuildMessage.DiagnosticInfo]
) async throws -> Void
) async throws {
let (session, diagnostics) = try await createSession(service: service, name: name, toolchain: toolchain, packageManagerResourcesDirectory: packageManagerResourcesDirectory)
do {
try await body(session, diagnostics)
} catch let bodyError {
do {
try await session.close()
} catch _ {
// Assumption is that the first error is the most important one
throw bodyError
}
throw bodyError
}
do {
try await session.close()
} catch {
throw SessionFailedError(error: error, diagnostics: diagnostics)
}
}
package final class SwiftBuildSystemPlanningOperationDelegate: SWBPlanningOperationDelegate, SWBIndexingDelegate, Sendable {
private let shouldEnableDebuggingEntitlement: Bool
package init(shouldEnableDebuggingEntitlement: Bool) {
self.shouldEnableDebuggingEntitlement = shouldEnableDebuggingEntitlement
}
public func provisioningTaskInputs(
targetGUID: String,
provisioningSourceData: SWBProvisioningTaskInputsSourceData
) async -> SWBProvisioningTaskInputs {
let identity = if provisioningSourceData.signingCertificateIdentifier.isEmpty && shouldEnableDebuggingEntitlement {
"-"
} else {
provisioningSourceData.signingCertificateIdentifier
}
if identity == "-" {
let getTaskAllowEntitlementKey: String
let applicationIdentifierEntitlementKey: String
if provisioningSourceData.sdkRoot.contains("macos") || provisioningSourceData.sdkRoot
.contains("simulator")
{
getTaskAllowEntitlementKey = "com.apple.security.get-task-allow"
applicationIdentifierEntitlementKey = "com.apple.application-identifier"
} else {
getTaskAllowEntitlementKey = "get-task-allow"
applicationIdentifierEntitlementKey = "application-identifier"
}
let signedEntitlements = provisioningSourceData
.entitlementsDestination == "Signature" ? provisioningSourceData.productTypeEntitlements.merging(
[applicationIdentifierEntitlementKey: .plString(provisioningSourceData.bundleIdentifier)],
uniquingKeysWith: { _, new in new }
).merging(provisioningSourceData.projectEntitlements ?? [:], uniquingKeysWith: { _, new in new })
: [:]
let simulatedEntitlements = provisioningSourceData.entitlementsDestination == "__entitlements"
? provisioningSourceData.productTypeEntitlements.merging(
["application-identifier": .plString(provisioningSourceData.bundleIdentifier)],
uniquingKeysWith: { _, new in new }
).merging(provisioningSourceData.projectEntitlements ?? [:], uniquingKeysWith: { _, new in new })
: [:]
var additionalEntitlements: [String: SWBPropertyListItem] = [:]
if shouldEnableDebuggingEntitlement {
additionalEntitlements[getTaskAllowEntitlementKey] = .plBool(true)
}
return SWBProvisioningTaskInputs(
identityHash: "-",
identityName: "-",
profileName: nil,
profileUUID: nil,
profilePath: nil,
designatedRequirements: nil,
signedEntitlements: signedEntitlements.merging(
additionalEntitlements,
uniquingKeysWith: { _, new in new }
),
simulatedEntitlements: simulatedEntitlements,
appIdentifierPrefix: nil,
teamIdentifierPrefix: nil,
isEnterpriseTeam: nil,
keychainPath: nil,
errors: [],
warnings: []
)
} else if identity.isEmpty {
return SWBProvisioningTaskInputs()
} else {
return SWBProvisioningTaskInputs(
identityHash: "-",
errors: [
[
"description": "unable to supply accurate provisioning inputs for CODE_SIGN_IDENTITY=\(identity)\"",
],
]
)
}
}
public func executeExternalTool(
commandLine: [String],
workingDirectory: String?,
environment: [String: String]
) async throws -> SWBExternalToolResult {
.deferred
}
}
public final class SwiftBuildSystem: SPMBuildCore.BuildSystem {
package let buildParameters: BuildParameters
package let hostBuildParameters: BuildParameters
private let packageGraphLoader: () async throws -> ModulesGraph
private let packageManagerResourcesDirectory: Basics.AbsolutePath?
private let logLevel: Basics.Diagnostic.Severity
private var packageGraph: AsyncThrowingValueMemoizer<ModulesGraph> = .init()
private var pifBuilder: AsyncThrowingValueMemoizer<PIFBuilder> = .init()
private let fileSystem: FileSystem
private let observabilityScope: ObservabilityScope
/// The output stream for the build delegate.
private let outputStream: OutputByteStream
/// The delegate used by the build system.
public weak var delegate: SPMBuildCore.BuildSystemDelegate?
/// Configuration for building and invoking plugins.
private let pluginConfiguration: PluginConfiguration
/// Additional rules for different file types generated from plugins.
private let additionalFileRules: [FileRuleDescription]
public var builtTestProducts: [BuiltTestProduct] {
get async {
do {
let graph = try await getPackageGraph()
var builtProducts: [BuiltTestProduct] = []
for package in graph.rootPackages {
for product in package.products where product.type == .test {
let binaryPath = try buildParameters.binaryPath(for: product)
builtProducts.append(
BuiltTestProduct(
productName: product.name,
umbrellaProductName: package.manifest.umbrellaPackageTestsProductName,
binaryPath: binaryPath,
packagePath: package.path,
testEntryPointPath: product.underlying.testEntryPointPath
)
)
}
}
return builtProducts
} catch {
self.observabilityScope.emit(error)
return []
}
}
}
public var buildPlan: SPMBuildCore.BuildPlan {
get throws {
throw StringError("Swift Build does not provide a build plan")
}
}
public var hasIntegratedAPIDigesterSupport: Bool { true }
public var enableTaskBacktraces: Bool {
self.buildParameters.outputParameters.enableTaskBacktraces
}
public init(
buildParameters: BuildParameters,
hostBuildParameters: BuildParameters,
packageGraphLoader: @escaping () async throws -> ModulesGraph,
packageManagerResourcesDirectory: Basics.AbsolutePath?,
additionalFileRules: [FileRuleDescription],
outputStream: OutputByteStream,
logLevel: Basics.Diagnostic.Severity,
fileSystem: FileSystem,
observabilityScope: ObservabilityScope,
pluginConfiguration: PluginConfiguration,
delegate: BuildSystemDelegate?
) throws {
self.buildParameters = buildParameters
self.hostBuildParameters = hostBuildParameters
self.packageGraphLoader = packageGraphLoader
self.packageManagerResourcesDirectory = packageManagerResourcesDirectory
self.additionalFileRules = additionalFileRules
self.outputStream = outputStream
self.logLevel = logLevel
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope.makeChildScope(description: "Swift Build System")
self.pluginConfiguration = pluginConfiguration
self.delegate = delegate
}
private func createREPLArguments(
session: SWBBuildServiceSession,
request: SWBBuildRequest
) async throws -> CLIArguments {
self.outputStream.send("Gathering repl arguments...")
self.outputStream.flush()
func getUniqueBuildSettingsIncludingDependencies(of targetGuid: [SWBConfiguredTarget], buildSettings: [String]) async throws -> Set<String> {
let dependencyGraph = try await session.computeDependencyGraph(
targetGUIDs: request.configuredTargets.map { SWBTargetGUID(rawValue: $0.guid)},
buildParameters: request.parameters,
includeImplicitDependencies: true,
)
var uniquePaths = Set<String>()
for setting in buildSettings {
self.outputStream.send(".")
self.outputStream.flush()
for (target, targetDependencies) in dependencyGraph {
for t in [target] + targetDependencies {
try await session.evaluateMacroAsStringList(
setting,
level: .target(t.rawValue),
buildParameters: request.parameters,
overrides: nil,
).forEach({
uniquePaths.insert($0)
})
}
}
}
return uniquePaths
}
// TODO: Need to determine how to get the include path of package system library dependencies
let includePaths = try await getUniqueBuildSettingsIncludingDependencies(
of: request.configuredTargets,
buildSettings: [
"BUILT_PRODUCTS_DIR",
"HEADER_SEARCH_PATHS",
"USER_HEADER_SEARCH_PATHS",
"FRAMEWORK_SEARCH_PATHS",
]
)
let graph = try await self.getPackageGraph()
// Link the special REPL product that contains all of the library targets.
let replProductName: String = try graph.getReplProductName()
// The graph should have the REPL product.
assert(graph.product(for: replProductName) != nil)
let arguments = ["repl", "-l\(replProductName)"] + includePaths.map {
"-I\($0)"
}
self.outputStream.send("Done.\n")
return arguments
}
private func supportedSwiftVersions() throws -> [SwiftLanguageVersion] {
// Swift Build should support any of the supported language versions of SwiftPM and the rest of the toolchain
SwiftLanguageVersion.supportedSwiftLanguageVersions
}
public func build(subset: BuildSubset, buildOutputs: [BuildOutput]) async throws -> BuildResult {
// If any plugins are part of the build set, compile them now to surface
// any errors up-front. Returns true if we should proceed with the build
// or false if not. It will already have thrown any appropriate error.
var result = BuildResult(
serializedDiagnosticPathsByTargetName: .failure(StringError("Building was skipped")),
replArguments: nil,
)
guard !buildParameters.shouldSkipBuilding else {
result.serializedDiagnosticPathsByTargetName = .failure(StringError("Building was skipped"))
return result
}
guard try await self.compilePlugins(in: subset) else {
result.serializedDiagnosticPathsByTargetName = .failure(StringError("Plugin compilation failed"))
return result
}
try await writePIF(buildParameters: self.buildParameters)
return try await startSWBuildOperation(
pifTargetName: subset.pifTargetName,
buildOutputs: buildOutputs,
)
}
/// Compiles any plugins specified or implied by the build subset, returning
/// true if the build should proceed. Throws an error in case of failure. A
/// reason why the build might not proceed even on success is if only plugins
/// should be compiled.
func compilePlugins(in subset: BuildSubset) async throws -> Bool {
// Figure out what, if any, plugin descriptions to compile, and whether
// to continue building after that based on the subset.
let graph = try await getPackageGraph()
/// Description for a plugin module. This is treated a bit differently from the
/// regular kinds of modules, and is not included in the LLBuild description.
/// But because the modules graph and build plan are not loaded for incremental
/// builds, this information is included in the BuildDescription, and the plugin
/// modules are compiled directly.
struct PluginBuildDescription: Codable {
/// The identity of the package in which the plugin is defined.
public let package: PackageIdentity
/// The name of the plugin module in that package (this is also the name of
/// the plugin).
public let moduleName: String
/// The language-level module name.
public let moduleC99Name: String
/// The names of any plugin products in that package that vend the plugin
/// to other packages.
public let productNames: [String]
/// The tools version of the package that declared the module. This affects
/// the API that is available in the PackagePlugin module.
public let toolsVersion: ToolsVersion
/// Swift source files that comprise the plugin.
public let sources: Sources
/// Initialize a new plugin module description. The module is expected to be
/// a `PluginTarget`.
init(
module: ResolvedModule,
products: [ResolvedProduct],
package: ResolvedPackage,
toolsVersion: ToolsVersion,
testDiscoveryTarget: Bool = false,
fileSystem: FileSystem
) throws {
guard module.underlying is PluginModule else {
throw InternalError("underlying target type mismatch \(module)")
}
self.package = package.identity
self.moduleName = module.name
self.moduleC99Name = module.c99name
self.productNames = products.map(\.name)
self.toolsVersion = toolsVersion
self.sources = module.sources
}
}
var allPlugins: [PluginBuildDescription] = []
for pluginModule in graph.allModules.filter({ ($0.underlying as? PluginModule) != nil }) {
guard let package = graph.package(for: pluginModule) else {
throw InternalError("Package not found for module: \(pluginModule.name)")
}
let toolsVersion = package.manifest.toolsVersion
let pluginProducts = package.products.filter { $0.modules.contains(id: pluginModule.id) }
allPlugins.append(try PluginBuildDescription(
module: pluginModule,
products: pluginProducts,
package: package,
toolsVersion: toolsVersion,
fileSystem: fileSystem
))
}
let pluginsToCompile: [PluginBuildDescription]
let continueBuilding: Bool
switch subset {
case .allExcludingTests, .allIncludingTests:
pluginsToCompile = allPlugins
continueBuilding = true
case .product(let productName, _):
pluginsToCompile = allPlugins.filter{ $0.productNames.contains(productName) }
continueBuilding = pluginsToCompile.isEmpty
case .target(let targetName, _):
pluginsToCompile = allPlugins.filter{ $0.moduleName == targetName }
continueBuilding = pluginsToCompile.isEmpty
}
final class Delegate: PluginScriptCompilerDelegate {
var failed: Bool = false
var observabilityScope: ObservabilityScope
public init(observabilityScope: ObservabilityScope) {
self.observabilityScope = observabilityScope
}
func willCompilePlugin(commandLine: [String], environment: [String: String]) { }
func didCompilePlugin(result: PluginCompilationResult) {
if !result.compilerOutput.isEmpty && !result.succeeded {
print(result.compilerOutput, to: &stdoutStream)
} else if !result.compilerOutput.isEmpty {
observabilityScope.emit(info: result.compilerOutput)
}
failed = !result.succeeded
}
func skippedCompilingPlugin(cachedResult: PluginCompilationResult) { }
}
// Compile any plugins we ended up with. If any of them fails, it will
// throw.
for plugin in pluginsToCompile {
let delegate = Delegate(observabilityScope: observabilityScope)
_ = try await self.pluginConfiguration.scriptRunner.compilePluginScript(
sourceFiles: plugin.sources.paths,
pluginName: plugin.moduleName,
toolsVersion: plugin.toolsVersion,
workers: self.buildParameters.workers,
observabilityScope: observabilityScope,
callbackQueue: DispatchQueue.sharedConcurrent,
delegate: delegate
)
if delegate.failed {
throw Diagnostics.fatalError
}
}
// If we get this far they all succeeded. Return whether to continue the
// build, based on the subset.
return continueBuilding
}
private func startSWBuildOperation(
pifTargetName: String,
buildOutputs: [BuildOutput]
) async throws -> BuildResult {
let buildStartTime = ContinuousClock.Instant.now
var symbolGraphOptions: BuildOutput.SymbolGraphOptions?
for output in buildOutputs {
switch output {
case .symbolGraph(let options):
symbolGraphOptions = options
default:
continue
}
}
var replArguments: CLIArguments?
var artifacts: [(String, PluginInvocationBuildResult.BuiltArtifact)]?
var dependencyGraph: [String: [String]]?
return try await withService(connectionMode: .inProcessStatic(swiftbuildServiceEntryPoint)) { service in
let derivedDataPath = self.buildParameters.dataPath
let buildMessageHandler = SwiftBuildSystemMessageHandler(
observabilityScope: self.observabilityScope,
outputStream: self.outputStream,
logLevel: self.logLevel,
enableBacktraces: self.enableTaskBacktraces,
buildDelegate: self.delegate,
traceEventsFilePath: self.buildParameters.outputParameters.traceEventsFilePath
)
do {
try await withSession(service: service, name: self.buildParameters.pifManifest.pathString, toolchain: self.buildParameters.toolchain, packageManagerResourcesDirectory: self.packageManagerResourcesDirectory) { session, _ in
self.outputStream.send("Building for \(self.buildParameters.configuration == .debug ? "debugging" : "production")...\n")
// Load the workspace, and set the system information to the default
do {
try await session.loadWorkspace(containerPath: self.buildParameters.pifManifest.pathString)
try await session.setSystemInfo(.default())
} catch {
self.observabilityScope.emit(error: error.localizedDescription)
throw error
}
// Find the targets to build.
let workspaceInfo = try await session.workspaceInfo()
let configuredTargets: [SWBTargetGUID]
do {
configuredTargets = try [pifTargetName].map { targetName in
// TODO we filter dynamic targets until Swift Build doesn't give them to us anymore
let infos = workspaceInfo.targetInfos.filter { $0.targetName == targetName && !TargetSuffix.dynamic.hasSuffix(id: GUID($0.guid)) }
switch infos.count {
case 0:
self.observabilityScope.emit(error: "Could not find target named '\(targetName)'")
throw Diagnostics.fatalError
case 1:
return SWBTargetGUID(rawValue: infos[0].guid)
default:
self.observabilityScope.emit(error: "Found multiple targets named '\(targetName)'")
throw Diagnostics.fatalError
}
}
} catch {
self.observabilityScope.emit(error: error.localizedDescription)
throw error
}
let request = try await self.makeBuildRequest(service: service, session: session, configuredTargets: configuredTargets, derivedDataPath: derivedDataPath, symbolGraphOptions: symbolGraphOptions)
let operation = try await session.createBuildOperation(
request: request,
delegate: SwiftBuildSystemPlanningOperationDelegate(shouldEnableDebuggingEntitlement: self.buildParameters
.debuggingParameters.shouldEnableDebuggingEntitlement
),
retainBuildDescription: true
)
var buildDescriptionID: SWBBuildDescriptionID? = nil
for try await event in try await operation.start() {
if case .reportBuildDescription(let info) = event {
if buildDescriptionID != nil {
self.observabilityScope.emit(debug: "build unexpectedly reported multiple build description IDs")
}
buildDescriptionID = SWBBuildDescriptionID(info.buildDescriptionID)
}
if let delegateCallback = try buildMessageHandler.emitEvent(event) {
delegateCallback(self)
}
}
await operation.waitForCompletion()
switch operation.state {
case .succeeded:
guard !self.logLevel.isQuiet else { return }
buildMessageHandler.progressAnimation.update(step: 100, total: 100, text: "")
buildMessageHandler.progressAnimation.complete(success: true)
let duration = ContinuousClock.Instant.now - buildStartTime
let formattedDuration = duration.formatted(.units(allowed: [.seconds], fractionalPart: .show(length: 2, rounded: .up)))
self.outputStream.send("Build complete! (\(formattedDuration))\n")
self.outputStream.flush()
case .failed:
self.observabilityScope.emit(error: "Build failed")
throw Diagnostics.fatalError
case .cancelled:
self.observabilityScope.emit(error: "Build was cancelled")
throw Diagnostics.fatalError
case .requested, .running, .aborted:
self.observabilityScope.emit(error: "Unexpected build state")
throw Diagnostics.fatalError
}
if buildOutputs.contains(.replArguments) {
replArguments = try await self.createREPLArguments(session: session, request: request)
}
if buildOutputs.contains(.dependencyGraph) {
let depGraph = try await session.computeDependencyGraph(
targetGUIDs: request.configuredTargets.map { SWBTargetGUID(rawValue: $0.guid) },
buildParameters: request.parameters,
includeImplicitDependencies: true
)
// SWBTargetGUID wraps the GUID that PIFBuilder generates
var result: [String: [String]] = [:]
for (target, dependencies) in depGraph {
let targetInfo = workspaceInfo.targetInfos.first { $0.guid == target.rawValue }
guard let targetName = targetInfo?.targetName else { continue }
let depNames = dependencies.compactMap { depGUID in
workspaceInfo.targetInfos.first { $0.guid == depGUID.rawValue }?.targetName
}
result[targetName] = depNames
}
dependencyGraph = result
}
if buildOutputs.contains(.builtArtifacts) {
if let buildDescriptionID {
let targetInfo = try await session.configuredTargets(buildDescription: buildDescriptionID, buildRequest: request)
artifacts = targetInfo.compactMap { target in
guard let artifactInfo = target.artifactInfo else {
return nil
}
let kind: PluginInvocationBuildResult.BuiltArtifact.Kind = switch artifactInfo.kind {
case .executable:
.executable
case .staticLibrary:
.staticLibrary
case .dynamicLibrary:
.dynamicLibrary
case .framework:
// We treat frameworks as dylibs here, but the plugin API should grow to accomodate more product types
.dynamicLibrary
}
var name = target.name
// FIXME: We need a better way to map between SwiftPM target/product names and PIF target names
if pifTargetName.hasSuffix("-product") {
name = String(name.dropLast(8))
}
return (name, .init(
path: artifactInfo.path,
kind: kind
))
}
} else {
self.observabilityScope.emit(error: "failed to compute built artifacts list")
}
}
if let buildDescriptionID {
await session.releaseBuildDescription(id: buildDescriptionID)
}
}
} catch let sessError as SessionFailedError {
for diagnostic in sessError.diagnostics {
self.observabilityScope.emit(error: diagnostic.message)
}
throw sessError.error
} catch {
throw error
}
return BuildResult(
serializedDiagnosticPathsByTargetName: .success(buildMessageHandler.serializedDiagnosticPathsByTargetName),
symbolGraph: SymbolGraphResult(
outputLocationForTarget: { target, buildParameters in
return ["\(buildParameters.triple.archName)", "\(target).symbolgraphs"]
}
),
replArguments: replArguments,
builtArtifacts: artifacts,
dependencyGraph: dependencyGraph
)
}
}
private func buildTargetInfo(session: SWBBuildServiceSession) async throws -> SWBBuildTargetInfo {
let (toolchainPath, isEmbeddedInXcode) = try toolchainDeveloperPathInfo(toolchain: buildParameters.toolchain)
if isEmbeddedInXcode {
return try await session.buildTargetInfo(triple: buildParameters.triple.tripleString)
} else {
return try await session.buildTargetInfo(triple: buildParameters.triple.tripleString)
}
}
private func makeRunDestination(session: SWBBuildServiceSession) async throws -> SwiftBuild.SWBRunDestinationInfo {
if let sdkManifestPath = self.buildParameters.toolchain.swiftSDK.swiftSDKManifest {
return SwiftBuild.SWBRunDestinationInfo(
buildTarget: .swiftSDK(sdkManifestPath: sdkManifestPath.pathString, triple: self.buildParameters.triple.tripleString),
targetArchitecture: buildParameters.triple.archName,
supportedArchitectures: [],
disableOnlyActiveArch: (buildParameters.architectures?.count ?? 1) > 1,
)
} else {
let buildTargetInfo = try await self.buildTargetInfo(session: session)
return SwiftBuild.SWBRunDestinationInfo(
buildTarget: .toolchainSDK(
platform: buildTargetInfo.platformName,
sdk: buildTargetInfo.sdkName,
sdkVariant: buildTargetInfo.sdkVariant
),
targetArchitecture: buildParameters.triple.archName,
supportedArchitectures: [],
disableOnlyActiveArch: (buildParameters.architectures?.count ?? 1) > 1,
hostTargetedPlatform: nil
)
}
}
internal func makeBuildParameters(
service: SWBBuildService,
session: SWBBuildServiceSession,
symbolGraphOptions: BuildOutput.SymbolGraphOptions?,
setToolchainSetting: Bool = true,
) async throws -> SwiftBuild.SWBBuildParameters {
// Generate the run destination parameters.
let runDestination = try await makeRunDestination(session: session)
var verboseFlag: [String] = []
if self.logLevel == .debug {
verboseFlag = ["-v"] // Clang's verbose flag
}
// Generate a table of any overriding build settings.
var settings: [String: String] = [:]
if setToolchainSetting {
// If the SwiftPM toolchain corresponds to a toolchain registered with the lower level build system, add it to the toolchain stack.
// Otherwise, apply overrides for each component of the SwiftPM toolchain.
let toolchainID = try await session.lookupToolchain(at: buildParameters.toolchain.toolchainDir.pathString)
if toolchainID == nil {
// FIXME: This list of overrides is incomplete.
// An error with determining the override should not be fatal here.
settings["CC"] = try? buildParameters.toolchain.getClangCompiler().pathString
// Always specify the path of the effective Swift compiler, which was determined in the same way as for the
// native build system.
settings["SWIFT_EXEC"] = buildParameters.toolchain.swiftCompilerPath.pathString
}
let overrideToolchains = [buildParameters.toolchain.metalToolchainId, toolchainID?.rawValue].compactMap { $0 }
if !overrideToolchains.isEmpty {
settings["TOOLCHAINS"] = (overrideToolchains + ["$(inherited)"]).joined(separator: " ")
}
}
for sanitizer in buildParameters.sanitizers.sanitizers {
self.observabilityScope.emit(debug:"Enabling \(sanitizer) sanitizer")
switch sanitizer {
case .address:
settings["ENABLE_ADDRESS_SANITIZER"] = "YES"
case .thread:
settings["ENABLE_THREAD_SANITIZER"] = "YES"
case .undefined:
settings["ENABLE_UNDEFINED_BEHAVIOR_SANITIZER"] = "YES"
case .fuzzer, .scudo:
throw StringError("\(sanitizer) is not currently supported with this build system.")
}
}
// FIXME: workaround for old Xcode installations such as what is in CI
settings["LM_SKIP_METADATA_EXTRACTION"] = "YES"
if let symbolGraphOptions {
settings["RUN_SYMBOL_GRAPH_EXTRACT"] = "YES"
if symbolGraphOptions.prettyPrint {
settings["DOCC_PRETTY_PRINT"] = "YES"
}
if symbolGraphOptions.emitExtensionBlocks {
settings["DOCC_EXTRACT_EXTENSION_SYMBOLS"] = "YES"
}
if !symbolGraphOptions.includeInheritedDocs {
settings["DOCC_SKIP_INHERITED_DOCS"] = "YES"
}
if !symbolGraphOptions.includeSynthesized {
settings["DOCC_SKIP_SYNTHESIZED_MEMBERS"] = "YES"
}
if symbolGraphOptions.includeSPI {
settings["DOCC_EXTRACT_SPI_DOCUMENTATION"] = "YES"
}
switch symbolGraphOptions.minimumAccessLevel {
case .private:
settings["DOCC_MINIMUM_ACCESS_LEVEL"] = "private"
case .fileprivate:
settings["DOCC_MINIMUM_ACCESS_LEVEL"] = "fileprivate"
case .internal:
settings["DOCC_MINIMUM_ACCESS_LEVEL"] = "internal"
case .package:
settings["DOCC_MINIMUM_ACCESS_LEVEL"] = "package"
case .public:
settings["DOCC_MINIMUM_ACCESS_LEVEL"] = "public"
case .open:
settings["DOCC_MINIMUM_ACCESS_LEVEL"] = "open"
}
}
if !buildParameters.customToolsetPaths.isEmpty {
settings["SWIFT_SDK_TOOLSETS"] =
(["$(inherited)"] + buildParameters.customToolsetPaths.map { $0.pathString })
.joined(separator: " ")
}
let buildTargetInfo = try await self.buildTargetInfo(session: session)
if let deploymentTargetSettingName = buildTargetInfo.deploymentTargetSettingName, let value = buildTargetInfo.deploymentTarget {
// Only override the deployment target if a version is explicitly specified;
// for Apple platforms this normally comes from the package manifest and may
// not be set to the same value for all packages in the package graph.
settings[deploymentTargetSettingName] = value
}
// FIXME: "none" triples get a placeholder SDK/platform and don't support any specific triple by default. Unlike most platforms, where the vendor and environment is implied as a function of the arch and "platform", bare metal operates in terms of triples directly. We need to replace this bringup convenience with a more idiomatic mechanism, perhaps in the build request.
if buildParameters.triple.os == .noneOS {
settings["ARCHS"] = buildParameters.triple.archName
settings["VALID_ARCHS"] = buildParameters.triple.archName
settings["LLVM_TARGET_TRIPLE_VENDOR"] = buildParameters.triple.vendorName
if !buildParameters.triple.environmentName.isEmpty {
settings["LLVM_TARGET_TRIPLE_SUFFIX"] = "-" + buildParameters.triple.environmentName
}
}
let swiftCompilerFlags = buildParameters.toolchain.extraFlags.swiftCompilerFlags + buildParameters.flags.swiftCompilerFlags
let compilerAndLinkerFlags = [
"OTHER_CFLAGS": buildParameters.toolchain.extraFlags.cCompilerFlags + buildParameters.flags.cCompilerFlags,
"OTHER_CPLUSPLUSFLAGS": buildParameters.toolchain.extraFlags.cxxCompilerFlags + buildParameters.flags.cxxCompilerFlags,
"OTHER_SWIFT_FLAGS": swiftCompilerFlags,
"OTHER_LDFLAGS": (buildParameters.toolchain.extraFlags.linkerFlags + buildParameters.flags.linkerFlags)
]
for (settingName, buildFlags) in compilerAndLinkerFlags {
var rawFlags = buildFlags.rawFlagsForSwiftBuild
if settingName == "OTHER_LDFLAGS" {
rawFlags = rawFlags.asSwiftcLinkerFlags()
}
settings[settingName] = (verboseFlag + ["$(inherited)"] +
rawFlags.map { $0.shellEscaped() }).joined(separator: " ")
}
// Historically, SwiftPM passed -Xswiftc flags to swiftc when used as a linker driver.
// To maintain compatibility, forward swift compiler flags to OTHER_LDFLAGS when using
// swiftc to link.
if !swiftCompilerFlags.rawFlagsForSwiftBuild.isEmpty {
settings["OTHER_LDFLAGS_SWIFTC_LINKER_DRIVER_swiftc"] =
(["$(inherited)"] + swiftCompilerFlags.rawFlagsForSwiftBuild.map { $0.shellEscaped() }).joined(separator: " ")
settings["OTHER_LDFLAGS"] =
(settings["OTHER_LDFLAGS"] ?? "$(inherited)") + " $(OTHER_LDFLAGS_SWIFTC_LINKER_DRIVER_$(LINKER_DRIVER))"
}
if buildParameters.driverParameters.emitSILFiles {
settings["SWIFT_EMIT_SIL_FILES"] = "YES"
if let outputDir = buildParameters.driverParameters.silOutputDirectory {
settings["SWIFT_SIL_OUTPUT_DIR"] = outputDir.pathString
}
}
if buildParameters.driverParameters.emitIRFiles {
settings["SWIFT_EMIT_IR_FILES"] = "YES"
if let outputDir = buildParameters.driverParameters.irOutputDirectory {
settings["SWIFT_IR_OUTPUT_DIR"] = outputDir.pathString
}
}
if buildParameters.driverParameters.emitOptimizationRecord {
settings["SWIFT_EMIT_OPT_RECORDS"] = "YES"
if let outputDir = buildParameters.driverParameters.optimizationRecordDirectory {
settings["SWIFT_OPT_RECORD_OUTPUT_DIR"] = outputDir.pathString
}
}
// Optionally also set the list of architectures to build for.
if let architectures = buildParameters.architectures, !architectures.isEmpty {
settings["ARCHS"] = architectures.joined(separator: " ")
} else {
// If the user did not explicitly specify a list of architectures, build only the active arch.
// We may want to consider building universal binaries by default in Apple-platform release builds
// in the future, but for now we maintain compatibility with the old build system.
settings["ONLY_ACTIVE_ARCH"] = "YES"
}
// When building with the CLI for macOS, test bundles should generate entrypoints for compatibility with swiftpm-testing-helper.
if buildParameters.triple.isMacOSX {
settings["GENERATE_TEST_ENTRYPOINTS_FOR_BUNDLES"] = "YES"
}
// Set the value of the index store
struct IndexStoreSettings {
let enableVariableName: String
let pathVariable: String
}
let indexStoreSettingNames: [IndexStoreSettings] = [
IndexStoreSettings(
enableVariableName: "CLANG_INDEX_STORE_ENABLE",
pathVariable: "CLANG_INDEX_STORE_PATH",
),
IndexStoreSettings(
enableVariableName: "SWIFT_INDEX_STORE_ENABLE",
pathVariable: "SWIFT_INDEX_STORE_PATH",
),
]
switch self.buildParameters.indexStoreMode {
case .on:
for setting in indexStoreSettingNames {
settings[setting.enableVariableName] = "YES"
settings[setting.pathVariable] = self.buildParameters.indexStore.pathString
}
case .off:
for setting in indexStoreSettingNames {
settings[setting.enableVariableName] = "NO"
}
case .auto: