]> vilimpoc.org git repositories - dotfiles/blob - setup-windows-no-uac.ps1
dotfiles: add Android Studio, and a per-user Android SDK
[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 (x64 only)
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 (x64 only - the NuGet package publishes win-x64 alone)
21     - Global git identity, and core.sshCommand pointed at a Win32-OpenSSH
22       client so git shares the Windows ssh-agent: the fast ssh.exe the elevated
23       half unpacks beside rsync.exe if it is there, the in-box one otherwise
24     - Rust's stable MSVC toolchain for this host - x86_64 on x64, aarch64 on
25       ARM64 - installed through rustup and made the default
26     - The Android SDK, per-user in %LOCALAPPDATA%\Android\Sdk (x64 only): the
27       command-line tools, platform-tools and the newest stable platform and
28       build-tools, SDK licences accepted, ANDROID_HOME set - and JAVA_HOME, to
29       Android Studio's bundled JDK, when there is none
30     - An architecture audit: the real PE machine type of every tool this box
31       provisions, resolved the way a shell would. Informational, never fatal.
32       Anything running emulated without a listed reason is called out.
33
34   FILL IN $GitUserName / $GitUserEmail below before the first run.
35
36   The steps are the 'user' rows of setup-windows-steps.ps1. The batch file runs
37   this with -Only <the steps its plan left selected> -Yes, having already asked.
38   Run by hand, it lists what it will do and asks before doing any of it; -Only
39   and -Skip pick steps, and -Yes skips the question.
40
41   Steps are independent: one failing warns and the rest still run. The exit code
42   is 1 if any step failed, 2 if there was no console to ask on (re-run with
43   -Yes), 0 otherwise.
44 #>
45
46 [CmdletBinding()]
47 param(
48     # Steps to take (-Only) or leave out (-Skip), by the names the plan shows.
49     # For several, separate them with commas. `powershell -File` hands "A,B" to
50     # an array parameter as ONE string, so it is split here and either way works:
51     #     .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig
52     #     powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig
53     [string[]] $Only,
54     [string[]] $Skip = @(),
55     # Do not ask first. setup-windows.bat passes it, having asked already.
56     [switch]   $Yes
57 )
58
59 $ErrorActionPreference = 'Stop'
60
61 # Host architecture, from the machine environment in the registry. Both of the
62 # obvious sources report the EMULATED architecture inside an emulated x64
63 # PowerShell - which is what `powershell` resolves to when launched from an x64
64 # shell on an ARM64 box. Measured on this machine:
65 #     [RuntimeInformation]::OSArchitecture      X64     <- wrong
66 #     $env:PROCESSOR_ARCHITECTURE               AMD64   <- wrong
67 #     HKLM\...\Session Manager\Environment      ARM64   <- right
68 # OSArchitecture is documented as the OS's architecture, and on .NET Core it is;
69 # under .NET Framework on Prism it is not, so it is kept only as a fallback.
70 # $IsArm64 decides which steps run at all, so this has to be the real one.
71 $rawArch  = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -ErrorAction SilentlyContinue).PROCESSOR_ARCHITECTURE
72 if (-not $rawArch) { $rawArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() }
73 $IsArm64  = ($rawArch -eq 'ARM64')
74 $HostArch = if ($IsArm64) { 'Arm64' } elseif ($rawArch -eq 'AMD64') { 'X64' } else { $rawArch }
75
76 # Steps that do not run on ARM64 - WinMergePath, BinSkim and LlvmPath - are
77 # marked -X64Only, with the reason, in setup-windows-steps.ps1. The plan printed
78 # before anything runs shows each of them with that reason.
79 #
80 # The ARM64 machine is provisioned as a single-compiler build box, so the
81 # packages these three steps wire up are not installed there. Skipping the step
82 # rather than letting it find nothing matters: Install-BinSkim would happily
83 # download and PATH the x64 build, and Add-LlvmToUserPath is the step that put an
84 # emulated-adjacent toolchain on the PATH ahead of MSVC in the first place.
85 #
86 # -Only and -Skip work on top of this; they can only subtract.
87 . (Join-Path $PSScriptRoot 'setup-windows-steps.ps1')
88
89 # --- Global git identity: FILL THESE IN BEFORE RUNNING ---
90 # Left empty, Set-GlobalGitConfig skips the identity and says so, rather than
91 # stamping a placeholder onto your commits. Leaving them empty is a legitimate
92 # choice - it keeps your identity per-repository. core.sshCommand is set either
93 # way, so the ssh side works regardless.
94 $GitUserName  = ''   # e.g. 'Ada Lovelace'
95 $GitUserEmail = ''   # e.g. 'ada@example.com'
96
97 # BinSkim's win-x64 build, from the NuGet flat container.
98 $BinSkimPackage = 'microsoft.codeanalysis.binskim'
99 $BinSkimDir     = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim'
100
101 # Where the elevated half puts rsync.exe and the ssh.exe it ships with. Only
102 # read here, to prefer that ssh.exe for git - keep it in step with $RsyncDir in
103 # setup-windows-with-uac.ps1 if you move the install.
104 $RsyncDir = 'C:\Tools\rsync'
105
106 # Where rustup keeps itself (.cargo) and its toolchains (.rustup): rustup-init's
107 # own defaults, unless CARGO_HOME / RUSTUP_HOME say otherwise. The host triple is
108 # the one Rust toolchain this box is set up with - see Set-RustDefaultToolchain.
109 $CargoHome  = if ($env:CARGO_HOME)  { $env:CARGO_HOME }  else { Join-Path $env:USERPROFILE '.cargo' }
110 $RustupHome = if ($env:RUSTUP_HOME) { $env:RUSTUP_HOME } else { Join-Path $env:USERPROFILE '.rustup' }
111 $RustHost   = switch ($HostArch) {
112     'Arm64' { 'aarch64-pc-windows-msvc' }
113     'X64'   { 'x86_64-pc-windows-msvc' }
114     default { $null }
115 }
116
117 # The Android SDK: where Android Studio puts it by default, unless ANDROID_HOME
118 # already names one. "Latest" is read from Google's package index at run time,
119 # the same index sdkmanager and Android Studio's SDK Manager read.
120 $AndroidSdkRoot = if ($env:ANDROID_HOME) { $env:ANDROID_HOME } else { Join-Path $env:LOCALAPPDATA 'Android\Sdk' }
121 $AndroidRepo    = 'https://dl.google.com/android/repository/'
122 $AndroidIndex   = $AndroidRepo + 'repository2-3.xml'
123
124 function Write-Step([string]$Msg) {
125     Write-Host "`n==> $Msg" -ForegroundColor Cyan
126 }
127
128 function Add-ToUserPath {
129     # HKCU PATH, not the process PATH: this must outlive the script. Idempotent,
130     # and re-applied on every run so an entry lost to an unrelated PATH edit is
131     # repaired without re-doing the install that put it there.
132     #
133     # -Prepend puts the directory FIRST and moves it there if it is already
134     # present further down, which is the difference between "on the PATH" and
135     # "the one that wins". Only for entries where that matters; appending is the
136     # polite default and stays the default.
137     param(
138         [string] $Dir,
139         [switch] $Prepend
140     )
141     $user = [Environment]::GetEnvironmentVariable('Path', 'User')
142     if (-not $user) { $user = '' }
143     # Compare trailing-backslash-insensitively: C:\x and C:\x\ are the same
144     # directory, and adding a second spelling of one is just noise.
145     $norm    = { param($s) $s.Trim().TrimEnd('\') }
146     $entries = @($user -split ';' | Where-Object { $_.Trim() })
147     $already = $entries | Where-Object { (& $norm $_) -eq (& $norm $Dir) }
148
149     if (-not $Prepend) {
150         if ($already) { Write-Host "    $Dir already in user PATH."; return }
151         $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir }
152         [Environment]::SetEnvironmentVariable('Path', $new, 'User')
153         Write-Host "    Added $Dir to user PATH (restart your shell to pick it up)."
154         return
155     }
156
157     if ($already -and (& $norm $entries[0]) -eq (& $norm $Dir)) {
158         Write-Host "    $Dir already first in user PATH."
159         return
160     }
161     $rest = $entries | Where-Object { (& $norm $_) -ne (& $norm $Dir) }
162     [Environment]::SetEnvironmentVariable('Path', (@($Dir) + $rest) -join ';', 'User')
163     if ($already) {
164         Write-Host "    Moved $Dir to the front of the user PATH (restart your shell to pick it up)."
165     } else {
166         Write-Host "    Added $Dir to the front of the user PATH (restart your shell to pick it up)."
167     }
168 }
169
170 function Add-WinMergeToUserPath {
171     Write-Step 'WinMerge on the user PATH'
172     $candidates = @(
173         (Join-Path $env:ProgramFiles 'WinMerge'),
174         (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'),
175         (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge')
176     )
177     $dir = $candidates |
178            Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } |
179            Select-Object -First 1
180     if (-not $dir) {
181         Write-Warning 'WinMerge not found; user PATH unchanged.'
182         return
183     }
184     Add-ToUserPath $dir
185 }
186
187 function Add-VsWhereToUserPath {
188     # vswhere.exe is how scripts locate Visual Studio (MSBuild, VsDevCmd.bat,
189     # the Windows SDK), and the VS installer drops it in a fixed directory that
190     # is never on the PATH. VsDevCmd.bat itself prints "'vswhere.exe' is not
191     # recognized" on every run without it. The directory is fixed by contract
192     # (32-bit Program Files, no version in the path), so there is nothing to
193     # search for: if it is missing, Visual Studio is not installed.
194     Write-Step 'vswhere on the user PATH'
195     $dir = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer'
196     if (-not (Test-Path (Join-Path $dir 'vswhere.exe'))) {
197         Write-Warning "vswhere.exe not found in $dir (no Visual Studio installer present); user PATH unchanged."
198         return
199     }
200     Add-ToUserPath $dir
201 }
202
203 function Install-BinSkim {
204     # BinSkim checks the exact mitigations the native project enables in
205     # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies,
206     # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained build, so
207     # this needs no .NET SDK/runtime: the .nupkg is a zip - extract the tool
208     # folder for this architecture and put it on the PATH. After restarting the
209     # shell:
210     #     binskim analyze path\to\your.exe
211     #
212     # ARCHITECTURE. The package currently publishes win-x64 only (its other RIDs
213     # are linux-x64, linux-arm64 and osx-x64) - there is no win-arm64 build. So on
214     # ARM64 this installs the x64 tool and it runs under emulation. That is a
215     # slowdown and nothing more: BinSkim READS PE headers and load configs, so the
216     # architecture of the binaries it analyses is independent of its own - an
217     # emulated x64 BinSkim checks ARM64 binaries perfectly well. $BinSkimRids is
218     # ordered preference, so if a win-arm64 build ever ships, an ARM64 box picks
219     # it up with no further change here.
220     #
221     # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so
222     # ask NuGet what the newest stable version is BEFORE fetching anything, and
223     # skip the download entirely when the installed copy already matches.
224     # Re-provisioning an up-to-date box should not pay for it.
225     #
226     # The installed version is recorded in nupkg-version.txt next to the tool.
227     # For a copy installed before that marker existed, fall back to BinSkim.exe's
228     # own ProductVersion; either way the marker is (re)written once we know the
229     # version, so the fallback runs at most once per install. The
230     # flat-container URL pins the exact version we checked,
231     # unlike the v2 /package/<id> endpoint, which just redirects to whatever is
232     # newest at the moment of the request.
233     Write-Step 'BinSkim'
234     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
235     # No progress bar: Windows PowerShell 5.1 redraws it per chunk, and on a
236     # download this size that, not the network, is the wait - see
237     # Install-AndroidSdk for the measurement. Local to this function.
238     $ProgressPreference = 'SilentlyContinue'
239
240     $exe    = Join-Path $BinSkimDir 'BinSkim.exe'
241     $marker = Join-Path $BinSkimDir 'nupkg-version.txt'
242
243     $have = $null
244     if (Test-Path $exe) {
245         if (Test-Path $marker) {
246             $have = (Get-Content $marker -Raw).Trim()
247         } else {
248             $pv = (Get-Item $exe).VersionInfo.ProductVersion
249             # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha").
250             if ($pv) { $have = $pv.Split('+')[0].Trim() }
251         }
252     }
253
254     $latest = $null
255     try {
256         $index = Invoke-RestMethod -UseBasicParsing `
257             -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json"
258         # Versions come back oldest-first; '-' marks a prerelease.
259         $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1
260     } catch {
261         Write-Warning "BinSkim version check failed: $($_.Exception.Message)"
262     }
263
264     if (-not $latest) {
265         if (-not $have) {
266             Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.'
267             return
268         }
269         Write-Host "    BinSkim $have kept (could not reach NuGet to check for a newer one)."
270     } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) {
271         Write-Host "    BinSkim $have is already the newest stable release; skipping download."
272         # Records what the ProductVersion fallback just worked out, so the next
273         # run reads the marker instead of re-deriving it.
274         Set-Content -Path $marker -Value $latest -Encoding ascii
275     } else {
276         if ($have) {
277             Write-Host "    BinSkim $have -> $latest; downloading."
278         } else {
279             Write-Host "    BinSkim $latest; downloading."
280         }
281         $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N'))
282         New-Item -ItemType Directory -Force -Path $tmp | Out-Null
283         try {
284             $zip = Join-Path $tmp 'binskim.zip'
285             Invoke-WebRequest -UseBasicParsing -OutFile $zip `
286                 -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg"
287             Expand-Archive -Path $zip -DestinationPath $tmp -Force
288
289             # Native RID first, emulatable one second. Matched against the path
290             # so the newest matching tools\<tfm>\<rid>\ folder wins, as before.
291             $BinSkimRids = if ($IsArm64) { @('win-arm64', 'win-x64') } else { @('win-x64') }
292             $src = $null
293             $allExes = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe'
294             foreach ($rid in $BinSkimRids) {
295                 $src = $allExes | Where-Object { $_.FullName -match [regex]::Escape($rid) } |
296                        Sort-Object FullName | Select-Object -Last 1
297                 if ($src) {
298                     if ($rid -ne $BinSkimRids[0]) {
299                         Write-Host "    No $($BinSkimRids[0]) build in the package; using $rid (runs under emulation)." -ForegroundColor Yellow
300                     }
301                     break
302                 }
303             }
304             if (-not $src) { throw "BinSkim.exe ($($BinSkimRids -join ' / ')) not found in package." }
305
306             # Replace wholesale rather than merging over the old tree, so files
307             # dropped between releases don't linger.
308             if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir }
309             New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null
310             Copy-Item -Path (Join-Path $src.Directory.FullName '*') `
311                       -Destination $BinSkimDir -Recurse -Force
312             # Written last: the marker must only claim a version that fully landed.
313             Set-Content -Path $marker -Value $latest -Encoding ascii
314             Write-Host "    BinSkim $latest installed to $BinSkimDir"
315         } finally {
316             Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
317         }
318     }
319
320     Add-ToUserPath $BinSkimDir
321 }
322
323 function Get-GitPath {
324     # winget installed Git moments ago, but this process inherited its PATH
325     # before that happened, so Get-Command can miss it on a first run. Prefer a
326     # git already on PATH, then the usual install roots.
327     $onPath = Get-Command git.exe -ErrorAction SilentlyContinue
328     if ($onPath) { return $onPath.Source }
329     $roots = @(
330         (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'),
331         (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'),
332         (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe')
333     )
334     return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1
335 }
336
337 function Set-GlobalGitConfig {
338     Write-Step 'Global git config'
339     $git = Get-GitPath
340     if (-not $git) {
341         Write-Warning 'git.exe not found; skipping global git config.'
342         return
343     }
344     Write-Host "    using $git"
345
346     if (-not $GitUserName -or -not $GitUserEmail) {
347         Write-Host '    Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow
348         Write-Host '    Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow
349         Write-Host '    your identity per-repository.' -ForegroundColor Yellow
350     } else {
351         & $git config --global user.name  $GitUserName
352         & $git config --global user.email $GitUserEmail
353         Write-Host "    identity: $GitUserName <$GitUserEmail>"
354     }
355
356     # --- Make git use a Win32-OpenSSH client ---
357     # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client
358     # cannot reach the Windows ssh-agent service that the elevated half enables:
359     # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not
360     # speak. So keys added with `ssh-add` from PowerShell stay invisible to git,
361     # and a push falls back to hunting for a key file and prompting for its
362     # passphrase. Pointing core.sshCommand at a Win32-OpenSSH ssh.exe gives git
363     # the same client, the same agent, and the same %USERPROFILE%\.ssh\config as
364     # `ssh` from an ordinary shell.
365     #
366     # Two of those are on the box, and the one beside rsync.exe is preferred.
367     # It is the same client from the same source, with the same ~/.ssh, agent
368     # and known_hosts, built with a pump on its stdin: the in-box one reads
369     # stdin 3KB at a time, which holds anything git PUSHES to ~17MB/s however
370     # fast the link is. It only exists once the elevated half has run, so the
371     # in-box client stays the fallback - and on a first provisioning run from
372     # setup-windows.bat it is the elevated half that runs first, so the fast one
373     # is normally already there.
374     #
375     # ON ARM64 the preference is the same but the trade is different: that build
376     # is published for x64 only, so it is the EMULATED client being preferred over
377     # a native ARM64 one. It is still the right pick when it runs - a push is
378     # bounded by the socket, not by emulated CPU, so lifting the 3KB stdin cap
379     # wins by far more than emulation costs - but it may well not run at all,
380     # because it links against a System32 libcrypto.dll that is an ARM64 binary
381     # here. That is exactly why candidates are tried by RUNNING them below rather
382     # than by Test-Path, and why the elevated half deletes that ssh.exe outright
383     # when it will not start. Either way this lands on a working client.
384     $sshCandidates = @(
385         (Join-Path $RsyncDir 'ssh.exe'),
386         (Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe')
387     )
388     $winSsh = $null
389     foreach ($cand in $sshCandidates) {
390         if (-not (Test-Path $cand)) { continue }
391         # Run it, rather than just believing the file is there: the build beside
392         # rsync.exe links against the libcrypto.dll the OpenSSH Client capability
393         # puts in System32, and without that capability it is a binary that does
394         # not start. Better to find that out here than on the next `git push`.
395         #
396         # EAP back to Continue for the call: ssh -V writes its version to
397         # STDERR, and with $ErrorActionPreference = 'Stop' a native command's
398         # stderr becomes a terminating RemoteException - so the working client
399         # would look like the broken one.
400         $prevEap = $ErrorActionPreference
401         $ErrorActionPreference = 'Continue'
402         $version = $null
403         # Clear the exit code first, explicitly at global scope. An exe that
404         # cannot start at all - the missing-libcrypto case - throws here without
405         # ever setting one, and the stale 0 from the last native command that DID
406         # run would otherwise read as success. $global: because a bare assignment
407         # would make a local copy that the native call then does not update.
408         $global:LASTEXITCODE = $null
409         # Collect ALL the output, THEN take its first line. Piped straight into
410         # `Select-Object -First 1`, which is how this used to read, PowerShell
411         # stops the pipeline the moment ssh.exe prints its banner - before it
412         # has exited - kills it, and the exit code comes back -1 instead of 0.
413         # Measured under Windows PowerShell 5.1 against a healthy
414         # C:\Tools\rsync\ssh.exe: 19 of 20 runs reported -1 that way, 0 of 20
415         # once collected first. So this check usually judged the fast client
416         # broken and handed git the in-box one it exists to avoid.
417         # setup-windows-with-uac.ps1 fixed the same trap in its own ssh.exe
418         # check (see DRAIN THE OUTPUT there); this copy was missed.
419         try { $sshOut = @(& $cand -V 2>&1); $version = $sshOut[0] } catch { }
420         finally { $ErrorActionPreference = $prevEap }
421         if ($LASTEXITCODE -eq 0) { $winSsh = $cand; break }
422         $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" }
423         Write-Warning "$cand did not run ($why)$(if ($version) { ": $version" })"
424     }
425     if (-not $winSsh) {
426         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."
427         return
428     }
429     # Forward slashes on purpose: git parses core.sshCommand with shell quoting
430     # rules, in which a backslash is an escape character.
431     $value = $winSsh -replace '\\', '/'
432     & $git config --global core.sshCommand $value
433     Write-Host "    core.sshCommand: $value"
434     Write-Host "    $version"
435 }
436
437 function Set-NativeNinjaFirst {
438     # Make the native ninja.exe the one that wins, including inside a Visual
439     # Studio Developer Command Prompt.
440     #
441     # WHY THIS IS INSURANCE RATHER THAN THE FIX. VS ships an x64 ninja.exe even on
442     # ARM64 and puts it on the PATH from
443     # Common7\Tools\vsdevcmd\ext\cmake.bat, which does:
444     #     set "PATH=%PATH%;...\CMake\bin;...\CMake\Ninja"
445     # That APPENDS - the VS directories land at the very end of the composed
446     # PATH, behind every machine and user entry. So a native ninja installed
447     # anywhere on the user PATH already beats it, and measurement on an ARM64 box
448     # confirms it does. (An earlier revision of this script claimed VsDevCmd
449     # prepends and that the VS copy therefore always won; that was wrong.)
450     #
451     # It is still worth pinning the order explicitly: winget appends its package
452     # directory to the user PATH, so the margin depends on nothing more than two
453     # append orders staying as they are, in a file Microsoft owns and revises.
454     # Putting the directory first costs nothing and removes the dependency.
455     #
456     # Ninja is worth this attention where a one-off tool would not be: it is
457     # re-invoked for every edge in the build graph, so it is the one place an
458     # emulated binary is paid over and over rather than once.
459     Write-Step 'Native ninja ahead of the Visual Studio copy'
460
461     $candidates = @()
462     $candidates += Get-ChildItem (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages') `
463                        -Filter 'ninja.exe' -Recurse -Depth 2 -ErrorAction SilentlyContinue |
464                    ForEach-Object { $_.FullName }
465     $candidates += @(
466         (Join-Path $env:ProgramFiles 'Ninja\ninja.exe')
467         (Join-Path $env:LOCALAPPDATA 'Programs\Ninja\ninja.exe')
468     )
469     # A ninja already on the PATH counts too - but only if it is not the VS one,
470     # which is the binary this step exists to get out in front of.
471     $onPath = (Get-Command ninja.exe -ErrorAction SilentlyContinue | Select-Object -First 1).Source
472     if ($onPath -and $onPath -notmatch 'CommonExtensions\\Microsoft\\CMake') { $candidates += $onPath }
473
474     $native = $null
475     foreach ($c in ($candidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique)) {
476         $m = Get-PEMachine $c
477         if ($m -eq $(if ($IsArm64) { 'ARM64' } else { 'x64' })) { $native = $c; break }
478     }
479
480     if (-not $native) {
481         Write-Warning 'No native ninja.exe found. Install it with: winget install Ninja-build.Ninja'
482         Write-Warning 'Until then a build using the Ninja generator gets the x64 ninja Visual Studio bundles.'
483         return
484     }
485
486     Write-Host "    native ninja: $native ($(Get-PEMachine $native))"
487     Add-ToUserPath (Split-Path $native -Parent) -Prepend
488 }
489
490 function Add-LlvmToUserPath {
491     # Put the upstream LLVM's bin directory on the user PATH.
492     #
493     # Two reasons this needs a step rather than trusting the installer:
494     #
495     # 1. WHERE IT LANDS. LLVM's NSIS installer targets %ProgramFiles%\LLVM, and
496     #    when it cannot write there - a standard user, no elevation - it does not
497     #    fail. It silently falls back to a per-user directory, observed as
498     #    %USERPROFILE%\Documents\LLVM, and winget still reports "Successfully
499     #    installed". So the package is registered, the compiler is genuinely
500     #    there and native, and nothing can find it.
501     # 2. PATH. The installer's "add to PATH" option is not taken in a silent
502     #    install, so clang-cl is not a command afterwards either way.
503     #
504     # Appended, not prepended: this is a second compiler kept deliberately
505     # alongside MSVC, and it should not quietly win a `clang-cl` that some script
506     # meant for Visual Studio's copy. Note VS does NOT put its own
507     # VC\Tools\Llvm on the PATH (its clang-cl is reached through CMake's
508     # -T ClangCL), so there is no collision to lose here.
509     Write-Step 'Upstream LLVM on the user PATH'
510     $candidates = @(
511         (Join-Path $env:ProgramFiles 'LLVM\bin')
512         (Join-Path ${env:ProgramFiles(x86)} 'LLVM\bin')
513         (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin')
514         (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin')
515         (Join-Path $env:USERPROFILE 'Documents\LLVM\bin')
516     )
517     $dir = $candidates | Where-Object { Test-Path (Join-Path $_ 'clang-cl.exe') } | Select-Object -First 1
518     if (-not $dir) {
519         Write-Host '    Not installed (winget install LLVM.LLVM); Visual Studio''s own clang-cl is unaffected.' -ForegroundColor DarkGray
520         return
521     }
522     $exe  = Join-Path $dir 'clang-cl.exe'
523     $mach = Get-PEMachine $exe
524     Write-Host "    $exe ($mach)"
525     if ($IsArm64 -and $mach -ne 'ARM64') {
526         Write-Warning "This LLVM is $mach, not ARM64. winget install LLVM.LLVM should resolve to the -woa64 build on this host."
527     }
528     if ($dir -notmatch [regex]::Escape($env:ProgramFiles)) {
529         Write-Host '    Note: not under Program Files - the installer fell back to a per-user' -ForegroundColor Yellow
530         Write-Host '    location because it could not write there. Re-run elevated for a machine-wide install.' -ForegroundColor Yellow
531     }
532     Add-ToUserPath $dir
533 }
534
535 function Get-RustupPath {
536     # winget installed rustup moments ago, but this process inherited its PATH
537     # before rustup-init added .cargo\bin to it, so Get-Command can miss it on a
538     # first run. Prefer one already on the PATH, then the cargo home.
539     $onPath = Get-Command rustup.exe -ErrorAction SilentlyContinue
540     if ($onPath) { return $onPath.Source }
541     $exe = Join-Path $CargoHome 'bin\rustup.exe'
542     if (Test-Path $exe) { return $exe }
543     $null
544 }
545
546 function Set-RustDefaultToolchain {
547     # Install Rust's stable MSVC toolchain for THIS host and make it the default:
548     # stable-x86_64-pc-windows-msvc on x64, stable-aarch64-pc-windows-msvc on
549     # ARM64.
550     #
551     # winget's rustup install mostly does this already - it runs
552     # `rustup-init -y -q`, which installs stable for the host rustup detects - so
553     # on a fresh box this step largely confirms it. It exists to make the answer
554     # explicit rather than inherited. rustup takes its default host from its own
555     # build, so an x64 rustup on an ARM64 box - an install from before the
556     # manifest had an arm64 rustup-init, or one started from an emulated x64
557     # shell - quietly sets up an x86_64 host and an emulated compiler. Naming the
558     # triple pins both the toolchain installed here and, through
559     # `set default-host`, what a bare `stable` means to rustup from then on.
560     #
561     # MSVC rather than GNU: the -msvc toolchains link with link.exe and the
562     # Windows SDK from the Visual Studio the elevated half installs - including
563     # the ARM64 build tools an aarch64 host links with. Those are needed to BUILD,
564     # not to install, so this step does not depend on the elevated half.
565     #
566     # Re-runs are cheap: `toolchain install` on an installed toolchain updates it
567     # to the current stable, or reports it unchanged. Setting the default each
568     # time is the point of the step - a default you changed by hand (to nightly,
569     # say) is put back to stable, so leave the step out of the plan to keep it.
570     Write-Step 'Rust: stable MSVC toolchain as the default'
571     if (-not $RustHost) {
572         Write-Warning "No Rust host toolchain is set up for host architecture '$HostArch'; skipping."
573         return
574     }
575     $rustup = Get-RustupPath
576     if (-not $rustup) {
577         Write-Warning 'rustup not found. Install it with: winget install Rustlang.Rustup'
578         return
579     }
580     Write-Host "    using $rustup ($(Get-PEMachine $rustup))"
581
582     # EAP back to Continue for the calls: rustup reports progress on STDERR, and
583     # under $ErrorActionPreference = 'Stop' a native command's stderr can become
584     # a terminating error. Judged by the exit code instead - cleared first, as
585     # for ssh.exe above, so an exe that cannot start at all does not inherit the
586     # last one's 0.
587     $toolchain = "stable-$RustHost"
588     $calls = @(
589         @('set', 'default-host', $RustHost),
590         @('toolchain', 'install', $toolchain),
591         @('default', $toolchain)
592     )
593     $prevEap = $ErrorActionPreference
594     $ErrorActionPreference = 'Continue'
595     try {
596         foreach ($call in $calls) {
597             $global:LASTEXITCODE = $null
598             & $rustup @call
599             if ($LASTEXITCODE -ne 0) {
600                 $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" }
601                 throw "rustup $($call -join ' ') failed ($why)"
602             }
603         }
604     } finally {
605         $ErrorActionPreference = $prevEap
606     }
607
608     # Report the compiler itself. .cargo\bin\rustc.exe is a rustup proxy - a copy
609     # of rustup.exe - so its architecture says nothing about the toolchain's.
610     $rustc = Join-Path $RustupHome "toolchains\$toolchain\bin\rustc.exe"
611     if (Test-Path $rustc) {
612         Write-Host "    default: $toolchain - $(& $rustc -V) ($(Get-PEMachine $rustc))"
613     } else {
614         Write-Warning "rustup reported success, but $rustc is not there."
615     }
616
617     # An x86_64 host toolchain left on an ARM64 box - from before this step
618     # pinned the triple - is an emulated compiler that is no longer the default.
619     # Named rather than removed; whether it goes is your call. Building x64 code
620     # from here wants the x64 TARGET on the native toolchain, not an x64 host.
621     $x64Stable = Join-Path $RustupHome 'toolchains\stable-x86_64-pc-windows-msvc'
622     if ($IsArm64 -and (Test-Path $x64Stable)) {
623         Write-Host '    Also installed: stable-x86_64-pc-windows-msvc, an x64 compiler that runs emulated here.' -ForegroundColor Yellow
624         Write-Host "    Remove it with 'rustup toolchain uninstall stable-x86_64-pc-windows-msvc'; to build" -ForegroundColor Yellow
625         Write-Host "    x64 code from this box, use 'rustup target add x86_64-pc-windows-msvc' instead." -ForegroundColor Yellow
626     }
627 }
628
629 function Set-UserEnvironmentVariable([string] $Name, [string] $Value) {
630     # HKCU, like Add-ToUserPath, so it outlives the script; written only when it
631     # differs, so a re-run changes nothing.
632     if ([Environment]::GetEnvironmentVariable($Name, 'User') -eq $Value) {
633         Write-Host "    $Name is already $Value"
634         return
635     }
636     [Environment]::SetEnvironmentVariable($Name, $Value, 'User')
637     Write-Host "    Set $Name = $Value (restart your shell to pick it up)."
638 }
639
640 function Get-AndroidRevision($Package) {
641     # A package's revision from the index, as a [version]: <major>, optional
642     # <minor> and <micro>. [int] of a missing element is 0.
643     $r = $Package.revision
644     [version]('{0}.{1}.{2}' -f [int]$r.major, [int]$r.minor, [int]$r.micro)
645 }
646
647 function ConvertTo-Revision([string] $Text) {
648     # "23.0" as the same three-part [version] the index gives, so the two
649     # compare. [version]'23.0' has no third part - it reads as -1 - and so
650     # counted as OLDER than 23.0.0: an installed, current copy looked stale.
651     $parts = @($Text.Trim() -split '\.' | Where-Object { $_ -ne '' })
652     while ($parts.Count -lt 3) { $parts += '0' }
653     [version]($parts[0..2] -join '.')
654 }
655
656 function Invoke-AndroidCli {
657     # The Android CLI (cmdline-tools\latest\bin\android.exe) against this SDK,
658     # its output shown as it comes - a first install downloads well over 100 MB
659     # and should not look stalled. Returns the exit code, $null if it would not
660     # start. EAP Continue for the call, as for the other native tools here.
661     #
662     # stdin is one empty line, so it is closed rather than the console: a
663     # prompt nobody expected gets "no" instead of an unattended run waiting on
664     # it forever.
665     param([string[]] $Arguments)
666     $cli = Join-Path $AndroidSdkRoot 'cmdline-tools\latest\bin\android.exe'
667     $prevEap = $ErrorActionPreference
668     $ErrorActionPreference = 'Continue'
669     try {
670         $global:LASTEXITCODE = $null
671         # Its stderr becomes error records under 2>&1 in Windows PowerShell,
672         # which would print as red "NativeCommandError" noise; back to plain
673         # lines first. The one JVM warning dropped is the bundled Java noting,
674         # on every call, a flag this Windows 10 does not support.
675         '' | & $cli "--sdk=$AndroidSdkRoot" @Arguments 2>&1 | ForEach-Object { "$_" } |
676             Where-Object { $_ -notmatch 'UseAllWindowsProcessorGroups flag is not supported' } | Out-Host
677         $LASTEXITCODE
678     } finally {
679         $ErrorActionPreference = $prevEap
680     }
681 }
682
683 function Install-AndroidSdk {
684     # The Android SDK for building apps, per-user, in Android Studio's default
685     # location (%LOCALAPPDATA%\Android\Sdk) unless ANDROID_HOME names another:
686     # the command-line tools, platform-tools, and the newest stable platform and
687     # build-tools. That is what Android Studio's first-run wizard would set up,
688     # done without the wizard - on the x64 laptop Studio was installed and that
689     # wizard had never run, so there was no SDK at all. Gradle fetches any other
690     # platform or build-tools a project asks for by itself, once the licences are
691     # accepted, so this is the floor rather than the whole set.
692     #
693     # "Newest stable" comes from Google's package index, read here each run:
694     # channel-0 (stable) and no <preview> revision, the platform by API level
695     # (android-37.2 beats android-37.1 beats android-36), build-tools by version.
696     #
697     # THE COMMAND-LINE TOOLS ARE NOT WHAT THEY WERE. From 23.0, sdkmanager is
698     # deprecated and sdkmanager.bat is a shim over the new Android CLI
699     # (cmdline-tools\latest\bin\android.exe, `android sdk install ...`), which on
700     # first use installs itself into %USERPROFILE%\.android (bin\android-cli.exe,
701     # about 90 MB, and cli\ - a bundled Java runtime, and a metrics spool). So
702     # the CLI is called directly here, with its own "platforms/android-37.2"
703     # package paths: no deprecated shim, and no cmd parsing to split the old
704     # "platforms;android-37.2" at its semicolon. `sdk install` installs a
705     # package or, if it is there, updates it to the latest - so it is also the
706     # re-run path, downloading nothing when everything is current.
707     #
708     # ITS EXIT CODE IS NOT TRUSTED. CLI 1.0.16406183 finishes every `sdk`
709     # command and then crashes on the way out, 0xC0000409 (a fail-fast in
710     # ucrtbase) - on the x64 laptop's Windows 10, every time, in a console or
711     # not, while `--version` and `info` exit 0. So success is judged by the
712     # result: each package asked for must have the package.xml the CLI writes
713     # once a package is complete. A nonzero exit with everything present is a
714     # note, not a failure; anything missing is a failure, whatever the exit.
715     #
716     # The command-line tools themselves are bootstrapped from the index's own
717     # "cmdline-tools;latest" archive (SHA-1 from the index), and replaced only
718     # when the index has a newer revision than the one in source.properties.
719     # The CLI cannot do that for them: the archive calls itself
720     # cmdline-tools;23.0, a fixed version, so it would never "update" it.
721     #
722     # The SDK licences are accepted on your behalf; the plan says so before
723     # anything runs. The CLI does it as it installs - sdkmanager --licenses is
724     # now a no-op - writing licenses\android-sdk-license. Gradle needs it to
725     # build, and to fetch what a project asks for.
726     #
727     # The CLI brings its own Java, so the SDK needs no JDK. Gradle does: when
728     # there is no JAVA_HOME, the one Android Studio bundles (jbr) becomes the
729     # user's, so a command-line gradlew works. An existing JAVA_HOME is never
730     # changed.
731     Write-Step "Android SDK in $AndroidSdkRoot"
732
733     [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
734     # No progress bar for the downloads. Windows PowerShell 5.1's
735     # Invoke-WebRequest redraws it per chunk, and that - not the network - is
736     # what a large download then waits on: measured on the x64 laptop, the
737     # 148 MB command-line tools took about ten minutes and five minutes of CPU
738     # with it on. Local to this function, so nothing else changes.
739     $ProgressPreference = 'SilentlyContinue'
740     [xml]$index = (Invoke-WebRequest -UseBasicParsing -Uri $AndroidIndex).Content
741     $stable = @($index.DocumentElement.remotePackage |
742                 Where-Object { $_.channelRef.ref -eq 'channel-0' -and -not $_.revision.preview })
743
744     # --- the command-line tools: bootstrapped, and kept current, from the index ---
745     $ct      = @($stable | Where-Object { $_.path -eq 'cmdline-tools;latest' })[0]
746     if (-not $ct) { throw "No stable cmdline-tools;latest in $AndroidIndex." }
747     $ctWant  = Get-AndroidRevision $ct
748     $ctDir   = Join-Path $AndroidSdkRoot 'cmdline-tools\latest'
749     $ctHave  = $null
750     $props   = Join-Path $ctDir 'source.properties'
751     if (Test-Path $props) {
752         $m = [regex]::Match((Get-Content $props -Raw), '(?m)^Pkg\.Revision=(\d+(\.\d+){0,2})')
753         if ($m.Success) { $ctHave = ConvertTo-Revision $m.Groups[1].Value }
754     }
755     if ($ctHave -and $ctHave -ge $ctWant) {
756         Write-Host "    command-line tools $ctHave are current."
757     } else {
758         $archive = @($ct.archives.archive | Where-Object { $_.'host-os' -eq 'windows' })[0]
759         $sum     = $archive.complete.checksum
760         $sha1    = if ($sum -is [string]) { $sum } else { $sum.'#text' }
761         $url     = $AndroidRepo + $archive.complete.url
762         Write-Host "    command-line tools $(if ($ctHave) { "$ctHave -> " })$ctWant; downloading $($archive.complete.url)."
763         # PATH LENGTH. The archive nests deep - a guava jar in it sits well over
764         # 150 characters below its top - and Windows PowerShell 5.1 is bound by
765         # the 260-character MAX_PATH. So the temp directory's name is 8
766         # characters: %TEMP%\xxxxxxxx\cmdline-tools\... is then no deeper than
767         # %LOCALAPPDATA%\Android\Sdk\cmdline-tools\latest\..., and whenever the
768         # SDK's own path fits, unpacking it does too. (A 43-character name here
769         # made the unpack deeper than the SDK it was for.)
770         $tmp = Join-Path $env:TEMP ([guid]::NewGuid().ToString('N').Substring(0, 8))
771         New-Item -ItemType Directory -Force -Path $tmp | Out-Null
772         try {
773             $zip = Join-Path $tmp 'ct.zip'
774             Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip
775             $got = (Get-FileHash $zip -Algorithm SHA1).Hash.ToLower()
776             if ($sha1 -and $got -ne $sha1.ToLower()) { throw "SHA-1 mismatch for $url`: expected $sha1, got $got" }
777             Expand-Archive -Path $zip -DestinationPath $tmp -Force
778             # The archive holds a top-level cmdline-tools\ directory; the SDK
779             # layout wants it at cmdline-tools\latest. Replaced wholesale, as
780             # BinSkim is, so files dropped between releases do not linger - but
781             # the old copy is RENAMED aside first and deleted last. A rename is
782             # one operation whatever the depth below it; deleting walks every
783             # file and can trip over a path that is too long. Done this way, a
784             # delete that fails leaves a stray folder to report, not an SDK
785             # with no command-line tools in it. The aside name is six
786             # characters, like "latest", so the delete is no deeper either.
787             New-Item -ItemType Directory -Force -Path (Split-Path $ctDir) | Out-Null
788             $old = $null
789             if (Test-Path $ctDir) {
790                 $old = Join-Path (Split-Path $ctDir) ('old' + [guid]::NewGuid().ToString('N').Substring(0, 3))
791                 Rename-Item -Path $ctDir -NewName (Split-Path $old -Leaf)
792             }
793             Move-Item -Path (Join-Path $tmp 'cmdline-tools') -Destination $ctDir
794             if ($old) {
795                 try { Remove-Item -Recurse -Force $old }
796                 catch { Write-Warning "The new command-line tools are in place, but the old copy could not be removed: $old ($($_.Exception.Message))" }
797             }
798         } finally {
799             Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
800         }
801     }
802
803     # --- the newest stable platform and build-tools, by the index ---
804     $platform = @($stable | ForEach-Object {
805                     $m = [regex]::Match($_.path, '^platforms;android-(\d+)(?:\.(\d+))?$')
806                     if ($m.Success) {
807                         [pscustomobject]@{ Path = $_.path; Api = [version]('{0}.{1}' -f $m.Groups[1].Value, [int]$m.Groups[2].Value) }
808                     }
809                 } | Sort-Object Api)[-1].Path
810     $buildTools = @($stable | Where-Object { $_.path -match '^build-tools;\d+(\.\d+)*$' } |
811                     Sort-Object { [version]($_.path -replace '^build-tools;', '') })[-1].path
812     if (-not $platform -or -not $buildTools) { throw "Could not find a stable platform and build-tools in $AndroidIndex." }
813
814     # The index names packages "platforms;android-37.2"; the CLI, and the SDK's
815     # directories, use "platforms/android-37.2".
816     $packages = @('platform-tools', ($platform -replace ';', '/'), ($buildTools -replace ';', '/'))
817     Write-Host "    installing or updating: $($packages -join ', ')"
818     $rc = Invoke-AndroidCli -Arguments (@('sdk', 'install') + $packages)
819     $missing = @($packages | Where-Object { -not (Test-Path (Join-Path $AndroidSdkRoot (($_ -replace '/', '\') + '\package.xml'))) })
820     if ($missing) {
821         $why = if ($null -eq $rc) { 'it would not start' } else { "exit $rc" }
822         throw "android sdk install left out $($missing -join ', ') ($why)"
823     }
824     if ($null -eq $rc) {
825         Write-Warning 'The Android CLI would not start; the packages already installed were left as they were, not updated.'
826     } elseif ($rc -ne 0) {
827         Write-Host ("    note: the Android CLI exited {0} (0x{0:X8}) after finishing - its crash on the way out, not a failed" -f $rc) -ForegroundColor DarkGray
828         Write-Host '    install: every package asked for is in place.' -ForegroundColor DarkGray
829     }
830
831     # Report what is there now, from each package's own source.properties.
832     foreach ($pkg in $packages) {
833         $p = Join-Path $AndroidSdkRoot (($pkg -replace '/', '\') + '\source.properties')
834         $rev = if (Test-Path $p) { [regex]::Match((Get-Content $p -Raw), '(?m)^Pkg\.Revision=(.*)$').Groups[1].Value.Trim() } else { '?' }
835         Write-Host ('    {0,-28} {1}' -f $pkg, $rev)
836     }
837
838     Set-UserEnvironmentVariable 'ANDROID_HOME' $AndroidSdkRoot
839
840     # JAVA_HOME, for Gradle - only when there is none, and only to Android
841     # Studio's bundled JDK. Without Studio this just says what is missing.
842     if (-not [Environment]::GetEnvironmentVariable('JAVA_HOME', 'User') -and
843         -not [Environment]::GetEnvironmentVariable('JAVA_HOME', 'Machine')) {
844         $jbr = @((Join-Path $env:ProgramFiles 'Android\Android Studio\jbr'),
845                  (Join-Path $env:LOCALAPPDATA 'Programs\Android Studio\jbr') |
846                  Where-Object { Test-Path (Join-Path $_ 'bin\java.exe') })[0]
847         if ($jbr) {
848             Set-UserEnvironmentVariable 'JAVA_HOME' $jbr
849         } else {
850             Write-Warning 'No JAVA_HOME, and no Android Studio JDK to point it at: a command-line gradlew will need one. Install Android Studio (the AndroidStudio step) or a JDK.'
851         }
852     }
853
854     # The Android CLI (android), and the tools beside it (lint, d8, r8,
855     # apkanalyzer, the sdkmanager/avdmanager shims), in any shell.
856     # platform-tools is NOT added: the PlatformTools step already puts adb on the
857     # PATH, and two adb.exe on it would only make which one answers depend on
858     # the order.
859     Add-ToUserPath (Join-Path $ctDir 'bin')
860 }
861
862 function Get-PEMachine {
863     # Architecture of a PE, read straight from the COFF header: the 2 bytes at
864     # the e_lfanew offset + 4. Cheap, and it answers the only question that
865     # matters here - would this exe run natively, or through emulation?
866     #
867     # Deliberately NOT Get-Command's .FileVersionInfo or the package metadata:
868     # a multi-architecture package (Sysinternals) ships every build in one zip
869     # under different names, and an installer's own metadata says nothing about
870     # which binary got laid down. The file itself cannot be wrong.
871     param([string]$Path)
872     if (-not (Test-Path $Path)) { return $null }
873     try {
874         $fs = [IO.File]::OpenRead($Path)
875         $br = New-Object IO.BinaryReader($fs)
876         try {
877             $fs.Seek(0x3c, 'Begin') | Out-Null
878             $pe = $br.ReadInt32()
879             if ($pe -le 0 -or $pe -gt ($fs.Length - 6)) { return 'not-PE' }
880             $fs.Seek($pe + 4, 'Begin') | Out-Null
881             switch ($br.ReadUInt16()) {
882                 0x8664  { 'x64' }
883                 0xAA64  { 'ARM64' }
884                 0x014c  { 'x86' }
885                 0x01c4  { 'ARM32' }
886                 default { 'unknown' }
887             }
888         } finally { $br.Close(); $fs.Close() }
889     } catch { $null }
890 }
891
892 function Invoke-ArchAudit {
893     # Report the actual architecture of the tools this box provisions, resolved
894     # the way a shell would (PATH first, then the usual install roots), so what
895     # is printed is what you would really run.
896     #
897     # This exists because "winget installed it" does not mean "you got the native
898     # build", and the gap is not always where you would guess - Visual Studio's
899     # own bundled ninja.exe is x64 even on an ARM64 host. A per-run audit turns
900     # that from something you trip over into something the log tells you.
901     #
902     # Purely informational: it never fails the run. On x64 everything is expected
903     # to be x64 and the output is dull; the value is on ARM64, where each line is
904     # either native or a known, listed exception.
905     Write-Step "Architecture audit (host: $HostArch)"
906
907     # Resolve against the PATH a NEW shell would get, not this process's.
908     #
909     # The steps above write the HKCU PATH, which a running process never sees -
910     # so auditing $env:PATH would report the state from before this script ran and
911     # warn about a problem it had just fixed. Compose machine + user from the
912     # registry (the order Windows itself uses), then append anything extra this
913     # process happens to carry: that tail is where a Developer Command Prompt's VS
914     # directories live, and keeping it last mirrors how VsDevCmd appends them.
915     $composed = @()
916     foreach ($scope in 'Machine', 'User') {
917         $v = [Environment]::GetEnvironmentVariable('Path', $scope)
918         if ($v) { $composed += ($v -split ';' | Where-Object { $_.Trim() }) }
919     }
920     $composed += ($env:PATH -split ';' | Where-Object { $_.Trim() })
921     $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
922     $searchPath = @($composed | Where-Object { $seen.Add($_.Trim().TrimEnd('\')) })
923
924     function Resolve-OnPath([string]$Exe) {
925         foreach ($d in $searchPath) {
926             $p = Join-Path $d $Exe
927             if (Test-Path $p -PathType Leaf) { return $p }
928         }
929         return $null
930     }
931
932     # Tools with no native ARM64 build available anywhere, with the reason. These
933     # print as expected rather than as problems - see the README's ARM64 section.
934     #
935     # Shorter than it was: BinSkim, OpenCppCoverage and NASM used to be listed
936     # here as accepted emulation, and are now simply not installed on ARM64. That
937     # is the whole shape of the change - the exceptions that were tolerable one at
938     # a time added up to a VM full of x64 binaries.
939     #
940     # rsync came off this list when the release started publishing an arm64
941     # asset. An x64 rsync.exe on an ARM64 box is now a leftover from a run before
942     # that, not an accepted exception, so it warns and gets a remedy below.
943     $KnownEmulated = @{
944         'iperf3.exe'           = 'no ARM64 build published; network-bound anyway'
945         'py.exe'               = 'python.org ships the launcher shim as x86; it execs the native python.exe'
946         'vswhere.exe'          = 'Microsoft ships x86 only; runs once per script'
947         'adb.exe'              = 'Google ships platform-tools as x86 only; bound by the USB/TCP link'
948     }
949
950     # Fixable cases: a native build DOES exist, something just resolved ahead of
951     # it. Printed with the finding so the log carries the remedy, not just the
952     # complaint.
953     #
954     # ninja is the one that actually bites: Visual Studio bundles an x64 ninja.exe
955     # even on ARM64, and it is re-invoked for every edge in the build graph, so
956     # an emulated one is paid over and over rather than once. The NinjaPath step
957     # puts the native copy first; this is the check that it worked.
958     #
959     # All of these are for tools ARM64 still installs. The clang-cl and WinMerge
960     # remedies were removed with their rows: advising an install that the
961     # x64-only set has just declined to do would be the audit arguing with the
962     # provisioning.
963     $Remedies = @{
964         'ninja.exe' = 'Visual Studio bundles an x64 ninja. Install the native one (winget install Ninja-build.Ninja) and re-run - the NinjaPath step puts its directory at the front of the user PATH.'
965         'cmake.exe' = 'Install the native build with: winget install Kitware.CMake (its MSI is machine-scope, so it needs an administrator).'
966         'rsync.exe' = 'Left over from before the release published an arm64 asset. Re-run setup-windows-with-uac.ps1 as an administrator to replace it, and the ARM64 ssh.exe beside it, with the native build.'
967         'claude.exe' = 'Not the build for this host. Re-run setup-windows.bat -Only ClaudeCode, which installs the right one. If the path above is under WinGet, it is the old winget copy: winget uninstall Anthropic.ClaudeCode.'
968         'rustc.exe' = 'Only the x64 host toolchain is installed. Run .\setup-windows-no-uac.ps1 -Only RustToolchain: it installs stable for this host and makes it the default.'
969     }
970
971     $vs = $null
972     $vsWhereExe = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
973     if (Test-Path $vsWhereExe) {
974         $vs = & $vsWhereExe -products '*' -property installationPath -format value | Select-Object -First 1
975     }
976
977     # name -> extra candidate paths searched when the name is not on the PATH.
978     $targets = [ordered]@{
979         # The native installer's launcher, then the old winget route's link.
980         # PATH-first like the rest, so this reports whichever claude wins.
981         'claude.exe'          = @((Join-Path $env:USERPROFILE '.local\bin\claude.exe'), (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links\claude.exe'))
982         'git.exe'             =@("$env:LOCALAPPDATA\Programs\Git\cmd\git.exe", (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'))
983         'python.exe'          = @()
984         # Both homes of the launcher: C:\Windows for an all-users install, the
985         # per-user Launcher directory otherwise. Often neither - it is a separate
986         # component from the interpreter, and "- not installed" here next to a
987         # native python.exe is the normal result of an unelevated Python install.
988         'py.exe'              = @("$env:WINDIR\py.exe", "$env:LOCALAPPDATA\Programs\Python\Launcher\py.exe")
989         'pwsh.exe'            = @()
990         'cmake.exe'           = @((Join-Path $env:ProgramFiles 'CMake\bin\cmake.exe'))
991         'ninja.exe'           = @()
992         # Upstream LLVM. The Documents path is not a typo - see Add-LlvmToUserPath
993         # for why an unelevated install lands there.
994         'clang-cl.exe'        = @(
995             (Join-Path $env:ProgramFiles 'LLVM\bin\clang-cl.exe')
996             (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin\clang-cl.exe')
997             (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin\clang-cl.exe')
998         )
999         # rustup itself, then the compiler the stable toolchain really runs. The
1000         # rustc.exe in .cargo\bin that a shell would find is a rustup proxy - a
1001         # copy of rustup.exe - so its architecture is rustup's, not the
1002         # toolchain's. The labelled row looks inside the toolchain instead,
1003         # native host first, so an x64 toolchain on ARM64 only shows up when it
1004         # is the one there is.
1005         'rustup.exe'          = @((Join-Path $CargoHome 'bin\rustup.exe'))
1006         'rustc.exe (stable)'  = @(
1007             $(if ($RustHost) { Join-Path $RustupHome "toolchains\stable-$RustHost\bin\rustc.exe" })
1008             (Join-Path $RustupHome 'toolchains\stable-x86_64-pc-windows-msvc\bin\rustc.exe')
1009         )
1010         'dotnet.exe'          = @((Join-Path $env:ProgramFiles 'dotnet\dotnet.exe'))
1011         'WinMergeU.exe'       = @((Join-Path $env:ProgramFiles 'WinMerge\WinMergeU.exe'), (Join-Path ${env:ProgramFiles(x86)} 'WinMerge\WinMergeU.exe'))
1012         'BinSkim.exe'         = @((Join-Path $BinSkimDir 'BinSkim.exe'))
1013         'rsync.exe'           = @((Join-Path $RsyncDir 'rsync.exe'))
1014         'ssh.exe'             = @((Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe'))
1015         # NASM's installer falls back to a per-user directory when it cannot
1016         # write to Program Files - see the NASM comment in setup-windows.bat. It
1017         # registers nothing there, so winget cannot see it (and re-downloads and
1018         # re-runs the installer on every run), and it puts nothing on the PATH.
1019         # Without these candidates the audit reported "- not installed" for a
1020         # nasm.exe that was on disk all along, and then still concluded that
1021         # everything had resolved.
1022         'nasm.exe'            = @(
1023             (Join-Path $env:LOCALAPPDATA 'bin\NASM\nasm.exe')
1024             (Join-Path $env:ProgramFiles 'NASM\nasm.exe')
1025             (Join-Path ${env:ProgramFiles(x86)} 'NASM\nasm.exe')
1026         )
1027         'iperf3.exe'          = @()
1028         # A winget portable package: unpacked under WinGet\Packages, with that
1029         # directory put on the user PATH. This finds it should the PATH entry
1030         # have gone missing.
1031         'adb.exe'             = @(Resolve-Path (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages\Google.PlatformTools_*\platform-tools\adb.exe') -ErrorAction SilentlyContinue |
1032                                   ForEach-Object { $_.Path })
1033         'OpenCppCoverage.exe' = @((Join-Path $env:ProgramFiles 'OpenCppCoverage\OpenCppCoverage.exe'), (Join-Path ${env:ProgramFiles(x86)} 'OpenCppCoverage\OpenCppCoverage.exe'))
1034         'vswhere.exe'         = @($vsWhereExe)
1035         'xperf.exe'           = @((Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'))
1036     }
1037     if ($vs) {
1038         $targets['MSBuild.exe'] = @((Join-Path $vs 'MSBuild\Current\Bin\arm64\MSBuild.exe'), (Join-Path $vs 'MSBuild\Current\Bin\MSBuild.exe'))
1039         # The MSVC and VS-Clang compilers, under whichever MSVC version is present.
1040         $msvc = Get-ChildItem (Join-Path $vs 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |
1041                 Sort-Object Name | Select-Object -Last 1
1042         if ($msvc) {
1043             $hostDir = if ($IsArm64) { 'Hostarm64\arm64' } else { 'Hostx64\x64' }
1044             $targets['cl.exe (MSVC)'] = @((Join-Path $msvc.FullName "bin\$hostDir\cl.exe"))
1045         }
1046         $llvmHost = if ($IsArm64) { 'ARM64\bin' } else { 'x64\bin' }
1047         $targets['clang-cl.exe (VS)'] = @((Join-Path $vs "VC\Tools\Llvm\$llvmHost\clang-cl.exe"))
1048     }
1049
1050     # Tools this box does not provision on ARM64. Dropped from the audit rather
1051     # than left to print "- not installed", because that line reads as a gap in
1052     # the provisioning when it is the provisioning working as intended - and a
1053     # dull audit is one you keep reading.
1054     #
1055     # The rows survive on x64, where all of these are installed and expected.
1056     # Anything still on disk from before the split shows up in the winget list,
1057     # not here.
1058     if ($IsArm64) {
1059         foreach ($gone in 'WinMergeU.exe', 'BinSkim.exe', 'nasm.exe',
1060                           'OpenCppCoverage.exe', 'clang-cl.exe', 'clang-cl.exe (VS)') {
1061             $targets.Remove($gone)
1062         }
1063     }
1064
1065     $native = if ($IsArm64) { 'ARM64' } else { 'x64' }
1066     $unexpected = @()
1067     foreach ($name in $targets.Keys) {
1068         # A LABELLED entry - "clang-cl.exe (VS)" - names one specific copy, so it
1069         # is resolved ONLY from its explicit candidates. Falling back to the PATH
1070         # there would silently answer with a different installation of the same
1071         # tool: with upstream LLVM on the PATH, the "(VS)" row reported the
1072         # upstream compiler and so claimed Visual Studio's was present when it was
1073         # not. Unlabelled entries still resolve PATH-first, because for those the
1074         # question is which binary a build would actually invoke.
1075         $exe      = ($name -split ' ')[0]
1076         $isPinned = $name -ne $exe
1077         if ($isPinned) {
1078             $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1
1079         } else {
1080             $path = Resolve-OnPath $exe
1081             if (-not $path) { $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 }
1082         }
1083         if (-not $path) { Write-Host ("    {0,-22} {1}" -f $name, '- not installed') -ForegroundColor DarkGray; continue }
1084
1085         $mach = Get-PEMachine $path
1086         if (-not $mach) { continue }
1087         if ($mach -eq $native) {
1088             Write-Host ("    {0,-22} {1,-6} native" -f $name, $mach) -ForegroundColor Green
1089         } elseif ($KnownEmulated.ContainsKey($exe)) {
1090             Write-Host ("    {0,-22} {1,-6} expected: {2}" -f $name, $mach, $KnownEmulated[$exe]) -ForegroundColor DarkGray
1091         } else {
1092             Write-Host ("    {0,-22} {1,-6} NOT NATIVE - $path" -f $name, $mach) -ForegroundColor Yellow
1093             if ($Remedies.ContainsKey($exe)) {
1094                 Write-Host ("    {0,-22} {1,-6} -> {2}" -f '', '', $Remedies[$exe]) -ForegroundColor Yellow
1095             }
1096             $unexpected += "$name ($mach)"
1097         }
1098     }
1099
1100     if ($unexpected) {
1101         Write-Warning "Running under emulation with no listed reason: $($unexpected -join ', ')."
1102         Write-Warning 'If a native build exists, prefer it (see the -> lines above); otherwise add it to $KnownEmulated with the reason.'
1103     } else {
1104         Write-Host '    Everything resolved to a native build, or to a listed exception.' -ForegroundColor Green
1105     }
1106 }
1107
1108 # ---------------------------------------------------------------------------
1109 # Main
1110 # ---------------------------------------------------------------------------
1111 Write-Host "Host architecture: $HostArch" -ForegroundColor Cyan
1112
1113 if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
1114         [Security.Principal.WindowsBuiltInRole]::Administrator)) {
1115     Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.'
1116 }
1117
1118 # What each step runs. The ORDER comes from setup-windows-steps.ps1, which lists
1119 # ArchAudit last on purpose: it reports on what the steps before it (and the
1120 # winget installs in setup-windows.bat) actually put on the box.
1121 $steps = @{
1122     WinMergePath  = { Add-WinMergeToUserPath }
1123     VsWhere       = { Add-VsWhereToUserPath }
1124     BinSkim       = { Install-BinSkim }
1125     GitConfig     = { Set-GlobalGitConfig }
1126     NinjaPath     = { Set-NativeNinjaFirst }
1127     LlvmPath      = { Add-LlvmToUserPath }
1128     RustToolchain = { Set-RustDefaultToolchain }
1129     AndroidSdk    = { Install-AndroidSdk }
1130     ArchAudit     = { Invoke-ArchAudit }
1131 }
1132
1133 # The catalog and the table above have to agree exactly. A catalog row with no
1134 # code here would be shown in the plan and then never taken; an entry here with
1135 # no row would never be shown, so never selected. Either is a bug in these
1136 # scripts, not in the box, so it stops the run before anything happens.
1137 $catalog  = @(Get-SetupCatalog -IsArm64 $IsArm64 | Where-Object Runner -eq 'user')
1138 $unbacked = @($catalog | Where-Object { -not $steps.ContainsKey($_.Id) } | ForEach-Object { $_.Id })
1139 $unlisted = @($steps.Keys | Where-Object { @($catalog.Id) -notcontains $_ })
1140 if ($unbacked -or $unlisted) {
1141     $diff = @()
1142     if ($unbacked) { $diff += "in the catalog but not here: $($unbacked -join ', ')" }
1143     if ($unlisted) { $diff += "here but not in the catalog: $($unlisted -join ', ')" }
1144     throw "setup-windows-steps.ps1 and this script disagree - $($diff -join '; ')."
1145 }
1146
1147 # 'WinMerge' was this step's name until the catalog put it beside the winget
1148 # step of the same name; still accepted.
1149 $plan = @(Resolve-SetupSelection -Steps $catalog `
1150             -Only $(if ($PSBoundParameters.ContainsKey('Only')) { $Only } else { $null }) -Skip $Skip `
1151             -Aliases @{ WinMerge = 'WinMergePath' } -IsArm64 $IsArm64)
1152 Write-SetupPlan $plan 'Plan for setup-windows-no-uac.ps1'
1153 $runCount = @($plan | Where-Object Selected).Count
1154 if ($runCount -eq 0) {
1155     Write-Host '    Nothing selected, so there is nothing to do.'
1156     exit 0
1157 }
1158 $ok = Confirm-SetupPlan -Yes:$Yes -Count $runCount
1159 if ($ok -ne $true) { exit $(if ($null -eq $ok) { 2 } else { 0 }) }
1160
1161 $failed = @()
1162 foreach ($p in $plan) {
1163     if (-not $p.Selected) {
1164         # Only the skips with a reason; the plan above already listed the rest.
1165         if ($p.Why) { Write-Host "`n==> $($p.Id) (skipped: $($p.Why))" -ForegroundColor DarkGray }
1166         continue
1167     }
1168     try {
1169         & $steps[$p.Id]
1170     } catch {
1171         # One broken step must not cost the others. Collect and report at the end.
1172         Write-Warning "$($p.Id) failed: $($_.Exception.Message)"
1173         $failed += $p.Id
1174     }
1175 }
1176
1177 if ($failed) {
1178     Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red
1179     exit 1
1180 }
1181 Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green
1182 exit 0