-
Notifications
You must be signed in to change notification settings - Fork 187
Expand file tree
/
Copy pathSwiftBuildOperationTests.swift
More file actions
646 lines (580 loc) · 37.4 KB
/
Copy pathSwiftBuildOperationTests.swift
File metadata and controls
646 lines (580 loc) · 37.4 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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import Testing
import SWBCore
import SWBTestSupport
import SWBUtil
import SWBTaskExecution
@Suite
fileprivate struct SwiftBuildOperationTests: CoreBasedTests {
@Test(.requireSDKs(.host))
func caseInsensitiveObjectLibraryCollision() async throws {
try await withTemporaryDirectory { (tmpDir: Path) in
let testProject = try await TestProject(
"TestProject",
sourceRoot: tmpDir,
groupTree: TestGroup(
"SomeFiles",
children: [
TestFile("objlib.swift"),
]),
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"ARCHS": "$(ARCHS_STANDARD)",
"CODE_SIGNING_ALLOWED": "NO",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SDKROOT": "$(HOST_PLATFORM)",
"SUPPORTED_PLATFORMS": "$(HOST_PLATFORM)",
"SWIFT_VERSION": swiftVersion,
])
],
targets: [
TestStandardTarget(
"Objlib",
type: .objectLibrary,
buildConfigurations: [
TestBuildConfiguration("Debug"),
],
buildPhases: [
TestSourcesBuildPhase(["objlib.swift"]),
]
),
])
let tester = try await BuildOperationTester(getCore(), testProject, simulated: false)
let projectDir = tester.workspace.projects[0].sourceRoot
try await tester.fs.writeFileContents(projectDir.join("objlib.swift")) { stream in
stream <<< "func foo() {}"
}
try await tester.checkBuild(runDestination: .host) { results in
// The source and modulewrap objects should not collide when assembling the object library.
results.checkNoDiagnostics()
}
}
}
/// Test that building a project with module-only architectures and generated Objective-C headers still generates the headers for the module-only architectures.
@Test(.requireSDKs(.watchOS))
func swiftModuleOnlyArchsWithGeneratedObjectiveCHeaders() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup(
"Sources",
children: [
TestFile("App.m"),
TestFile("App.swift"),
TestFile("API.swift"),
TestFile("Bridging.h"),
]),
buildConfigurations: [
TestBuildConfiguration(
"Debug",
buildSettings: [
"ARCHS": "arm64_32",
"GENERATE_INFOPLIST_FILE": "YES",
"PRODUCT_NAME": "$(TARGET_NAME)",
"SWIFT_MODULE_ONLY_ARCHS": "armv7k",
"SWIFT_MODULE_ONLY_WATCHOS_DEPLOYMENT_TARGET": "$(WATCHOS_DEPLOYMENT_TARGET)",
"SWIFT_PRECOMPILE_BRIDGING_HEADER[arch=armv7k]": "NO",
"SDKROOT": "watchos",
"SWIFT_VERSION": "5.0",
]),
],
targets: [
TestStandardTarget(
"Application",
type: .application,
buildConfigurations: [
TestBuildConfiguration("Debug", buildSettings: [
"SWIFT_OBJC_BRIDGING_HEADER": "Bridging.h",
])
],
buildPhases: [
TestSourcesBuildPhase([
"App.m",
"App.swift",
]),
],
dependencies: ["Framework"]
),
TestStandardTarget(
"Framework",
type: .framework,
buildPhases: [
TestSourcesBuildPhase([
"API.swift",
]),
]
)
])
])
let tester = try await BuildOperationTester(getCore(), testWorkspace, simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/Bridging.h")) {
$0 <<< "#import <Framework/Framework-Swift.h>\n"
// Reference some type exposed by the header. This will ensure we fail to build if the type is not visible to the current architecture when precompiling the bridging header.
$0 <<< "@interface Baz\n"
$0 <<< "@property (readonly) Foo *foo;\n"
$0 <<< "@end\n"
}
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/API.swift")) {
$0 <<< "import Foundation\n"
$0 <<< "@objc public class Foo: NSObject { public func bar() { } }\n"
}
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/App.m")) {
$0 <<< "#import <Framework/Framework-Swift.h>\n"
}
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/App.swift")) {
$0 <<< "import Framework\n"
$0 <<< "@main struct Main { static func main() { } }\n"
}
try await tester.checkBuild(runDestination: .anywatchOSDevice) { results in
results.consumeTasksMatchingRuleTypes()
results.consumeTasksMatchingRuleTypes(["CopySwiftLibs", "GenerateDSYMFile", "ProcessInfoPlistFile", "RegisterExecutionPolicyException", "Touch", "Validate", "ExtractAppIntentsMetadata", "AppIntentsSSUTraining", "SwiftExplicitDependencyCompileModuleFromInterface", "SwiftExplicitDependencyGeneratePcm", "ProcessSDKImports"])
for (arch, isModuleOnly) in [("armv7k", true), ("arm64_32", false)] {
let moduleBaseNameSuffix = isModuleOnly ? "-watchos" : ""
let archRuleItem = isModuleOnly ? "\(arch)\(moduleBaseNameSuffix)" : arch
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftDriver Compilation Requirements", "Framework", "normal", archRuleItem, "com.apple.xcode.tools.swift.compiler"])) { task in
}
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftEmitModule", "normal", archRuleItem, "Emitting module for Framework"])) { _ in }
results.checkTask(.matchTargetName("Framework"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Framework.framework/Modules/Framework.swiftmodule/\(arch)-apple-watchos.swiftdoc", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Framework.build/Objects-normal/\(arch)/Framework\(moduleBaseNameSuffix).swiftdoc"])) { _ in }
results.checkTask(.matchTargetName("Framework"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Framework.framework/Modules/Framework.swiftmodule/\(arch)-apple-watchos.swiftmodule", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Framework.build/Objects-normal/\(arch)/Framework\(moduleBaseNameSuffix).swiftmodule"])) { _ in }
results.checkTask(.matchTargetName("Framework"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Framework.framework/Modules/Framework.swiftmodule/Project/\(arch)-apple-watchos.swiftsourceinfo", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Framework.build/Objects-normal/\(arch)/Framework\(moduleBaseNameSuffix).swiftsourceinfo"])) { _ in }
results.checkTask(.matchTargetName("Framework"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Framework.framework/Modules/Framework.swiftmodule/\(arch)-apple-watchos.abi.json", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Framework.build/Objects-normal/\(arch)/Framework\(moduleBaseNameSuffix).abi.json"])) { _ in }
if isModuleOnly {
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftDriver GenerateModule", "Framework", "normal", archRuleItem, "com.apple.xcode.tools.swift.compiler"])) { _ in }
} else {
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftDriver", "Framework", "normal", arch, "com.apple.xcode.tools.swift.compiler"])) { _ in }
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftDriver Compilation", "Framework", "normal", archRuleItem, "com.apple.xcode.tools.swift.compiler"])) { task in
}
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftCompile", "normal", archRuleItem, "Compiling API.swift", "\(tmpDirPath.str)/Test/aProject/API.swift"])) { _ in }
}
}
// The SwiftMergeGeneratedHeaders task should include normal AND module-only architectures.
results.checkTask(.matchTargetName("Framework"), .matchRule(["SwiftMergeGeneratedHeaders", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Framework.framework/Headers/Framework-Swift.h", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Framework.build/Objects-normal/arm64_32/Framework-Swift.h", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Framework.build/Objects-normal/armv7k/Framework-Swift.h"])) { _ in }
// There's only one "real" architecture, so should be only one linker task.
results.checkTask(.matchTargetName("Framework"), .matchRuleType("Ld")) { _ in }
results.checkTask(.matchTargetName("Framework"), .matchRuleType("GenerateTAPI")) { _ in }
results.checkNoTask(.matchTargetName("Framework"))
for (arch, isModuleOnly) in [("armv7k", true), ("arm64_32", false)] {
let moduleBaseNameSuffix = isModuleOnly ? "-watchos" : ""
let archRuleItem = isModuleOnly ? "\(arch)\(moduleBaseNameSuffix)" : arch
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftDriver Compilation Requirements", "Application", "normal", archRuleItem, "com.apple.xcode.tools.swift.compiler"])) { task in
}
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftEmitModule", "normal", archRuleItem, "Emitting module for Application"])) { _ in }
results.checkTask(.matchTargetName("Application"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Application.swiftmodule/\(arch)-apple-watchos.swiftdoc", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/\(arch)/Application\(moduleBaseNameSuffix).swiftdoc"])) { _ in }
results.checkTask(.matchTargetName("Application"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Application.swiftmodule/\(arch)-apple-watchos.swiftmodule", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/\(arch)/Application\(moduleBaseNameSuffix).swiftmodule"])) { _ in }
results.checkTask(.matchTargetName("Application"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Application.swiftmodule/Project/\(arch)-apple-watchos.swiftsourceinfo", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/\(arch)/Application\(moduleBaseNameSuffix).swiftsourceinfo"])) { _ in }
results.checkTask(.matchTargetName("Application"), .matchRule(["Copy", "\(tmpDirPath.str)/Test/aProject/build/Debug-watchos/Application.swiftmodule/\(arch)-apple-watchos.abi.json", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/\(arch)/Application\(moduleBaseNameSuffix).abi.json"])) { _ in }
if isModuleOnly {
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftDriver GenerateModule", "Application", "normal", archRuleItem, "com.apple.xcode.tools.swift.compiler"])) { _ in }
} else {
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftDriver", "Application", "normal", arch, "com.apple.xcode.tools.swift.compiler"])) { _ in }
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftDriver Compilation", "Application", "normal", archRuleItem, "com.apple.xcode.tools.swift.compiler"])) { task in
}
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftCompile", "normal", archRuleItem, "Compiling App.swift", "\(tmpDirPath.str)/Test/aProject/App.swift"])) { _ in }
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftGeneratePch", "normal", archRuleItem, "Compiling bridging header"])) { task in }
results.checkTask(.matchTargetName("Application"), .matchRule(["CompileC", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/\(arch)/App-\(BuildPhaseWithBuildFiles.filenameUniquefierSuffixFor(path: tmpDirPath.join("Test/aProject/App.m"))).o", "\(tmpDirPath.str)/Test/aProject/App.m", "normal", arch, "objective-c", "com.apple.compilers.llvm.clang.1_0.compiler"])) { _ in }
}
}
// The SwiftMergeGeneratedHeaders task should include normal AND module-only architectures.
results.checkTask(.matchTargetName("Application"), .matchRule(["SwiftMergeGeneratedHeaders", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/DerivedSources/Application-Swift.h", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/arm64_32/Application-Swift.h", "\(tmpDirPath.str)/Test/aProject/build/aProject.build/Debug-watchos/Application.build/Objects-normal/armv7k/Application-Swift.h"])) { _ in }
// There's only one "real" architecture, so should be only one linker task.
results.checkTask(.matchTargetName("Application"), .matchRuleType("Ld")) { _ in }
results.checkNoTask(.matchTargetName("Application"))
results.checkNoTask()
results.checkWarning(.contains("'SWIFT_NORETURN' macro redefined"), failIfNotFound: false)
results.checkWarning(.contains("'SWIFT_NORETURN' macro redefined"), failIfNotFound: false)
results.checkWarning(.equal("SWIFT_MODULE_ONLY_ARCHS assigned at level: project. Module-only architecture back deployment is now handled automatically by the build system and this setting will be ignored. Remove it from your project. (in target 'Application' from project 'aProject')"))
results.checkWarning(.equal("SWIFT_MODULE_ONLY_WATCHOS_DEPLOYMENT_TARGET assigned at level: project. Module-only architecture back deployment is now handled automatically by the build system and this setting will be ignored. Remove it from your project. (in target 'Application' from project 'aProject')"))
results.checkWarning(.equal("SWIFT_MODULE_ONLY_ARCHS assigned at level: project. Module-only architecture back deployment is now handled automatically by the build system and this setting will be ignored. Remove it from your project. (in target 'Framework' from project 'aProject')"))
results.checkWarning(.equal("SWIFT_MODULE_ONLY_WATCHOS_DEPLOYMENT_TARGET assigned at level: project. Module-only architecture back deployment is now handled automatically by the build system and this setting will be ignored. Remove it from your project. (in target 'Framework' from project 'aProject')"))
results.checkNoDiagnostics()
}
}
}
@Test(.requireSDKs(.macOS))
func buildLibraryForDistributionIgnoresExecutables() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup(
"Sources",
children: [
TestFile("main.swift"),
TestFile("API.swift"),
]),
buildConfigurations: [
TestBuildConfiguration(
"Debug",
buildSettings: [
"CODE_SIGNING_ALLOWED": "NO",
"PRODUCT_NAME": "$(TARGET_NAME)",
"BUILD_LIBRARY_FOR_DISTRIBUTION": "YES",
"SWIFT_VERSION": "5.0",
]),
],
targets: [
TestStandardTarget(
"Tool",
type: .commandLineTool,
buildPhases: [
TestSourcesBuildPhase([
"main.swift",
]),
],
dependencies: ["Framework"]
),
TestStandardTarget(
"Framework",
type: .framework,
buildPhases: [
TestSourcesBuildPhase([
"API.swift",
]),
]
)
])
])
let tester = try await BuildOperationTester(getCore(), testWorkspace, simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/API.swift")) {
$0 <<< "public final class Foo { public func bar() { } }\n"
}
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/main.swift")) {
$0 <<< "import Framework\n"
$0 <<< "for _ in 0..<100 { }\nprint(\"hello\")\n"
}
try await tester.checkBuild(runDestination: .host) { results in
results.checkNoTask(.matchTargetName("Tool"), .matchRuleType("SwiftVerifyEmittedModuleInterface"))
// The build should not fail when BUILD_LIBRARY_FOR_DISTRIBUTION is applied to an executable.
results.checkNoDiagnostics()
}
}
}
/// Test that stale Swift stdlib dylibs are removed on incremental builds (rdar://43151403).
@Test(.requireSDKs(.macOS))
func staleSwiftStdlibDylibRemovedOnIncrementalBuild() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup(
"Sources",
children: [
TestFile("main.swift"),
]),
buildConfigurations: [
TestBuildConfiguration(
"Debug",
buildSettings: [
"PRODUCT_NAME": "$(TARGET_NAME)",
"SWIFT_VERSION": "5.0",
"ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES": "YES",
"CODE_SIGNING_ALLOWED": "NO",
"GENERATE_INFOPLIST_FILE": "YES",
]),
],
targets: [
TestStandardTarget(
"App",
type: .application,
buildPhases: [
TestSourcesBuildPhase([
"main.swift",
]),
])
])
])
let tester = try await BuildOperationTester(getCore(), testWorkspace, simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/main.swift")) {
$0 <<< "import Foundation\nprint(\"hello\")\n"
}
try await tester.checkBuild(runDestination: .macOS, persistent: true) { results in
results.checkTasks(.matchRuleType("CopySwiftLibs"), .matchTargetName("App")) { _ in }
}
let frameworksDir = tmpDirPath.join("Test/aProject/build/Debug/App.app/Contents/Frameworks")
let legitimateDylibs: [String]
if tester.fs.exists(frameworksDir) {
legitimateDylibs = try tester.fs.listdir(frameworksDir).filter {
$0.hasPrefix("libswift") && $0.hasSuffix(".dylib")
}
} else {
legitimateDylibs = []
}
try tester.fs.createDirectory(frameworksDir, recursive: true)
let staleDylibPath = frameworksDir.join("libswiftFakeModule.dylib")
try await tester.fs.writeFileContents(staleDylibPath) { $0 <<< "fake" }
#expect(tester.fs.exists(staleDylibPath), "Stale dylib should exist before incremental build")
let userDylibPath = frameworksDir.join("libMyCustomLib.dylib")
try await tester.fs.writeFileContents(userDylibPath) { $0 <<< "user" }
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/main.swift")) {
$0 <<< "import Foundation\nprint(\"hello world\")\n"
}
try await tester.checkBuild(runDestination: .macOS, persistent: true) { results in
results.checkTasks(.matchRuleType("CopySwiftLibs"), .matchTargetName("App")) { _ in }
}
#expect(!tester.fs.exists(staleDylibPath), "Stale libswiftFakeModule.dylib should have been removed on incremental build")
#expect(tester.fs.exists(userDylibPath), "Non-Swift dylib libMyCustomLib.dylib should not have been removed")
for dylib in legitimateDylibs {
#expect(tester.fs.exists(frameworksDir.join(dylib)), "Legitimate stdlib dylib \(dylib) should not have been removed")
}
}
}
@Test(.requireSDKs(.host), .requireClangFeatures(.invokeSsaf))
func invokeSsafCommandLineFlags() async throws {
func makeTestWorkspace(_ tmpDirPath: Path, invokeSSAF: String, extractSummaries: String = "") -> TestWorkspace {
TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup("Sources", children: [TestFile("File1.cpp")]),
buildConfigurations: [TestBuildConfiguration(
"Debug",
buildSettings: [
"PRODUCT_NAME": "$(TARGET_NAME)",
"INVOKE_SSAF": invokeSSAF,
"EXTRACT_SUMMARIES": extractSummaries,
// Uncomment to test with a local build of clang
// "CC": "<LOCAL_CLANG_PATH>/bin/clang",
"CODE_SIGNING_ALLOWED": "NO",
])],
targets: [
TestStandardTarget(
"Test",
type: .dynamicLibrary,
buildPhases: [TestSourcesBuildPhase(["File1.cpp"])])
])
])
}
// INVOKE_SSAF=YES: both flags are present and the summary file path is co-located with
// the object file, sharing the same basename but with a .json extension.
try await withTemporaryDirectory { tmpDirPath in
let tester = try await BuildOperationTester(getCore(), makeTestWorkspace(tmpDirPath, invokeSSAF: "YES", extractSummaries: "CallGraph"), simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/File1.cpp")) {
$0 <<< "void foo() {}\n"
$0 <<< "\n"
$0 <<< "void bar() {\n"
$0 <<< " foo();\n"
$0 <<< "}\n"
$0 <<< "\n"
$0 <<< "void baz() {}\n"
$0 <<< "\n"
$0 <<< "void test_call() {\n"
$0 <<< " bar();\n"
$0 <<< " baz();\n"
$0 <<< "}\n"
}
try await tester.checkBuild(runDestination: .host) { results in
try results.checkTask(.matchRuleType("CompileC")) { task throws in
let objectPath = try #require(task.outputPaths.first { $0.str.hasSuffix(".o") })
let expectedJsonPath = objectPath.dirname.join(objectPath.basenameWithoutSuffix + ".ssaf-tu.json").str
task.checkCommandLineContains(["--ssaf-extract-summaries=CallGraph"])
task.checkCommandLineContains(["--ssaf-tu-summary-file=\(expectedJsonPath)"])
let jsonBytes = try tester.fs.read(Path(expectedJsonPath))
#expect(!jsonBytes.isEmpty)
}
// The entity linker should receive File1.ssaf-tu.json as input and produce a .linked-summaries.json file.
try results.checkTask(.matchRuleType("LinkEntity")) { task throws in
#expect(task.inputPaths.contains(where: { $0.str.hasSuffix("File1.ssaf-tu.json") }))
let linkedSummaryPath = try #require(task.outputPaths.first { $0.str.hasSuffix(".linked-summaries.json") })
#expect(tester.fs.exists(linkedSummaryPath))
let linkedSummaryBytes = try tester.fs.read(linkedSummaryPath)
#expect(!linkedSummaryBytes.isEmpty)
}
results.checkNoDiagnostics()
}
}
// INVOKE_SSAF=NO: neither SSAF flag is present.
try await withTemporaryDirectory { tmpDirPath in
let tester = try await BuildOperationTester(getCore(), makeTestWorkspace(tmpDirPath, invokeSSAF: "NO"), simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/File1.cpp")) {
$0 <<< "void foo() {}\n"
$0 <<< "\n"
$0 <<< "void bar() {\n"
$0 <<< " foo();\n"
$0 <<< "}\n"
$0 <<< "\n"
$0 <<< "void baz() {}\n"
$0 <<< "\n"
$0 <<< "void test_call() {\n"
$0 <<< " bar();\n"
$0 <<< " baz();\n"
$0 <<< "}\n"
}
try await tester.checkBuild(runDestination: .host) { results in
results.checkTask(.matchRuleType("CompileC")) { task in
task.checkCommandLineNoMatch([.prefix("--ssaf-extract-summaries=")])
task.checkCommandLineNoMatch([.prefix("--ssaf-tu-summary-file=")])
}
results.checkNoTask(.matchRuleType("LinkEntity"))
results.checkNoDiagnostics()
}
}
}
@Test(.requireSDKs(.host), .requireClangFeatures(.invokeSsaf))
func invokeSsafCommandLineFlagsUnsafeBuffer() async throws {
func makeTestWorkspace(_ tmpDirPath: Path, invokeSSAF: String, extractSummaries: String = "") -> TestWorkspace {
TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup("Sources", children: [TestFile("File1.cpp")]),
buildConfigurations: [TestBuildConfiguration(
"Debug",
buildSettings: [
"PRODUCT_NAME": "$(TARGET_NAME)",
"INVOKE_SSAF": invokeSSAF,
"EXTRACT_SUMMARIES": extractSummaries,
// Uncomment to test with a local build of clang
// "CC": "<LOCAL_CLANG_PATH>/bin/clang",
"CODE_SIGNING_ALLOWED": "NO",
])],
targets: [
TestStandardTarget(
"Test",
type: .dynamicLibrary,
buildPhases: [TestSourcesBuildPhase(["File1.cpp"])])
])
])
}
// INVOKE_SSAF=YES: both flags are present and the summary file path is co-located with
// the object file, sharing the same basename but with a .json extension.
try await withTemporaryDirectory { tmpDirPath in
let tester = try await BuildOperationTester(getCore(), makeTestWorkspace(tmpDirPath, invokeSSAF: "YES", extractSummaries: "UnsafeBufferUsage"), simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/File1.cpp")) {
$0 <<< "inline int shared_inline(int *p) {\n"
$0 <<< " int * l = p;\n"
$0 <<< " return l[5];\n"
$0 <<< "}\n"
$0 <<< "\n"
$0 <<< "int f(int *x) {\n"
$0 <<< " return shared_inline(x);\n"
$0 <<< "}\n"
$0 <<< "int g(int *y) {\n"
$0 <<< " return shared_inline(y);\n"
$0 <<< "}\n"
}
try await tester.checkBuild(runDestination: .host) { results in
try results.checkTask(.matchRuleType("CompileC")) { task throws in
let objectPath = try #require(task.outputPaths.first { $0.str.hasSuffix(".o") })
let expectedJsonPath = objectPath.dirname.join(objectPath.basenameWithoutSuffix + ".ssaf-tu.json").str
task.checkCommandLineContains(["--ssaf-extract-summaries=UnsafeBufferUsage"])
task.checkCommandLineContains(["--ssaf-tu-summary-file=\(expectedJsonPath)"])
let jsonBytes = try tester.fs.read(Path(expectedJsonPath))
#expect(!jsonBytes.isEmpty)
}
// The entity linker should receive File1.ssaf-tu.json as input and produce a .linked-summaries.json file.
try results.checkTask(.matchRuleType("LinkEntity")) { task throws in
#expect(task.inputPaths.contains(where: { $0.str.hasSuffix("File1.ssaf-tu.json") }))
let linkedSummaryPath = try #require(task.outputPaths.first { $0.str.hasSuffix(".linked-summaries.json") })
#expect(tester.fs.exists(linkedSummaryPath))
let linkedSummaryBytes = try tester.fs.read(linkedSummaryPath)
#expect(!linkedSummaryBytes.isEmpty)
}
// The analyzer should receive the .linked-summaries.json as input, pass -a UnsafeBufferReachableAnalysisResult,
// and produce a non-empty .ssaf-analysis.json file.
try results.checkTask(.matchRuleType("AnalyzeSSAF")) { task throws in
#expect(task.inputPaths.contains(where: { $0.str.hasSuffix(".linked-summaries.json") }))
task.checkCommandLineContains(["-a", "UnsafeBufferUsageAnalysisResult"])
let analysisPath = try #require(task.outputPaths.first { $0.str.hasSuffix(".ssaf-analysis.json") })
#expect(tester.fs.exists(analysisPath))
let analysisBytes = try tester.fs.read(analysisPath)
#expect(!analysisBytes.isEmpty)
}
results.checkNoDiagnostics()
}
}
// INVOKE_SSAF=NO: neither SSAF flag is present and no entity linker or analyzer task is created.
try await withTemporaryDirectory { tmpDirPath in
let tester = try await BuildOperationTester(getCore(), makeTestWorkspace(tmpDirPath, invokeSSAF: "NO"), simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/File1.cpp")) {
$0 <<< "inline int shared_inline(int *p) {\n"
$0 <<< " int * l = p;\n"
$0 <<< " return l[5];\n"
$0 <<< "}\n"
$0 <<< "\n"
$0 <<< "int f(int *x) {\n"
$0 <<< " return shared_inline(x);\n"
$0 <<< "}\n"
$0 <<< "int g(int *y) {\n"
$0 <<< " return shared_inline(y);\n"
$0 <<< "}\n"
}
try await tester.checkBuild(runDestination: .host) { results in
results.checkTask(.matchRuleType("CompileC")) { task in
task.checkCommandLineNoMatch([.prefix("--ssaf-extract-summaries=")])
task.checkCommandLineNoMatch([.prefix("--ssaf-tu-summary-file=")])
}
results.checkNoTask(.matchRuleType("LinkEntity"))
results.checkNoTask(.matchRuleType("AnalyzeSSAF"))
results.checkNoDiagnostics()
}
}
}
@Test(.requireSDKs(.host))
func avoidEmitModuleSourceInfo() async throws {
try await withTemporaryDirectory { tmpDirPath async throws -> Void in
let testWorkspace = TestWorkspace(
"Test",
sourceRoot: tmpDirPath.join("Test"),
projects: [
TestProject(
"aProject",
groupTree: TestGroup(
"Sources",
children: [
TestFile("Foo.swift"),
]),
buildConfigurations: [
TestBuildConfiguration(
"Debug",
buildSettings: [
"CODE_SIGNING_ALLOWED": "NO",
"PRODUCT_NAME": "$(TARGET_NAME)",
"OTHER_SWIFT_FLAGS": "-avoid-emit-module-source-info",
"SWIFT_VERSION": "5",
]),
],
targets: [
TestStandardTarget(
"library",
type: .staticLibrary,
buildPhases: [
TestSourcesBuildPhase(["Foo.swift"]),
])
])
])
let tester = try await BuildOperationTester(getCore(), testWorkspace, simulated: false)
try await tester.fs.writeFileContents(tmpDirPath.join("Test/aProject/Foo.swift")) {
$0 <<< "public struct Foo {}\n"
}
try await tester.checkBuild(runDestination: .host) { results in
// The .swiftsourceinfo file should not be copied when -avoid-emit-module-source-info is set, and the build should succeed.
results.checkNoTask(.matchRuleType("Copy"), .matchRuleItemPattern(.suffix(".swiftsourceinfo")))
results.checkNoDiagnostics()
}
}
}
}