Files
rust-discovery/deploy/windows/Build-NativeMsvc.ps1
T
2026-11-14 03:53:48 +01:00

275 lines
20 KiB
PowerShell

#requires -Version 5.1
<#!
Native development build only. No tool installation, download, service change,
enrollment, RMM job, reboot, certificate-store or persistent policy modification.
Invoke this file in the authorized bootstrap process with RemoteSigned; GPO
precedence is retained. This is no policy exception for the RMM job executor.
Preflight creates a private receipt; Build requires its explicitly selected
source/tool hashes and creates a NEW private case. A failed case is never reused.
!#>
[CmdletBinding()]
param(
[ValidateSet('Preflight','Build')][string]$Mode='Preflight',
[Parameter(Mandatory=$true)][string]$SourceRoot,
[string]$EvidenceRoot=(Join-Path $env:USERPROFILE 'RmmNativeBuilds'),
[string]$ExpectedPreflight,
[string]$RustupExe,
[string]$RustupHome,
[string]$CargoHome,
[string]$ScriptFile=$PSCommandPath,
[ValidatePattern('^10\.0\.26100\.0$')][string]$SdkVersion='10.0.26100.0',
[ValidateRange(10,100)][int]$MinimumFreeGiB=20,
[Guid]$CaseId=([Guid]::NewGuid())
)
Set-StrictMode -Version Latest
$ErrorActionPreference='Stop'
$Target='x86_64-pc-windows-msvc'
$Toolchain='1.99.1-x86_64-pc-windows-msvc'
$case=$null
$report=[ordered]@{schema_version=1;case_id=$CaseId.ToString();mode=$Mode;completed=$false;stage='initial';
target=$Target;toolchain=$Toolchain;tool_installation=$false;services_changed=$false;reboot_requested=$false;
jobs_created=$false;clock_qualified=$false;unit_tests_executed=$false;abi_probe_executed=$false}
$savedEnvironment=@{}
function Require([bool]$Condition,[string]$Code) {if (-not $Condition) {throw $Code}}
function Hash([string]$Path) {return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()}
function No-Reparse([string]$Path) {
$item=Get-Item -LiteralPath $Path -Force
while ($null -ne $item) {
Require (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -eq 0) 'BUILD_REPARSE_PATH'
if ($item -is [IO.FileInfo]) {$item=$item.Directory} else {$item=$item.Parent}
}
}
function Protected-BuildRoot([string]$Path) {
$acl=Get-Acl -LiteralPath $Path
$me=[Security.Principal.WindowsIdentity]::GetCurrent().User.Value
$trusted=@($me,'S-1-5-18','S-1-5-32-544')
Require ($acl.GetOwner([Security.Principal.SecurityIdentifier]).Value -in $trusted) 'BUILD_ROOT_OWNER'
$write=[Security.AccessControl.FileSystemRights]::Write -bor [Security.AccessControl.FileSystemRights]::Delete -bor
[Security.AccessControl.FileSystemRights]::DeleteSubdirectoriesAndFiles -bor
[Security.AccessControl.FileSystemRights]::ChangePermissions -bor [Security.AccessControl.FileSystemRights]::TakeOwnership
foreach ($ace in $acl.Access) {
if ($ace.AccessControlType -eq 'Allow' -and ($ace.FileSystemRights -band $write) -ne 0) {
Require ($ace.IdentityReference.Translate([Security.Principal.SecurityIdentifier]).Value -in $trusted) 'UNTRUSTED_BUILD_ROOT_WRITER'
}
}
}
function New-PrivateDirectory([string]$Path) {
Require (-not (Test-Path -LiteralPath $Path)) 'BUILD_CASE_ALREADY_EXISTS'
[void][IO.Directory]::CreateDirectory($Path)
$acl=New-Object Security.AccessControl.DirectorySecurity
$acl.SetAccessRuleProtection($true,$false)
$me=[Security.Principal.WindowsIdentity]::GetCurrent().User
$acl.SetOwner($me)
foreach ($sid in @($me.Value,'S-1-5-18','S-1-5-32-544') | Select-Object -Unique) {
$rule=New-Object Security.AccessControl.FileSystemAccessRule(
(New-Object Security.Principal.SecurityIdentifier($sid)),
[Security.AccessControl.FileSystemRights]::FullControl,
([Security.AccessControl.InheritanceFlags]::ContainerInherit -bor [Security.AccessControl.InheritanceFlags]::ObjectInherit),
[Security.AccessControl.PropagationFlags]::None,[Security.AccessControl.AccessControlType]::Allow)
$acl.AddAccessRule($rule)
}
Set-Acl -LiteralPath $Path -AclObject $acl
No-Reparse $Path
}
function Write-New([string]$Path,[string]$Value) {
$stream=[IO.File]::Open($Path,[IO.FileMode]::CreateNew,[IO.FileAccess]::Write,[IO.FileShare]::None)
try {$bytes=(New-Object Text.UTF8Encoding($false)).GetBytes($Value);$stream.Write($bytes,0,$bytes.Length);$stream.Flush($true)}
finally {$stream.Dispose()}
}
function Receipt([string]$Name) {Write-New (Join-Path $case $Name) ($report | ConvertTo-Json -Depth 50)}
function Set-BuildEnvironment([string]$Name,[string]$Value) {
if (-not $savedEnvironment.ContainsKey($Name)) {$savedEnvironment[$Name]=[Environment]::GetEnvironmentVariable($Name,'Process')}
[Environment]::SetEnvironmentVariable($Name,$Value,'Process')
}
function Microsoft-Tool([string]$Path) {
No-Reparse $Path
$sig=Get-AuthenticodeSignature -LiteralPath $Path
Require ($sig.Status -eq 'Valid' -and $null -ne $sig.SignerCertificate -and
$sig.SignerCertificate.Subject -match 'Microsoft Corporation') 'MICROSOFT_TOOL_SIGNATURE_INVALID'
return [ordered]@{path=$Path;sha256=(Hash $Path);signature_status=[string]$sig.Status;
signer_thumbprint=$sig.SignerCertificate.Thumbprint;file_version=(Get-Item -LiteralPath $Path).VersionInfo.FileVersion}
}
function Source-Files([string]$Root) {
$files=@(Get-Item -LiteralPath (Join-Path $Root 'Cargo.toml'),(Join-Path $Root 'Cargo.lock'),(Join-Path $Root 'rust-toolchain.toml'))
foreach ($name in @('crates','proto')) {
$files+=Get-ChildItem -LiteralPath (Join-Path $Root $name) -Recurse -File -Force |
Where-Object {$_.Extension -in @('.rs','.toml','.c','.h','.idl','.proto')}
}
$files+=Get-Item -LiteralPath (Join-Path $Root 'deploy/windows/msvc/clock_abi_probe.c'),(Join-Path $Root 'deploy/windows/Build-NativeMsvc.ps1')
$result=[ordered]@{}
foreach ($item in $files | Sort-Object FullName -Unique) {
No-Reparse $item.FullName
$relative=$item.FullName.Substring($Root.Length+1).Replace('\','/')
Require ($relative -notmatch '(^|/)(credentials|devstate|target|\.git|node_modules)(/|$)') 'NON_SOURCE_BUILD_INPUT'
$result[$relative]=Hash $item.FullName
}
return $result
}
function Same-Map($Expected,$Actual) {
$keys=@($Expected.PSObject.Properties | ForEach-Object {$_.Name})
if ($Expected -is [Collections.IDictionary]) {$keys=@($Expected.Keys)}
Require ($keys.Count -eq $Actual.Count) 'SOURCE_OR_TOOL_COUNT_CHANGED'
foreach ($key in $keys) {
$old=if ($Expected -is [Collections.IDictionary]) {$Expected[$key]} else {$Expected.$key}
Require ($Actual.Contains($key) -and $old -eq $Actual[$key]) 'SOURCE_OR_TOOL_HASH_CHANGED'
}
}
function Quoted([string]$Value) {
Require ($Value -notmatch '["\x00\r\n]') 'NATIVE_ARGUMENT_ENCODING'
return '"'+($Value -replace '(\\+)$','$1$1')+'"'
}
function Invoke-BuildTool([string]$Exe,[string[]]$Arguments,[string]$Label,[int]$Seconds=1800,[bool]$AllowFailure=$false) {
$out=Join-Path $case ($Label+'.stdout');$err=Join-Path $case ($Label+'.stderr')
$quoted=@($Arguments | ForEach-Object {Quoted $_}) -join ' '
$process=Start-Process -FilePath $Exe -ArgumentList $quoted -WorkingDirectory $case -PassThru -WindowStyle Hidden -RedirectStandardOutput $out -RedirectStandardError $err
Write-New (Join-Path $case ($Label+'.started.json')) (@{pid=$process.Id;executable_sha256=(Hash $Exe);label=$Label} | ConvertTo-Json)
if (-not $process.WaitForExit($Seconds*1000)) {
# A compiler/build-script timeout is retained for inspection. No blind
# retry, process-tree kill, service action or installation rollback.
throw 'NATIVE_BUILD_TIMEOUT_PROCESS_STATE_RETAINED'
}
$process.Refresh()
Write-New (Join-Path $case ($Label+'.result.json')) (@{exit_code=$process.ExitCode;stdout_sha256=(Hash $out);stderr_sha256=(Hash $err)} | ConvertTo-Json)
if (-not $AllowFailure) {Require ($process.ExitCode -eq 0) ('BUILD_TOOL_FAILED_'+$Label)}
return $out
}
try {
Require ($env:OS -eq 'Windows_NT' -and [Environment]::Is64BitProcess -and [Environment]::Is64BitOperatingSystem) 'NATIVE_WINDOWS_AMD64_REQUIRED'
Require ($SourceRoot -match '^[A-Za-z]:\\' -and $EvidenceRoot -match '^[A-Za-z]:\\') 'LOCAL_BUILD_DRIVE_REQUIRED'
$SourceRoot=(Get-Item -LiteralPath $SourceRoot).FullName.TrimEnd('\');No-Reparse $SourceRoot
Require ($ScriptFile -eq (Join-Path $SourceRoot 'deploy/windows/Build-NativeMsvc.ps1')) 'RUNNER_FROM_EXACT_SOURCE_BUNDLE_REQUIRED'
Require ($SourceRoot -notmatch '(?i)\\ProgramData\\RustDiscovery|\\Program Files\\RustDiscovery') 'NO_CLIENT_STATE_AS_SOURCE'
if (-not (Test-Path -LiteralPath $EvidenceRoot)) {[void][IO.Directory]::CreateDirectory($EvidenceRoot)}
$EvidenceRoot=(Get-Item -LiteralPath $EvidenceRoot).FullName.TrimEnd('\');No-Reparse $EvidenceRoot
Protected-BuildRoot $EvidenceRoot
Require (-not $EvidenceRoot.StartsWith($SourceRoot+'\',[StringComparison]::OrdinalIgnoreCase) -and
$EvidenceRoot -notmatch '(?i)\\ProgramData\\RustDiscovery|\\Program Files\\RustDiscovery') 'BUILD_EVIDENCE_OUTSIDE_SOURCE_AND_RUNTIME'
$case=Join-Path $EvidenceRoot $CaseId.ToString();New-PrivateDirectory $case
$report.source_root=$SourceRoot;$report.source_files=Source-Files $SourceRoot
Require ([IO.File]::ReadAllText((Join-Path $SourceRoot 'crates/agent-windows/src/clock.rs')) -match
'(?m)^pub const ADAPTER_QUALIFIED: bool = false;\r?$') 'CLOCK_GATE_MUST_REMAIN_CLOSED'
$report.runner_sha256=Hash $ScriptFile
$drive=New-Object IO.DriveInfo([IO.Path]::GetPathRoot($case));$report.free_bytes=$drive.AvailableFreeSpace
$missing=New-Object Collections.Generic.List[string]
if ($drive.AvailableFreeSpace -lt $MinimumFreeGiB*1GB) {$missing.Add('FREE_DISK_BELOW_BOUND')}
foreach ($name in @('CL','_CL_','LINK','_LINK_','RUSTFLAGS','CARGO_ENCODED_RUSTFLAGS','RUSTC_WRAPPER','RUSTC_WORKSPACE_WRAPPER')) {
Require ([string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable($name,'Process'))) 'UNEXPECTED_BUILD_FLAG_OR_WRAPPER'
}
foreach ($name in [Environment]::GetEnvironmentVariables('Process').Keys) {
if ($name -match '^(CFLAGS|CXXFLAGS|CPPFLAGS|LDFLAGS)(_|$)|^CARGO_(BUILD|TARGET_.+)_(RUSTFLAGS|RUSTC_WRAPPER|RUNNER)$') {
Require ([string]::IsNullOrEmpty([Environment]::GetEnvironmentVariable($name,'Process'))) 'UNEXPECTED_NATIVE_BUILD_OVERRIDE'
}
}
$tools=[ordered]@{};$hashes=[ordered]@{}
$tools.cmd=Microsoft-Tool (Join-Path ([Environment]::SystemDirectory) 'cmd.exe')
$vswhere=Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio/Installer/vswhere.exe'
if (-not (Test-Path -LiteralPath $vswhere)) {$missing.Add('VISUAL_STUDIO_BUILD_TOOLS')}
else {
$tools.vswhere=Microsoft-Tool $vswhere
$instances=@(& $vswhere -products '*' -version '[17.14,19.0)' -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -latest -format json | ConvertFrom-Json)
Require ($LASTEXITCODE -eq 0) 'VSWHERE_QUERY_FAILED'
if ($instances.Count -ne 1) {$missing.Add('MSVC_AMD64_WORKLOAD')}
else {
$instance=$instances[0];$report.visual_studio_version=$instance.installationVersion
$batch=Join-Path $instance.installationPath 'VC/Auxiliary/Build/vcvarsall.bat';No-Reparse $batch
Require ($batch -notmatch '[&|<>^%"!\r\n]') 'DEVELOPER_ENVIRONMENT_PATH'
$report.vcvarsall_sha256=Hash $batch
$environment=@(& $tools.cmd.path /d /s /c ('""'+$batch+'" amd64 '+$SdkVersion+' >nul && set"'))
Require ($LASTEXITCODE -eq 0) 'MSVC_SDK_ENVIRONMENT_UNAVAILABLE'
$allowed=@('PATH','INCLUDE','LIB','LIBPATH','WindowsSdkDir','WindowsSDKVersion','VCToolsInstallDir','VSCMD_ARG_TGT_ARCH')
foreach ($line in $environment) {if ($line -match '^([^=]+)=(.*)$' -and $Matches[1] -in $allowed) {Set-BuildEnvironment $Matches[1] $Matches[2]}}
Require ($env:WindowsSDKVersion.TrimEnd('\') -eq $SdkVersion -and $env:VSCMD_ARG_TGT_ARCH -eq 'x64') 'EXACT_AMD64_SDK_ENVIRONMENT'
foreach ($name in @('cl','link','lib','dumpbin')) {
$path=Join-Path $env:VCToolsInstallDir ('bin/Hostx64/x64/'+$name+'.exe');$tools[$name]=Microsoft-Tool $path
}
$midl=Join-Path $env:WindowsSdkDir ('bin/'+$SdkVersion+'/x64/midl.exe');$tools.midl=Microsoft-Tool $midl
$report.sdk_version=$SdkVersion
}
}
$rustup=if ([string]::IsNullOrEmpty($RustupExe)) {Get-Command rustup.exe -CommandType Application -ErrorAction SilentlyContinue}
else {Require (-not [string]::IsNullOrEmpty($RustupHome) -and -not [string]::IsNullOrEmpty($CargoHome)) 'ISOLATED_RUST_HOMES_REQUIRED';
No-Reparse $RustupExe;Protected-BuildRoot $RustupHome;Protected-BuildRoot $CargoHome;
Set-BuildEnvironment 'RUSTUP_HOME' $RustupHome;Set-BuildEnvironment 'CARGO_HOME' $CargoHome;@{Source=(Get-Item -LiteralPath $RustupExe).FullName}}
$report.rustup_home=[Environment]::GetEnvironmentVariable('RUSTUP_HOME','Process')
$report.cargo_home=[Environment]::GetEnvironmentVariable('CARGO_HOME','Process')
if ($null -eq $rustup) {$missing.Add('RUSTUP_AND_PINNED_MSVC_TOOLCHAIN')}
else {
No-Reparse $rustup.Source;$tools.rustup=@{path=$rustup.Source;sha256=(Hash $rustup.Source)}
foreach ($name in @('rustc','cargo','rustdoc','clippy-driver','rustfmt')) {
$label='rustup-which-'+$name
$output=Invoke-BuildTool $rustup.Source @('which','--toolchain',$Toolchain,$name) $label 30 $true
$query=Get-Content -LiteralPath (Join-Path $case ($label+'.result.json')) -Raw | ConvertFrom-Json
$path=@(Get-Content -LiteralPath $output)
if ($query.exit_code -ne 0 -or $path.Count -ne 1 -or -not (Test-Path -LiteralPath $path[0])) {$missing.Add('PINNED_RUST_TOOL_'+$name);continue}
No-Reparse $path[0];$tools[$name]=@{path=$path[0];sha256=(Hash $path[0])}
}
if ($tools.Contains('rustc')) {
$version=@(Get-Content -LiteralPath (Invoke-BuildTool $tools.rustc.path @('-vV') 'rust-version' 30))
Require ('release: 1.99.1' -in $version -and 'host: x86_64-pc-windows-msvc' -in $version) 'PINNED_NATIVE_RUST_VERSION'
$report.rust_version=$version
}
}
foreach ($name in $tools.Keys) {$hashes[$name]=$tools[$name].sha256}
$report.tools=$tools;$report.tool_hashes=$hashes;$report.missing_tools=@($missing);$report.ready=($missing.Count -eq 0)
$report.stage='preflight';Receipt 'preflight.json'
if ($Mode -eq 'Preflight') {Write-Output ('PREFLIGHT ready='+$report.ready+' case='+$CaseId);exit $(if ($report.ready) {0} else {3})}
Require $report.ready 'NATIVE_BUILD_PREREQUISITES_MISSING'
Require (-not [string]::IsNullOrEmpty($ExpectedPreflight)) 'EXPLICIT_PREFLIGHT_RECEIPT_REQUIRED'
No-Reparse $ExpectedPreflight;$expected=Get-Content -LiteralPath $ExpectedPreflight -Raw | ConvertFrom-Json
Require ($expected.ready -eq $true -and $expected.target -eq $Target -and $expected.toolchain -eq $Toolchain -and
$expected.runner_sha256 -eq $report.runner_sha256 -and $expected.rustup_home -eq $report.rustup_home -and
$expected.cargo_home -eq $report.cargo_home) 'EXPECTED_PREFLIGHT_BINDING'
Same-Map $expected.source_files $report.source_files;Same-Map $expected.tool_hashes $hashes
$report.expected_preflight_sha256=Hash $ExpectedPreflight
$snapshot=Join-Path $case 'source';[void][IO.Directory]::CreateDirectory($snapshot)
foreach ($relative in $report.source_files.Keys) {
$destination=Join-Path $snapshot $relative;[void][IO.Directory]::CreateDirectory([IO.Path]::GetDirectoryName($destination))
[IO.File]::Copy((Join-Path $SourceRoot $relative),$destination,$false)
Require ((Hash $destination) -eq $report.source_files[$relative]) 'IMMUTABLE_SOURCE_COPY_CHANGED'
}
Same-Map $expected.source_files (Source-Files $SourceRoot)
Set-BuildEnvironment 'RUSTUP_TOOLCHAIN' $Toolchain;Set-BuildEnvironment 'RUSTC' $tools.rustc.path;Set-BuildEnvironment 'RUSTDOC' $tools.rustdoc.path
Set-BuildEnvironment 'CARGO_TARGET_DIR' (Join-Path $case 'target');Set-BuildEnvironment 'RMM_MIDL_EXE' $tools.midl.path
Set-BuildEnvironment 'CC_x86_64_pc_windows_msvc' $tools.cl.path;Set-BuildEnvironment 'AR_x86_64_pc_windows_msvc' $tools.lib.path
Set-BuildEnvironment 'CARGO_TARGET_X86_64_PC_WINDOWS_MSVC_LINKER' $tools.link.path
$abi=Join-Path $case 'abi';[void][IO.Directory]::CreateDirectory($abi)
[void](Invoke-BuildTool $tools.midl.path @('/nologo','/env','amd64','/Oicf','/robust','/Zp8','/client','stub','/server','none','/h','w32time.h','/cstub','w32time_c.c','/out',$abi,(Join-Path $snapshot 'crates/agent-windows/native/w32time.idl')) 'midl' 60)
$probe=Join-Path $abi 'clock_abi_probe.exe'
[void](Invoke-BuildTool $tools.cl.path @('/nologo','/std:c11','/Zp8','/W4','/WX','/TC',('/I'+$abi),(Join-Path $snapshot 'deploy/windows/msvc/clock_abi_probe.c'),('/Fo'+(Join-Path $abi 'clock_abi_probe.obj')),('/Fe'+$probe),'/link','rpcrt4.lib') 'abi-compile' 60)
$abiOutput=Invoke-BuildTool $probe @() 'abi-seh' 20
$abiResult=Get-Content -LiteralPath $abiOutput -Raw | ConvertFrom-Json
Require ($abiResult.amd64 -eq $true -and $abiResult.numeric_size -eq 64 -and $abiResult.wire_size -eq 120 -and
$abiResult.seh_caught -eq 1722 -and $abiResult.network_called -eq $false) 'NATIVE_MIDL_ABI_OR_SEH_FAILED'
$report.abi_seh_verified=$true;$report.abi_probe_executed=$true;$report.abi_probe_sha256=Hash $probe
$report.generated_rpc=@{header_sha256=(Hash (Join-Path $abi 'w32time.h'));client_sha256=(Hash (Join-Path $abi 'w32time_c.c'))}
$manifest=Join-Path $snapshot 'Cargo.toml'
[void](Invoke-BuildTool $tools.cargo.path @('clippy','--manifest-path',$manifest,'--locked','--offline','--target',$Target,'-p','rmm-agent-windows','--features','system-helper','--all-targets','--','-D','warnings') 'clippy')
[void](Invoke-BuildTool $tools.cargo.path @('build','--manifest-path',$manifest,'--locked','--offline','--target',$Target,'-p','rmm-agent-windows','--features','system-helper','--bins','--examples','--release') 'release')
[void](Invoke-BuildTool $tools.cargo.path @('test','--manifest-path',$manifest,'--locked','--offline','--target',$Target,'-p','rmm-agent-windows','--features','system-helper','--lib','--no-run','--message-format=json') 'windows-unit-link')
[void](Invoke-BuildTool $tools.cargo.path @('test','--manifest-path',$manifest,'--locked','--offline','--target',$Target,'-p','rmm-agent-core','--tests','--no-run','--message-format=json') 'core-unit-link')
$artifacts=[ordered]@{}
foreach ($name in @('rmm-agent-windows','rmm-helper-windows')) {
$path=Join-Path $env:CARGO_TARGET_DIR ($Target+'/release/'+$name+'.exe')
$pe=[IO.File]::ReadAllBytes($path);$offset=[BitConverter]::ToInt32($pe,0x3c)
Require ($pe.Length -gt ($offset+24) -and [BitConverter]::ToUInt16($pe,0) -eq 0x5a4d -and [BitConverter]::ToUInt32($pe,$offset) -eq 0x4550 -and
[BitConverter]::ToUInt16($pe,$offset+4) -eq 0x8664) 'NATIVE_AMD64_PE_REQUIRED'
$dependencies=Invoke-BuildTool $tools.dumpbin.path @('/nologo','/dependents',$path) ($name+'-dependents') 30
$artifacts[$name]=@{path=$path;sha256=(Hash $path);size_bytes=$pe.Length;authenticode_status=[string](Get-AuthenticodeSignature -LiteralPath $path).Status;
dependents_sha256=(Hash $dependencies)}
}
Same-Map $expected.source_files (Source-Files $SourceRoot)
foreach ($name in $tools.Keys) {Require ((Hash $tools[$name].path) -eq $hashes[$name]) 'BUILD_TOOL_CHANGED_DURING_BUILD'}
$report.artifacts=$artifacts;$report.source_before_after_equal=$true;$report.completed=$true;$report.stage='built_not_deployed';Receipt 'result.json'
Write-Output ('PASS native MSVC source build '+$CaseId+'; no runtime installation, clock qualification or RMM job')
} catch {
$report.stage='incomplete';$report.error_class=$_.Exception.GetType().Name
$report.error_code=if ($_.Exception.Message -match '^[A-Z0-9_]{1,96}$') {$_.Exception.Message} else {'BUILD_SETUP_OR_TOOL_FAILED'}
if ($null -ne $case) {try {Receipt ('error-'+[Guid]::NewGuid().ToString()+'.json')} catch {}}
Write-Output ('NATIVE_MSVC_INCOMPLETE case='+$CaseId+'; private receipt retained; no automatic retry')
exit 2
} finally {
foreach ($name in $savedEnvironment.Keys) {[Environment]::SetEnvironmentVariable($name,$savedEnvironment[$name],'Process')}
}