]> vilimpoc.org git repositories - dotfiles/blob - setup-windows-no-uac.ps1
dotfiles: make the Windows setup work natively on ARM64
[dotfiles] / setup-windows-no-uac.ps1
1 <#
2   setup-windows-no-uac.ps1
3   Non-elevated portion of the Windows provisioning. Invoked by setup-windows.bat
4   after its winget installs, or run directly from an ordinary (NOT elevated)
5   prompt:
6
7       powershell -NoProfile -ExecutionPolicy Bypass -File .\setup-windows-no-uac.ps1
8
9   Run it non-elevated on purpose. Every step here writes per-user state - the
10   HKCU PATH and the global .gitconfig under $env:USERPROFILE - so running it
11   elevated would configure the *administrator's* profile instead of yours.
12
13   What this installs / configures:
14     - WinMerge on the user PATH
15     - vswhere.exe on the user PATH: the Visual Studio installer puts it in
16       %ProgramFiles(x86)%\Microsoft Visual Studio\Installer, which nothing adds
17       to the PATH, so build scripts (and VsDevCmd.bat itself) complain that
18       'vswhere.exe' is not recognized
19     - BinSkim (binary hardening analyzer) in %LOCALAPPDATA%\Programs\BinSkim,
20       on the user PATH. The package has no win-arm64 build, so on ARM64 this is
21       the x64 tool under emulation - which analyses ARM64 binaries fine, since it
22       only reads their headers.
23     - Global git identity, and core.sshCommand pointed at a Win32-OpenSSH
24       client so git shares the Windows ssh-agent: the fast ssh.exe the elevated
25       half unpacks beside rsync.exe if it is there, the in-box one otherwise
26     - An architecture audit: the real PE machine type of every tool this box
27       provisions, resolved the way a shell would. Informational, never fatal.
28       Anything running emulated without a listed reason is called out.
29
30   FILL IN $GitUserName / $GitUserEmail below before the first run.
31
32   Steps are independent: one failing warns and the rest still run. The exit code
33   is 1 if any step failed, 0 otherwise.
34 #>
35
36 [CmdletBinding()]
37 param(
38     # Skip individual steps. Note that `powershell -File` cannot pass more than
39     # one value to an array parameter (neither comma- nor space-separated), so
40     # for several, dot-call the script or use -Command:
41     #     .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig
42     #     powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim
43     [ValidateSet('WinMerge', 'VsWhere', 'BinSkim', 'GitConfig', 'ArchAudit')]
44     [string[]] $Skip = @()
45 )
46
47 $ErrorActionPreference = 'Stop'
48
49 # Host architecture. RuntimeInformation rather than PROCESSOR_ARCHITECTURE: an
50 # emulated PowerShell reports the emulated architecture in the environment
51 # variable while this API reports the real one. Values: X64, Arm64, X86.
52 $HostArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()
53 $IsArm64  = ($HostArch -eq 'Arm64')
54
55 # --- Global git identity: FILL THESE IN BEFORE RUNNING ---
56 # Left empty, Set-GlobalGitConfig skips the identity and says so, rather than
57 # stamping a placeholder onto your commits. Leaving them empty is a legitimate
58 # choice - it keeps your identity per-repository. core.sshCommand is set either
59 # way, so the ssh side works regardless.
60 $GitUserName  = ''   # e.g. 'Ada Lovelace'
61 $GitUserEmail = ''   # e.g. 'ada@example.com'
62
63 # BinSkim's win-x64 build, from the NuGet flat container.
64 $BinSkimPackage = 'microsoft.codeanalysis.binskim'
65 $BinSkimDir     = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim'
66
67 # Where the elevated half puts rsync.exe and the ssh.exe it ships with. Only
68 # read here, to prefer that ssh.exe for git - keep it in step with $RsyncDir in
69 # setup-windows-with-uac.ps1 if you move the install.
70 $RsyncDir = 'C:\Tools\rsync'
71
72 function Write-Step([string]$Msg) {
73     Write-Host "`n==> $Msg" -ForegroundColor Cyan
74 }
75
76 function Add-ToUserPath([string]$Dir) {
77     # HKCU PATH, not the process PATH: this must outlive the script. Idempotent,
78     # and re-applied on every run so an entry lost to an unrelated PATH edit is
79     # repaired without re-doing the install that put it there.
80     $user = [Environment]::GetEnvironmentVariable('Path', 'User')
81     if (-not $user) { $user = '' }
82     if (($user -split ';') -contains $Dir) {
83         Write-Host "    $Dir already in user PATH."
84         return
85     }
86     $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir }
87     [Environment]::SetEnvironmentVariable('Path', $new, 'User')
88     Write-Host "    Added $Dir to user PATH (restart your shell to pick it up)."
89 }
90
91 function Add-WinMergeToUserPath {
92     Write-Step 'WinMerge on the user PATH'
93     $candidates = @(
94         (Join-Path $env:ProgramFiles 'WinMerge'),
95         (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'),
96         (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge')
97     )
98     $dir = $candidates |
99            Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } |
100            Select-Object -First 1
101     if (-not $dir) {
102         Write-Warning 'WinMerge not found; user PATH unchanged.'
103         return
104     }
105     Add-ToUserPath $dir
106 }
107
108 function Add-VsWhereToUserPath {
109     # vswhere.exe is how scripts locate Visual Studio (MSBuild, VsDevCmd.bat,
110     # the Windows SDK), and the VS installer drops it in a fixed directory that
111     # is never on the PATH. VsDevCmd.bat itself prints "'vswhere.exe' is not
112     # recognized" on every run without it. The directory is fixed by contract
113     # (32-bit Program Files, no version in the path), so there is nothing to
114     # search for: if it is missing, Visual Studio is not installed.
115     Write-Step 'vswhere on the user PATH'
116     $dir = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer'
117     if (-not (Test-Path (Join-Path $dir 'vswhere.exe'))) {
118         Write-Warning "vswhere.exe not found in $dir (no Visual Studio installer present); user PATH unchanged."
119         return
120     }
121     Add-ToUserPath $dir
122 }
123
124 function Install-BinSkim {
125     # BinSkim checks the exact mitigations the native project enables in
126     # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies,
127     # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained build, so
128     # this needs no .NET SDK/runtime: the .nupkg is a zip - extract the tool
129     # folder for this architecture and put it on the PATH. After restarting the
130     # shell:
131     #     binskim analyze path\to\your.exe
132     #
133     # ARCHITECTURE. The package currently publishes win-x64 only (its other RIDs
134     # are linux-x64, linux-arm64 and osx-x64) - there is no win-arm64 build. So on
135     # ARM64 this installs the x64 tool and it runs under emulation. That is a
136     # slowdown and nothing more: BinSkim READS PE headers and load configs, so the
137     # architecture of the binaries it analyses is independent of its own - an
138     # emulated x64 BinSkim checks ARM64 binaries perfectly well. $BinSkimRids is
139     # ordered preference, so if a win-arm64 build ever ships, an ARM64 box picks
140     # it up with no further change here.
141     #
142     # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so
143     # ask NuGet what the newest stable version is BEFORE fetching anything, and
144     # skip the download entirely when the installed copy already matches.
145     # Re-provisioning an up-to-date box should not pay for it.
146     #
147     # The installed version is recorded in nupkg-version.txt next to the tool.
148     # For a copy installed before that marker existed, fall back to BinSkim.exe's
149     # own ProductVersion; either way the marker is (re)written once we know the
150     # version, so the fallback runs at most once per install. The
151     # flat-container URL pins the exact version we checked,
152     # unlike the v2 /package/<id> endpoint, which just redirects to whatever is
153     # newest at the moment of the request.
154     Write-Step 'BinSkim'
155     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
156
157     $exe    = Join-Path $BinSkimDir 'BinSkim.exe'
158     $marker = Join-Path $BinSkimDir 'nupkg-version.txt'
159
160     $have = $null
161     if (Test-Path $exe) {
162         if (Test-Path $marker) {
163             $have = (Get-Content $marker -Raw).Trim()
164         } else {
165             $pv = (Get-Item $exe).VersionInfo.ProductVersion
166             # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha").
167             if ($pv) { $have = $pv.Split('+')[0].Trim() }
168         }
169     }
170
171     $latest = $null
172     try {
173         $index = Invoke-RestMethod -UseBasicParsing `
174             -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json"
175         # Versions come back oldest-first; '-' marks a prerelease.
176         $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1
177     } catch {
178         Write-Warning "BinSkim version check failed: $($_.Exception.Message)"
179     }
180
181     if (-not $latest) {
182         if (-not $have) {
183             Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.'
184             return
185         }
186         Write-Host "    BinSkim $have kept (could not reach NuGet to check for a newer one)."
187     } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) {
188         Write-Host "    BinSkim $have is already the newest stable release; skipping download."
189         # Records what the ProductVersion fallback just worked out, so the next
190         # run reads the marker instead of re-deriving it.
191         Set-Content -Path $marker -Value $latest -Encoding ascii
192     } else {
193         if ($have) {
194             Write-Host "    BinSkim $have -> $latest; downloading."
195         } else {
196             Write-Host "    BinSkim $latest; downloading."
197         }
198         $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N'))
199         New-Item -ItemType Directory -Force -Path $tmp | Out-Null
200         try {
201             $zip = Join-Path $tmp 'binskim.zip'
202             Invoke-WebRequest -UseBasicParsing -OutFile $zip `
203                 -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg"
204             Expand-Archive -Path $zip -DestinationPath $tmp -Force
205
206             # Native RID first, emulatable one second. Matched against the path
207             # so the newest matching tools\<tfm>\<rid>\ folder wins, as before.
208             $BinSkimRids = if ($IsArm64) { @('win-arm64', 'win-x64') } else { @('win-x64') }
209             $src = $null
210             $allExes = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe'
211             foreach ($rid in $BinSkimRids) {
212                 $src = $allExes | Where-Object { $_.FullName -match [regex]::Escape($rid) } |
213                        Sort-Object FullName | Select-Object -Last 1
214                 if ($src) {
215                     if ($rid -ne $BinSkimRids[0]) {
216                         Write-Host "    No $($BinSkimRids[0]) build in the package; using $rid (runs under emulation)." -ForegroundColor Yellow
217                     }
218                     break
219                 }
220             }
221             if (-not $src) { throw "BinSkim.exe ($($BinSkimRids -join ' / ')) not found in package." }
222
223             # Replace wholesale rather than merging over the old tree, so files
224             # dropped between releases don't linger.
225             if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir }
226             New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null
227             Copy-Item -Path (Join-Path $src.Directory.FullName '*') `
228                       -Destination $BinSkimDir -Recurse -Force
229             # Written last: the marker must only claim a version that fully landed.
230             Set-Content -Path $marker -Value $latest -Encoding ascii
231             Write-Host "    BinSkim $latest installed to $BinSkimDir"
232         } finally {
233             Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
234         }
235     }
236
237     Add-ToUserPath $BinSkimDir
238 }
239
240 function Get-GitPath {
241     # winget installed Git moments ago, but this process inherited its PATH
242     # before that happened, so Get-Command can miss it on a first run. Prefer a
243     # git already on PATH, then the usual install roots.
244     $onPath = Get-Command git.exe -ErrorAction SilentlyContinue
245     if ($onPath) { return $onPath.Source }
246     $roots = @(
247         (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'),
248         (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'),
249         (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe')
250     )
251     return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1
252 }
253
254 function Set-GlobalGitConfig {
255     Write-Step 'Global git config'
256     $git = Get-GitPath
257     if (-not $git) {
258         Write-Warning 'git.exe not found; skipping global git config.'
259         return
260     }
261     Write-Host "    using $git"
262
263     if (-not $GitUserName -or -not $GitUserEmail) {
264         Write-Host '    Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow
265         Write-Host '    Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow
266         Write-Host '    your identity per-repository.' -ForegroundColor Yellow
267     } else {
268         & $git config --global user.name  $GitUserName
269         & $git config --global user.email $GitUserEmail
270         Write-Host "    identity: $GitUserName <$GitUserEmail>"
271     }
272
273     # --- Make git use a Win32-OpenSSH client ---
274     # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client
275     # cannot reach the Windows ssh-agent service that the elevated half enables:
276     # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not
277     # speak. So keys added with `ssh-add` from PowerShell stay invisible to git,
278     # and a push falls back to hunting for a key file and prompting for its
279     # passphrase. Pointing core.sshCommand at a Win32-OpenSSH ssh.exe gives git
280     # the same client, the same agent, and the same %USERPROFILE%\.ssh\config as
281     # `ssh` from an ordinary shell.
282     #
283     # Two of those are on the box, and the one beside rsync.exe is preferred.
284     # It is the same client from the same source, with the same ~/.ssh, agent
285     # and known_hosts, built with a pump on its stdin: the in-box one reads
286     # stdin 3KB at a time, which holds anything git PUSHES to ~17MB/s however
287     # fast the link is. It only exists once the elevated half has run, so the
288     # in-box client stays the fallback - and on a first provisioning run from
289     # setup-windows.bat it is the elevated half that runs first, so the fast one
290     # is normally already there.
291     #
292     # ON ARM64 the preference is the same but the trade is different: that build
293     # is published for x64 only, so it is the EMULATED client being preferred over
294     # a native ARM64 one. It is still the right pick when it runs - a push is
295     # bounded by the socket, not by emulated CPU, so lifting the 3KB stdin cap
296     # wins by far more than emulation costs - but it may well not run at all,
297     # because it links against a System32 libcrypto.dll that is an ARM64 binary
298     # here. That is exactly why candidates are tried by RUNNING them below rather
299     # than by Test-Path, and why the elevated half deletes that ssh.exe outright
300     # when it will not start. Either way this lands on a working client.
301     $sshCandidates = @(
302         (Join-Path $RsyncDir 'ssh.exe'),
303         (Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe')
304     )
305     $winSsh = $null
306     foreach ($cand in $sshCandidates) {
307         if (-not (Test-Path $cand)) { continue }
308         # Run it, rather than just believing the file is there: the build beside
309         # rsync.exe links against the libcrypto.dll the OpenSSH Client capability
310         # puts in System32, and without that capability it is a binary that does
311         # not start. Better to find that out here than on the next `git push`.
312         #
313         # EAP back to Continue for the call: ssh -V writes its version to
314         # STDERR, and with $ErrorActionPreference = 'Stop' a native command's
315         # stderr becomes a terminating RemoteException - so the working client
316         # would look like the broken one.
317         $prevEap = $ErrorActionPreference
318         $ErrorActionPreference = 'Continue'
319         $version = $null
320         # Clear the exit code first, explicitly at global scope. An exe that
321         # cannot start at all - the missing-libcrypto case - throws here without
322         # ever setting one, and the stale 0 from the last native command that DID
323         # run would otherwise read as success. $global: because a bare assignment
324         # would make a local copy that the native call then does not update.
325         $global:LASTEXITCODE = $null
326         try { $version = (& $cand -V 2>&1 | Select-Object -First 1) } catch { }
327         finally { $ErrorActionPreference = $prevEap }
328         if ($LASTEXITCODE -eq 0) { $winSsh = $cand; break }
329         $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" }
330         Write-Warning "$cand did not run ($why)$(if ($version) { ": $version" })"
331     }
332     if (-not $winSsh) {
333         Write-Warning "No working Win32-OpenSSH client found (looked in $($sshCandidates -join ', ')). Add the 'OpenSSH Client' optional feature and re-run; until then git uses its own bundled ssh.exe, which cannot see keys held by the Windows ssh-agent service."
334         return
335     }
336     # Forward slashes on purpose: git parses core.sshCommand with shell quoting
337     # rules, in which a backslash is an escape character.
338     $value = $winSsh -replace '\\', '/'
339     & $git config --global core.sshCommand $value
340     Write-Host "    core.sshCommand: $value"
341     Write-Host "    $version"
342 }
343
344 function Get-PEMachine {
345     # Architecture of a PE, read straight from the COFF header: the 2 bytes at
346     # the e_lfanew offset + 4. Cheap, and it answers the only question that
347     # matters here - would this exe run natively, or through emulation?
348     #
349     # Deliberately NOT Get-Command's .FileVersionInfo or the package metadata:
350     # a multi-architecture package (Sysinternals) ships every build in one zip
351     # under different names, and an installer's own metadata says nothing about
352     # which binary got laid down. The file itself cannot be wrong.
353     param([string]$Path)
354     if (-not (Test-Path $Path)) { return $null }
355     try {
356         $fs = [IO.File]::OpenRead($Path)
357         $br = New-Object IO.BinaryReader($fs)
358         try {
359             $fs.Seek(0x3c, 'Begin') | Out-Null
360             $pe = $br.ReadInt32()
361             if ($pe -le 0 -or $pe -gt ($fs.Length - 6)) { return 'not-PE' }
362             $fs.Seek($pe + 4, 'Begin') | Out-Null
363             switch ($br.ReadUInt16()) {
364                 0x8664  { 'x64' }
365                 0xAA64  { 'ARM64' }
366                 0x014c  { 'x86' }
367                 0x01c4  { 'ARM32' }
368                 default { 'unknown' }
369             }
370         } finally { $br.Close(); $fs.Close() }
371     } catch { $null }
372 }
373
374 function Invoke-ArchAudit {
375     # Report the actual architecture of the tools this box provisions, resolved
376     # the way a shell would (PATH first, then the usual install roots), so what
377     # is printed is what you would really run.
378     #
379     # This exists because "winget installed it" does not mean "you got the native
380     # build", and the gap is not always where you would guess - Visual Studio's
381     # own bundled ninja.exe is x64 even on an ARM64 host. A per-run audit turns
382     # that from something you trip over into something the log tells you.
383     #
384     # Purely informational: it never fails the run. On x64 everything is expected
385     # to be x64 and the output is dull; the value is on ARM64, where each line is
386     # either native or a known, listed exception.
387     Write-Step "Architecture audit (host: $HostArch)"
388
389     # Tools with no native ARM64 build available anywhere, with the reason. These
390     # print as expected rather than as problems - see the README's ARM64 section.
391     $KnownEmulated = @{
392         'BinSkim.exe'          = 'NuGet package publishes win-x64 only; it reads PE headers, so it still analyses ARM64 binaries'
393         'rsync.exe'            = 'no ARM64 asset published; transfer is socket-bound, not CPU-bound'
394         'OpenCppCoverage.exe'  = 'x86/x64 only, and cannot instrument ARM64 binaries - run coverage against the x64 build'
395         'nasm.exe'             = 'x86/x86-64 assembler by definition; ARM64 uses armasm64.exe from MSVC'
396         'iperf3.exe'           = 'no ARM64 build published; network-bound anyway'
397         'py.exe'               = 'python.org ships the launcher shim as x86; it execs the native python.exe'
398         'vswhere.exe'          = 'Microsoft ships x86 only; runs once per script'
399     }
400
401     # Fixable cases: a native build DOES exist, something just resolved ahead of
402     # it. Printed with the finding so the log carries the remedy, not just the
403     # complaint.
404     #
405     # ninja is the one that actually bites. Visual Studio bundles an x64 ninja.exe
406     # even on ARM64, and VsDevCmd.bat PREPENDS the VS directories to PATH - so
407     # inside a Developer Command Prompt the emulated one wins over the native
408     # winget copy, and that is exactly the shell C++ builds happen in. It matters
409     # more than a one-off tool because ninja is re-invoked for every edge in the
410     # build graph.
411     $Remedies = @{
412         'ninja.exe'    = 'Visual Studio bundles an x64 ninja and VsDevCmd prepends its directory. Pass -DCMAKE_MAKE_PROGRAM to the native one (winget install Ninja-build.Ninja), or put its directory ahead of the VS one.'
413         'cmake.exe'    = 'Install the native build with: winget install Kitware.CMake'
414         'clang-cl.exe' = 'Install the upstream native LLVM with: winget install LLVM.LLVM'
415     }
416
417     $vs = $null
418     $vsWhereExe = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
419     if (Test-Path $vsWhereExe) {
420         $vs = & $vsWhereExe -products '*' -property installationPath -format value | Select-Object -First 1
421     }
422
423     # name -> extra candidate paths searched when the name is not on the PATH.
424     $targets = [ordered]@{
425         'git.exe'             = @("$env:LOCALAPPDATA\Programs\Git\cmd\git.exe", (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'))
426         'python.exe'          = @()
427         'py.exe'              = @("$env:WINDIR\py.exe")
428         'pwsh.exe'            = @()
429         'cmake.exe'           = @((Join-Path $env:ProgramFiles 'CMake\bin\cmake.exe'))
430         'ninja.exe'           = @()
431         'clang-cl.exe'        = @((Join-Path $env:ProgramFiles 'LLVM\bin\clang-cl.exe'))
432         'dotnet.exe'          = @((Join-Path $env:ProgramFiles 'dotnet\dotnet.exe'))
433         'WinMergeU.exe'       = @((Join-Path $env:ProgramFiles 'WinMerge\WinMergeU.exe'), (Join-Path ${env:ProgramFiles(x86)} 'WinMerge\WinMergeU.exe'))
434         'BinSkim.exe'         = @((Join-Path $BinSkimDir 'BinSkim.exe'))
435         'rsync.exe'           = @((Join-Path $RsyncDir 'rsync.exe'))
436         'ssh.exe'             = @((Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe'))
437         'nasm.exe'            = @()
438         'iperf3.exe'          = @()
439         'OpenCppCoverage.exe' = @((Join-Path $env:ProgramFiles 'OpenCppCoverage\OpenCppCoverage.exe'), (Join-Path ${env:ProgramFiles(x86)} 'OpenCppCoverage\OpenCppCoverage.exe'))
440         'vswhere.exe'         = @($vsWhereExe)
441         'xperf.exe'           = @((Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'))
442     }
443     if ($vs) {
444         $targets['MSBuild.exe'] = @((Join-Path $vs 'MSBuild\Current\Bin\arm64\MSBuild.exe'), (Join-Path $vs 'MSBuild\Current\Bin\MSBuild.exe'))
445         # The MSVC and VS-Clang compilers, under whichever MSVC version is present.
446         $msvc = Get-ChildItem (Join-Path $vs 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |
447                 Sort-Object Name | Select-Object -Last 1
448         if ($msvc) {
449             $hostDir = if ($IsArm64) { 'Hostarm64\arm64' } else { 'Hostx64\x64' }
450             $targets['cl.exe (MSVC)'] = @((Join-Path $msvc.FullName "bin\$hostDir\cl.exe"))
451         }
452         $llvmHost = if ($IsArm64) { 'ARM64\bin' } else { 'x64\bin' }
453         $targets['clang-cl.exe (VS)'] = @((Join-Path $vs "VC\Tools\Llvm\$llvmHost\clang-cl.exe"))
454     }
455
456     $native = if ($IsArm64) { 'ARM64' } else { 'x64' }
457     $unexpected = @()
458     foreach ($name in $targets.Keys) {
459         # PATH first - that is the binary a build would actually invoke - then the
460         # explicit candidates. The bare exe name is stripped of any " (label)".
461         $exe = ($name -split ' ')[0]
462         $path = (Get-Command $exe -ErrorAction SilentlyContinue |
463                  Select-Object -First 1).Source
464         if (-not $path) { $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 }
465         if (-not $path) { Write-Host ("    {0,-22} {1}" -f $name, '- not installed') -ForegroundColor DarkGray; continue }
466
467         $mach = Get-PEMachine $path
468         if (-not $mach) { continue }
469         if ($mach -eq $native) {
470             Write-Host ("    {0,-22} {1,-6} native" -f $name, $mach) -ForegroundColor Green
471         } elseif ($KnownEmulated.ContainsKey($exe)) {
472             Write-Host ("    {0,-22} {1,-6} expected: {2}" -f $name, $mach, $KnownEmulated[$exe]) -ForegroundColor DarkGray
473         } else {
474             Write-Host ("    {0,-22} {1,-6} NOT NATIVE - $path" -f $name, $mach) -ForegroundColor Yellow
475             if ($Remedies.ContainsKey($exe)) {
476                 Write-Host ("    {0,-22} {1,-6} -> {2}" -f '', '', $Remedies[$exe]) -ForegroundColor Yellow
477             }
478             $unexpected += "$name ($mach)"
479         }
480     }
481
482     if ($unexpected) {
483         Write-Warning "Running under emulation with no listed reason: $($unexpected -join ', ')."
484         Write-Warning 'If a native build exists, prefer it (see the -> lines above); otherwise add it to $KnownEmulated with the reason.'
485     } else {
486         Write-Host '    Everything resolved to a native build, or to a listed exception.' -ForegroundColor Green
487     }
488 }
489
490 # ---------------------------------------------------------------------------
491 # Main
492 # ---------------------------------------------------------------------------
493 Write-Host "Host architecture: $HostArch" -ForegroundColor Cyan
494
495 if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
496         [Security.Principal.WindowsBuiltInRole]::Administrator)) {
497     Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.'
498 }
499
500 $steps = [ordered]@{
501     WinMerge  = { Add-WinMergeToUserPath }
502     VsWhere   = { Add-VsWhereToUserPath }
503     BinSkim   = { Install-BinSkim }
504     GitConfig = { Set-GlobalGitConfig }
505     # Last on purpose: it reports on what the steps above (and the winget installs
506     # in setup-windows.bat) actually put on the box.
507     ArchAudit = { Invoke-ArchAudit }
508 }
509
510 $failed = @()
511 foreach ($name in $steps.Keys) {
512     if ($Skip -contains $name) {
513         Write-Host "`n==> $name (skipped)" -ForegroundColor DarkGray
514         continue
515     }
516     try {
517         & $steps[$name]
518     } catch {
519         # One broken step must not cost the others. Collect and report at the end.
520         Write-Warning "$name failed: $($_.Exception.Message)"
521         $failed += $name
522     }
523 }
524
525 if ($failed) {
526     Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red
527     exit 1
528 }
529 Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green
530 exit 0