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
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2015-2023 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
//
//===----------------------------------------------------------------------===//
import Basics
import LLBuildManifest
import PackageGraph
import PackageModel
import SPMBuildCore
#if USE_IMPL_ONLY_IMPORTS
@_implementationOnly import SwiftDriver
#else
import SwiftDriver
#endif
import struct TSCBasic.ByteString
import func TSCBasic.topologicalSort
/// High-level interface to ``LLBuildManifest`` and ``LLBuildManifestWriter``.
public class LLBuildManifestBuilder {
enum Error: Swift.Error {
case ldPathDriverOptionUnavailable(option: String)
var description: String {
switch self {
case .ldPathDriverOptionUnavailable(let option):
return "Unable to pass \(option), currently used version of `swiftc` doesn't support it."
}
}
}
public enum TargetKind {
case main
case test
public var targetName: String {
switch self {
case .main: return "main"
case .test: return "test"
}
}
}
/// The build plan to work on.
public let plan: BuildPlan
/// Whether to sandbox commands from build tool plugins.
public let disableSandboxForPluginCommands: Bool
/// File system reference.
let fileSystem: any FileSystem
/// ObservabilityScope with which to emit diagnostics
public let observabilityScope: ObservabilityScope
public internal(set) var manifest: LLBuildManifest = .init()
/// Mapping from Swift compiler path to Swift get version files.
var swiftGetVersionFiles = [AbsolutePath: AbsolutePath]()
/// Create a new builder with a build plan.
public init(
_ plan: BuildPlan,
disableSandboxForPluginCommands: Bool = false,
fileSystem: any FileSystem,
observabilityScope: ObservabilityScope
) {
self.plan = plan
self.disableSandboxForPluginCommands = disableSandboxForPluginCommands
self.fileSystem = fileSystem
self.observabilityScope = observabilityScope
}
// MARK: - Generate Build Manifest
/// Generate build manifest at the given path.
@discardableResult
public func generateManifest(at path: AbsolutePath) throws -> LLBuildManifest {
self.swiftGetVersionFiles.removeAll()
self.manifest.createTarget(TargetKind.main.targetName)
self.manifest.createTarget(TargetKind.test.targetName)
self.manifest.defaultTarget = TargetKind.main.targetName
addPackageStructureCommand()
addBinaryDependencyCommands()
if self.plan.destinationBuildParameters.driverParameters.useExplicitModuleBuild {
// Explicit module builds use the integrated driver directly and
// require that every target's build jobs specify its dependencies explicitly to plan
// its build.
// Currently behind:
// --experimental-explicit-module-build
try addTargetsToExplicitBuildManifest()
} else {
// Create commands for all target descriptions in the plan.
for (_, description) in self.plan.targetMap {
switch description {
case .swift(let desc):
try self.createSwiftCompileCommand(desc)
case .clang(let desc):
try self.createClangCompileCommand(desc)
}
}
}
try self.addTestDiscoveryGenerationCommand()
try self.addTestEntryPointGenerationCommand()
// Create command for all products in the plan.
for (_, description) in self.plan.productMap {
try self.createProductCommand(description)
}
try LLBuildManifestWriter.write(self.manifest, at: path, fileSystem: self.fileSystem)
return self.manifest
}
package func generatePrepareManifest(at path: AbsolutePath) throws -> LLBuildManifest {
self.swiftGetVersionFiles.removeAll()
self.manifest.createTarget(TargetKind.main.targetName)
self.manifest.createTarget(TargetKind.test.targetName)
self.manifest.defaultTarget = TargetKind.main.targetName
addPackageStructureCommand()
for (_, description) in self.plan.targetMap {
switch description {
case .swift(let desc):
try self.createSwiftCompileCommand(desc)
case .clang(let desc):
if desc.target.buildTriple == .tools {
// Need the clang modules for tools
try self.createClangCompileCommand(desc)
} else {
// Hook up the clang module target
try self.createClangPrepareCommand(desc)
}
}
}
for (_, description) in self.plan.productMap {
// Need to generate macro products
switch description.product.type {
case .macro, .plugin:
try self.createProductCommand(description)
default:
break
}
}
try LLBuildManifestWriter.write(self.manifest, at: path, fileSystem: self.fileSystem)
return self.manifest
}
func addNode(_ node: Node, toTarget targetKind: TargetKind) {
self.manifest.addNode(node, toTarget: targetKind.targetName)
}
}
// MARK: - Package Structure
extension LLBuildManifestBuilder {
private func addPackageStructureCommand() {
let inputs = self.plan.inputs.map {
switch $0 {
case .directoryStructure(let path): return Node.directoryStructure(path)
case .file(let path): return Node.file(path)
}
}
let name = "PackageStructure"
let output: Node = .virtual(name)
self.manifest.addPkgStructureCmd(
name: name,
inputs: inputs,
outputs: [output]
)
self.manifest.addNode(output, toTarget: name)
}
}
// MARK: - Binary Dependencies
extension LLBuildManifestBuilder {
// Creates commands for copying all binary artifacts depended on in the plan.
private func addBinaryDependencyCommands() {
// Make sure we don't have multiple copy commands for each destination by mapping each destination to
// its source binary.
var destinations = [AbsolutePath: AbsolutePath]()
for target in self.plan.targetMap.values {
for binaryPath in target.libraryBinaryPaths {
destinations[target.buildParameters.destinationPath(forBinaryAt: binaryPath)] = binaryPath
}
}
for (destination, source) in destinations {
self.addCopyCommand(from: source, to: destination)
}
}
}
// MARK: - Compilation
extension LLBuildManifestBuilder {
func addBuildToolPlugins(_ target: ModuleBuildDescription) throws -> [Node] {
// For any build command that doesn't declare any outputs, we need to create a phony output to ensure they will still be run by the build system.
var phonyOutputs = [Node]()
// If we have multiple commands with no output files and no display name, this serves as a way to disambiguate the virtual nodes being created.
var pluginNumber = 1
// Add any regular build commands created by plugins for the target.
for result in target.buildToolPluginInvocationResults {
// Only go through the regular build commands — prebuild commands are handled separately.
for command in result.buildCommands {
// Create a shell command to invoke the executable. We include the path of the executable as a
// dependency, and make sure the name is unique.
let execPath = command.configuration.executable
let uniquedName = ([execPath.pathString] + command.configuration.arguments).joined(separator: "|")
let displayName = command.configuration.displayName ?? execPath.basename
var commandLine = [execPath.pathString] + command.configuration.arguments
if !self.disableSandboxForPluginCommands {
commandLine = try Sandbox.apply(
command: commandLine,
fileSystem: self.fileSystem,
strictness: .writableTemporaryDirectory,
writableDirectories: [result.pluginOutputDirectory]
)
}
let additionalOutputs: [Node]
if command.outputFiles.isEmpty {
if target.toolsVersion >= .v6_0 {
additionalOutputs = [.virtual("\(target.target.c99name)-\(command.configuration.displayName ?? "\(pluginNumber)")")]
phonyOutputs += additionalOutputs
} else {
additionalOutputs = []
observabilityScope.emit(warning: "Build tool command '\(displayName)' (applied to target '\(target.target.name)') does not declare any output files and therefore will not run. You may want to consider updating the given package to tools-version 6.0 (or higher) which would run such a build tool command even without declared outputs.")
}
pluginNumber += 1
} else {
additionalOutputs = []
}
self.manifest.addShellCmd(
name: displayName + "-" + ByteString(encodingAsUTF8: uniquedName).sha256Checksum,
description: displayName,
inputs: command.inputFiles.map { .file($0) },
outputs: command.outputFiles.map { .file($0) } + additionalOutputs,
arguments: commandLine,
environment: command.configuration.environment,
workingDirectory: command.configuration.workingDirectory?.pathString
)
}
}
return phonyOutputs
}
}
// MARK: - Test File Generation
extension LLBuildManifestBuilder {
private func addTestDiscoveryGenerationCommand() throws {
for testDiscoveryTarget in self.plan.targets.compactMap(\.testDiscoveryTargetBuildDescription) {
let testTargets = testDiscoveryTarget.target.dependencies
.compactMap(\.module).compactMap { self.plan.targetMap[$0.id] }
let objectFiles = try testTargets.flatMap { try $0.objects }.sorted().map(Node.file)
let outputs = testDiscoveryTarget.target.sources.paths
guard let mainOutput = (outputs.first { $0.basename == TestDiscoveryTool.mainFileName }) else {
throw InternalError("main output (\(TestDiscoveryTool.mainFileName)) not found")
}
let cmdName = mainOutput.pathString
self.manifest.addTestDiscoveryCmd(
name: cmdName,
inputs: objectFiles,
outputs: outputs.map(Node.file)
)
}
}
private func addTestEntryPointGenerationCommand() throws {
for target in self.plan.targets {
guard case .swift(let target) = target,
case .entryPoint(let isSynthesized) = target.testTargetRole,
isSynthesized else { continue }
let testEntryPointTarget = target
// Get the Swift target build descriptions of all discovery modules this synthesized entry point target
// depends on.
let discoveredTargetDependencyBuildDescriptions = testEntryPointTarget.target.dependencies
.compactMap(\.module?.id)
.compactMap { self.plan.targetMap[$0] }
.compactMap(\.testDiscoveryTargetBuildDescription)
// The module outputs of the discovery modules this synthesized entry point target depends on are
// considered the inputs to the entry point command.
let inputs = discoveredTargetDependencyBuildDescriptions.map(\.moduleOutputPath)
let outputs = testEntryPointTarget.target.sources.paths
let mainFileName = TestEntryPointTool.mainFileName
guard let mainOutput = (outputs.first { $0.basename == mainFileName }) else {
throw InternalError("main output (\(mainFileName)) not found")
}
let cmdName = mainOutput.pathString
self.manifest.addTestEntryPointCmd(
name: cmdName,
inputs: inputs.map(Node.file),
outputs: outputs.map(Node.file)
)
}
}
}
extension ModuleBuildDescription {
/// If receiver represents a Swift target build description whose test target role is Discovery,
/// then this returns that Swift target build description, else returns nil.
fileprivate var testDiscoveryTargetBuildDescription: SwiftModuleBuildDescription? {
guard case .swift(let targetBuildDescription) = self,
case .discovery = targetBuildDescription.testTargetRole else { return nil }
return targetBuildDescription
}
}
extension ModuleBuildDescription {
package var llbuildResourcesCmdName: String {
"\(self.target.name)-\(self.buildParameters.triple.tripleString)-\(self.buildParameters.buildConfig)\(self.buildParameters.suffix).module-resources"
}
}
extension ClangModuleBuildDescription {
package var llbuildTargetName: String {
self.target.getLLBuildTargetName(buildParameters: self.buildParameters)
}
}
extension ResolvedModule {
public func getLLBuildTargetName(buildParameters: BuildParameters) -> String {
"\(self.name)-\(buildParameters.triple.tripleString)-\(buildParameters.buildConfig)\(buildParameters.suffix).module"
}
}
// MARK: - Helper
extension LLBuildManifestBuilder {
@discardableResult
func addCopyCommand(
from source: AbsolutePath,
to destination: AbsolutePath
) -> (inputNode: Node, outputNode: Node) {
let isDirectory = self.fileSystem.isDirectory(source)
let nodeType = isDirectory ? Node.directory : Node.file
let inputNode = nodeType(source)
let outputNode = nodeType(destination)
self.manifest.addCopyCmd(name: destination.pathString, inputs: [inputNode], outputs: [outputNode])
return (inputNode, outputNode)
}
}
extension BuildParameters {
func destinationPath(forBinaryAt path: AbsolutePath) -> AbsolutePath {
self.buildPath.appending(component: path.basename)
}
var buildConfig: String { self.configuration.dirname }
}
extension Sequence where Element: Hashable {
/// Unique the elements in a sequence.
func uniqued() -> [Element] {
var seen: Set<Element> = []
return filter { seen.insert($0).inserted }
}
}
|