Repository navigation
Expand file tree
/
Copy pathsetup-windows-whp.ps1
More file actions
1762 lines (1662 loc) · 62 KB
/
Copy pathsetup-windows-whp.ps1
File metadata and controls
1762 lines (1662 loc) · 62 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
[CmdletBinding()]
param(
[Parameter()]
[string]$Workspace,
[Parameter()]
[string]$GuestArtifactsDirectory,
[Parameter()]
[switch]$CheckOnly,
[Parameter()]
[switch]$SkipBuild,
[Parameter()]
[switch]$RunnerOnly,
[Parameter()]
[string]$RunnerName,
[Parameter()]
[switch]$BenchmarkRunner,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$RepositoryUrl = "https://github.com/microsoft/nvx",
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]$RunnerDirectory = "$env:SystemDrive\actions-runner",
[Parameter()]
[string]$BenchmarkScratchDirectory,
[Parameter()]
[switch]$RunnerTokenStdin,
[Parameter()]
[ValidatePattern('^[A-Za-z0-9_.-]+(,[A-Za-z0-9_.-]+)*$')]
[string]$ExtraRunnerLabels
)
Set-StrictMode -Version 2.0
$ErrorActionPreference = "Stop"
# Reads the tool manifest as data, without evaluating it, and rejects it
# unless every line is well formed.
function Read-ToolManifest {
param([Parameter(Mandatory = $true)][string]$Path)
if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) {
throw "tool manifest not found: $Path"
}
$entries = New-Object 'System.Collections.Generic.Dictionary[string,string]' `
([StringComparer]::Ordinal)
$keyPattern = '^[a-z][a-z0-9_]*\.(version|toolchain|artifacts\.([a-z0-9_-]+)\.(name|sha256))$'
$lineNumber = 0
$text = [Text.Encoding]::UTF8.GetString([IO.File]::ReadAllBytes($Path))
foreach ($line in $text.Split([char]10)) {
$lineNumber += 1
# Ordinal comparisons keep characters such as a byte order mark that
# culture-aware ones ignore, as the shell reader does.
if ($line.EndsWith([string][char]13, [StringComparison]::Ordinal)) {
$line = $line.Substring(0, $line.Length - 1)
}
if ($line.Length -eq 0 -or $line.StartsWith("#", [StringComparison]::Ordinal)) {
continue
}
$location = "invalid tool manifest ${Path}:${lineNumber}"
$separator = $line.IndexOf([char]"=")
if ($line -cmatch '[ \t]' -or $separator -lt 0) {
throw "${location}: expected KEY=VALUE without spaces"
}
$key = $line.Substring(0, $separator)
$value = $line.Substring($separator + 1)
if ($key -cnotmatch $keyPattern) {
throw "${location}: unsupported key: $key"
}
$field = $Matches[1]
if ($field.StartsWith("artifacts.")) {
$platform = $Matches[2]
$field = $Matches[3]
if ($platform -cnotin @("linux-x86_64", "windows-x86_64")) {
throw "${location}: unsupported platform: $platform"
}
}
if ($entries.ContainsKey($key)) {
throw "${location}: duplicate key: $key"
}
$candidate = $value
$pattern = '^[0-9]+\.[0-9]+\.[0-9]+$'
if ($field -ceq "sha256") {
$pattern = '^[0-9a-f]{64}$'
}
elseif ($field -ceq "name") {
$candidate = $value.Replace("{version}", "v")
$pattern = '^[A-Za-z0-9_-][A-Za-z0-9._-]*(/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$'
}
if ($candidate -cnotmatch $pattern) {
throw "${location}: invalid value for ${key}: $value"
}
$entries[$key] = $value
}
return [pscustomobject]@{ Path = $Path; Entries = $entries }
}
function Get-ToolManifestValue {
param(
[Parameter(Mandatory = $true)][object]$Manifest,
[Parameter(Mandatory = $true)][string]$Key
)
if (-not $Manifest.Entries.ContainsKey($Key)) {
throw "tool manifest $($Manifest.Path) does not define $Key"
}
return $Manifest.Entries[$Key]
}
# Returns a tool's release and the name and checksum of its artifact for a
# platform.
function Get-ToolArtifact {
param(
[Parameter(Mandatory = $true)][object]$Manifest,
[Parameter(Mandatory = $true)][string]$Tool,
[Parameter(Mandatory = $true)][string]$Platform
)
$version = Get-ToolManifestValue $Manifest "$Tool.version"
$name = Get-ToolManifestValue $Manifest "$Tool.artifacts.$Platform.name"
$sha256 = Get-ToolManifestValue $Manifest "$Tool.artifacts.$Platform.sha256"
return [pscustomobject]@{
Version = $version
Name = $name.Replace("{version}", $version)
Sha256 = $sha256
}
}
function Get-ExpectedRunnerLabels {
param(
[string]$AdditionalLabels,
[switch]$BenchmarkRunner
)
$labels = @("windows", "whp", "virtual-machine")
if ($BenchmarkRunner) {
$labels += "benchmark"
}
else {
$labels += "general"
}
if (-not [string]::IsNullOrEmpty($AdditionalLabels)) {
foreach ($label in $AdditionalLabels.Split(',')) {
if ($label -in @("general", "benchmark")) {
throw "runner role label must be selected with -BenchmarkRunner: $label"
}
if ($label -cnotmatch '^[A-Za-z0-9_.-]+$' -or
$labels -contains $label) {
throw "invalid or duplicate runner label: $label"
}
$labels += $label
}
}
return $labels -join ','
}
# The versions, artifacts, and checksums of the tools that this script
# installs; stage the manifest next to the script.
$ToolPlatform = "windows-x86_64"
$ToolManifest = Read-ToolManifest (Join-Path $PSScriptRoot "tool-versions.conf")
$RustToolchain = Get-ToolManifestValue $ToolManifest "rust.toolchain"
$CargoNextestVersion = Get-ToolManifestValue $ToolManifest "cargo_nextest.version"
$rustupRelease = Get-ToolArtifact $ToolManifest "rustup" $ToolPlatform
$RustupVersion = $rustupRelease.Version
$RustupArtifact = $rustupRelease.Name
$RustupSha256 = $rustupRelease.Sha256
$sccacheRelease = Get-ToolArtifact $ToolManifest "sccache" $ToolPlatform
$SccacheVersion = $sccacheRelease.Version
$SccacheArtifact = $sccacheRelease.Name
$SccacheSha256 = $sccacheRelease.Sha256
$runnerRelease = Get-ToolArtifact $ToolManifest "actions_runner" $ToolPlatform
$RunnerVersion = $runnerRelease.Version
$RunnerArtifact = $runnerRelease.Name
$RunnerSha256 = $runnerRelease.Sha256
$ExpectedRunnerLabels = Get-ExpectedRunnerLabels `
-AdditionalLabels $ExtraRunnerLabels -BenchmarkRunner:$BenchmarkRunner
if (-not $RunnerOnly) {
if ([string]::IsNullOrWhiteSpace($Workspace)) {
$Workspace = Join-Path $PSScriptRoot "..\.."
}
$Workspace = (Resolve-Path -LiteralPath $Workspace).Path
}
$ToolRoot = Join-Path $env:ProgramData "nvx"
$TrustedCargoHome = Join-Path $ToolRoot "cargo"
$CargoHome = Join-Path $RunnerDirectory "_work\_temp\cargo-home"
$SccacheDirectory = Join-Path $RunnerDirectory "_work\_sccache"
$BenchmarkScratchVariable = "NVX_BENCHMARK_SCRATCH"
$BenchmarkScratchName = "nvx-benchmark-scratch"
$RustupHome = Join-Path $ToolRoot "rustup"
$RequiredGuestArtifacts = @(
"vmlinux",
"vmlinux.config",
"vmlinux.provenance.json",
"initramfs.cpio.gz",
"initramfs.cpio.gz.packages.json",
"initramfs.provenance.json",
"initramfs-ubuntu.cpio.gz",
"initramfs-ubuntu.cpio.gz.packages.json",
"ubuntu-distro.erofs",
"ubuntu-distro.erofs.manifest.json",
"initramfs-azurelinux.cpio.gz",
"initramfs-azurelinux.cpio.gz.packages.json"
)
function Assert-LastExitCode {
param([Parameter(Mandatory = $true)][string]$Description)
if ($LASTEXITCODE -ne 0) {
throw "$Description failed with exit code $LASTEXITCODE"
}
}
function Invoke-Native {
param(
[Parameter(Mandatory = $true)][string]$FilePath,
[Parameter()][string[]]$Arguments = @()
)
& $FilePath @Arguments
Assert-LastExitCode $FilePath
}
function Update-ProcessPath {
$machinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")
$env:Path = "$TrustedCargoHome\bin;$machinePath"
}
function Add-MachinePathEntry {
param([Parameter(Mandatory = $true)][string]$Path)
$machinePath = [Environment]::GetEnvironmentVariable("Path", "Machine")
$entries = @($machinePath -split ";" |
Where-Object { $_ -and $_ -ne $Path })
[Environment]::SetEnvironmentVariable(
"Path",
((@($Path) + $entries) -join ";"),
"Machine"
)
}
function Set-ServiceDirectoryAcl {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$ServiceRights,
[Parameter()][string[]]$ExcludeChildren = @(),
[Parameter()][switch]$AllowInternalLinks,
[Parameter()][switch]$SkipChildren
)
$rootItem = Get-Item -LiteralPath $Path -Force
if ($rootItem.Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "directory tree must not contain a reparse point: $($rootItem.FullName)"
}
$entries = @()
if (-not $SkipChildren) {
$entries = @(Get-ChildItem -LiteralPath $Path -Force)
foreach ($entry in $entries) {
if ($entry.Name -notin $ExcludeChildren) {
if ($AllowInternalLinks) {
Assert-TreeLinksAreInternal `
-Root $entry.FullName `
-Boundary $Path
}
else {
Assert-NoTreeLinks -Root $entry.FullName
}
}
}
}
$acl = New-Object Security.AccessControl.DirectorySecurity
$acl.SetAccessRuleProtection($true, $false)
$inheritance = [Security.AccessControl.InheritanceFlags]::ObjectInherit -bor
[Security.AccessControl.InheritanceFlags]::ContainerInherit
$propagation = [Security.AccessControl.PropagationFlags]::None
$allow = [Security.AccessControl.AccessControlType]::Allow
foreach ($entry in @(
@("S-1-5-18", "FullControl"),
@("S-1-5-32-544", "FullControl"),
@("S-1-5-20", $ServiceRights)
)) {
$identity = [Security.Principal.SecurityIdentifier]::new($entry[0])
$rights = [Security.AccessControl.FileSystemRights]$entry[1]
$rule = [Security.AccessControl.FileSystemAccessRule]::new(
$identity,
$rights,
$inheritance,
$propagation,
$allow
)
[void]$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $Path -AclObject $acl
foreach ($entry in $entries) {
if ($entry.Name -in $ExcludeChildren) {
continue
}
$arguments = @($entry.FullName, "/reset", "/L", "/Q")
if ($entry.PSIsContainer) {
$arguments += "/T"
}
Invoke-Native "icacls.exe" $arguments
}
}
function Assert-ServiceDirectoryAcl {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter()][switch]$Writable
)
$acl = Get-Acl -LiteralPath $Path
if (-not $acl.AreAccessRulesProtected) {
throw "service directory ACL inherits permissions: $Path"
}
$networkServiceSid = "S-1-5-20"
$allRules = @($acl.GetAccessRules(
$true,
$true,
[Security.Principal.SecurityIdentifier]
))
$rules = @($allRules | Where-Object {
$_.IdentityReference.Value -eq $networkServiceSid -and
$_.AccessControlType -eq "Allow"
})
$required = if ($Writable) {
[Security.AccessControl.FileSystemRights]::Modify
}
else {
[Security.AccessControl.FileSystemRights]::ReadAndExecute
}
if (@($rules | Where-Object {
($_.FileSystemRights -band $required) -eq $required
}).Count -eq 0) {
throw "Network Service lacks $required on $Path"
}
$writeMask = [Security.AccessControl.FileSystemRights]::Write -bor
[Security.AccessControl.FileSystemRights]::Delete -bor
[Security.AccessControl.FileSystemRights]::ChangePermissions -bor
[Security.AccessControl.FileSystemRights]::TakeOwnership
$allowedWriters = @("S-1-5-18", "S-1-5-32-544")
if ($Writable) {
$allowedWriters += $networkServiceSid
}
if (@($allRules | Where-Object {
$_.AccessControlType -eq "Allow" -and
($_.FileSystemRights -band $writeMask) -ne 0 -and
$_.IdentityReference.Value -notin $allowedWriters
}).Count -ne 0) {
throw "untrusted identity can modify service directory: $Path"
}
}
function Get-TreeItemsWithoutFollowingLinks {
param([Parameter(Mandatory = $true)][string]$Root)
$pending = [Collections.Generic.Stack[IO.FileSystemInfo]]::new()
foreach ($entry in Get-ChildItem -LiteralPath $Root -Force) {
$pending.Push($entry)
}
while ($pending.Count -ne 0) {
$entry = $pending.Pop()
$entry
if ($entry.PSIsContainer -and
-not ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
foreach ($child in Get-ChildItem -LiteralPath $entry.FullName -Force) {
$pending.Push($child)
}
}
}
}
function Assert-NoTreeLinks {
param([Parameter(Mandatory = $true)][string]$Root)
$rootItem = Get-Item -LiteralPath $Root -Force
if ($rootItem.Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "directory tree must not contain a reparse point: $($rootItem.FullName)"
}
$linkedItems = @(Get-TreeItemsWithoutFollowingLinks -Root $Root |
Where-Object {
$_.Attributes -band [IO.FileAttributes]::ReparsePoint -or
$_.LinkType -eq "HardLink"
})
if ($linkedItems.Count -ne 0) {
throw "directory tree must not contain a link: $($linkedItems[0].FullName)"
}
}
function Assert-TreeLinksAreInternal {
param(
[Parameter(Mandatory = $true)][string]$Root,
[Parameter(Mandatory = $true)][string]$Boundary
)
$rootItem = Get-Item -LiteralPath $Root -Force
$items = @($rootItem)
if (-not ($rootItem.Attributes -band [IO.FileAttributes]::ReparsePoint) -and
$rootItem.PSIsContainer) {
$items += @(Get-TreeItemsWithoutFollowingLinks -Root $Root)
}
$hardLinks = @($items | Where-Object { $_.LinkType -eq "HardLink" })
if ($hardLinks.Count -ne 0) {
throw "trusted tree must not contain a hard link: $($hardLinks[0].FullName)"
}
$boundaryPath = [IO.Path]::GetFullPath($Boundary).TrimEnd("\")
$boundaryPrefix = "$boundaryPath\"
foreach ($item in $items | Where-Object {
$_.Attributes -band [IO.FileAttributes]::ReparsePoint
}) {
$target = @($item.Target)[0]
if ([string]::IsNullOrWhiteSpace($target)) {
throw "reparse point has no target: $($item.FullName)"
}
if (-not [IO.Path]::IsPathRooted($target)) {
$target = Join-Path `
([IO.Path]::GetDirectoryName($item.FullName)) `
$target
}
$targetPath = [IO.Path]::GetFullPath($target)
$insideBoundary = [StringComparer]::OrdinalIgnoreCase.Equals(
$targetPath,
$boundaryPath
) -or $targetPath.StartsWith(
$boundaryPrefix,
[StringComparison]::OrdinalIgnoreCase
)
$targetItem = Get-Item `
-LiteralPath $targetPath `
-Force `
-ErrorAction SilentlyContinue
if (-not $insideBoundary -or $null -eq $targetItem -or
$targetItem.Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "trusted tree link has unsafe target: $($item.FullName)"
}
}
}
function Assert-ActionsRunnerWritablePaths {
$workDirectory = Join-Path $RunnerDirectory "_work"
foreach ($path in @(
$RunnerDirectory,
$workDirectory,
(Join-Path $RunnerDirectory "_work\_temp"),
(Join-Path $RunnerDirectory "_work\_diag"),
$CargoHome,
$SccacheDirectory
)) {
$item = Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
if ($null -eq $item) {
continue
}
if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) {
throw "runner writable path must not be a reparse point: $path"
}
if (-not $item.PSIsContainer) {
throw "runner writable path is not a directory: $path"
}
}
}
function Assert-FreshRunnerDirectory {
param([Parameter(Mandatory = $true)][string]$Path)
$root = Get-Item -LiteralPath $Path -Force
$unexpected = @(Get-ChildItem -LiteralPath $Path -Force |
Where-Object {
$_.Name -ne "_work" -or
-not $_.PSIsContainer -or
($_.Attributes -band [IO.FileAttributes]::ReparsePoint)
})
if (-not $root.PSIsContainer -or
$root.Attributes -band [IO.FileAttributes]::ReparsePoint -or
$unexpected.Count -ne 0) {
throw "refusing to install into partial runner directory: $Path"
}
}
function Assert-ActionsRunnerStatePaths {
Assert-ActionsRunnerWritablePaths
foreach ($name in @(
".credentials",
".credentials_rsaparams",
".nvx-labels",
".runner",
".service"
)) {
$path = Join-Path $RunnerDirectory $name
$item = Get-Item -LiteralPath $path -Force -ErrorAction SilentlyContinue
if ($null -eq $item) {
continue
}
if ($item.PSIsContainer -or
$item.Attributes -band [IO.FileAttributes]::ReparsePoint -or
$item.LinkType -eq "HardLink") {
throw "runner state path is not a regular file: $path"
}
}
}
function Get-ProtectedActionsRunnerItems {
Get-Item -LiteralPath $RunnerDirectory -Force
foreach ($entry in Get-ChildItem -LiteralPath $RunnerDirectory -Force) {
if ($entry.Name -in @("_work", "_diag")) {
continue
}
$entry
if ($entry.PSIsContainer -and
-not ($entry.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
Get-TreeItemsWithoutFollowingLinks -Root $entry.FullName
}
}
}
function Assert-NoProtectedActionsRunnerLinks {
$linkedItems = @(Get-ProtectedActionsRunnerItems | Where-Object {
$_.Attributes -band [IO.FileAttributes]::ReparsePoint -or
$_.LinkType -eq "HardLink"
})
if ($linkedItems.Count -ne 0) {
throw "protected runner path must not be a link: $($linkedItems[0].FullName)"
}
}
function Set-ActionsRunnerOwners {
Assert-NoProtectedActionsRunnerLinks
Invoke-Native "icacls.exe" @(
$RunnerDirectory, "/setowner", "*S-1-5-18", "/L", "/Q"
)
foreach ($entry in Get-ChildItem -LiteralPath $RunnerDirectory -Force) {
if ($entry.Name -in @("_work", "_diag")) {
continue
}
Invoke-Native "icacls.exe" @(
$entry.FullName, "/setowner", "*S-1-5-18", "/T", "/L", "/Q"
)
}
}
function Assert-ActionsRunnerOwners {
Assert-NoProtectedActionsRunnerLinks
foreach ($item in Get-ProtectedActionsRunnerItems) {
$owner = (Get-Acl -LiteralPath $item.FullName).GetOwner(
[Security.Principal.SecurityIdentifier]
).Value
if ($owner -ne "S-1-5-18") {
throw "protected runner path is owned by ${owner}: $($item.FullName)"
}
}
}
function Assert-TrustedToolchainAcl {
Assert-TreeLinksAreInternal -Root $ToolRoot -Boundary $ToolRoot
Assert-ServiceDirectoryAcl -Path $ToolRoot
}
function Set-ActionsRunnerDisableUpdate {
Assert-ActionsRunnerStatePaths
$runnerConfiguration = Join-Path $RunnerDirectory ".runner"
$configuration = Get-Content -LiteralPath $runnerConfiguration -Raw |
ConvertFrom-Json
$configuration | Add-Member `
-NotePropertyName disableUpdate `
-NotePropertyValue $true `
-Force
$encoding = [Text.UTF8Encoding]::new($true)
$json = $configuration | ConvertTo-Json -Depth 16
$bytes = $encoding.GetBytes($json)
$stream = [IO.File]::Open(
$runnerConfiguration,
[IO.FileMode]::Open,
[IO.FileAccess]::Write,
[IO.FileShare]::Read
)
try {
$stream.SetLength(0)
$stream.Write($bytes, 0, $bytes.Length)
}
finally {
$stream.Dispose()
}
}
function Test-ActionsRunnerDiagnosticsLink {
param(
[Parameter(Mandatory = $true)][string]$Path,
[Parameter(Mandatory = $true)][string]$ExpectedTarget
)
$item = Get-Item `
-LiteralPath $Path `
-Force `
-ErrorAction SilentlyContinue
if ($null -eq $item) {
return $false
}
if (-not ($item.Attributes -band [IO.FileAttributes]::ReparsePoint)) {
return $false
}
$target = @($item.Target)[0]
if ([string]::IsNullOrWhiteSpace($target)) {
return $false
}
if (-not [IO.Path]::IsPathRooted($target)) {
$target = Join-Path $item.Parent.FullName $target
}
$actual = [IO.Path]::GetFullPath($target).TrimEnd("\")
$expected = [IO.Path]::GetFullPath($ExpectedTarget).TrimEnd("\")
return [StringComparer]::OrdinalIgnoreCase.Equals($actual, $expected)
}
function Protect-ActionsRunner {
$workDirectory = Join-Path $RunnerDirectory "_work"
$temporaryDirectory = Join-Path $workDirectory "_temp"
$diagnosticsDirectory = Join-Path $RunnerDirectory "_diag"
$diagnosticsTarget = Join-Path $workDirectory "_diag"
Assert-ActionsRunnerWritablePaths
New-Item `
-ItemType Directory `
-Path `
$workDirectory, `
$temporaryDirectory, `
$diagnosticsTarget, `
$CargoHome, `
$SccacheDirectory `
-Force |
Out-Null
$diagnostics = Get-Item `
-LiteralPath $diagnosticsDirectory `
-Force `
-ErrorAction SilentlyContinue
if ($null -ne $diagnostics -and
-not (Test-ActionsRunnerDiagnosticsLink `
-Path $diagnosticsDirectory `
-ExpectedTarget $diagnosticsTarget)) {
if ($diagnostics.Attributes -band [IO.FileAttributes]::ReparsePoint) {
Remove-Item -LiteralPath $diagnosticsDirectory -Force
}
else {
Get-ChildItem -LiteralPath $diagnosticsDirectory -Force |
Move-Item -Destination $diagnosticsTarget -Force
Remove-Item -LiteralPath $diagnosticsDirectory -Recurse -Force
}
}
if (-not (Test-Path -LiteralPath $diagnosticsDirectory)) {
New-Item `
-ItemType Junction `
-Path $diagnosticsDirectory `
-Target $diagnosticsTarget |
Out-Null
}
Set-ActionsRunnerOwners
Set-ServiceDirectoryAcl `
-Path $RunnerDirectory `
-ServiceRights "ReadAndExecute" `
-ExcludeChildren @("_work", "_diag")
foreach ($path in @(
$workDirectory,
$temporaryDirectory,
$diagnosticsTarget,
$CargoHome,
$SccacheDirectory
)) {
Set-ServiceDirectoryAcl `
-Path $path `
-ServiceRights "Modify" `
-SkipChildren
}
Invoke-Native "icacls.exe" @(
$diagnosticsDirectory, "/reset", "/L", "/Q"
)
}
function Get-RequiredCommand {
param([Parameter(Mandatory = $true)][string]$Name)
$command = Get-Command $Name -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($null -eq $command) {
throw "required command not found: $Name"
}
return $command.Source
}
function Get-WinGetCommand {
$command = Get-Command winget.exe -ErrorAction SilentlyContinue |
Select-Object -First 1
if ($null -ne $command) {
return $command.Source
}
$packages = @(Get-AppxPackage `
-AllUsers `
-Name Microsoft.DesktopAppInstaller `
-ErrorAction SilentlyContinue |
Sort-Object Version -Descending)
foreach ($package in $packages) {
$path = Join-Path $package.InstallLocation "winget.exe"
if (Test-Path -LiteralPath $path -PathType Leaf) {
return $path
}
}
return $null
}
function Get-PythonCommand {
param([Parameter()][switch]$AllowMissing)
$commands = @(Get-Command python.exe -All -ErrorAction SilentlyContinue |
Where-Object { $_.Source -notlike "*\WindowsApps\python.exe" } |
Select-Object -ExpandProperty Source -Unique)
foreach ($path in $commands) {
$version = & $path -c `
"import sys; print(f'{sys.version_info.major}.{sys.version_info.minor}')" `
2>$null
if ($LASTEXITCODE -eq 0 -and [version]$version -ge [version]"3.10") {
return $path
}
}
if ($AllowMissing) {
return $null
}
throw "Python 3.10 or newer was not found"
}
function Assert-SupportedHost {
param([Parameter()][switch]$SkipWorkspace)
if ($env:OS -ne "Windows_NT") {
throw "this script requires Windows"
}
if (-not [Environment]::Is64BitOperatingSystem) {
throw "this script requires 64-bit Windows"
}
if ($SkipWorkspace) {
return
}
if (-not (Test-Path -LiteralPath "$Workspace\scripts\nvx.py" -PathType Leaf)) {
throw "NVX checkout not found at $Workspace"
}
if (-not (Test-Path -LiteralPath "$Workspace\openvmm\Cargo.toml" -PathType Leaf)) {
throw "OpenVMM submodule is not initialized"
}
if ($null -ne (Get-Process openvmm -ErrorAction SilentlyContinue)) {
throw "an OpenVMM process is already running"
}
}
function Assert-Administrator {
$identity = [Security.Principal.WindowsIdentity]::GetCurrent()
$principal = New-Object Security.Principal.WindowsPrincipal($identity)
if (-not $principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
throw "run this script from an elevated Windows PowerShell session"
}
}
function Install-WinGet {
$winget = Get-WinGetCommand
if ($null -ne $winget) {
return $winget
}
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Install-PackageProvider -Name NuGet -Force -Scope AllUsers -Confirm:$false |
Out-Null
Install-Module Microsoft.WinGet.Client `
-Repository PSGallery `
-Scope AllUsers `
-Force `
-AllowClobber `
-Confirm:$false
Import-Module Microsoft.WinGet.Client -Force
Repair-WinGetPackageManager -AllUsers -Force -Latest
$winget = Get-WinGetCommand
if ($null -eq $winget) {
throw "required command not found: winget.exe"
}
Update-ProcessPath
return $winget
}
function Install-WinGetPackage {
param(
[Parameter(Mandatory = $true)][string]$Id,
[Parameter()][string[]]$AdditionalArguments = @()
)
$arguments = @(
"install",
"--id", $Id,
"--exact",
"--silent",
"--accept-source-agreements",
"--accept-package-agreements",
"--disable-interactivity"
) + $AdditionalArguments
Invoke-Native $script:WinGet $arguments
}
function Test-VisualStudioBuildTools {
$vswhere = Join-Path ${env:ProgramFiles(x86)} `
"Microsoft Visual Studio\Installer\vswhere.exe"
if (-not (Test-Path -LiteralPath $vswhere -PathType Leaf)) {
return $false
}
$instances = @(& $vswhere `
-products * `
-requires `
Microsoft.VisualStudio.Component.VC.Tools.x86.x64 `
Microsoft.VisualStudio.Component.Windows11SDK.26100 `
-property installationPath)
return $LASTEXITCODE -eq 0 -and $instances.Count -gt 0
}
function Install-Toolchain {
Assert-ActionsRunnerWritablePaths
$script:WinGet = Install-WinGet
Update-ProcessPath
if ($null -eq (Get-Command git.exe -ErrorAction SilentlyContinue |
Select-Object -First 1)) {
Install-WinGetPackage "Git.Git" @("--scope", "machine")
Update-ProcessPath
}
if ($null -eq (Get-PythonCommand -AllowMissing)) {
Install-WinGetPackage "Python.Python.3.12" @("--scope", "machine")
Update-ProcessPath
}
if (-not (Test-VisualStudioBuildTools)) {
$vsArguments = @(
"--override",
"--wait --quiet --norestart --add Microsoft.VisualStudio.Workload.VCTools --add Microsoft.VisualStudio.Component.Windows11SDK.26100 --includeRecommended"
)
Install-WinGetPackage "Microsoft.VisualStudio.2022.BuildTools" $vsArguments
}
Update-ProcessPath
New-Item -ItemType Directory `
-Path $TrustedCargoHome, $RustupHome `
-Force |
Out-Null
Set-ServiceDirectoryAcl `
-Path $ToolRoot `
-ServiceRights "ReadAndExecute" `
-AllowInternalLinks
[Environment]::SetEnvironmentVariable("CARGO_HOME", $CargoHome, "Machine")
[Environment]::SetEnvironmentVariable("RUSTUP_HOME", $RustupHome, "Machine")
Add-MachinePathEntry "$TrustedCargoHome\bin"
$env:CARGO_HOME = $TrustedCargoHome
$env:RUSTUP_HOME = $RustupHome
Update-ProcessPath
$rustupPath = Join-Path $TrustedCargoHome "bin\rustup.exe"
if (-not (Test-Path -LiteralPath $rustupPath -PathType Leaf)) {
$rustupInstaller = Join-Path $ToolRoot `
"rustup-init-$RustupVersion-$([guid]::NewGuid().ToString('N')).exe"
try {
Invoke-WebRequest `
-UseBasicParsing `
-Uri "https://static.rust-lang.org/rustup/archive/$RustupVersion/$RustupArtifact" `
-OutFile $rustupInstaller
$actualHash = (Get-FileHash `
-LiteralPath $rustupInstaller `
-Algorithm SHA256).Hash.ToLowerInvariant()
if ($actualHash -ne $RustupSha256) {
throw "Rustup installer checksum mismatch: $actualHash"
}
Invoke-Native $rustupInstaller @(
"-y",
"--profile", "minimal",
"--default-toolchain", $RustToolchain
)
}
finally {
Remove-Item `
-LiteralPath $rustupInstaller `
-Force `
-ErrorAction SilentlyContinue
}
}
Update-ProcessPath
# Keep the pinned rustup. Its self-update replaces rustup.exe from a
# detached process after rustup exits, racing the next rustup command.
Invoke-Native $rustupPath @(
"toolchain", "install", $RustToolchain, "--profile", "minimal",
"--no-self-update"
)
Invoke-Native $rustupPath @(
"target", "add",
"x86_64-unknown-none",
"x86_64-unknown-uefi",
"--toolchain", $RustToolchain
)
$cargo = Join-Path $TrustedCargoHome "bin\cargo.exe"
$nextest = Join-Path $TrustedCargoHome "bin\cargo-nextest.exe"
$installNextest = -not (Test-Path -LiteralPath $nextest -PathType Leaf)
if (-not $installNextest) {
$nextestVersion = & $nextest --version
Assert-LastExitCode "cargo-nextest --version"
$installNextest = ($nextestVersion -join "`n") -notmatch `
"cargo-nextest $([regex]::Escape($CargoNextestVersion))"
}
if ($installNextest) {
Invoke-Native $cargo @(
"+$RustToolchain", "install", "--locked", "--force", "cargo-nextest",
"--version", $CargoNextestVersion
)
}
$sccache = Join-Path $TrustedCargoHome "bin\sccache.exe"
$installSccache = -not (Test-Path -LiteralPath $sccache -PathType Leaf)
if (-not $installSccache) {
$installedSccacheVersion = & $sccache --version
Assert-LastExitCode "sccache --version"
$installSccache = ($installedSccacheVersion -join "`n") -notmatch `
"sccache $([regex]::Escape($SccacheVersion))"
}
if ($installSccache) {
# The archive holds a directory named after it.
$sccachePackage = $SccacheArtifact -replace '\.tar\.gz$', ''
$archive = Join-Path $ToolRoot `
"$sccachePackage-$([guid]::NewGuid().ToString('N')).tar.gz"
$extractDirectory = Join-Path $ToolRoot `
"sccache-v$SccacheVersion-$([guid]::NewGuid().ToString('N'))"
try {
Invoke-WebRequest `
-UseBasicParsing `
-Uri "https://github.com/mozilla/sccache/releases/download/v$SccacheVersion/$SccacheArtifact" `
-OutFile $archive
$actualHash = (Get-FileHash `
-LiteralPath $archive `
-Algorithm SHA256).Hash.ToLowerInvariant()
if ($actualHash -ne $SccacheSha256) {
throw "sccache archive checksum mismatch: $actualHash"
}
New-Item `
-ItemType Directory `
-Path $extractDirectory `
-Force |
Out-Null
Invoke-Native (Get-RequiredCommand "tar.exe") @(
"-xzf", $archive, "-C", $extractDirectory
)
$extracted = Join-Path `
$extractDirectory `
"$sccachePackage\sccache.exe"
if (-not (Test-Path -LiteralPath $extracted -PathType Leaf)) {
throw "sccache executable was not found after extraction"
}
Copy-Item -LiteralPath $extracted -Destination $sccache -Force
}
finally {
Remove-Item `
-LiteralPath $archive, $extractDirectory `
-Recurse `
-Force `
-ErrorAction SilentlyContinue
}
}
Set-ServiceDirectoryAcl `
-Path $ToolRoot `
-ServiceRights "ReadAndExecute" `
-AllowInternalLinks
$env:CARGO_HOME = $CargoHome
}
function Configure-SccacheEnvironment {
New-Item -ItemType Directory -Path $SccacheDirectory -Force |
Out-Null
Set-ServiceDirectoryAcl `
-Path $SccacheDirectory `
-ServiceRights "Modify" `
-SkipChildren
foreach ($entry in @{
CARGO_INCREMENTAL = "0"
RUSTC_WRAPPER = "sccache"
SCCACHE_CACHE_SIZE = "10G"
SCCACHE_DIR = $SccacheDirectory
}.GetEnumerator()) {
[Environment]::SetEnvironmentVariable(
$entry.Key,
$entry.Value,
"Machine"
)
[Environment]::SetEnvironmentVariable(
$entry.Key,
$entry.Value,
"Process"
)
}
}
function Test-SystemVolumePath {
param([Parameter(Mandatory = $true)][string]$Path)
$root = [IO.Path]::GetPathRoot([IO.Path]::GetFullPath($Path)).TrimEnd("\")
return [StringComparer]::OrdinalIgnoreCase.Equals(
$root,
$env:SystemDrive.TrimEnd("\")
)
}
function Get-BenchmarkScratchDirectory {
if (-not [string]::IsNullOrWhiteSpace($BenchmarkScratchDirectory)) {