atllbuild.swift 20.6 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Drew's avatar
Drew committed
14

Drew's avatar
Drew committed
15
import Foundation
16
import atpkg
Drew's avatar
Drew committed
17

18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
 /**Synthesize a module map.
 - parameter name: The name of the module to synthesize
 - parameter umbrellaHeader: A path to the umbrella header.  The path must be relative to the exported module map file.
 - returns String contents of the synthesized modulemap
 */
 private func synthesizeModuleMap(name: String, umbrellaHeader: String?) -> String {
     var s = ""
     s += "module \(name) {\n"
     if let u = umbrellaHeader {
         s += "  umbrella header \"\(u)\"\n"
     }
     s += "\n"
     s += "}\n"
     return s
 }
Drew's avatar
Drew committed
33

Drew's avatar
Drew committed
34

Drew's avatar
Drew committed
35 36
/**The ATllbuild tool builds a swift module via llbuild.
For more information on this tool, see `docs/attllbuild.md` */
Drew's avatar
Drew committed
37
final class ATllbuild : Tool {
38

39 40 41 42 43 44 45
    /**We inject this sourcefile in xctestify=true on OSX
    On Linux, the API requires you to explicitly list tests
    which is not required on OSX.  Injecting this file into test targets
    will enforce that API on OSX as well */
    private static let xcTestCaseProvider: String = { () -> String in
        var s = ""
        s += "import XCTest\n"
46 47
        s += "public func testCase<T: XCTestCase>(allTests: [(String, T -> () throws -> Void)]) -> XCTestCase {\n"
        s += "    fatalError(\"Can't get here.\")\n"
48 49 50 51 52 53 54 55
        s += "}\n"
        s += "\n"
        s += "public func XCTMain(testCases: [XCTestCase]) {\n"
        s += "    fatalError(\"Can't get here.\")\n"
        s += "}\n"
        s += "\n"
        return s
    }()
56

57 58 59
    enum OutputType {
        case Executable
        case StaticLibrary
Drew's avatar
Drew committed
60
        case DynamicLibrary
61
    }
Drew's avatar
Drew committed
62 63 64 65 66

    enum ModuleMapType {
        case None
        case Synthesized
    }
67

68 69 70 71 72 73 74
    /**
     * Calculates the llbuild.yaml contents for the given configuration options
     *   - parameter sources: A resolved list of swift sources
     *   - parameter workdir: A temporary working directory for `atllbuild` to use
     *   - parameter modulename: The name of the module to be built.
     *   - returns: The string contents for llbuild.yaml suitable for processing by swift-build-tool
     */
Drew's avatar
Drew committed
75
    func llbuildyaml(sources: [String], workdir: String, modulename: String, linkSDK: Bool, compileOptions: [String], linkOptions: [String], outputType: OutputType, linkWithProduct:[String], swiftCPath: String) -> String {
76
        let productPath = workdir + "products/"
Drew's avatar
Drew committed
77 78
        //this format is largely undocumented, but I reverse-engineered it from SwiftPM.
        var yaml = "client:\n  name: swift-build\n\n"
79

Drew's avatar
Drew committed
80 81
        yaml += "tools: {}\n\n"

82

Drew's avatar
Drew committed
83
        yaml += "targets:\n"
Drew's avatar
Drew committed
84 85
        yaml += "  \"\": [<atllbuild>]\n"
        yaml += "  atllbuild: [<atllbuild>]\n"
86

Drew's avatar
Drew committed
87
        //this is the "compile" command
88

Drew's avatar
Drew committed
89 90 91
        yaml += "commands:\n"
        yaml += "  <atllbuild-swiftc>:\n"
        yaml += "     tool: swift-compiler\n"
Drew's avatar
Drew committed
92
        yaml += "     executable: \"\(swiftCPath)\"\n"
Drew's avatar
Drew committed
93 94
        yaml += "     inputs: \(sources)\n"
        yaml += "     sources: \(sources)\n"
95

Drew's avatar
Drew committed
96 97
        //swiftPM wants "objects" which is just a list of %.swift.o files.  We have to put them in a temp directory though.
        let objects = sources.map { (source) -> String in
Drew's avatar
Drew committed
98
            workdir + "objects/" + source.toNSString.lastPathComponent + ".o"
Drew's avatar
Drew committed
99 100
        }
        yaml += "     objects: \(objects)\n"
Drew's avatar
Drew committed
101 102
        //this crazy syntax is how llbuild specifies outputs
        var llbuild_outputs = ["<atllbuild-swiftc>"]
103
        llbuild_outputs.append(contentsOf: objects)
Drew's avatar
Drew committed
104
        yaml += "     outputs: \(llbuild_outputs)\n"
105

106 107 108
        switch(outputType) {
        case .Executable:
            break
Drew's avatar
Drew committed
109
        case .StaticLibrary, .DynamicLibrary:
110 111
            yaml += "     is-library: true\n" //I have no idea what the effect of this is, but swiftPM does it, so I'm including it.
        }
112

Drew's avatar
Drew committed
113
        yaml += "     module-name: \(modulename)\n"
114 115
        let swiftModulePath = "\(productPath + modulename).swiftmodule"
        yaml += "     module-output-path: \(swiftModulePath)\n"
Drew's avatar
Drew committed
116
        yaml += "     temps-path: \(workdir)/llbuildtmp\n"
117

Drew's avatar
Drew committed
118
        var args : [String] = []
119
        args.append(contentsOf: ["-j8", "-D","ATBUILD","-I",workdir+"products/"])
120

121
        if linkSDK {
Drew's avatar
Drew committed
122
            #if os(OSX) //we don't have SDKPath on linux
123
            args.append(contentsOf: ["-sdk", SDKPath])
Drew's avatar
Drew committed
124
            #endif
125
        }
126
        args.append(contentsOf: compileOptions)
127

Drew's avatar
Drew committed
128
        yaml += "     other-args: \(args)\n"
129

Drew's avatar
Drew committed
130 131
        //and this is the "link" command
        yaml += "  <atllbuild>:\n"
132 133 134 135 136
        switch(outputType) {
        case .Executable:
            yaml += "    tool: shell\n"
            //this crazy syntax is how sbt declares a dependency
            var llbuild_inputs = ["<atllbuild-swiftc>"]
137
            llbuild_inputs.append(contentsOf: objects)
Drew's avatar
Drew committed
138
            let builtProducts = linkWithProduct.map {workdir+"products/"+$0}
139
            llbuild_inputs.append(contentsOf: builtProducts)
140
            let executablePath = productPath+modulename
141
            yaml += "    inputs: \(llbuild_inputs)\n"
142
            yaml += "    outputs: [\"<atllbuild>\", \"\(executablePath)\"]\n"
143
            //and now we have the crazy 'args'
Drew's avatar
Drew committed
144
            args = [swiftCPath, "-o",executablePath]
145 146 147
            args.append(contentsOf: objects)
            args.append(contentsOf: builtProducts)
            args.append(contentsOf: linkOptions)
148
            yaml += "    args: \(args)\n"
149 150
            yaml += "    description: Linking executable \(executablePath)\n"
            return yaml
Drew's avatar
Drew committed
151

152

153 154 155
        case .StaticLibrary:
            yaml += "    tool: shell\n"
            var llbuild_inputs = ["<atllbuild-swiftc>"]
156
            llbuild_inputs.append(contentsOf: objects)
157
            yaml += "    inputs: \(llbuild_inputs)\n"
158
            let libPath = productPath + modulename + ".a"
159
            yaml += "    outputs: [\"<atllbuild>\", \"\(libPath)\"]\n"
160

161 162 163 164 165 166 167 168
            //build the crazy args, mostly consisting of an `ar` shell command
            var shellCmd = "rm -rf \(libPath); ar cr '\(libPath)'"
            for obj in objects {
                shellCmd += " '\(obj)'"
            }
            let args = "[\"/bin/sh\",\"-c\",\(shellCmd)]"
            yaml += "    args: \(args)\n"
            yaml += "    description: \"Linking Library:  \(libPath)\""
169
            return yaml
Drew's avatar
Drew committed
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

        case .DynamicLibrary:
            yaml += "    tool: shell\n"
            var llbuild_inputs = ["<atllbuild-swiftc>"]
            llbuild_inputs.append(contentsOf: objects)
            let builtProducts = linkWithProduct.map {workdir+"products/"+$0}
            llbuild_inputs.append(contentsOf: builtProducts)
            yaml += "    inputs: \(llbuild_inputs)\n"
            let libPath = productPath + modulename + DynamicLibraryExtension
            yaml += "    outputs: [\"<atllbuild>\", \"\(libPath)\"]\n"
            var args = [swiftCPath, "-o", libPath, "-emit-library"]
            args.append(contentsOf: objects)
            args.append(contentsOf: builtProducts)
            args.append(contentsOf: linkOptions)
            yaml += "    args: \(args)\n"
            yaml += "    description: \"Linking Library:  \(libPath)\""
            return yaml
187
        }
188
     }
189

Drew's avatar
Drew committed
190 191 192 193
    private enum Options: String {
        case Tool = "tool"
        case Name = "name"
        case Dependencies = "dependencies"
194 195 196
        case OutputType = "output-type"
        case Source = "sources"
        case BootstrapOnly = "bootstrap-only"
Drew's avatar
Drew committed
197
        case llBuildYaml = "llbuildyaml"
198 199 200 201 202
        case CompileOptions = "compile-options"
        case LinkOptions = "link-options"
        case LinkSDK = "link-sdk"
        case LinkWithProduct = "link-with"
        case SwiftCPath = "swiftc-path"
Drew's avatar
Drew committed
203
        case XCTestify = "xctestify"
204
        case XCTestStrict = "xctest-strict"
205
		case IncludeWithUser = "include-with-user"
206
        case PublishProduct = "publish-product"
207
        case UmbrellaHeader = "umbrella-header"
Drew's avatar
Drew committed
208
        case ModuleMap = "module-map"
Drew's avatar
Drew committed
209
        case WholeModuleOptimization = "whole-module-optimization"
210
        case Framework = "framework"
211

212

Drew's avatar
Drew committed
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227
        static var allOptions : [Options] {
            return [
                Name,
                Dependencies,
                OutputType,
                Source,
                BootstrapOnly,
                llBuildYaml,
                CompileOptions,
                LinkOptions,
                LinkSDK,
                LinkWithProduct,
                SwiftCPath,
                XCTestify,
                XCTestStrict,
228
				IncludeWithUser,
229
                PublishProduct,
Drew's avatar
Drew committed
230
				UmbrellaHeader,
231 232
                WholeModuleOptimization,
                Framework
Drew's avatar
Drew committed
233 234 235
            ]
        }
    }
Drew's avatar
Drew committed
236

Drew's avatar
Drew committed
237
    func run(task: Task, toolchain: String) {
238
        run(task: task, toolchain: toolchain, wmoHack: false)
Drew's avatar
Drew committed
239
    }
240

Drew's avatar
Drew committed
241
    func run(task: Task, toolchain: String, wmoHack : Bool = false) {
242

243
        //warn if we don't understand an option
244 245 246 247
        var knownOptions = Options.allOptions.map({$0.rawValue})
        for option in Task.Option.allOptions.map({$0.rawValue}) {
            knownOptions.append(option)
        }
248
        for key in task.allKeys {
249
            if !knownOptions.contains(key) {
Drew's avatar
Drew committed
250
                print("Warning: unknown option \(key) for task \(task.qualifiedName)")
251 252
            }
        }
253

Drew's avatar
Drew committed
254 255 256
        //create the working directory
        let workDirectory = ".atllbuild/"
        let manager = NSFileManager.defaultManager()
257

Drew's avatar
Drew committed
258 259 260 261
        //NSFileManager is pretty anal about throwing errors if we try to remove something that doesn't exist, etc.
        //We just want to create a state where .atllbuild/objects and .atllbuild/llbuildtmp and .atllbuild/products exists.
        //and in particular, without erasing the product directory, since that accumulates build products across
        //multiple invocations of atllbuild.
Drew's avatar
Drew committed
262
        if Process.arguments.contains("--clean") {
263 264
            let _ = try? manager.removeItem(atPath: workDirectory + "/objects")
            let _ = try? manager.removeItem(atPath: workDirectory + "/llbuildtmp")
Drew's avatar
Drew committed
265
        }
266
        let _ = try? manager.removeItem(atPath: workDirectory + "/include")
267

Drew's avatar
Drew committed
268 269


270 271 272 273
        let _ = try? manager.createDirectory(atPath: workDirectory, withIntermediateDirectories: false, attributes: nil)
        let _ = try? manager.createDirectory(atPath: workDirectory + "/products", withIntermediateDirectories: false, attributes: nil)
        let _ = try? manager.createDirectory(atPath: workDirectory + "/objects", withIntermediateDirectories: false, attributes: nil)
        let _ = try? manager.createDirectory(atPath: workDirectory + "/include", withIntermediateDirectories: false, attributes: nil)
Drew's avatar
Drew committed
274

Drew's avatar
Drew committed
275
        //parse arguments
Drew's avatar
Drew committed
276
        var linkWithProduct: [String] = []
Drew's avatar
Drew committed
277 278 279 280
        if let arr_ = task[Options.LinkWithProduct.rawValue] {
            guard let arr = arr_.vector else {
                fatalError("Non-vector link directive \(arr_)")
            }
Drew's avatar
Drew committed
281
            for product in arr {
Drew's avatar
Drew committed
282 283 284 285
                guard var p = product.string else { fatalError("non-string product \(product)") }
                if p.hasSuffix(".dynamic") {
                    p = p.replacingOccurrences(of: ".dynamic", with: DynamicLibraryExtension)
                }
Drew's avatar
Drew committed
286 287 288
                linkWithProduct.append(p)
            }
        }
Drew's avatar
Drew committed
289

290
        let outputType: OutputType
Drew's avatar
Drew committed
291
        if task[Options.OutputType.rawValue]?.string == "static-library" {
292 293
            outputType = .StaticLibrary
        }
Drew's avatar
Drew committed
294
        else if task[Options.OutputType.rawValue]?.string == "executable" {
295 296
            outputType = .Executable
        }
Drew's avatar
Drew committed
297 298 299
        else if task[Options.OutputType.rawValue]?.string == "dynamic-library" {
            outputType = .DynamicLibrary
        }
300
        else {
301
            fatalError("Unknown \(Options.OutputType.rawValue) \(task["outputType"])")
302
        }
303

304
        var compileOptions: [String] = []
Drew's avatar
Drew committed
305
        if let opts = task[Options.CompileOptions.rawValue]?.vector {
306
            for o in opts {
307
                guard let os = o.string else { fatalError("Compile option \(o) is not a string") }
308 309 310
                compileOptions.append(os)
            }
        }
Drew's avatar
Drew committed
311 312 313 314

        if wmoHack {
            compileOptions.append("-whole-module-optimization")
        }
315

316
        if let includePaths = task[Options.IncludeWithUser.rawValue]?.vector {
Drew's avatar
Drew committed
317 318 319 320 321 322
            for path_s in includePaths {
                guard let path = path_s.string else { fatalError("Non-string path \(path_s)") }
                compileOptions.append("-I")
                compileOptions.append(userPath() + "/" + path)
            }
        }
Drew's avatar
Drew committed
323
        var linkOptions: [String] = []
Drew's avatar
Drew committed
324
        if let opts = task[Options.LinkOptions.rawValue]?.vector {
Drew's avatar
Drew committed
325 326 327 328 329
            for o in opts {
                guard let os = o.string else { fatalError("Link option \(o) is not a string") }
                linkOptions.append(os)
            }
        }
Drew's avatar
Drew committed
330 331 332

        //check for modulemaps
        for product in linkWithProduct {
333
            let productName = product.components(separatedBy: ".")[0]
Drew's avatar
Drew committed
334
            let moduleMapPath = workDirectory + "/products/\(productName).modulemap"
335
            if manager.fileExists(atPath: moduleMapPath) {
Drew's avatar
Drew committed
336 337 338 339 340
                /*per http://clang.llvm.org/docs/Modules.html#command-line-parameters, pretty much
                the only way to do this is to create a file called `module.modulemap`.  That
                potentially conflicts with other modulemaps, so we give it its own directory, namespaced
                by the product name. */
                let pathName = workDirectory + "/include/\(productName)"
341
                try! manager.createDirectory(atPath: pathName, withIntermediateDirectories:false, attributes: nil)
342
                try! manager.copyItemAtPath_SWIFTBUG(srcPath: moduleMapPath, toPath: pathName + "/module.modulemap")
343
                compileOptions.append(contentsOf: ["-I",pathName])
Drew's avatar
Drew committed
344 345 346
            }
        }

Drew's avatar
Drew committed
347
        guard let sourceDescriptions = task[Options.Source.rawValue]?.vector?.flatMap({$0.string}) else { fatalError("Can't find sources for atllbuild.") }
348 349
        var sources = collectSources(sourceDescriptions: sourceDescriptions, taskForCalculatingPath: task)

Drew's avatar
Drew committed
350
        //xctestify
Drew's avatar
Drew committed
351
        if task[Options.XCTestify.rawValue]?.bool == true {
352
            precondition(outputType == .Executable, "You must use :\(Options.OutputType.rawValue) executable with xctestify.")
Drew's avatar
Drew committed
353 354
            //inject platform-specific flags
            #if os(OSX)
355 356
                compileOptions.append(contentsOf: ["-F", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/"])
                linkOptions.append(contentsOf: ["-F", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/", "-target", "x86_64-apple-macosx10.11", "-Xlinker", "-rpath", "-Xlinker", "/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/Library/Frameworks/", "-Xlinker", "-bundle"])
357 358
            #endif
        }
Drew's avatar
Drew committed
359
        if task[Options.XCTestStrict.rawValue]?.bool == true {
360 361 362
            #if os(OSX)
            //inject XCTestCaseProvider.swift
            var xcTestCaseProviderPath = "/tmp/XXXXXXX"
363
            var template = xcTestCaseProviderPath.cString(using: NSUTF8StringEncoding)!
364 365
            xcTestCaseProviderPath = String(cString: mkdtemp(&template), encoding: NSUTF8StringEncoding)!

366
            xcTestCaseProviderPath += "/XCTestCaseProvider.swift"
367 368

            try! ATllbuild.xcTestCaseProvider.write(toFile: xcTestCaseProviderPath, atomically: false, encoding: NSUTF8StringEncoding)
369
            sources.append(xcTestCaseProviderPath)
Drew's avatar
Drew committed
370 371
            #endif
        }
Drew's avatar
Drew committed
372 373 374 375 376 377 378
        let moduleMap: ModuleMapType
        if task[Options.ModuleMap.rawValue]?.string == "synthesized" {
            moduleMap = .Synthesized
        }
        else {
            moduleMap = .None
        }
Drew's avatar
Drew committed
379

Drew's avatar
Drew committed
380
        guard let name = task[Options.Name.rawValue]?.string else { fatalError("No name for atllbuild task") }
381 382 383 384 385 386 387 388 389 390

        if task[Options.Framework.rawValue]?.bool == true {
            #if !os(OSX)
            fatalError("\(Options.Framework.rawValue) is not supported on this platform.")
            #endif
            linkOptions.append("-Xlinker")
            linkOptions.append("-install_name")
            linkOptions.append("-Xlinker")
            linkOptions.append("@rpath/\(name).framework/Versions/A/\(name)")
        }
391

392
        if let umbrellaHeader = task[Options.UmbrellaHeader.rawValue]?.string {
Drew's avatar
Drew committed
393
            precondition(moduleMap == .Synthesized, ":\(Options.UmbrellaHeader.rawValue) \"synthesized\" must be used with the \(Options.UmbrellaHeader.rawValue) option")
394
            let s = synthesizeModuleMap(name: name, umbrellaHeader: "Umbrella.h")
395
            try! s.write(toFile: workDirectory+"/include/module.modulemap", atomically: false, encoding: NSUTF8StringEncoding)
396
            try! manager.copyItemAtPath_SWIFTBUG(srcPath: task.importedPath + umbrellaHeader, toPath: workDirectory + "/include/Umbrella.h")
397 398 399 400
            compileOptions.append("-I")
            compileOptions.append(workDirectory + "/include/")
            compileOptions.append("-import-underlying-module")
        }
401

Drew's avatar
Drew committed
402
        let bootstrapOnly: Bool
Drew's avatar
Drew committed
403

Drew's avatar
Drew committed
404
        if task[Options.BootstrapOnly.rawValue]?.bool == true {
Drew's avatar
Drew committed
405 406 407 408 409
            bootstrapOnly = true
        }
        else {
            bootstrapOnly = false
        }
410

411
        let sdk: Bool
Drew's avatar
Drew committed
412
        if task[Options.LinkSDK.rawValue]?.bool == false {
413 414 415
            sdk = false
        }
        else { sdk = true }
416

Drew's avatar
Drew committed
417
        let llbuildyamlpath : String
Drew's avatar
Drew committed
418

Drew's avatar
Drew committed
419
        if let value = task[Options.llBuildYaml.rawValue]?.string {
420
            llbuildyamlpath = value
Drew's avatar
Drew committed
421 422 423 424
        }
        else {
            llbuildyamlpath = workDirectory + "llbuild.yaml"
        }
Drew's avatar
Drew committed
425 426

        let swiftCPath: String
Drew's avatar
Drew committed
427
        if let c = task[Options.SwiftCPath.rawValue]?.string {
Drew's avatar
Drew committed
428 429 430
            swiftCPath = c
        }
        else {
431
            swiftCPath = findToolPath(toolName: "swiftc",toolchain: toolchain)
Drew's avatar
Drew committed
432
        }
433 434

        let yaml = llbuildyaml(sources: sources, workdir: workDirectory, modulename: name, linkSDK: sdk, compileOptions: compileOptions, linkOptions: linkOptions, outputType: outputType, linkWithProduct: linkWithProduct, swiftCPath: swiftCPath)
435
        let _ = try? yaml.write(toFile: llbuildyamlpath, atomically: false, encoding: NSUTF8StringEncoding)
Drew's avatar
Drew committed
436
        if bootstrapOnly { return }
Drew's avatar
Drew committed
437 438 439 440 441

        switch moduleMap {
                case .None:
                break
                case .Synthesized:
442
                let s = synthesizeModuleMap(name: name, umbrellaHeader: nil)
443
                try! s.write(toFile: workDirectory + "/products/\(name).modulemap", atomically: false, encoding: NSUTF8StringEncoding)
Drew's avatar
Drew committed
444
        }
445

Drew's avatar
Drew committed
446
        //SR-566
447
        let cmd = "\(findToolPath(toolName: "swift-build-tool",toolchain: toolchain)) -f \(llbuildyamlpath)"
Drew's avatar
Drew committed
448 449
        if system(cmd) != 0 {
            fatalError(cmd)
Drew's avatar
Drew committed
450
        }
Drew's avatar
Drew committed
451
        if task[Options.PublishProduct.rawValue]?.bool == true {
452 453
            if !manager.fileExists(atPath: "bin") {
                try! manager.createDirectory(atPath: "bin", withIntermediateDirectories: false, attributes: nil)
454
            }
455 456
            try! copyByOverwriting(fromPath: "\(workDirectory)/products/\(name).swiftmodule", toPath: "bin/\(name).swiftmodule")
            try! copyByOverwriting(fromPath: "\(workDirectory)/products/\(name).swiftdoc", toPath: "bin/\(name).swiftdoc")
457 458
            switch outputType {
            case .Executable:
459
                try! copyByOverwriting(fromPath: "\(workDirectory)/products/\(name)", toPath: "bin/\(name)")
460
            case .StaticLibrary:
461
                try! copyByOverwriting(fromPath: "\(workDirectory)/products/\(name).a", toPath: "bin/\(name).a")
Drew's avatar
Drew committed
462
            case .DynamicLibrary:
463
                try! copyByOverwriting(fromPath: "\(workDirectory)/products/\(name)\(DynamicLibraryExtension)", toPath: "bin/\(name)\(DynamicLibraryExtension)")
464
            }
Drew's avatar
Drew committed
465 466 467 468
            switch moduleMap {
                case .None:
                break
                case .Synthesized:
469
                try! copyByOverwriting(fromPath: "\(workDirectory)/products/\(name).modulemap", toPath: "bin/\(name).modulemap")
Drew's avatar
Drew committed
470
            }
471
        }
Drew's avatar
Drew committed
472 473 474

        if task[Options.WholeModuleOptimization.rawValue]?.bool == true && !wmoHack {
            print("Work around SR-881")
475
            run(task: task, toolchain: toolchain, wmoHack: true)
Drew's avatar
Drew committed
476 477
        }

478 479 480 481 482
    }
}

private func copyByOverwriting(fromPath: String, toPath: String) throws {
    let manager = NSFileManager.defaultManager()
483 484
    if manager.fileExists(atPath: toPath) {
        try manager.removeItem(atPath: toPath)
Drew's avatar
Drew committed
485
    }
486
    try! manager.copyItemAtPath_SWIFTBUG(srcPath: fromPath, toPath: toPath)
Drew's avatar
Drew committed
487
}