<# setup-windows-no-uac.ps1 Non-elevated portion of the Windows provisioning. Invoked by setup-windows.bat after its winget installs, or run directly from an ordinary (NOT elevated) prompt: powershell -NoProfile -ExecutionPolicy Bypass -File .\setup-windows-no-uac.ps1 Run it non-elevated on purpose. Every step here writes per-user state - the HKCU PATH and the global .gitconfig under $env:USERPROFILE - so running it elevated would configure the *administrator's* profile instead of yours. What this installs / configures: - %USERPROFILE%\.local\bin on the user PATH: where Claude Code's native installer puts claude.exe, and nothing else guarantees it is on the PATH - WinMerge on the user PATH (x64 only) - vswhere.exe on the user PATH: the Visual Studio installer puts it in %ProgramFiles(x86)%\Microsoft Visual Studio\Installer, which nothing adds to the PATH, so build scripts (and VsDevCmd.bat itself) complain that 'vswhere.exe' is not recognized - BinSkim (binary hardening analyzer) in %LOCALAPPDATA%\Programs\BinSkim, on the user PATH (x64 only - the NuGet package publishes win-x64 alone) - Global git identity, and core.sshCommand pointed at a Win32-OpenSSH client so git shares the Windows ssh-agent: the fast ssh.exe the elevated half unpacks beside rsync.exe if it is there, the in-box one otherwise - Rust's stable MSVC toolchain for this host - x86_64 on x64, aarch64 on ARM64 - installed through rustup and made the default - The Android SDK, per-user in %LOCALAPPDATA%\Android\Sdk (x64 only): the command-line tools, platform-tools and the newest stable platform and build-tools, SDK licences accepted, ANDROID_HOME set - and JAVA_HOME, to Android Studio's bundled JDK, when there is none - An architecture audit: the real PE machine type of every tool this box provisions, resolved the way a shell would. Informational, never fatal. Anything running emulated without a listed reason is called out. FILL IN $GitUserName / $GitUserEmail below before the first run. The steps are the 'user' rows of setup-windows-steps.ps1. The batch file runs this with -Only -Yes, having already asked. Run by hand, it lists what it will do and asks before doing any of it; -Only and -Skip pick steps, and -Yes skips the question. Steps are independent: one failing warns and the rest still run. The exit code is 1 if any step failed, 2 if there was no console to ask on (re-run with -Yes), 0 otherwise. #> [CmdletBinding()] param( # Steps to take (-Only) or leave out (-Skip), by the names the plan shows. # For several, separate them with commas. `powershell -File` hands "A,B" to # an array parameter as ONE string, so it is split here and either way works: # .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig # powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig [string[]] $Only, [string[]] $Skip = @(), # Do not ask first. setup-windows.bat passes it, having asked already. [switch] $Yes ) $ErrorActionPreference = 'Stop' # Host architecture, from the machine environment in the registry. Both of the # obvious sources report the EMULATED architecture inside an emulated x64 # PowerShell - which is what `powershell` resolves to when launched from an x64 # shell on an ARM64 box. Measured on this machine: # [RuntimeInformation]::OSArchitecture X64 <- wrong # $env:PROCESSOR_ARCHITECTURE AMD64 <- wrong # HKLM\...\Session Manager\Environment ARM64 <- right # OSArchitecture is documented as the OS's architecture, and on .NET Core it is; # under .NET Framework on Prism it is not, so it is kept only as a fallback. # $IsArm64 decides which steps run at all, so this has to be the real one. $rawArch = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -ErrorAction SilentlyContinue).PROCESSOR_ARCHITECTURE if (-not $rawArch) { $rawArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() } $IsArm64 = ($rawArch -eq 'ARM64') $HostArch = if ($IsArm64) { 'Arm64' } elseif ($rawArch -eq 'AMD64') { 'X64' } else { $rawArch } # Steps that do not run on ARM64 - WinMergePath, BinSkim and LlvmPath - are # marked -X64Only, with the reason, in setup-windows-steps.ps1. The plan printed # before anything runs shows each of them with that reason. # # The ARM64 machine is provisioned as a single-compiler build box, so the # packages these three steps wire up are not installed there. Skipping the step # rather than letting it find nothing matters: Install-BinSkim would happily # download and PATH the x64 build, and Add-LlvmToUserPath is the step that put an # emulated-adjacent toolchain on the PATH ahead of MSVC in the first place. # # -Only and -Skip work on top of this; they can only subtract. . (Join-Path $PSScriptRoot 'setup-windows-steps.ps1') # --- Global git identity: FILL THESE IN BEFORE RUNNING --- # Left empty, Set-GlobalGitConfig skips the identity and says so, rather than # stamping a placeholder onto your commits. Leaving them empty is a legitimate # choice - it keeps your identity per-repository. core.sshCommand is set either # way, so the ssh side works regardless. $GitUserName = '' # e.g. 'Ada Lovelace' $GitUserEmail = '' # e.g. 'ada@example.com' # BinSkim's win-x64 build, from the NuGet flat container. $BinSkimPackage = 'microsoft.codeanalysis.binskim' $BinSkimDir = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim' # Where the elevated half puts rsync.exe and the ssh.exe it ships with. Only # read here, to prefer that ssh.exe for git - keep it in step with $RsyncDir in # setup-windows-with-uac.ps1 if you move the install. $RsyncDir = 'C:\Tools\rsync' # Where rustup keeps itself (.cargo) and its toolchains (.rustup): rustup-init's # own defaults, unless CARGO_HOME / RUSTUP_HOME say otherwise. The host triple is # the one Rust toolchain this box is set up with - see Set-RustDefaultToolchain. $CargoHome = if ($env:CARGO_HOME) { $env:CARGO_HOME } else { Join-Path $env:USERPROFILE '.cargo' } $RustupHome = if ($env:RUSTUP_HOME) { $env:RUSTUP_HOME } else { Join-Path $env:USERPROFILE '.rustup' } $RustHost = switch ($HostArch) { 'Arm64' { 'aarch64-pc-windows-msvc' } 'X64' { 'x86_64-pc-windows-msvc' } default { $null } } # The Android SDK: where Android Studio puts it by default, unless ANDROID_HOME # already names one. "Latest" is read from Google's package index at run time, # the same index sdkmanager and Android Studio's SDK Manager read. $AndroidSdkRoot = if ($env:ANDROID_HOME) { $env:ANDROID_HOME } else { Join-Path $env:LOCALAPPDATA 'Android\Sdk' } $AndroidRepo = 'https://dl.google.com/android/repository/' $AndroidIndex = $AndroidRepo + 'repository2-3.xml' function Write-Step([string]$Msg) { Write-Host "`n==> $Msg" -ForegroundColor Cyan } function Add-ToUserPath { # HKCU PATH, not the process PATH: this must outlive the script. Idempotent, # and re-applied on every run so an entry lost to an unrelated PATH edit is # repaired without re-doing the install that put it there. # # -Prepend puts the directory FIRST and moves it there if it is already # present further down, which is the difference between "on the PATH" and # "the one that wins". Only for entries where that matters; appending is the # polite default and stays the default. param( [string] $Dir, [switch] $Prepend ) $user = [Environment]::GetEnvironmentVariable('Path', 'User') if (-not $user) { $user = '' } # Compare trailing-backslash-insensitively: C:\x and C:\x\ are the same # directory, and adding a second spelling of one is just noise. $norm = { param($s) $s.Trim().TrimEnd('\') } $entries = @($user -split ';' | Where-Object { $_.Trim() }) $already = $entries | Where-Object { (& $norm $_) -eq (& $norm $Dir) } if (-not $Prepend) { if ($already) { Write-Host " $Dir already in user PATH."; return } $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir } [Environment]::SetEnvironmentVariable('Path', $new, 'User') Write-Host " Added $Dir to user PATH (restart your shell to pick it up)." return } if ($already -and (& $norm $entries[0]) -eq (& $norm $Dir)) { Write-Host " $Dir already first in user PATH." return } $rest = $entries | Where-Object { (& $norm $_) -ne (& $norm $Dir) } [Environment]::SetEnvironmentVariable('Path', (@($Dir) + $rest) -join ';', 'User') if ($already) { Write-Host " Moved $Dir to the front of the user PATH (restart your shell to pick it up)." } else { Write-Host " Added $Dir to the front of the user PATH (restart your shell to pick it up)." } } function Add-LocalBinToUserPath { # %USERPROFILE%\.local\bin is where Claude Code's native installer puts # claude.exe (see setup-windows.bat). The installer only prints a reminder # when the directory is not on the PATH, and it is the per-user bin # directory other tools reach for too, so put it there regardless and create # it if it is missing - an entry for a directory that is not there yet would # only be dead until something fills it. Write-Step '%USERPROFILE%\.local\bin on the user PATH' $dir = Join-Path $env:USERPROFILE '.local\bin' if (-not (Test-Path $dir)) { New-Item -ItemType Directory -Path $dir | Out-Null Write-Host " Created $dir." } Add-ToUserPath $dir } function Add-WinMergeToUserPath { Write-Step 'WinMerge on the user PATH' $candidates = @( (Join-Path $env:ProgramFiles 'WinMerge'), (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'), (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge') ) $dir = $candidates | Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } | Select-Object -First 1 if (-not $dir) { Write-Warning 'WinMerge not found; user PATH unchanged.' return } Add-ToUserPath $dir } function Add-VsWhereToUserPath { # vswhere.exe is how scripts locate Visual Studio (MSBuild, VsDevCmd.bat, # the Windows SDK), and the VS installer drops it in a fixed directory that # is never on the PATH. VsDevCmd.bat itself prints "'vswhere.exe' is not # recognized" on every run without it. The directory is fixed by contract # (32-bit Program Files, no version in the path), so there is nothing to # search for: if it is missing, Visual Studio is not installed. Write-Step 'vswhere on the user PATH' $dir = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer' if (-not (Test-Path (Join-Path $dir 'vswhere.exe'))) { Write-Warning "vswhere.exe not found in $dir (no Visual Studio installer present); user PATH unchanged." return } Add-ToUserPath $dir } function Install-BinSkim { # BinSkim checks the exact mitigations the native project enables in # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies, # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained build, so # this needs no .NET SDK/runtime: the .nupkg is a zip - extract the tool # folder for this architecture and put it on the PATH. After restarting the # shell: # binskim analyze path\to\your.exe # # ARCHITECTURE. The package currently publishes win-x64 only (its other RIDs # are linux-x64, linux-arm64 and osx-x64) - there is no win-arm64 build. So on # ARM64 this installs the x64 tool and it runs under emulation. That is a # slowdown and nothing more: BinSkim READS PE headers and load configs, so the # architecture of the binaries it analyses is independent of its own - an # emulated x64 BinSkim checks ARM64 binaries perfectly well. $BinSkimRids is # ordered preference, so if a win-arm64 build ever ships, an ARM64 box picks # it up with no further change here. # # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so # ask NuGet what the newest stable version is BEFORE fetching anything, and # skip the download entirely when the installed copy already matches. # Re-provisioning an up-to-date box should not pay for it. # # The installed version is recorded in nupkg-version.txt next to the tool. # For a copy installed before that marker existed, fall back to BinSkim.exe's # own ProductVersion; either way the marker is (re)written once we know the # version, so the fallback runs at most once per install. The # flat-container URL pins the exact version we checked, # unlike the v2 /package/ endpoint, which just redirects to whatever is # newest at the moment of the request. Write-Step 'BinSkim' [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # No progress bar: Windows PowerShell 5.1 redraws it per chunk, and on a # download this size that, not the network, is the wait - see # Install-AndroidSdk for the measurement. Local to this function. $ProgressPreference = 'SilentlyContinue' $exe = Join-Path $BinSkimDir 'BinSkim.exe' $marker = Join-Path $BinSkimDir 'nupkg-version.txt' $have = $null if (Test-Path $exe) { if (Test-Path $marker) { $have = (Get-Content $marker -Raw).Trim() } else { $pv = (Get-Item $exe).VersionInfo.ProductVersion # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha"). if ($pv) { $have = $pv.Split('+')[0].Trim() } } } $latest = $null try { $index = Invoke-RestMethod -UseBasicParsing ` -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json" # Versions come back oldest-first; '-' marks a prerelease. $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1 } catch { Write-Warning "BinSkim version check failed: $($_.Exception.Message)" } if (-not $latest) { if (-not $have) { Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.' return } Write-Host " BinSkim $have kept (could not reach NuGet to check for a newer one)." } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) { Write-Host " BinSkim $have is already the newest stable release; skipping download." # Records what the ProductVersion fallback just worked out, so the next # run reads the marker instead of re-deriving it. Set-Content -Path $marker -Value $latest -Encoding ascii } else { if ($have) { Write-Host " BinSkim $have -> $latest; downloading." } else { Write-Host " BinSkim $latest; downloading." } $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N')) New-Item -ItemType Directory -Force -Path $tmp | Out-Null try { $zip = Join-Path $tmp 'binskim.zip' Invoke-WebRequest -UseBasicParsing -OutFile $zip ` -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg" Expand-Archive -Path $zip -DestinationPath $tmp -Force # Native RID first, emulatable one second. Matched against the path # so the newest matching tools\\\ folder wins, as before. $BinSkimRids = if ($IsArm64) { @('win-arm64', 'win-x64') } else { @('win-x64') } $src = $null $allExes = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe' foreach ($rid in $BinSkimRids) { $src = $allExes | Where-Object { $_.FullName -match [regex]::Escape($rid) } | Sort-Object FullName | Select-Object -Last 1 if ($src) { if ($rid -ne $BinSkimRids[0]) { Write-Host " No $($BinSkimRids[0]) build in the package; using $rid (runs under emulation)." -ForegroundColor Yellow } break } } if (-not $src) { throw "BinSkim.exe ($($BinSkimRids -join ' / ')) not found in package." } # Replace wholesale rather than merging over the old tree, so files # dropped between releases don't linger. if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir } New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null Copy-Item -Path (Join-Path $src.Directory.FullName '*') ` -Destination $BinSkimDir -Recurse -Force # Written last: the marker must only claim a version that fully landed. Set-Content -Path $marker -Value $latest -Encoding ascii Write-Host " BinSkim $latest installed to $BinSkimDir" } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue } } Add-ToUserPath $BinSkimDir } function Get-GitPath { # winget installed Git moments ago, but this process inherited its PATH # before that happened, so Get-Command can miss it on a first run. Prefer a # git already on PATH, then the usual install roots. $onPath = Get-Command git.exe -ErrorAction SilentlyContinue if ($onPath) { return $onPath.Source } $roots = @( (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'), (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'), (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe') ) return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1 } function Set-GlobalGitConfig { Write-Step 'Global git config' $git = Get-GitPath if (-not $git) { Write-Warning 'git.exe not found; skipping global git config.' return } Write-Host " using $git" if (-not $GitUserName -or -not $GitUserEmail) { Write-Host ' Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow Write-Host ' Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow Write-Host ' your identity per-repository.' -ForegroundColor Yellow } else { & $git config --global user.name $GitUserName & $git config --global user.email $GitUserEmail Write-Host " identity: $GitUserName <$GitUserEmail>" } # --- Make git use a Win32-OpenSSH client --- # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client # cannot reach the Windows ssh-agent service that the elevated half enables: # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not # speak. So keys added with `ssh-add` from PowerShell stay invisible to git, # and a push falls back to hunting for a key file and prompting for its # passphrase. Pointing core.sshCommand at a Win32-OpenSSH ssh.exe gives git # the same client, the same agent, and the same %USERPROFILE%\.ssh\config as # `ssh` from an ordinary shell. # # Two of those are on the box, and the one beside rsync.exe is preferred. # It is the same client from the same source, with the same ~/.ssh, agent # and known_hosts, built with a pump on its stdin: the in-box one reads # stdin 3KB at a time, which holds anything git PUSHES to ~17MB/s however # fast the link is. It only exists once the elevated half has run, so the # in-box client stays the fallback - and on a first provisioning run from # setup-windows.bat it is the elevated half that runs first, so the fast one # is normally already there. # # ON ARM64 the preference is the same but the trade is different: that build # is published for x64 only, so it is the EMULATED client being preferred over # a native ARM64 one. It is still the right pick when it runs - a push is # bounded by the socket, not by emulated CPU, so lifting the 3KB stdin cap # wins by far more than emulation costs - but it may well not run at all, # because it links against a System32 libcrypto.dll that is an ARM64 binary # here. That is exactly why candidates are tried by RUNNING them below rather # than by Test-Path, and why the elevated half deletes that ssh.exe outright # when it will not start. Either way this lands on a working client. $sshCandidates = @( (Join-Path $RsyncDir 'ssh.exe'), (Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe') ) $winSsh = $null foreach ($cand in $sshCandidates) { if (-not (Test-Path $cand)) { continue } # Run it, rather than just believing the file is there: the build beside # rsync.exe links against the libcrypto.dll the OpenSSH Client capability # puts in System32, and without that capability it is a binary that does # not start. Better to find that out here than on the next `git push`. # # EAP back to Continue for the call: ssh -V writes its version to # STDERR, and with $ErrorActionPreference = 'Stop' a native command's # stderr becomes a terminating RemoteException - so the working client # would look like the broken one. $prevEap = $ErrorActionPreference $ErrorActionPreference = 'Continue' $version = $null # Clear the exit code first, explicitly at global scope. An exe that # cannot start at all - the missing-libcrypto case - throws here without # ever setting one, and the stale 0 from the last native command that DID # run would otherwise read as success. $global: because a bare assignment # would make a local copy that the native call then does not update. $global:LASTEXITCODE = $null # Collect ALL the output, THEN take its first line. Piped straight into # `Select-Object -First 1`, which is how this used to read, PowerShell # stops the pipeline the moment ssh.exe prints its banner - before it # has exited - kills it, and the exit code comes back -1 instead of 0. # Measured under Windows PowerShell 5.1 against a healthy # C:\Tools\rsync\ssh.exe: 19 of 20 runs reported -1 that way, 0 of 20 # once collected first. So this check usually judged the fast client # broken and handed git the in-box one it exists to avoid. # setup-windows-with-uac.ps1 fixed the same trap in its own ssh.exe # check (see DRAIN THE OUTPUT there); this copy was missed. try { $sshOut = @(& $cand -V 2>&1); $version = $sshOut[0] } catch { } finally { $ErrorActionPreference = $prevEap } if ($LASTEXITCODE -eq 0) { $winSsh = $cand; break } $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" } Write-Warning "$cand did not run ($why)$(if ($version) { ": $version" })" } if (-not $winSsh) { 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." return } # Forward slashes on purpose: git parses core.sshCommand with shell quoting # rules, in which a backslash is an escape character. $value = $winSsh -replace '\\', '/' & $git config --global core.sshCommand $value Write-Host " core.sshCommand: $value" Write-Host " $version" } function Set-NativeNinjaFirst { # Make the native ninja.exe the one that wins, including inside a Visual # Studio Developer Command Prompt. # # WHY THIS IS INSURANCE RATHER THAN THE FIX. VS ships an x64 ninja.exe even on # ARM64 and puts it on the PATH from # Common7\Tools\vsdevcmd\ext\cmake.bat, which does: # set "PATH=%PATH%;...\CMake\bin;...\CMake\Ninja" # That APPENDS - the VS directories land at the very end of the composed # PATH, behind every machine and user entry. So a native ninja installed # anywhere on the user PATH already beats it, and measurement on an ARM64 box # confirms it does. (An earlier revision of this script claimed VsDevCmd # prepends and that the VS copy therefore always won; that was wrong.) # # It is still worth pinning the order explicitly: winget appends its package # directory to the user PATH, so the margin depends on nothing more than two # append orders staying as they are, in a file Microsoft owns and revises. # Putting the directory first costs nothing and removes the dependency. # # Ninja is worth this attention where a one-off tool would not be: it is # re-invoked for every edge in the build graph, so it is the one place an # emulated binary is paid over and over rather than once. Write-Step 'Native ninja ahead of the Visual Studio copy' $candidates = @() $candidates += Get-ChildItem (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages') ` -Filter 'ninja.exe' -Recurse -Depth 2 -ErrorAction SilentlyContinue | ForEach-Object { $_.FullName } $candidates += @( (Join-Path $env:ProgramFiles 'Ninja\ninja.exe') (Join-Path $env:LOCALAPPDATA 'Programs\Ninja\ninja.exe') ) # A ninja already on the PATH counts too - but only if it is not the VS one, # which is the binary this step exists to get out in front of. $onPath = (Get-Command ninja.exe -ErrorAction SilentlyContinue | Select-Object -First 1).Source if ($onPath -and $onPath -notmatch 'CommonExtensions\\Microsoft\\CMake') { $candidates += $onPath } $native = $null foreach ($c in ($candidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique)) { $m = Get-PEMachine $c if ($m -eq $(if ($IsArm64) { 'ARM64' } else { 'x64' })) { $native = $c; break } } if (-not $native) { Write-Warning 'No native ninja.exe found. Install it with: winget install Ninja-build.Ninja' Write-Warning 'Until then a build using the Ninja generator gets the x64 ninja Visual Studio bundles.' return } Write-Host " native ninja: $native ($(Get-PEMachine $native))" Add-ToUserPath (Split-Path $native -Parent) -Prepend } function Add-LlvmToUserPath { # Put the upstream LLVM's bin directory on the user PATH. # # Two reasons this needs a step rather than trusting the installer: # # 1. WHERE IT LANDS. LLVM's NSIS installer targets %ProgramFiles%\LLVM, and # when it cannot write there - a standard user, no elevation - it does not # fail. It silently falls back to a per-user directory, observed as # %USERPROFILE%\Documents\LLVM, and winget still reports "Successfully # installed". So the package is registered, the compiler is genuinely # there and native, and nothing can find it. # 2. PATH. The installer's "add to PATH" option is not taken in a silent # install, so clang-cl is not a command afterwards either way. # # Appended, not prepended: this is a second compiler kept deliberately # alongside MSVC, and it should not quietly win a `clang-cl` that some script # meant for Visual Studio's copy. Note VS does NOT put its own # VC\Tools\Llvm on the PATH (its clang-cl is reached through CMake's # -T ClangCL), so there is no collision to lose here. Write-Step 'Upstream LLVM on the user PATH' $candidates = @( (Join-Path $env:ProgramFiles 'LLVM\bin') (Join-Path ${env:ProgramFiles(x86)} 'LLVM\bin') (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin') (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin') (Join-Path $env:USERPROFILE 'Documents\LLVM\bin') ) $dir = $candidates | Where-Object { Test-Path (Join-Path $_ 'clang-cl.exe') } | Select-Object -First 1 if (-not $dir) { Write-Host ' Not installed (winget install LLVM.LLVM); Visual Studio''s own clang-cl is unaffected.' -ForegroundColor DarkGray return } $exe = Join-Path $dir 'clang-cl.exe' $mach = Get-PEMachine $exe Write-Host " $exe ($mach)" if ($IsArm64 -and $mach -ne 'ARM64') { Write-Warning "This LLVM is $mach, not ARM64. winget install LLVM.LLVM should resolve to the -woa64 build on this host." } if ($dir -notmatch [regex]::Escape($env:ProgramFiles)) { Write-Host ' Note: not under Program Files - the installer fell back to a per-user' -ForegroundColor Yellow Write-Host ' location because it could not write there. Re-run elevated for a machine-wide install.' -ForegroundColor Yellow } Add-ToUserPath $dir } function Get-RustupPath { # winget installed rustup moments ago, but this process inherited its PATH # before rustup-init added .cargo\bin to it, so Get-Command can miss it on a # first run. Prefer one already on the PATH, then the cargo home. $onPath = Get-Command rustup.exe -ErrorAction SilentlyContinue if ($onPath) { return $onPath.Source } $exe = Join-Path $CargoHome 'bin\rustup.exe' if (Test-Path $exe) { return $exe } $null } function Set-RustDefaultToolchain { # Install Rust's stable MSVC toolchain for THIS host and make it the default: # stable-x86_64-pc-windows-msvc on x64, stable-aarch64-pc-windows-msvc on # ARM64. # # winget's rustup install mostly does this already - it runs # `rustup-init -y -q`, which installs stable for the host rustup detects - so # on a fresh box this step largely confirms it. It exists to make the answer # explicit rather than inherited. rustup takes its default host from its own # build, so an x64 rustup on an ARM64 box - an install from before the # manifest had an arm64 rustup-init, or one started from an emulated x64 # shell - quietly sets up an x86_64 host and an emulated compiler. Naming the # triple pins both the toolchain installed here and, through # `set default-host`, what a bare `stable` means to rustup from then on. # # MSVC rather than GNU: the -msvc toolchains link with link.exe and the # Windows SDK from the Visual Studio the elevated half installs - including # the ARM64 build tools an aarch64 host links with. Those are needed to BUILD, # not to install, so this step does not depend on the elevated half. # # Re-runs are cheap: `toolchain install` on an installed toolchain updates it # to the current stable, or reports it unchanged. Setting the default each # time is the point of the step - a default you changed by hand (to nightly, # say) is put back to stable, so leave the step out of the plan to keep it. Write-Step 'Rust: stable MSVC toolchain as the default' if (-not $RustHost) { Write-Warning "No Rust host toolchain is set up for host architecture '$HostArch'; skipping." return } $rustup = Get-RustupPath if (-not $rustup) { Write-Warning 'rustup not found. Install it with: winget install Rustlang.Rustup' return } Write-Host " using $rustup ($(Get-PEMachine $rustup))" # EAP back to Continue for the calls: rustup reports progress on STDERR, and # under $ErrorActionPreference = 'Stop' a native command's stderr can become # a terminating error. Judged by the exit code instead - cleared first, as # for ssh.exe above, so an exe that cannot start at all does not inherit the # last one's 0. $toolchain = "stable-$RustHost" $calls = @( @('set', 'default-host', $RustHost), @('toolchain', 'install', $toolchain), @('default', $toolchain) ) $prevEap = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { foreach ($call in $calls) { $global:LASTEXITCODE = $null & $rustup @call if ($LASTEXITCODE -ne 0) { $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" } throw "rustup $($call -join ' ') failed ($why)" } } } finally { $ErrorActionPreference = $prevEap } # Report the compiler itself. .cargo\bin\rustc.exe is a rustup proxy - a copy # of rustup.exe - so its architecture says nothing about the toolchain's. $rustc = Join-Path $RustupHome "toolchains\$toolchain\bin\rustc.exe" if (Test-Path $rustc) { Write-Host " default: $toolchain - $(& $rustc -V) ($(Get-PEMachine $rustc))" } else { Write-Warning "rustup reported success, but $rustc is not there." } # An x86_64 host toolchain left on an ARM64 box - from before this step # pinned the triple - is an emulated compiler that is no longer the default. # Named rather than removed; whether it goes is your call. Building x64 code # from here wants the x64 TARGET on the native toolchain, not an x64 host. $x64Stable = Join-Path $RustupHome 'toolchains\stable-x86_64-pc-windows-msvc' if ($IsArm64 -and (Test-Path $x64Stable)) { Write-Host ' Also installed: stable-x86_64-pc-windows-msvc, an x64 compiler that runs emulated here.' -ForegroundColor Yellow Write-Host " Remove it with 'rustup toolchain uninstall stable-x86_64-pc-windows-msvc'; to build" -ForegroundColor Yellow Write-Host " x64 code from this box, use 'rustup target add x86_64-pc-windows-msvc' instead." -ForegroundColor Yellow } } function Set-UserEnvironmentVariable([string] $Name, [string] $Value) { # HKCU, like Add-ToUserPath, so it outlives the script; written only when it # differs, so a re-run changes nothing. if ([Environment]::GetEnvironmentVariable($Name, 'User') -eq $Value) { Write-Host " $Name is already $Value" return } [Environment]::SetEnvironmentVariable($Name, $Value, 'User') Write-Host " Set $Name = $Value (restart your shell to pick it up)." } function Get-AndroidRevision($Package) { # A package's revision from the index, as a [version]: , optional # and . [int] of a missing element is 0. $r = $Package.revision [version]('{0}.{1}.{2}' -f [int]$r.major, [int]$r.minor, [int]$r.micro) } function ConvertTo-Revision([string] $Text) { # "23.0" as the same three-part [version] the index gives, so the two # compare. [version]'23.0' has no third part - it reads as -1 - and so # counted as OLDER than 23.0.0: an installed, current copy looked stale. $parts = @($Text.Trim() -split '\.' | Where-Object { $_ -ne '' }) while ($parts.Count -lt 3) { $parts += '0' } [version]($parts[0..2] -join '.') } function Invoke-AndroidCli { # The Android CLI (cmdline-tools\latest\bin\android.exe) against this SDK, # its output shown as it comes - a first install downloads well over 100 MB # and should not look stalled. Returns the exit code, $null if it would not # start. EAP Continue for the call, as for the other native tools here. # # stdin is one empty line, so it is closed rather than the console: a # prompt nobody expected gets "no" instead of an unattended run waiting on # it forever. param([string[]] $Arguments) $cli = Join-Path $AndroidSdkRoot 'cmdline-tools\latest\bin\android.exe' $prevEap = $ErrorActionPreference $ErrorActionPreference = 'Continue' try { $global:LASTEXITCODE = $null # Its stderr becomes error records under 2>&1 in Windows PowerShell, # which would print as red "NativeCommandError" noise; back to plain # lines first. The one JVM warning dropped is the bundled Java noting, # on every call, a flag this Windows 10 does not support. '' | & $cli "--sdk=$AndroidSdkRoot" @Arguments 2>&1 | ForEach-Object { "$_" } | Where-Object { $_ -notmatch 'UseAllWindowsProcessorGroups flag is not supported' } | Out-Host $LASTEXITCODE } finally { $ErrorActionPreference = $prevEap } } function Install-AndroidSdk { # The Android SDK for building apps, per-user, in Android Studio's default # location (%LOCALAPPDATA%\Android\Sdk) unless ANDROID_HOME names another: # the command-line tools, platform-tools, and the newest stable platform and # build-tools. That is what Android Studio's first-run wizard would set up, # done without the wizard - on the x64 laptop Studio was installed and that # wizard had never run, so there was no SDK at all. Gradle fetches any other # platform or build-tools a project asks for by itself, once the licences are # accepted, so this is the floor rather than the whole set. # # "Newest stable" comes from Google's package index, read here each run: # channel-0 (stable) and no revision, the platform by API level # (android-37.2 beats android-37.1 beats android-36), build-tools by version. # # THE COMMAND-LINE TOOLS ARE NOT WHAT THEY WERE. From 23.0, sdkmanager is # deprecated and sdkmanager.bat is a shim over the new Android CLI # (cmdline-tools\latest\bin\android.exe, `android sdk install ...`), which on # first use installs itself into %USERPROFILE%\.android (bin\android-cli.exe, # about 90 MB, and cli\ - a bundled Java runtime, and a metrics spool). So # the CLI is called directly here, with its own "platforms/android-37.2" # package paths: no deprecated shim, and no cmd parsing to split the old # "platforms;android-37.2" at its semicolon. `sdk install` installs a # package or, if it is there, updates it to the latest - so it is also the # re-run path, downloading nothing when everything is current. # # ITS EXIT CODE IS NOT TRUSTED. CLI 1.0.16406183 finishes every `sdk` # command and then crashes on the way out, 0xC0000409 (a fail-fast in # ucrtbase) - on the x64 laptop's Windows 10, every time, in a console or # not, while `--version` and `info` exit 0. So success is judged by the # result: each package asked for must have the package.xml the CLI writes # once a package is complete. A nonzero exit with everything present is a # note, not a failure; anything missing is a failure, whatever the exit. # # The command-line tools themselves are bootstrapped from the index's own # "cmdline-tools;latest" archive (SHA-1 from the index), and replaced only # when the index has a newer revision than the one in source.properties. # The CLI cannot do that for them: the archive calls itself # cmdline-tools;23.0, a fixed version, so it would never "update" it. # # The SDK licences are accepted on your behalf; the plan says so before # anything runs. The CLI does it as it installs - sdkmanager --licenses is # now a no-op - writing licenses\android-sdk-license. Gradle needs it to # build, and to fetch what a project asks for. # # The CLI brings its own Java, so the SDK needs no JDK. Gradle does: when # there is no JAVA_HOME, the one Android Studio bundles (jbr) becomes the # user's, so a command-line gradlew works. An existing JAVA_HOME is never # changed. Write-Step "Android SDK in $AndroidSdkRoot" [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # No progress bar for the downloads. Windows PowerShell 5.1's # Invoke-WebRequest redraws it per chunk, and that - not the network - is # what a large download then waits on: measured on the x64 laptop, the # 148 MB command-line tools took about ten minutes and five minutes of CPU # with it on. Local to this function, so nothing else changes. $ProgressPreference = 'SilentlyContinue' [xml]$index = (Invoke-WebRequest -UseBasicParsing -Uri $AndroidIndex).Content $stable = @($index.DocumentElement.remotePackage | Where-Object { $_.channelRef.ref -eq 'channel-0' -and -not $_.revision.preview }) # --- the command-line tools: bootstrapped, and kept current, from the index --- $ct = @($stable | Where-Object { $_.path -eq 'cmdline-tools;latest' })[0] if (-not $ct) { throw "No stable cmdline-tools;latest in $AndroidIndex." } $ctWant = Get-AndroidRevision $ct $ctDir = Join-Path $AndroidSdkRoot 'cmdline-tools\latest' $ctHave = $null $props = Join-Path $ctDir 'source.properties' if (Test-Path $props) { $m = [regex]::Match((Get-Content $props -Raw), '(?m)^Pkg\.Revision=(\d+(\.\d+){0,2})') if ($m.Success) { $ctHave = ConvertTo-Revision $m.Groups[1].Value } } if ($ctHave -and $ctHave -ge $ctWant) { Write-Host " command-line tools $ctHave are current." } else { $archive = @($ct.archives.archive | Where-Object { $_.'host-os' -eq 'windows' })[0] $sum = $archive.complete.checksum $sha1 = if ($sum -is [string]) { $sum } else { $sum.'#text' } $url = $AndroidRepo + $archive.complete.url Write-Host " command-line tools $(if ($ctHave) { "$ctHave -> " })$ctWant; downloading $($archive.complete.url)." # PATH LENGTH. The archive nests deep - a guava jar in it sits well over # 150 characters below its top - and Windows PowerShell 5.1 is bound by # the 260-character MAX_PATH. So the temp directory's name is 8 # characters: %TEMP%\xxxxxxxx\cmdline-tools\... is then no deeper than # %LOCALAPPDATA%\Android\Sdk\cmdline-tools\latest\..., and whenever the # SDK's own path fits, unpacking it does too. (A 43-character name here # made the unpack deeper than the SDK it was for.) $tmp = Join-Path $env:TEMP ([guid]::NewGuid().ToString('N').Substring(0, 8)) New-Item -ItemType Directory -Force -Path $tmp | Out-Null try { $zip = Join-Path $tmp 'ct.zip' Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip $got = (Get-FileHash $zip -Algorithm SHA1).Hash.ToLower() if ($sha1 -and $got -ne $sha1.ToLower()) { throw "SHA-1 mismatch for $url`: expected $sha1, got $got" } Expand-Archive -Path $zip -DestinationPath $tmp -Force # The archive holds a top-level cmdline-tools\ directory; the SDK # layout wants it at cmdline-tools\latest. Replaced wholesale, as # BinSkim is, so files dropped between releases do not linger - but # the old copy is RENAMED aside first and deleted last. A rename is # one operation whatever the depth below it; deleting walks every # file and can trip over a path that is too long. Done this way, a # delete that fails leaves a stray folder to report, not an SDK # with no command-line tools in it. The aside name is six # characters, like "latest", so the delete is no deeper either. New-Item -ItemType Directory -Force -Path (Split-Path $ctDir) | Out-Null $old = $null if (Test-Path $ctDir) { $old = Join-Path (Split-Path $ctDir) ('old' + [guid]::NewGuid().ToString('N').Substring(0, 3)) Rename-Item -Path $ctDir -NewName (Split-Path $old -Leaf) } Move-Item -Path (Join-Path $tmp 'cmdline-tools') -Destination $ctDir if ($old) { try { Remove-Item -Recurse -Force $old } catch { Write-Warning "The new command-line tools are in place, but the old copy could not be removed: $old ($($_.Exception.Message))" } } } finally { Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue } } # --- the newest stable platform and build-tools, by the index --- $platform = @($stable | ForEach-Object { $m = [regex]::Match($_.path, '^platforms;android-(\d+)(?:\.(\d+))?$') if ($m.Success) { [pscustomobject]@{ Path = $_.path; Api = [version]('{0}.{1}' -f $m.Groups[1].Value, [int]$m.Groups[2].Value) } } } | Sort-Object Api)[-1].Path $buildTools = @($stable | Where-Object { $_.path -match '^build-tools;\d+(\.\d+)*$' } | Sort-Object { [version]($_.path -replace '^build-tools;', '') })[-1].path if (-not $platform -or -not $buildTools) { throw "Could not find a stable platform and build-tools in $AndroidIndex." } # The index names packages "platforms;android-37.2"; the CLI, and the SDK's # directories, use "platforms/android-37.2". $packages = @('platform-tools', ($platform -replace ';', '/'), ($buildTools -replace ';', '/')) Write-Host " installing or updating: $($packages -join ', ')" $rc = Invoke-AndroidCli -Arguments (@('sdk', 'install') + $packages) $missing = @($packages | Where-Object { -not (Test-Path (Join-Path $AndroidSdkRoot (($_ -replace '/', '\') + '\package.xml'))) }) if ($missing) { $why = if ($null -eq $rc) { 'it would not start' } else { "exit $rc" } throw "android sdk install left out $($missing -join ', ') ($why)" } if ($null -eq $rc) { Write-Warning 'The Android CLI would not start; the packages already installed were left as they were, not updated.' } elseif ($rc -ne 0) { 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 Write-Host ' install: every package asked for is in place.' -ForegroundColor DarkGray } # Report what is there now, from each package's own source.properties. foreach ($pkg in $packages) { $p = Join-Path $AndroidSdkRoot (($pkg -replace '/', '\') + '\source.properties') $rev = if (Test-Path $p) { [regex]::Match((Get-Content $p -Raw), '(?m)^Pkg\.Revision=(.*)$').Groups[1].Value.Trim() } else { '?' } Write-Host (' {0,-28} {1}' -f $pkg, $rev) } Set-UserEnvironmentVariable 'ANDROID_HOME' $AndroidSdkRoot # JAVA_HOME, for Gradle - only when there is none, and only to Android # Studio's bundled JDK. Without Studio this just says what is missing. if (-not [Environment]::GetEnvironmentVariable('JAVA_HOME', 'User') -and -not [Environment]::GetEnvironmentVariable('JAVA_HOME', 'Machine')) { $jbr = @((Join-Path $env:ProgramFiles 'Android\Android Studio\jbr'), (Join-Path $env:LOCALAPPDATA 'Programs\Android Studio\jbr') | Where-Object { Test-Path (Join-Path $_ 'bin\java.exe') })[0] if ($jbr) { Set-UserEnvironmentVariable 'JAVA_HOME' $jbr } else { 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.' } } # The Android CLI (android), and the tools beside it (lint, d8, r8, # apkanalyzer, the sdkmanager/avdmanager shims), in any shell. # platform-tools is NOT added: the PlatformTools step already puts adb on the # PATH, and two adb.exe on it would only make which one answers depend on # the order. Add-ToUserPath (Join-Path $ctDir 'bin') } function Get-PEMachine { # Architecture of a PE, read straight from the COFF header: the 2 bytes at # the e_lfanew offset + 4. Cheap, and it answers the only question that # matters here - would this exe run natively, or through emulation? # # Deliberately NOT Get-Command's .FileVersionInfo or the package metadata: # a multi-architecture package (Sysinternals) ships every build in one zip # under different names, and an installer's own metadata says nothing about # which binary got laid down. The file itself cannot be wrong. param([string]$Path) if (-not (Test-Path $Path)) { return $null } try { $fs = [IO.File]::OpenRead($Path) $br = New-Object IO.BinaryReader($fs) try { $fs.Seek(0x3c, 'Begin') | Out-Null $pe = $br.ReadInt32() if ($pe -le 0 -or $pe -gt ($fs.Length - 6)) { return 'not-PE' } $fs.Seek($pe + 4, 'Begin') | Out-Null switch ($br.ReadUInt16()) { 0x8664 { 'x64' } 0xAA64 { 'ARM64' } 0x014c { 'x86' } 0x01c4 { 'ARM32' } default { 'unknown' } } } finally { $br.Close(); $fs.Close() } } catch { $null } } function Invoke-ArchAudit { # Report the actual architecture of the tools this box provisions, resolved # the way a shell would (PATH first, then the usual install roots), so what # is printed is what you would really run. # # This exists because "winget installed it" does not mean "you got the native # build", and the gap is not always where you would guess - Visual Studio's # own bundled ninja.exe is x64 even on an ARM64 host. A per-run audit turns # that from something you trip over into something the log tells you. # # Purely informational: it never fails the run. On x64 everything is expected # to be x64 and the output is dull; the value is on ARM64, where each line is # either native or a known, listed exception. Write-Step "Architecture audit (host: $HostArch)" # Resolve against the PATH a NEW shell would get, not this process's. # # The steps above write the HKCU PATH, which a running process never sees - # so auditing $env:PATH would report the state from before this script ran and # warn about a problem it had just fixed. Compose machine + user from the # registry (the order Windows itself uses), then append anything extra this # process happens to carry: that tail is where a Developer Command Prompt's VS # directories live, and keeping it last mirrors how VsDevCmd appends them. $composed = @() foreach ($scope in 'Machine', 'User') { $v = [Environment]::GetEnvironmentVariable('Path', $scope) if ($v) { $composed += ($v -split ';' | Where-Object { $_.Trim() }) } } $composed += ($env:PATH -split ';' | Where-Object { $_.Trim() }) $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase) $searchPath = @($composed | Where-Object { $seen.Add($_.Trim().TrimEnd('\')) }) function Resolve-OnPath([string]$Exe) { foreach ($d in $searchPath) { $p = Join-Path $d $Exe if (Test-Path $p -PathType Leaf) { return $p } } return $null } # Tools with no native ARM64 build available anywhere, with the reason. These # print as expected rather than as problems - see the README's ARM64 section. # # Shorter than it was: BinSkim, OpenCppCoverage and NASM used to be listed # here as accepted emulation, and are now simply not installed on ARM64. That # is the whole shape of the change - the exceptions that were tolerable one at # a time added up to a VM full of x64 binaries. # # rsync came off this list when the release started publishing an arm64 # asset. An x64 rsync.exe on an ARM64 box is now a leftover from a run before # that, not an accepted exception, so it warns and gets a remedy below. $KnownEmulated = @{ 'iperf3.exe' = 'no ARM64 build published; network-bound anyway' 'py.exe' = 'python.org ships the launcher shim as x86; it execs the native python.exe' 'vswhere.exe' = 'Microsoft ships x86 only; runs once per script' 'adb.exe' = 'Google ships platform-tools as x86 only; bound by the USB/TCP link' } # Fixable cases: a native build DOES exist, something just resolved ahead of # it. Printed with the finding so the log carries the remedy, not just the # complaint. # # ninja is the one that actually bites: Visual Studio bundles an x64 ninja.exe # even on ARM64, and it is re-invoked for every edge in the build graph, so # an emulated one is paid over and over rather than once. The NinjaPath step # puts the native copy first; this is the check that it worked. # # All of these are for tools ARM64 still installs. The clang-cl and WinMerge # remedies were removed with their rows: advising an install that the # x64-only set has just declined to do would be the audit arguing with the # provisioning. $Remedies = @{ '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.' 'cmake.exe' = 'Install the native build with: winget install Kitware.CMake (its MSI is machine-scope, so it needs an administrator).' '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.' '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.' '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.' } $vs = $null $vsWhereExe = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' if (Test-Path $vsWhereExe) { $vs = & $vsWhereExe -products '*' -property installationPath -format value | Select-Object -First 1 } # name -> extra candidate paths searched when the name is not on the PATH. $targets = [ordered]@{ # The native installer's launcher, then the old winget route's link. # PATH-first like the rest, so this reports whichever claude wins. 'claude.exe' = @((Join-Path $env:USERPROFILE '.local\bin\claude.exe'), (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Links\claude.exe')) 'git.exe' =@("$env:LOCALAPPDATA\Programs\Git\cmd\git.exe", (Join-Path $env:ProgramFiles 'Git\cmd\git.exe')) 'python.exe' = @() # Both homes of the launcher: C:\Windows for an all-users install, the # per-user Launcher directory otherwise. Often neither - it is a separate # component from the interpreter, and "- not installed" here next to a # native python.exe is the normal result of an unelevated Python install. 'py.exe' = @("$env:WINDIR\py.exe", "$env:LOCALAPPDATA\Programs\Python\Launcher\py.exe") 'pwsh.exe' = @() 'cmake.exe' = @((Join-Path $env:ProgramFiles 'CMake\bin\cmake.exe')) 'ninja.exe' = @() # Upstream LLVM. The Documents path is not a typo - see Add-LlvmToUserPath # for why an unelevated install lands there. 'clang-cl.exe' = @( (Join-Path $env:ProgramFiles 'LLVM\bin\clang-cl.exe') (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin\clang-cl.exe') (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin\clang-cl.exe') ) # rustup itself, then the compiler the stable toolchain really runs. The # rustc.exe in .cargo\bin that a shell would find is a rustup proxy - a # copy of rustup.exe - so its architecture is rustup's, not the # toolchain's. The labelled row looks inside the toolchain instead, # native host first, so an x64 toolchain on ARM64 only shows up when it # is the one there is. 'rustup.exe' = @((Join-Path $CargoHome 'bin\rustup.exe')) 'rustc.exe (stable)' = @( $(if ($RustHost) { Join-Path $RustupHome "toolchains\stable-$RustHost\bin\rustc.exe" }) (Join-Path $RustupHome 'toolchains\stable-x86_64-pc-windows-msvc\bin\rustc.exe') ) 'dotnet.exe' = @((Join-Path $env:ProgramFiles 'dotnet\dotnet.exe')) 'WinMergeU.exe' = @((Join-Path $env:ProgramFiles 'WinMerge\WinMergeU.exe'), (Join-Path ${env:ProgramFiles(x86)} 'WinMerge\WinMergeU.exe')) 'BinSkim.exe' = @((Join-Path $BinSkimDir 'BinSkim.exe')) 'rsync.exe' = @((Join-Path $RsyncDir 'rsync.exe')) 'ssh.exe' = @((Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe')) # NASM's installer falls back to a per-user directory when it cannot # write to Program Files - see the NASM comment in setup-windows.bat. It # registers nothing there, so winget cannot see it (and re-downloads and # re-runs the installer on every run), and it puts nothing on the PATH. # Without these candidates the audit reported "- not installed" for a # nasm.exe that was on disk all along, and then still concluded that # everything had resolved. 'nasm.exe' = @( (Join-Path $env:LOCALAPPDATA 'bin\NASM\nasm.exe') (Join-Path $env:ProgramFiles 'NASM\nasm.exe') (Join-Path ${env:ProgramFiles(x86)} 'NASM\nasm.exe') ) 'iperf3.exe' = @() # A winget portable package: unpacked under WinGet\Packages, with that # directory put on the user PATH. This finds it should the PATH entry # have gone missing. 'adb.exe' = @(Resolve-Path (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages\Google.PlatformTools_*\platform-tools\adb.exe') -ErrorAction SilentlyContinue | ForEach-Object { $_.Path }) 'OpenCppCoverage.exe' = @((Join-Path $env:ProgramFiles 'OpenCppCoverage\OpenCppCoverage.exe'), (Join-Path ${env:ProgramFiles(x86)} 'OpenCppCoverage\OpenCppCoverage.exe')) 'vswhere.exe' = @($vsWhereExe) 'xperf.exe' = @((Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe')) } if ($vs) { $targets['MSBuild.exe'] = @((Join-Path $vs 'MSBuild\Current\Bin\arm64\MSBuild.exe'), (Join-Path $vs 'MSBuild\Current\Bin\MSBuild.exe')) # The MSVC and VS-Clang compilers, under whichever MSVC version is present. $msvc = Get-ChildItem (Join-Path $vs 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue | Sort-Object Name | Select-Object -Last 1 if ($msvc) { $hostDir = if ($IsArm64) { 'Hostarm64\arm64' } else { 'Hostx64\x64' } $targets['cl.exe (MSVC)'] = @((Join-Path $msvc.FullName "bin\$hostDir\cl.exe")) } $llvmHost = if ($IsArm64) { 'ARM64\bin' } else { 'x64\bin' } $targets['clang-cl.exe (VS)'] = @((Join-Path $vs "VC\Tools\Llvm\$llvmHost\clang-cl.exe")) } # Tools this box does not provision on ARM64. Dropped from the audit rather # than left to print "- not installed", because that line reads as a gap in # the provisioning when it is the provisioning working as intended - and a # dull audit is one you keep reading. # # The rows survive on x64, where all of these are installed and expected. # Anything still on disk from before the split shows up in the winget list, # not here. if ($IsArm64) { foreach ($gone in 'WinMergeU.exe', 'BinSkim.exe', 'nasm.exe', 'OpenCppCoverage.exe', 'clang-cl.exe', 'clang-cl.exe (VS)') { $targets.Remove($gone) } } $native = if ($IsArm64) { 'ARM64' } else { 'x64' } $unexpected = @() foreach ($name in $targets.Keys) { # A LABELLED entry - "clang-cl.exe (VS)" - names one specific copy, so it # is resolved ONLY from its explicit candidates. Falling back to the PATH # there would silently answer with a different installation of the same # tool: with upstream LLVM on the PATH, the "(VS)" row reported the # upstream compiler and so claimed Visual Studio's was present when it was # not. Unlabelled entries still resolve PATH-first, because for those the # question is which binary a build would actually invoke. $exe = ($name -split ' ')[0] $isPinned = $name -ne $exe if ($isPinned) { $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 } else { $path = Resolve-OnPath $exe if (-not $path) { $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 } } if (-not $path) { Write-Host (" {0,-22} {1}" -f $name, '- not installed') -ForegroundColor DarkGray; continue } $mach = Get-PEMachine $path if (-not $mach) { continue } if ($mach -eq $native) { Write-Host (" {0,-22} {1,-6} native" -f $name, $mach) -ForegroundColor Green } elseif ($KnownEmulated.ContainsKey($exe)) { Write-Host (" {0,-22} {1,-6} expected: {2}" -f $name, $mach, $KnownEmulated[$exe]) -ForegroundColor DarkGray } else { Write-Host (" {0,-22} {1,-6} NOT NATIVE - $path" -f $name, $mach) -ForegroundColor Yellow if ($Remedies.ContainsKey($exe)) { Write-Host (" {0,-22} {1,-6} -> {2}" -f '', '', $Remedies[$exe]) -ForegroundColor Yellow } $unexpected += "$name ($mach)" } } if ($unexpected) { Write-Warning "Running under emulation with no listed reason: $($unexpected -join ', ')." Write-Warning 'If a native build exists, prefer it (see the -> lines above); otherwise add it to $KnownEmulated with the reason.' } else { Write-Host ' Everything resolved to a native build, or to a listed exception.' -ForegroundColor Green } } # --------------------------------------------------------------------------- # Main # --------------------------------------------------------------------------- Write-Host "Host architecture: $HostArch" -ForegroundColor Cyan if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator)) { Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.' } # What each step runs. The ORDER comes from setup-windows-steps.ps1, which lists # ArchAudit last on purpose: it reports on what the steps before it (and the # winget installs in setup-windows.bat) actually put on the box. $steps = @{ LocalBinPath = { Add-LocalBinToUserPath } WinMergePath = { Add-WinMergeToUserPath } VsWhere = { Add-VsWhereToUserPath } BinSkim = { Install-BinSkim } GitConfig = { Set-GlobalGitConfig } NinjaPath = { Set-NativeNinjaFirst } LlvmPath = { Add-LlvmToUserPath } RustToolchain = { Set-RustDefaultToolchain } AndroidSdk = { Install-AndroidSdk } ArchAudit = { Invoke-ArchAudit } } # The catalog and the table above have to agree exactly. A catalog row with no # code here would be shown in the plan and then never taken; an entry here with # no row would never be shown, so never selected. Either is a bug in these # scripts, not in the box, so it stops the run before anything happens. $catalog = @(Get-SetupCatalog -IsArm64 $IsArm64 | Where-Object Runner -eq 'user') $unbacked = @($catalog | Where-Object { -not $steps.ContainsKey($_.Id) } | ForEach-Object { $_.Id }) $unlisted = @($steps.Keys | Where-Object { @($catalog.Id) -notcontains $_ }) if ($unbacked -or $unlisted) { $diff = @() if ($unbacked) { $diff += "in the catalog but not here: $($unbacked -join ', ')" } if ($unlisted) { $diff += "here but not in the catalog: $($unlisted -join ', ')" } throw "setup-windows-steps.ps1 and this script disagree - $($diff -join '; ')." } # 'WinMerge' was this step's name until the catalog put it beside the winget # step of the same name; still accepted. $plan = @(Resolve-SetupSelection -Steps $catalog ` -Only $(if ($PSBoundParameters.ContainsKey('Only')) { $Only } else { $null }) -Skip $Skip ` -Aliases @{ WinMerge = 'WinMergePath' } -IsArm64 $IsArm64 ` -VirtualMachine (Get-SetupVirtualMachine)) Write-SetupPlan $plan 'Plan for setup-windows-no-uac.ps1' $runCount = @($plan | Where-Object Selected).Count if ($runCount -eq 0) { Write-Host ' Nothing selected, so there is nothing to do.' exit 0 } $ok = Confirm-SetupPlan -Yes:$Yes -Count $runCount if ($ok -ne $true) { exit $(if ($null -eq $ok) { 2 } else { 0 }) } $failed = @() foreach ($p in $plan) { if (-not $p.Selected) { # Only the skips with a reason; the plan above already listed the rest. if ($p.Why) { Write-Host "`n==> $($p.Id) (skipped: $($p.Why))" -ForegroundColor DarkGray } continue } try { & $steps[$p.Id] } catch { # One broken step must not cost the others. Collect and report at the end. Write-Warning "$($p.Id) failed: $($_.Exception.Message)" $failed += $p.Id } } if ($failed) { Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red exit 1 } Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green exit 0