-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathbuild.ps1
2164 lines (1901 loc) · 81 KB
/
build.ps1
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
# Copyright 2020 Saleem Abdulrasool <compnerd@compnerd.org>
# Copyright 2023 Tristan Labelle <tristan@thebrowser.company>
<#
.SYNOPSIS
Builds the Swift toolchain, installers, and optionally runs tests.
.DESCRIPTION
This script performs various steps associated with building the Swift toolchain:
- Builds the redistributable, SDK, devtools and toolchain binaries and files
- Builds the msi's and installer executable
- Creates a mock installation under S:\Program Files and S:\Library for local toolchain use
- Optionally runs tests for supported projects
- Optionally stages build artifacts for CI
.PARAMETER SourceCache
The path to a directory where projects contributing to the Swift.
toolchain have been cloned.
.PARAMETER BinaryCache
The path to a directory where to write build system files and outputs.
.PARAMETER ImageRoot
The path to a directory that mimics a file system image root,
under which "Library" and "Program Files" subdirectories will be created
with the files installed by CMake.
.PARAMETER CDebugFormat
The debug information format for C/C++ code: dwarf or codeview.
.PARAMETER SwiftDebugFormat
The debug information format for Swift code: dwarf or codeview.
.PARAMETER WindowsSDKs
An array of architectures for which the Windows Swift SDK should be built.
.PARAMETER ProductVersion
The product version to be used when building the installer.
Supports semantic version strings.
.PARAMETER PinnedBuild
The toolchain snapshot to build the early components with.
.PARAMETER PinnedSHA256
The SHA256 for the pinned toolchain.
.PARAMETER WinSDKVersion
The version number of the Windows SDK to be used.
Overrides the value resolved by the Visual Studio command prompt.
If no such Windows SDK is installed, it will be downloaded from nuget.
.PARAMETER SkipBuild
If set, does not run the build phase.
.PARAMETER SkipPackaging
If set, skips building the msi's and installer
.PARAMETER DebugInfo
If set, debug information will be generated for the builds.
.PARAMETER EnableCaching
If true, use `sccache` to cache the build rules.
.PARAMETER Clean
If true, clean non-compiler builds while building.
.PARAMETER Test
An array of names of projects to run tests for.
'*' runs all tests
.PARAMETER Stage
The path to a directory where built msi's and the installer executable should be staged (for CI).
.PARAMETER BuildTo
The name of a build step after which the script should terminate.
For example: -BuildTo ToolsSupportCore
.PARAMETER ToBatch
When set, runs the script in a special mode which outputs a listing of command invocations
in batch file format instead of executing them.
.PARAMETER HostArchName
The architecture where the toolchain will execute.
.EXAMPLE
PS> .\Build.ps1
.EXAMPLE
PS> .\Build.ps1 -WindowsSDKs x64 -ProductVersion 1.2.3 -Test foundation,xctest
#>
[CmdletBinding(PositionalBinding = $false)]
param(
[string] $SourceCache = "S:\SourceCache",
[string] $BinaryCache = "S:\b",
[string] $ImageRoot = "S:",
[string] $CDebugFormat = "dwarf",
[string] $SwiftDebugFormat = "dwarf",
[string[]] $WindowsSDKs = @("X64","X86","Arm64"),
[string] $ProductVersion = "0.0.0",
[string] $PinnedBuild = "",
[string] $PinnedSHA256 = "",
[string] $PythonVersion = "3.9.10",
[string] $WinSDKVersion = "",
[switch] $SkipBuild = $false,
[switch] $SkipRedistInstall = $false,
[switch] $SkipPackaging = $false,
[string[]] $Test = @(),
[string] $Stage = "",
[string] $BuildTo = "",
[string] $HostArchName = $(if ($env:PROCESSOR_ARCHITEW6432 -ne $null) { "$env:PROCESSOR_ARCHITEW6432" } else { "$env:PROCESSOR_ARCHITECTURE" }),
[switch] $Clean,
[switch] $DebugInfo,
[switch] $EnableCaching,
[switch] $Summary,
[switch] $ToBatch
)
$ErrorActionPreference = "Stop"
Set-StrictMode -Version 3.0
# Avoid being run in a "Developer" shell since this script launches its own sub-shells targeting
# different architectures, and these variables cause confusion.
if ($null -ne $env:VSCMD_ARG_HOST_ARCH -or $null -ne $env:VSCMD_ARG_TGT_ARCH) {
throw "At least one of VSCMD_ARG_HOST_ARCH and VSCMD_ARG_TGT_ARCH is set, which is incompatible with this script. Likely need to run outside of a Developer shell."
}
# Prevent elsewhere-installed swift modules from confusing our builds.
$env:SDKROOT = ""
$BuildArchName = $env:PROCESSOR_ARCHITEW6432
if ($null -eq $BuildArchName) { $BuildArchName = $env:PROCESSOR_ARCHITECTURE }
if ($PinnedBuild -eq "") {
switch ($BuildArchName) {
"AMD64" {
$PinnedBuild = "https://download.swift.org/swift-5.10-branch/windows10/swift-5.10-DEVELOPMENT-SNAPSHOT-2024-01-18-a/swift-5.10-DEVELOPMENT-SNAPSHOT-2024-01-18-a-windows10.exe"
$PinnedSHA256 = "006266d8c2a6a9c70e21b9d161ec35c07bcbb8a452b17e145899d814d07a29e7"
}
"ARM64" {
# TODO(hjyamauchi) once we have an arm64 release, fill in PinnedBuild and PinnedSHA256.
throw "Missing pinned toolchain for ARM64"
}
default { throw "Unsupported processor architecture" }
}
}
# Store the revision zero variant of the Windows SDK version (no-op if unspecified)
$WindowsSDKMajorMinorBuildMatch = [Regex]::Match($WinSDKVersion, "^\d+\.\d+\.\d+")
$WinSDKVersionRevisionZero = if ($WindowsSDKMajorMinorBuildMatch.Success) { $WindowsSDKMajorMinorBuildMatch.Value + ".0" } else { "" }
$CustomWinSDKRoot = $null # Overwritten if we download a Windows SDK from nuget
$vswhere = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Installer\vswhere.exe"
$VSInstallRoot = & $vswhere -nologo -latest -products "*" -all -prerelease -property installationPath
$msbuild = "$VSInstallRoot\MSBuild\Current\Bin\$BuildArchName\MSBuild.exe"
# Avoid $env:ProgramFiles in case this script is running as x86
$UnixToolsBinDir = "$env:SystemDrive\Program Files\Git\usr\bin"
$python = "${env:ProgramFiles(x86)}\Microsoft Visual Studio\Shared\Python39_64\python.exe"
if (-not (Test-Path $python)) {
$python = (where.exe python) | Select-Object -First 1
if (-not (Test-Path $python)) {
throw "Python.exe not found"
}
}
# Work around limitations of cmd passing in array arguments via powershell.exe -File
if ($WindowsSDKs.Length -eq 1) { $WindowsSDKs = $WindowsSDKs[0].Split(",") }
if ($Test.Length -eq 1) { $Test = $Test[0].Split(",") }
if ($Test -contains "*") {
# Explicitly don't include llbuild yet since tests are known to fail on Windows
$Test = @("swift", "dispatch", "foundation", "xctest")
}
# Architecture definitions
$ArchX64 = @{
VSName = "amd64";
ShortName = "x64";
LLVMName = "x86_64";
LLVMTarget = "x86_64-unknown-windows-msvc";
CMakeName = "AMD64";
BinaryDir = "bin64";
BuildID = 100;
BinaryCache = "$BinaryCache\x64";
PlatformInstallRoot = "$BinaryCache\x64\Windows.platform";
SDKInstallRoot = "$BinaryCache\x64\Windows.platform\Developer\SDKs\Windows.sdk";
XCTestInstallRoot = "$BinaryCache\x64\Windows.platform\Developer\Library\XCTest-development";
ToolchainInstallRoot = "$BinaryCache\x64\toolchains\$ProductVersion+Asserts";
}
$ArchX86 = @{
VSName = "x86";
ShortName = "x86";
LLVMName = "i686";
LLVMTarget = "i686-unknown-windows-msvc";
CMakeName = "i686";
BinaryDir = "bin32";
BuildID = 200;
BinaryCache = "$BinaryCache\x86";
PlatformInstallRoot = "$BinaryCache\x86\Windows.platform";
SDKInstallRoot = "$BinaryCache\x86\Windows.platform\Developer\SDKs\Windows.sdk";
XCTestInstallRoot = "$BinaryCache\x86\Windows.platform\Developer\Library\XCTest-development";
}
$ArchARM64 = @{
VSName = "arm64";
ShortName = "arm64";
LLVMName = "aarch64";
LLVMTarget = "aarch64-unknown-windows-msvc";
CMakeName = "ARM64";
BinaryDir = "bin64a";
BuildID = 300;
BinaryCache = "$BinaryCache\arm64";
PlatformInstallRoot = "$BinaryCache\arm64\Windows.platform";
SDKInstallRoot = "$BinaryCache\arm64\Windows.platform\Developer\SDKs\Windows.sdk";
XCTestInstallRoot = "$BinaryCache\arm64\Windows.platform\Developer\Library\XCTest-development";
ToolchainInstallRoot = "$BinaryCache\arm64\toolchains\$ProductVersion+Asserts";
}
$HostArch = switch ($HostArchName) {
"AMD64" { $ArchX64 }
"ARM64" { $ArchARM64 }
default { throw "Unsupported processor architecture" }
}
$BuildArch = switch ($BuildArchName) {
"AMD64" { $ArchX64 }
"ARM64" { $ArchARM64 }
default { throw "Unsupported processor architecture" }
}
$IsCrossCompiling = $HostArchName -ne $BuildArchName
$TimingData = New-Object System.Collections.Generic.List[System.Object]
function Get-InstallDir($Arch) {
if ($Arch -eq $HostArch) {
$ProgramFilesName = "Program Files"
} elseif ($Arch -eq $ArchX86) {
$ProgramFilesName = "Program Files (x86)"
} elseif (($HostArch -eq $ArchArm64) -and ($Arch -eq $ArchX64)) {
# x64 programs actually install under "Program Files" on arm64,
# but this would conflict with the native installation.
$ProgramFilesName = "Program Files (Amd64)"
} else {
# arm64 cannot be installed on x64
return $null
}
return "$ImageRoot\$ProgramFilesName\Swift"
}
$NugetRoot = "$BinaryCache\nuget"
$PinnedToolchain = [IO.Path]::GetFileNameWithoutExtension($PinnedBuild)
$LibraryRoot = "$ImageRoot\Library"
# For dev productivity, install the host toolchain directly using CMake.
# This allows iterating on the toolchain using ninja builds.
$HostArch.ToolchainInstallRoot = "$(Get-InstallDir $HostArch)\Toolchains\$ProductVersion+Asserts"
# Resolve the architectures received as argument
$WindowsSDKArchs = @($WindowsSDKs | ForEach-Object {
switch ($_) {
"X64" { $ArchX64 }
"X86" { $ArchX86 }
"Arm64" { $ArchArm64 }
default { throw "Unknown architecture $_" }
}
})
# Build functions
function Invoke-BuildStep([string]$Name) {
& $Name @Args
if ($Name.Replace("Build-", "") -eq $BuildTo) {
exit 0
}
}
enum TargetComponent {
LLVM
Runtime
Dispatch
Foundation
XCTest
}
function Get-TargetProjectBinaryCache($Arch, [TargetComponent]$Project) {
return "$BinaryCache\" + ($Arch.BuildID + $Project.value__)
}
enum HostComponent {
Compilers = 5
System = 10
ToolsSupportCore
LLBuild
Yams
ArgumentParser
Driver
Crypto
Collections
ASN1
Certificates
PackageManager
Markdown
Format
IndexStoreDB
SourceKitLSP
LMDB
SymbolKit
DocC
}
function Get-HostProjectBinaryCache([HostComponent]$Project) {
return "$BinaryCache\$($Project.value__)"
}
function Get-HostProjectCMakeModules([HostComponent]$Project) {
return "$BinaryCache\$($Project.value__)\cmake\modules"
}
enum BuildComponent {
BuildTools
Compilers
}
function Get-BuildProjectBinaryCache([BuildComponent]$Project) {
return "$BinaryCache\$($Project.value__)"
}
function Get-BuildProjectCMakeModules([BuildComponent]$Project) {
return "$BinaryCache\$($Project.value__)\cmake\modules"
}
function Copy-File($Src, $Dst) {
# Create the directory tree first so Copy-Item succeeds
# If $Dst is the target directory, make sure it ends with "\"
$DstDir = [IO.Path]::GetDirectoryName($Dst)
if ($ToBatch) {
Write-Output "md `"$DstDir`""
Write-Output "copy /Y `"$Src`" `"$Dst`""
} else {
New-Item -ItemType Directory -ErrorAction Ignore $DstDir | Out-Null
Copy-Item -Force $Src $Dst
}
}
function Copy-Directory($Src, $Dst) {
if ($Tobatch) {
Write-Output "md `"$Dst`""
Write-Output "copy /Y `"$Src`" `"$Dst`""
} else {
New-Item -ItemType Directory -ErrorAction Ignore $Dst | Out-Null
Copy-Item -Force -Recurse $Src $Dst
}
}
function Invoke-Program() {
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Position = 0, Mandatory = $true)]
[string] $Executable,
[switch] $OutNull = $false,
[string] $OutFile = "",
[Parameter(Position = 1, ValueFromRemainingArguments)]
[string[]] $Args
)
if ($ToBatch) {
# Print the invocation in batch file-compatible format
$OutputLine = "`"$Executable`""
$ShouldBreakLine = $false
for ($i = 0; $i -lt $Args.Length; $i++) {
if ($ShouldBreakLine -or $OutputLine.Length -ge 40) {
$OutputLine += " ^"
Write-Output $OutputLine
$OutputLine = " "
}
$Arg = $Args[$i]
if ($Arg.Contains(" ")) {
$OutputLine += " `"$Arg`""
} else {
$OutputLine += " $Arg"
}
# Break lines after non-switch arguments
$ShouldBreakLine = -not $Arg.StartsWith("-")
}
if ($OutNull) {
$OutputLine += " > nul"
} elseif ("" -ne $OutFile) {
$OutputLine += " > `"$OutFile`""
}
Write-Output $OutputLine
} else {
if ($OutNull) {
& $Executable @Args | Out-Null
} elseif ("" -ne $OutFile) {
& $Executable @Args | Out-File -Encoding UTF8 $OutFile
} else {
& $Executable @Args
}
if ($LastExitCode -ne 0) {
$ErrorMessage = "Error: $([IO.Path]::GetFileName($Executable)) exited with code $($LastExitCode).`n"
$ErrorMessage += "Invocation:`n"
$ErrorMessage += " $Executable $Args`n"
$ErrorMessage += "Call stack:`n"
foreach ($Frame in @(Get-PSCallStack)) {
$ErrorMessage += " $Frame`n"
}
throw $ErrorMessage
}
}
}
function Isolate-EnvVars([scriptblock]$Block) {
if ($ToBatch) {
Write-Output "setlocal enableextensions enabledelayedexpansion"
}
$OldVars = @{}
foreach ($Var in (Get-ChildItem env:*).GetEnumerator()) {
$OldVars.Add($Var.Key, $Var.Value)
}
& $Block
Remove-Item env:*
foreach ($Var in $OldVars.GetEnumerator()) {
New-Item -Path "env:\$($Var.Key)" -Value $Var.Value -ErrorAction Ignore | Out-Null
}
if ($ToBatch) {
Write-Output "endlocal"
}
}
function Invoke-VsDevShell($Arch) {
$DevCmdArguments = "-no_logo -host_arch=$($BuildArch.VSName) -arch=$($Arch.VSName)"
if ($CustomWinSDKRoot) {
$DevCmdArguments += " -winsdk=none"
} elseif ($WinSDKVersion) {
$DevCmdArguments += " -winsdk=$WinSDKVersionRevisionZero"
}
if ($ToBatch) {
Write-Output "call `"$VSInstallRoot\Common7\Tools\VsDevCmd.bat`" $DevCmdArguments"
} else {
# This dll path is valid for VS2019 and VS2022, but it was under a vsdevcmd subfolder in VS2017
Import-Module "$VSInstallRoot\Common7\Tools\Microsoft.VisualStudio.DevShell.dll"
Enter-VsDevShell -VsInstallPath $VSInstallRoot -SkipAutomaticLocation -DevCmdArguments $DevCmdArguments
if ($CustomWinSDKRoot) {
# Using a non-installed Windows SDK. Setup environment variables manually.
$WinSDKVerIncludeRoot = "$CustomWinSDKRoot\include\$WinSDKVersionRevisionZero"
$WinSDKIncludePath = "$WinSDKVerIncludeRoot\ucrt;$WinSDKVerIncludeRoot\um;$WinSDKVerIncludeRoot\shared;$WinSDKVerIncludeRoot\winrt;$WinSDKVerIncludeRoot\cppwinrt"
$WinSDKVerLibRoot = "$CustomWinSDKRoot\lib\$WinSDKVersionRevisionZero"
$env:WindowsLibPath = "$CustomWinSDKRoot\UnionMetadata\$WinSDKVersionRevisionZero;$CustomWinSDKRoot\References\$WinSDKVersionRevisionZero"
$env:WindowsSdkBinPath = "$CustomWinSDKRoot\bin"
$env:WindowsSDKLibVersion = "$WinSDKVersionRevisionZero\"
$env:WindowsSdkVerBinPath = "$CustomWinSDKRoot\bin\$WinSDKVersionRevisionZero"
$env:WindowsSDKVersion = "$WinSDKVersionRevisionZero\"
$env:EXTERNAL_INCLUDE += ";$WinSDKIncludePath"
$env:INCLUDE += ";$WinSDKIncludePath"
$env:LIB += ";$WinSDKVerLibRoot\ucrt\$($Arch.ShortName);$WinSDKVerLibRoot\um\$($Arch.ShortName)"
$env:LIBPATH += ";$env:WindowsLibPath"
$env:PATH += ";$env:WindowsSdkVerBinPath\$($Arch.ShortName);$env:WindowsSdkBinPath\$($Arch.ShortName)"
$env:UCRTVersion = $WinSDKVersionRevisionZero
$env:UniversalCRTSdkDir = $CustomWinSDKRoot
}
}
}
function Fetch-Dependencies {
$ProgressPreference = "SilentlyContinue"
$WebClient = New-Object Net.WebClient
function DownloadAndVerify($URL, $Destination, $Hash) {
if (Test-Path $Destination) {
return
}
Write-Output "$Destination not found. Downloading ..."
if ($ToBatch) {
Write-Output "md `"$(Split-Path -Path $Destination -Parent)`""
Write-Output "curl.exe -sL $URL -o $Destination"
Write-Output "(certutil -HashFile $Destination SHA256) == $Hash || (exit /b)"
} else {
New-Item -ItemType Directory (Split-Path -Path $Destination -Parent) -ErrorAction Ignore | Out-Null
$WebClient.DownloadFile($URL, $Destination)
$SHA256 = Get-FileHash -Path $Destination -Algorithm SHA256
if ($SHA256.Hash -ne $Hash) {
throw "SHA256 mismatch ($($SHA256.Hash) vs $Hash)"
}
}
}
$WiXVersion = "4.0.4"
$WiXURL = "https://www.nuget.org/api/v2/package/wix/$WiXVersion"
$WiXHash = "A9CA12214E61BB49430A8C6E5E48AC5AE6F27DC82573B5306955C4D35F2D34E2"
DownloadAndVerify $WixURL "$BinaryCache\WiX-$WiXVersion.zip" $WiXHash
# TODO(compnerd) stamp/validate that we need to re-extract
New-Item -ItemType Directory -ErrorAction Ignore $BinaryCache\WiX-$WiXVersion | Out-Null
Write-Output "Extracting WiX ..."
Expand-Archive -Path $BinaryCache\WiX-$WiXVersion.zip -Destination $BinaryCache\WiX-$WiXVersion -Force
DownloadAndVerify $PinnedBuild "$BinaryCache\$PinnedToolchain.exe" $PinnedSHA256
# TODO(compnerd) stamp/validate that we need to re-extract
Write-Output "Extracting $PinnedToolchain ..."
New-Item -ItemType Directory -ErrorAction Ignore $BinaryCache\toolchains | Out-Null
# The new runtime MSI is built to expand files into the immediate directory. So, setup the installation location.
New-Item -ItemType Directory -ErrorAction Ignore $BinaryCache\toolchains\$PinnedToolchain\LocalApp\Programs\Swift\Runtimes\0.0.0\usr\bin | Out-Null
Invoke-Program $BinaryCache\WiX-$WiXVersion\tools\net6.0\any\wix.exe -- burn extract $BinaryCache\$PinnedToolchain.exe -out $BinaryCache\toolchains\ -outba $BinaryCache\toolchains\
Get-ChildItem "$BinaryCache\toolchains\WixAttachedContainer" -Filter "*.msi" | % {
$LogFile = [System.IO.Path]::ChangeExtension($_.Name, "log")
$TARGETDIR = if ($_.Name -eq "rtl.msi") { "$BinaryCache\toolchains\$PinnedToolchain\LocalApp\Programs\Swift\Runtimes\0.0.0\usr\bin" } else { "$BinaryCache\toolchains\$PinnedToolchain" }
Invoke-Program -OutNull msiexec.exe /lvx! $BinaryCache\toolchains\$LogFile /qn /a $BinaryCache\toolchains\WixAttachedContainer\$_ ALLUSERS=0 TARGETDIR=$TARGETDIR
}
function Download-Python($ArchName) {
$PythonAMD64URL = "https://www.nuget.org/api/v2/package/python/$PythonVersion"
$PythonAMD64Hash = "ac43b491e9488ac926ed31c5594f0c9409a21ecbaf99dc7a93f8c7b24cf85867"
$PythonARM64URL = "https://www.nuget.org/api/v2/package/pythonarm64/$PythonVersion"
$PythonARM64Hash = "429ada77e7f30e4bd8ff22953a1f35f98b2728e84c9b1d006712561785641f69"
DownloadAndVerify (Get-Variable -Name "Python${ArchName}URL").Value $BinaryCache\Python$ArchName-$PythonVersion.zip (Get-Variable -Name "Python${ArchName}Hash").Value
if (-not $ToBatch) {
# TODO(compnerd) stamp/validate that we need to re-extract
New-Item -ItemType Directory -ErrorAction Ignore $BinaryCache\Python$ArchName-$PythonVersion | Out-Null
Write-Output "Extracting Python ($ArchName) ..."
Expand-Archive -Path $BinaryCache\Python$ArchName-$PythonVersion.zip -Destination $BinaryCache\Python$ArchName-$PythonVersion -Force
}
}
Download-Python $HostArchName
if ($IsCrossCompiling) {
Download-Python $BuildArchName
}
if ($WinSDKVersion) {
try {
# Check whether VsDevShell can already resolve the requested Windows SDK Version
Isolate-EnvVars { Invoke-VsDevShell $HostArch }
} catch {
$Package = Microsoft.Windows.SDK.CPP
Write-Output "Windows SDK $WinSDKVersion not found. Downloading from nuget.org ..."
Invoke-Program nuget install $Package -Version $WinSDKVersion -OutputDirectory $NugetRoot
# Set to script scope so Invoke-VsDevShell can read it.
$script:CustomWinSDKRoot = "$NugetRoot\$Package.$WinSDKVersion\c"
# Install each required architecture package and move files under the base /lib directory.
$WinSDKArchs = $WindowsSDKArchs.Clone()
if (-not ($HostArch -in $WinSDKArchs)) {
$WinSDKArch += $HostArch
}
foreach ($Arch in $WinSDKArchs) {
Invoke-Program nuget install $Package.$($Arch.ShortName) -Version $WinSDKVersion -OutputDirectory $NugetRoot
Copy-Directory "$NugetRoot\$Package.$($Arch.ShortName).$WinSDKVersion\c\*" "$CustomWinSDKRoot\lib\$WinSDKVersionRevisionZero"
}
}
}
}
function Get-PinnedToolchainTool() {
if (Test-Path "$BinaryCache\toolchains\${PinnedToolchain}\LocalApp\Programs\Swift\Toolchains\0.0.0+Asserts\usr\bin") {
return "$BinaryCache\toolchains\${PinnedToolchain}\LocalApp\Programs\Swift\Toolchains\0.0.0+Asserts\usr\bin"
}
return "$BinaryCache\toolchains\${PinnedToolchain}\Library\Developer\Toolchains\unknown-Asserts-development.xctoolchain\usr\bin"
}
function Get-PinnedToolchainSDK() {
if (Test-Path "$BinaryCache\toolchains\${PinnedToolchain}\LocalApp\Programs\Swift\Platforms\0.0.0\Windows.platform\Developer\SDKs\Windows.sdk") {
return "$BinaryCache\toolchains\${PinnedToolchain}\LocalApp\Programs\Swift\Platforms\0.0.0\Windows.platform\Developer\SDKs\Windows.sdk"
}
return "$BinaryCache\toolchains\${PinnedToolchain}\Library\Developer\Platforms\Windows.platform\Developer\SDKs\Windows.sdk"
}
function Get-PinnedToolchainRuntime() {
if (Test-Path "$BinaryCache\toolchains\${PinnedToolchain}\LocalApp\Programs\Swift\Runtimes\0.0.0\usr\bin\swiftCore.dll") {
return "$BinaryCache\toolchains\${PinnedToolchain}\LocalApp\Programs\Swift\Runtimes\0.0.0\usr\bin"
}
return "$BinaryCache\toolchains\${PinnedToolchain}\PFiles64\Swift\runtime-development\usr\bin"
}
function TryAdd-KeyValue([hashtable]$Hashtable, [string]$Key, [string]$Value) {
if (-not $Hashtable.Contains($Key)) {
$Hashtable.Add($Key, $Value)
}
}
function Append-FlagsDefine([hashtable]$Defines, [string]$Name, [string[]]$Value) {
if ($Defines.Contains($Name)) {
$Defines[$name] = @($Defines[$name]) + $Value
} else {
$Defines.Add($Name, $Value)
}
}
function Test-CMakeAtLeast([int]$Major, [int]$Minor, [int]$Patch = 0) {
if ($ToBatch) { return $false }
$CMakeVersionString = @(& cmake.exe --version)[0]
if (-not ($CMakeVersionString -match "^cmake version (\d+)\.(\d+)(?:\.(\d+))?")) {
throw "Unexpected CMake version string format"
}
if ([int]$Matches.1 -ne $Major) { return [int]$Matches.1 -gt $Major }
if ([int]$Matches.2 -ne $Minor) { return [int]$Matches.2 -gt $Minor }
if ($null -eq $Matches.3) { return 0 -gt $Patch }
return [int]$Matches.3 -ge $Patch
}
enum Platform {
Windows
Android
}
function Build-CMakeProject {
[CmdletBinding(PositionalBinding = $false)]
param(
[string] $Src,
[string] $Bin,
[string] $InstallTo = "",
[Platform] $Platform = "Windows",
[hashtable] $Arch,
[string] $Generator = "Ninja",
[string] $CacheScript = "",
[string[]] $UseMSVCCompilers = @(), # C,CXX
[string[]] $UseBuiltCompilers = @(), # ASM,C,CXX,Swift
[string[]] $UsePinnedCompilers = @(), # ASM,C,CXX,Swift
[switch] $UseSwiftSwiftDriver = $false,
[string] $SwiftSDK = "",
[hashtable] $Defines = @{}, # Values are either single strings or arrays of flags
[string[]] $BuildTargets = @()
)
if ($ToBatch) {
Write-Output ""
Write-Output "echo Building '$Src' to '$Bin' for arch '$($Arch.LLVMName)'..."
} else {
Write-Host -ForegroundColor Cyan "[$([DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss"))] Building '$Src' to '$Bin' for arch '$($Arch.LLVMName)'..."
}
$Stopwatch = [Diagnostics.Stopwatch]::StartNew()
# Enter the developer command shell early so we can resolve cmake.exe
# for version checks.
Isolate-EnvVars {
if ($Platform -eq "Windows") {
Invoke-VsDevShell $Arch
}
$CompilersBinaryCache = if ($IsCrossCompiling) {
Get-BuildProjectBinaryCache Compilers
} else {
Get-HostProjectBinaryCache Compilers
}
$DriverBinaryCache = Get-HostProjectBinaryCache Driver
if ($EnableCaching) {
$env:SCCACHE_DIRECT = "true"
$env:SCCACHE_DIR = "$BinaryCache\sccache"
}
if ($UseSwiftSwiftDriver) {
$env:SWIFT_DRIVER_SWIFT_FRONTEND_EXEC = ([IO.Path]::Combine($CompilersBinaryCache, "bin", "swift-frontend.exe"))
}
# TODO(compnerd) workaround swiftc.exe symlink not existing.
if ($UseSwiftSwiftDriver) {
Copy-Item -Force ([IO.Path]::Combine($DriverBinaryCache, "bin", "swift-driver.exe")) ([IO.Path]::Combine($DriverBinaryCache, "bin", "swiftc.exe"))
}
# Add additional defines (unless already present)
$Defines = $Defines.Clone()
if (($Platform -ne "Windows") -or ($Arch.CMakeName -ne $BuildArch.CMakeName)) {
TryAdd-KeyValue $Defines CMAKE_SYSTEM_NAME $Platform
TryAdd-KeyValue $Defines CMAKE_SYSTEM_PROCESSOR $Arch.CMakeName
}
TryAdd-KeyValue $Defines CMAKE_BUILD_TYPE Release
TryAdd-KeyValue $Defines CMAKE_MT "mt"
$CFlags = @()
if ($Platform -eq "Windows") {
$CFlags = @("/GS-", "/Gw", "/Gy", "/Oi", "/Oy", "/Zc:inline")
}
$CXXFlags = @()
if ($Platform -eq "Windows") {
$CXXFlags += $CFlags.Clone() + @("/Zc:__cplusplus")
}
if ($UseMSVCCompilers.Contains("C") -Or $UseMSVCCompilers.Contains("CXX") -Or
$UseBuiltCompilers.Contains("C") -Or $UseBuiltCompilers.Contains("CXX") -Or
$UsePinnedCompilers.Contains("C") -Or $UsePinnedCompilers.Contains("CXX")) {
if ($DebugInfo) {
Append-FlagsDefine $Defines CMAKE_MSVC_DEBUG_INFORMATION_FORMAT Embedded
Append-FlagsDefine $Defines CMAKE_POLICY_CMP0141 NEW
# Add additional linker flags for generating the debug info.
Append-FlagsDefine $Defines CMAKE_SHARED_LINKER_FLAGS "/debug"
Append-FlagsDefine $Defines CMAKE_EXE_LINKER_FLAGS "/debug"
}
}
if ($UseMSVCCompilers.Contains("C")) {
TryAdd-KeyValue $Defines CMAKE_C_COMPILER cl
if ($EnableCaching) {
TryAdd-KeyValue $Defines CMAKE_C_COMPILER_LAUNCHER sccache
}
Append-FlagsDefine $Defines CMAKE_C_FLAGS $CFlags
}
if ($UseMSVCCompilers.Contains("CXX")) {
TryAdd-KeyValue $Defines CMAKE_CXX_COMPILER cl
if ($EnableCaching) {
TryAdd-KeyValue $Defines CMAKE_CXX_COMPILER_LAUNCHER sccache
}
Append-FlagsDefine $Defines CMAKE_CXX_FLAGS $CXXFlags
}
if ($UsePinnedCompilers.Contains("ASM") -Or $UseBuiltCompilers.Contains("ASM")) {
if ($UseBuiltCompilers.Contains("ASM")) {
TryAdd-KeyValue $Defines CMAKE_ASM_COMPILER ([IO.Path]::Combine($CompilersBinaryCache, "bin", "clang-cl.exe"))
} else {
TryAdd-KeyValue $Defines CMAKE_ASM_COMPILER (Join-Path -Path (Get-PinnedToolchainTool) -ChildPath "clang-cl.exe")
}
Append-FlagsDefine $Defines CMAKE_ASM_FLAGS "--target=$($Arch.LLVMTarget)"
TryAdd-KeyValue $Defines CMAKE_ASM_COMPILE_OPTIONS_MSVC_RUNTIME_LIBRARY_MultiThreadedDLL "/MD"
}
if ($UsePinnedCompilers.Contains("C") -Or $UseBuiltCompilers.Contains("C")) {
if ($UseBuiltCompilers.Contains("C")) {
TryAdd-KeyValue $Defines CMAKE_C_COMPILER ([IO.Path]::Combine($CompilersBinaryCache, "bin", "clang-cl.exe"))
} else {
TryAdd-KeyValue $Defines CMAKE_C_COMPILER (Join-Path -Path (Get-PinnedToolchainTool) -ChildPath "clang-cl.exe")
}
TryAdd-KeyValue $Defines CMAKE_C_COMPILER_TARGET $Arch.LLVMTarget
if (-not (Test-CMakeAtLeast -Major 3 -Minor 26 -Patch 3)) {
# Workaround for https://github.com/ninja-build/ninja/issues/2280
TryAdd-KeyValue $Defines CMAKE_CL_SHOWINCLUDES_PREFIX "Note: including file: "
}
if ($DebugInfo -and $CDebugFormat -eq "dwarf") {
Append-FlagsDefine $Defines CMAKE_C_FLAGS "-gdwarf"
}
Append-FlagsDefine $Defines CMAKE_C_FLAGS $CFlags
}
if ($UsePinnedCompilers.Contains("CXX") -Or $UseBuiltCompilers.Contains("CXX")) {
if ($UseBuiltCompilers.Contains("CXX")) {
TryAdd-KeyValue $Defines CMAKE_CXX_COMPILER ([IO.Path]::Combine($CompilersBinaryCache, "bin", "clang-cl.exe"))
} else {
TryAdd-KeyValue $Defines CMAKE_CXX_COMPILER (Join-Path -Path (Get-PinnedToolchainTool) -ChildPath "clang-cl.exe")
}
TryAdd-KeyValue $Defines CMAKE_CXX_COMPILER_TARGET $Arch.LLVMTarget
if (-not (Test-CMakeAtLeast -Major 3 -Minor 26 -Patch 3)) {
# Workaround for https://github.com/ninja-build/ninja/issues/2280
TryAdd-KeyValue $Defines CMAKE_CL_SHOWINCLUDES_PREFIX "Note: including file: "
}
if ($DebugInfo -and $CDebugFormat -eq "dwarf") {
Append-FlagsDefine $Defines CMAKE_CXX_FLAGS "-gdwarf"
}
Append-FlagsDefine $Defines CMAKE_CXX_FLAGS $CXXFlags
}
if ($UsePinnedCompilers.Contains("Swift") -Or $UseBuiltCompilers.Contains("Swift")) {
$SwiftArgs = @()
if ($UseSwiftSwiftDriver) {
TryAdd-KeyValue $Defines CMAKE_Swift_COMPILER ([IO.Path]::Combine($DriverBinaryCache, "bin", "swiftc.exe"))
} elseif ($UseBuiltCompilers.Contains("Swift")) {
TryAdd-KeyValue $Defines CMAKE_Swift_COMPILER ([IO.Path]::Combine($CompilersBinaryCache, "bin", "swiftc.exe"))
} else {
TryAdd-KeyValue $Defines CMAKE_Swift_COMPILER (Join-Path -Path (Get-PinnedToolchainTool) -ChildPath "swiftc.exe")
}
TryAdd-KeyValue $Defines CMAKE_Swift_COMPILER_TARGET $Arch.LLVMTarget
if ($UseBuiltCompilers.Contains("Swift")) {
if ($SwiftSDK -ne "") {
$SwiftArgs += @("-sdk", $SwiftSDK)
} else {
$RuntimeBinaryCache = Get-TargetProjectBinaryCache $Arch Runtime
$SwiftResourceDir = "${RuntimeBinaryCache}\lib\swift"
$SwiftArgs += @("-resource-dir", "$SwiftResourceDir")
$SwiftArgs += @("-L", "$SwiftResourceDir\windows")
$SwiftArgs += @("-vfsoverlay", "$RuntimeBinaryCache\stdlib\windows-vfs-overlay.yaml", "-strict-implicit-module-context", "-Xcc", "-Xclang", "-Xcc", "-fbuiltin-headers-in-system-modules")
}
} else {
$SwiftArgs += @("-sdk", (Get-PinnedToolchainSDK))
}
# Debug Information
if ($DebugInfo) {
if ($SwiftDebugFormat -eq "dwarf") {
$SwiftArgs += @("-g", "-Xlinker", "/DEBUG:DWARF", "-use-ld=lld-link")
} else {
$SwiftArgs += @("-g", "-debug-info-format=codeview", "-Xlinker", "-debug")
}
} else {
$SwiftArgs += "-gnone"
}
$SwiftArgs += @("-Xlinker", "/INCREMENTAL:NO")
# Swift Requries COMDAT folding and de-duplication
$SwiftArgs += @("-Xlinker", "/OPT:REF")
$SwiftArgs += @("-Xlinker", "/OPT:ICF")
Append-FlagsDefine $Defines CMAKE_Swift_FLAGS $SwiftArgs
# Workaround CMake 3.26+ enabling `-wmo` by default on release builds
Append-FlagsDefine $Defines CMAKE_Swift_FLAGS_RELEASE "-O"
Append-FlagsDefine $Defines CMAKE_Swift_FLAGS_RELWITHDEBINFO "-O"
}
if ("" -ne $InstallTo) {
TryAdd-KeyValue $Defines CMAKE_INSTALL_PREFIX $InstallTo
}
# Generate the project
$cmakeGenerateArgs = @("-B", $Bin, "-S", $Src, "-G", $Generator)
if ("" -ne $CacheScript) {
$cmakeGenerateArgs += @("-C", $CacheScript)
}
foreach ($Define in ($Defines.GetEnumerator() | Sort-Object Name)) {
# The quoting gets tricky to support defines containing compiler flags args,
# some of which can contain spaces, for example `-D` `Flags=-flag "C:/Program Files"`
# Avoid backslashes since they are going into CMakeCache.txt,
# where they are interpreted as escapes.
if ($Define.Value -is [string]) {
# Single token value, no need to quote spaces, the splat operator does the right thing.
$Value = $Define.Value.Replace("\", "/")
} else {
# Flags array, multiple tokens, quoting needed for tokens containing spaces
$Value = ""
foreach ($Arg in $Define.Value) {
if ($Value.Length -gt 0) {
$Value += " "
}
$ArgWithForwardSlashes = $Arg.Replace("\", "/")
if ($ArgWithForwardSlashes.Contains(" ")) {
# Quote and escape the quote so it makes it through
$Value += "\""$ArgWithForwardSlashes\"""
} else {
$Value += $ArgWithForwardSlashes
}
}
}
$cmakeGenerateArgs += @("-D", "$($Define.Key)=$Value")
}
if ($UseBuiltCompilers.Contains("Swift")) {
$env:Path = "$($HostArch.SDKInstallRoot)\usr\bin;$($HostArch.ToolchainInstallRoot)\usr\bin;${env:Path}"
}
Invoke-Program cmake.exe @cmakeGenerateArgs
# Build all requested targets
foreach ($Target in $BuildTargets) {
if ($Target -eq "default") {
Invoke-Program cmake.exe --build $Bin
} else {
Invoke-Program cmake.exe --build $Bin --target $Target
}
}
if ("" -ne $InstallTo) {
Invoke-Program cmake.exe --build $Bin --target install
}
}
if (-not $ToBatch) {
Write-Host -ForegroundColor Cyan "[$([DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss"))] Finished building '$Src' to '$Bin' for arch '$($Arch.LLVMName)' in $($Stopwatch.Elapsed)"
Write-Host ""
}
if ($Summary) {
$TimingData.Add([PSCustomObject]@{
Arch = $Arch.LLVMName
Platform = $Platform
Checkout = $Src.Replace($SourceCache, '')
"Elapsed Time" = $Stopwatch.Elapsed.ToString()
})
}
}
function Build-SPMProject {
[CmdletBinding(PositionalBinding = $false)]
param(
[string] $Src,
[string] $Bin,
[hashtable] $Arch,
[switch] $Test = $false,
[Parameter(ValueFromRemainingArguments)]
[string[]] $AdditionalArguments
)
if ($ToBatch) {
Write-Output ""
Write-Output "echo Building '$Src' to '$Bin' for arch '$($Arch.LLVMName)'..."
} else {
Write-Host -ForegroundColor Cyan "[$([DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss"))] Building '$Src' to '$Bin' for arch '$($Arch.LLVMName)'..."
}
$Stopwatch = [Diagnostics.Stopwatch]::StartNew()
Isolate-EnvVars {
$SDKInstallRoot = [IO.Path]::Combine((Get-InstallDir $HostArch), "Platforms", "Windows.platform", "Developer", "SDKs", "Windows.sdk")
$RuntimeInstallRoot = [IO.Path]::Combine((Get-InstallDir $HostArch), "Runtimes", $ProductVersion)
$env:Path = "$RuntimeInstallRoot\usr\bin;$($HostArch.ToolchainInstallRoot)\usr\bin;${env:Path}"
$env:SDKROOT = $SDKInstallRoot
$Arguments = @(
"--scratch-path", $Bin,
"--package-path", $Src,
"-c", "release",
"-Xbuild-tools-swiftc", "-I$SDKInstallRoot\usr\lib\swift",
"-Xbuild-tools-swiftc", "-L$SDKInstallRoot\usr\lib\swift\windows",
"-Xcc", "-I$SDKInstallRoot\usr\lib\swift",
"-Xlinker", "-L$SDKInstallRoot\usr\lib\swift\windows"
)
if ($DebugInfo) {
if ($SwiftDebugFormat -eq "dwarf") {
$Arguments += @("-debug-info-format", "dwarf")
} else {
$Arguments += @("-debug-info-format", "codeview")
}
} else {
$Arguments += @("-debug-info-format", "none")
}
$Action = if ($Test) { "test" } else { "build" }
Invoke-Program "$($HostArch.ToolchainInstallRoot)\usr\bin\swift.exe" $Action @Arguments @AdditionalArguments
}
if (-not $ToBatch) {
Write-Host -ForegroundColor Cyan "[$([DateTime]::Now.ToString("yyyy-MM-dd HH:mm:ss"))] Finished building '$Src' to '$Bin' for arch '$($Arch.LLVMName)' in $($Stopwatch.Elapsed)"
Write-Host ""
}
if ($Summary) {
$TimingData.Add([PSCustomObject]@{
Arch = $Arch.LLVMName
Checkout = $Src.Replace($SourceCache, '')
Platform = "Windows"
"Elapsed Time" = $Stopwatch.Elapsed.ToString()
})
}
}
function Build-WiXProject() {
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Position = 0, Mandatory = $true)]
[string]$FileName,
[Parameter(Mandatory = $true)]
[hashtable]$Arch,
[switch]$Bundle,
[hashtable]$Properties = @{}
)
$ArchName = $Arch.VSName
$ProductVersionArg = $ProductVersion
if (-not $Bundle) {
# WiX v4 will accept a semantic version string for Bundles,
# but Packages still require a purely numerical version number,
# so trim any semantic versionning suffixes
$ProductVersionArg = [regex]::Replace($ProductVersion, "[-+].*", "")
}
$Properties = $Properties.Clone()
TryAdd-KeyValue $Properties Configuration Release
TryAdd-KeyValue $Properties BaseOutputPath "$($Arch.BinaryCache)\installer\"
TryAdd-KeyValue $Properties ProductArchitecture $ArchName
TryAdd-KeyValue $Properties ProductVersion $ProductVersionArg
$MSBuildArgs = @("$SourceCache\swift-installer-scripts\platforms\Windows\$FileName")
$MSBuildArgs += "-noLogo"
$MSBuildArgs += "-restore"
$MSBuildArgs += "-maxCpuCount"
foreach ($Property in $Properties.GetEnumerator()) {
if ($Property.Value.Contains(" ")) {
$MSBuildArgs += "-p:$($Property.Key)=$($Property.Value.Replace('\', '\\'))"