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