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)
7 powershell -NoProfile -ExecutionPolicy Bypass -File .\setup-windows-no-uac.ps1
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.
13 What this installs / configures:
14 - WinMerge on the user PATH (x64 only)
15 - vswhere.exe on the user PATH: the Visual Studio installer puts it in
16 %ProgramFiles(x86)%\Microsoft Visual Studio\Installer, which nothing adds
17 to the PATH, so build scripts (and VsDevCmd.bat itself) complain that
18 'vswhere.exe' is not recognized
19 - BinSkim (binary hardening analyzer) in %LOCALAPPDATA%\Programs\BinSkim,
20 on the user PATH (x64 only - the NuGet package publishes win-x64 alone)
21 - Global git identity, and core.sshCommand pointed at a Win32-OpenSSH
22 client so git shares the Windows ssh-agent: the fast ssh.exe the elevated
23 half unpacks beside rsync.exe if it is there, the in-box one otherwise
24 - An architecture audit: the real PE machine type of every tool this box
25 provisions, resolved the way a shell would. Informational, never fatal.
26 Anything running emulated without a listed reason is called out.
28 FILL IN $GitUserName / $GitUserEmail below before the first run.
30 Steps are independent: one failing warns and the rest still run. The exit code
31 is 1 if any step failed, 0 otherwise.
36 # Skip individual steps. Note that `powershell -File` cannot pass more than
37 # one value to an array parameter (neither comma- nor space-separated), so
38 # for several, dot-call the script or use -Command:
39 # .\setup-windows-no-uac.ps1 -Skip BinSkim,GitConfig
40 # powershell -File .\setup-windows-no-uac.ps1 -Skip BinSkim
41 [ValidateSet('WinMerge', 'VsWhere', 'BinSkim', 'GitConfig', 'NinjaPath', 'LlvmPath', 'ArchAudit')]
42 [string[]] $Skip = @()
45 $ErrorActionPreference = 'Stop'
47 # Host architecture, from the machine environment in the registry. Both of the
48 # obvious sources report the EMULATED architecture inside an emulated x64
49 # PowerShell - which is what `powershell` resolves to when launched from an x64
50 # shell on an ARM64 box. Measured on this machine:
51 # [RuntimeInformation]::OSArchitecture X64 <- wrong
52 # $env:PROCESSOR_ARCHITECTURE AMD64 <- wrong
53 # HKLM\...\Session Manager\Environment ARM64 <- right
54 # OSArchitecture is documented as the OS's architecture, and on .NET Core it is;
55 # under .NET Framework on Prism it is not, so it is kept only as a fallback.
56 # $IsArm64 decides which steps run at all, so this has to be the real one.
57 $rawArch = (Get-ItemProperty 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' -ErrorAction SilentlyContinue).PROCESSOR_ARCHITECTURE
58 if (-not $rawArch) { $rawArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() }
59 $IsArm64 = ($rawArch -eq 'ARM64')
60 $HostArch = if ($IsArm64) { 'Arm64' } elseif ($rawArch -eq 'AMD64') { 'X64' } else { $rawArch }
62 # Steps that do not run on ARM64, with the reason printed in place of the step.
64 # The ARM64 machine is provisioned as a single-compiler build box - see the
65 # x64-only set in setup-windows.bat - so the packages these three steps wire up
66 # are not installed there. Skipping the step rather than letting it find nothing
67 # matters: Install-BinSkim would happily download and PATH the x64 build, and
68 # Add-LlvmToUserPath is the step that put an emulated-adjacent toolchain on the
69 # PATH ahead of MSVC in the first place.
71 # -Skip still works on top of this; it can only subtract.
72 $Arm64Dropped = [ordered]@{
73 WinMerge = 'not installed on ARM64 - the only build an unelevated winget can fetch is the emulated x64 one'
74 BinSkim = 'not installed on ARM64 - the NuGet package publishes win-x64 only'
75 LlvmPath = 'not installed on ARM64 - this box carries MSVC alone'
78 # --- Global git identity: FILL THESE IN BEFORE RUNNING ---
79 # Left empty, Set-GlobalGitConfig skips the identity and says so, rather than
80 # stamping a placeholder onto your commits. Leaving them empty is a legitimate
81 # choice - it keeps your identity per-repository. core.sshCommand is set either
82 # way, so the ssh side works regardless.
83 $GitUserName = '' # e.g. 'Ada Lovelace'
84 $GitUserEmail = '' # e.g. 'ada@example.com'
86 # BinSkim's win-x64 build, from the NuGet flat container.
87 $BinSkimPackage = 'microsoft.codeanalysis.binskim'
88 $BinSkimDir = Join-Path $env:LOCALAPPDATA 'Programs\BinSkim'
90 # Where the elevated half puts rsync.exe and the ssh.exe it ships with. Only
91 # read here, to prefer that ssh.exe for git - keep it in step with $RsyncDir in
92 # setup-windows-with-uac.ps1 if you move the install.
93 $RsyncDir = 'C:\Tools\rsync'
95 function Write-Step([string]$Msg) {
96 Write-Host "`n==> $Msg" -ForegroundColor Cyan
99 function Add-ToUserPath {
100 # HKCU PATH, not the process PATH: this must outlive the script. Idempotent,
101 # and re-applied on every run so an entry lost to an unrelated PATH edit is
102 # repaired without re-doing the install that put it there.
104 # -Prepend puts the directory FIRST and moves it there if it is already
105 # present further down, which is the difference between "on the PATH" and
106 # "the one that wins". Only for entries where that matters; appending is the
107 # polite default and stays the default.
112 $user = [Environment]::GetEnvironmentVariable('Path', 'User')
113 if (-not $user) { $user = '' }
114 # Compare trailing-backslash-insensitively: C:\x and C:\x\ are the same
115 # directory, and adding a second spelling of one is just noise.
116 $norm = { param($s) $s.Trim().TrimEnd('\') }
117 $entries = @($user -split ';' | Where-Object { $_.Trim() })
118 $already = $entries | Where-Object { (& $norm $_) -eq (& $norm $Dir) }
121 if ($already) { Write-Host " $Dir already in user PATH."; return }
122 $new = if ($user.Trim()) { $user.TrimEnd(';') + ';' + $Dir } else { $Dir }
123 [Environment]::SetEnvironmentVariable('Path', $new, 'User')
124 Write-Host " Added $Dir to user PATH (restart your shell to pick it up)."
128 if ($already -and (& $norm $entries[0]) -eq (& $norm $Dir)) {
129 Write-Host " $Dir already first in user PATH."
132 $rest = $entries | Where-Object { (& $norm $_) -ne (& $norm $Dir) }
133 [Environment]::SetEnvironmentVariable('Path', (@($Dir) + $rest) -join ';', 'User')
135 Write-Host " Moved $Dir to the front of the user PATH (restart your shell to pick it up)."
137 Write-Host " Added $Dir to the front of the user PATH (restart your shell to pick it up)."
141 function Add-WinMergeToUserPath {
142 Write-Step 'WinMerge on the user PATH'
144 (Join-Path $env:ProgramFiles 'WinMerge'),
145 (Join-Path ${env:ProgramFiles(x86)} 'WinMerge'),
146 (Join-Path $env:LOCALAPPDATA 'Programs\WinMerge')
149 Where-Object { Test-Path (Join-Path $_ 'WinMergeU.exe') } |
150 Select-Object -First 1
152 Write-Warning 'WinMerge not found; user PATH unchanged.'
158 function Add-VsWhereToUserPath {
159 # vswhere.exe is how scripts locate Visual Studio (MSBuild, VsDevCmd.bat,
160 # the Windows SDK), and the VS installer drops it in a fixed directory that
161 # is never on the PATH. VsDevCmd.bat itself prints "'vswhere.exe' is not
162 # recognized" on every run without it. The directory is fixed by contract
163 # (32-bit Program Files, no version in the path), so there is nothing to
164 # search for: if it is missing, Visual Studio is not installed.
165 Write-Step 'vswhere on the user PATH'
166 $dir = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer'
167 if (-not (Test-Path (Join-Path $dir 'vswhere.exe'))) {
168 Write-Warning "vswhere.exe not found in $dir (no Visual Studio installer present); user PATH unchanged."
174 function Install-BinSkim {
175 # BinSkim checks the exact mitigations the native project enables in
176 # CMakeLists.txt (CFG/XFG, CET, ASLR/HighEntropyVA, DEP, /GS, stack cookies,
177 # DEPENDENTLOADFLAG, ...). The NuGet package ships a self-contained build, so
178 # this needs no .NET SDK/runtime: the .nupkg is a zip - extract the tool
179 # folder for this architecture and put it on the PATH. After restarting the
181 # binskim analyze path\to\your.exe
183 # ARCHITECTURE. The package currently publishes win-x64 only (its other RIDs
184 # are linux-x64, linux-arm64 and osx-x64) - there is no win-arm64 build. So on
185 # ARM64 this installs the x64 tool and it runs under emulation. That is a
186 # slowdown and nothing more: BinSkim READS PE headers and load configs, so the
187 # architecture of the binaries it analyses is independent of its own - an
188 # emulated x64 BinSkim checks ARM64 binaries perfectly well. $BinSkimRids is
189 # ordered preference, so if a win-arm64 build ever ships, an ARM64 box picks
190 # it up with no further change here.
192 # VERSION CHECK FIRST. The .nupkg is a large download (well over 100 MB), so
193 # ask NuGet what the newest stable version is BEFORE fetching anything, and
194 # skip the download entirely when the installed copy already matches.
195 # Re-provisioning an up-to-date box should not pay for it.
197 # The installed version is recorded in nupkg-version.txt next to the tool.
198 # For a copy installed before that marker existed, fall back to BinSkim.exe's
199 # own ProductVersion; either way the marker is (re)written once we know the
200 # version, so the fallback runs at most once per install. The
201 # flat-container URL pins the exact version we checked,
202 # unlike the v2 /package/<id> endpoint, which just redirects to whatever is
203 # newest at the moment of the request.
205 [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
207 $exe = Join-Path $BinSkimDir 'BinSkim.exe'
208 $marker = Join-Path $BinSkimDir 'nupkg-version.txt'
211 if (Test-Path $exe) {
212 if (Test-Path $marker) {
213 $have = (Get-Content $marker -Raw).Trim()
215 $pv = (Get-Item $exe).VersionInfo.ProductVersion
216 # NuGet versions carry no build metadata; ProductVersion may ("1.2.3+sha").
217 if ($pv) { $have = $pv.Split('+')[0].Trim() }
223 $index = Invoke-RestMethod -UseBasicParsing `
224 -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/index.json"
225 # Versions come back oldest-first; '-' marks a prerelease.
226 $latest = $index.versions | Where-Object { $_ -notmatch '-' } | Select-Object -Last 1
228 Write-Warning "BinSkim version check failed: $($_.Exception.Message)"
233 Write-Warning 'BinSkim not installed and NuGet unreachable; skipping.'
236 Write-Host " BinSkim $have kept (could not reach NuGet to check for a newer one)."
237 } elseif ($have -and ($have -eq $latest -or $have -eq "$latest.0")) {
238 Write-Host " BinSkim $have is already the newest stable release; skipping download."
239 # Records what the ProductVersion fallback just worked out, so the next
240 # run reads the marker instead of re-deriving it.
241 Set-Content -Path $marker -Value $latest -Encoding ascii
244 Write-Host " BinSkim $have -> $latest; downloading."
246 Write-Host " BinSkim $latest; downloading."
248 $tmp = Join-Path $env:TEMP ('binskim_' + [guid]::NewGuid().ToString('N'))
249 New-Item -ItemType Directory -Force -Path $tmp | Out-Null
251 $zip = Join-Path $tmp 'binskim.zip'
252 Invoke-WebRequest -UseBasicParsing -OutFile $zip `
253 -Uri "https://api.nuget.org/v3-flatcontainer/$BinSkimPackage/$latest/$BinSkimPackage.$latest.nupkg"
254 Expand-Archive -Path $zip -DestinationPath $tmp -Force
256 # Native RID first, emulatable one second. Matched against the path
257 # so the newest matching tools\<tfm>\<rid>\ folder wins, as before.
258 $BinSkimRids = if ($IsArm64) { @('win-arm64', 'win-x64') } else { @('win-x64') }
260 $allExes = Get-ChildItem -Path $tmp -Recurse -Filter 'BinSkim.exe'
261 foreach ($rid in $BinSkimRids) {
262 $src = $allExes | Where-Object { $_.FullName -match [regex]::Escape($rid) } |
263 Sort-Object FullName | Select-Object -Last 1
265 if ($rid -ne $BinSkimRids[0]) {
266 Write-Host " No $($BinSkimRids[0]) build in the package; using $rid (runs under emulation)." -ForegroundColor Yellow
271 if (-not $src) { throw "BinSkim.exe ($($BinSkimRids -join ' / ')) not found in package." }
273 # Replace wholesale rather than merging over the old tree, so files
274 # dropped between releases don't linger.
275 if (Test-Path $BinSkimDir) { Remove-Item -Recurse -Force $BinSkimDir }
276 New-Item -ItemType Directory -Force -Path $BinSkimDir | Out-Null
277 Copy-Item -Path (Join-Path $src.Directory.FullName '*') `
278 -Destination $BinSkimDir -Recurse -Force
279 # Written last: the marker must only claim a version that fully landed.
280 Set-Content -Path $marker -Value $latest -Encoding ascii
281 Write-Host " BinSkim $latest installed to $BinSkimDir"
283 Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
287 Add-ToUserPath $BinSkimDir
290 function Get-GitPath {
291 # winget installed Git moments ago, but this process inherited its PATH
292 # before that happened, so Get-Command can miss it on a first run. Prefer a
293 # git already on PATH, then the usual install roots.
294 $onPath = Get-Command git.exe -ErrorAction SilentlyContinue
295 if ($onPath) { return $onPath.Source }
297 (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'),
298 (Join-Path ${env:ProgramFiles(x86)} 'Git\cmd\git.exe'),
299 (Join-Path $env:LOCALAPPDATA 'Programs\Git\cmd\git.exe')
301 return $roots | Where-Object { Test-Path $_ } | Select-Object -First 1
304 function Set-GlobalGitConfig {
305 Write-Step 'Global git config'
308 Write-Warning 'git.exe not found; skipping global git config.'
311 Write-Host " using $git"
313 if (-not $GitUserName -or -not $GitUserEmail) {
314 Write-Host ' Identity not configured; leaving user.name / user.email alone.' -ForegroundColor Yellow
315 Write-Host ' Fill in $GitUserName / $GitUserEmail at the top of this script, or set' -ForegroundColor Yellow
316 Write-Host ' your identity per-repository.' -ForegroundColor Yellow
318 & $git config --global user.name $GitUserName
319 & $git config --global user.email $GitUserEmail
320 Write-Host " identity: $GitUserName <$GitUserEmail>"
323 # --- Make git use a Win32-OpenSSH client ---
324 # Git for Windows ships its own MSYS2 ssh.exe and prefers it, and that client
325 # cannot reach the Windows ssh-agent service that the elevated half enables:
326 # Win32-OpenSSH publishes the agent on a named pipe the MSYS2 build does not
327 # speak. So keys added with `ssh-add` from PowerShell stay invisible to git,
328 # and a push falls back to hunting for a key file and prompting for its
329 # passphrase. Pointing core.sshCommand at a Win32-OpenSSH ssh.exe gives git
330 # the same client, the same agent, and the same %USERPROFILE%\.ssh\config as
331 # `ssh` from an ordinary shell.
333 # Two of those are on the box, and the one beside rsync.exe is preferred.
334 # It is the same client from the same source, with the same ~/.ssh, agent
335 # and known_hosts, built with a pump on its stdin: the in-box one reads
336 # stdin 3KB at a time, which holds anything git PUSHES to ~17MB/s however
337 # fast the link is. It only exists once the elevated half has run, so the
338 # in-box client stays the fallback - and on a first provisioning run from
339 # setup-windows.bat it is the elevated half that runs first, so the fast one
340 # is normally already there.
342 # ON ARM64 the preference is the same but the trade is different: that build
343 # is published for x64 only, so it is the EMULATED client being preferred over
344 # a native ARM64 one. It is still the right pick when it runs - a push is
345 # bounded by the socket, not by emulated CPU, so lifting the 3KB stdin cap
346 # wins by far more than emulation costs - but it may well not run at all,
347 # because it links against a System32 libcrypto.dll that is an ARM64 binary
348 # here. That is exactly why candidates are tried by RUNNING them below rather
349 # than by Test-Path, and why the elevated half deletes that ssh.exe outright
350 # when it will not start. Either way this lands on a working client.
352 (Join-Path $RsyncDir 'ssh.exe'),
353 (Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe')
356 foreach ($cand in $sshCandidates) {
357 if (-not (Test-Path $cand)) { continue }
358 # Run it, rather than just believing the file is there: the build beside
359 # rsync.exe links against the libcrypto.dll the OpenSSH Client capability
360 # puts in System32, and without that capability it is a binary that does
361 # not start. Better to find that out here than on the next `git push`.
363 # EAP back to Continue for the call: ssh -V writes its version to
364 # STDERR, and with $ErrorActionPreference = 'Stop' a native command's
365 # stderr becomes a terminating RemoteException - so the working client
366 # would look like the broken one.
367 $prevEap = $ErrorActionPreference
368 $ErrorActionPreference = 'Continue'
370 # Clear the exit code first, explicitly at global scope. An exe that
371 # cannot start at all - the missing-libcrypto case - throws here without
372 # ever setting one, and the stale 0 from the last native command that DID
373 # run would otherwise read as success. $global: because a bare assignment
374 # would make a local copy that the native call then does not update.
375 $global:LASTEXITCODE = $null
376 try { $version = (& $cand -V 2>&1 | Select-Object -First 1) } catch { }
377 finally { $ErrorActionPreference = $prevEap }
378 if ($LASTEXITCODE -eq 0) { $winSsh = $cand; break }
379 $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" }
380 Write-Warning "$cand did not run ($why)$(if ($version) { ": $version" })"
383 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."
386 # Forward slashes on purpose: git parses core.sshCommand with shell quoting
387 # rules, in which a backslash is an escape character.
388 $value = $winSsh -replace '\\', '/'
389 & $git config --global core.sshCommand $value
390 Write-Host " core.sshCommand: $value"
391 Write-Host " $version"
394 function Set-NativeNinjaFirst {
395 # Make the native ninja.exe the one that wins, including inside a Visual
396 # Studio Developer Command Prompt.
398 # WHY THIS IS INSURANCE RATHER THAN THE FIX. VS ships an x64 ninja.exe even on
399 # ARM64 and puts it on the PATH from
400 # Common7\Tools\vsdevcmd\ext\cmake.bat, which does:
401 # set "PATH=%PATH%;...\CMake\bin;...\CMake\Ninja"
402 # That APPENDS - the VS directories land at the very end of the composed
403 # PATH, behind every machine and user entry. So a native ninja installed
404 # anywhere on the user PATH already beats it, and measurement on an ARM64 box
405 # confirms it does. (An earlier revision of this script claimed VsDevCmd
406 # prepends and that the VS copy therefore always won; that was wrong.)
408 # It is still worth pinning the order explicitly: winget appends its package
409 # directory to the user PATH, so the margin depends on nothing more than two
410 # append orders staying as they are, in a file Microsoft owns and revises.
411 # Putting the directory first costs nothing and removes the dependency.
413 # Ninja is worth this attention where a one-off tool would not be: it is
414 # re-invoked for every edge in the build graph, so it is the one place an
415 # emulated binary is paid over and over rather than once.
416 Write-Step 'Native ninja ahead of the Visual Studio copy'
419 $candidates += Get-ChildItem (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages') `
420 -Filter 'ninja.exe' -Recurse -Depth 2 -ErrorAction SilentlyContinue |
421 ForEach-Object { $_.FullName }
423 (Join-Path $env:ProgramFiles 'Ninja\ninja.exe')
424 (Join-Path $env:LOCALAPPDATA 'Programs\Ninja\ninja.exe')
426 # A ninja already on the PATH counts too - but only if it is not the VS one,
427 # which is the binary this step exists to get out in front of.
428 $onPath = (Get-Command ninja.exe -ErrorAction SilentlyContinue | Select-Object -First 1).Source
429 if ($onPath -and $onPath -notmatch 'CommonExtensions\\Microsoft\\CMake') { $candidates += $onPath }
432 foreach ($c in ($candidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique)) {
433 $m = Get-PEMachine $c
434 if ($m -eq $(if ($IsArm64) { 'ARM64' } else { 'x64' })) { $native = $c; break }
438 Write-Warning 'No native ninja.exe found. Install it with: winget install Ninja-build.Ninja'
439 Write-Warning 'Until then a build using the Ninja generator gets the x64 ninja Visual Studio bundles.'
443 Write-Host " native ninja: $native ($(Get-PEMachine $native))"
444 Add-ToUserPath (Split-Path $native -Parent) -Prepend
447 function Add-LlvmToUserPath {
448 # Put the upstream LLVM's bin directory on the user PATH.
450 # Two reasons this needs a step rather than trusting the installer:
452 # 1. WHERE IT LANDS. LLVM's NSIS installer targets %ProgramFiles%\LLVM, and
453 # when it cannot write there - a standard user, no elevation - it does not
454 # fail. It silently falls back to a per-user directory, observed as
455 # %USERPROFILE%\Documents\LLVM, and winget still reports "Successfully
456 # installed". So the package is registered, the compiler is genuinely
457 # there and native, and nothing can find it.
458 # 2. PATH. The installer's "add to PATH" option is not taken in a silent
459 # install, so clang-cl is not a command afterwards either way.
461 # Appended, not prepended: this is a second compiler kept deliberately
462 # alongside MSVC, and it should not quietly win a `clang-cl` that some script
463 # meant for Visual Studio's copy. Note VS does NOT put its own
464 # VC\Tools\Llvm on the PATH (its clang-cl is reached through CMake's
465 # -T ClangCL), so there is no collision to lose here.
466 Write-Step 'Upstream LLVM on the user PATH'
468 (Join-Path $env:ProgramFiles 'LLVM\bin')
469 (Join-Path ${env:ProgramFiles(x86)} 'LLVM\bin')
470 (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin')
471 (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin')
472 (Join-Path $env:USERPROFILE 'Documents\LLVM\bin')
474 $dir = $candidates | Where-Object { Test-Path (Join-Path $_ 'clang-cl.exe') } | Select-Object -First 1
476 Write-Host ' Not installed (winget install LLVM.LLVM); Visual Studio''s own clang-cl is unaffected.' -ForegroundColor DarkGray
479 $exe = Join-Path $dir 'clang-cl.exe'
480 $mach = Get-PEMachine $exe
481 Write-Host " $exe ($mach)"
482 if ($IsArm64 -and $mach -ne 'ARM64') {
483 Write-Warning "This LLVM is $mach, not ARM64. winget install LLVM.LLVM should resolve to the -woa64 build on this host."
485 if ($dir -notmatch [regex]::Escape($env:ProgramFiles)) {
486 Write-Host ' Note: not under Program Files - the installer fell back to a per-user' -ForegroundColor Yellow
487 Write-Host ' location because it could not write there. Re-run elevated for a machine-wide install.' -ForegroundColor Yellow
492 function Get-PEMachine {
493 # Architecture of a PE, read straight from the COFF header: the 2 bytes at
494 # the e_lfanew offset + 4. Cheap, and it answers the only question that
495 # matters here - would this exe run natively, or through emulation?
497 # Deliberately NOT Get-Command's .FileVersionInfo or the package metadata:
498 # a multi-architecture package (Sysinternals) ships every build in one zip
499 # under different names, and an installer's own metadata says nothing about
500 # which binary got laid down. The file itself cannot be wrong.
502 if (-not (Test-Path $Path)) { return $null }
504 $fs = [IO.File]::OpenRead($Path)
505 $br = New-Object IO.BinaryReader($fs)
507 $fs.Seek(0x3c, 'Begin') | Out-Null
508 $pe = $br.ReadInt32()
509 if ($pe -le 0 -or $pe -gt ($fs.Length - 6)) { return 'not-PE' }
510 $fs.Seek($pe + 4, 'Begin') | Out-Null
511 switch ($br.ReadUInt16()) {
516 default { 'unknown' }
518 } finally { $br.Close(); $fs.Close() }
522 function Invoke-ArchAudit {
523 # Report the actual architecture of the tools this box provisions, resolved
524 # the way a shell would (PATH first, then the usual install roots), so what
525 # is printed is what you would really run.
527 # This exists because "winget installed it" does not mean "you got the native
528 # build", and the gap is not always where you would guess - Visual Studio's
529 # own bundled ninja.exe is x64 even on an ARM64 host. A per-run audit turns
530 # that from something you trip over into something the log tells you.
532 # Purely informational: it never fails the run. On x64 everything is expected
533 # to be x64 and the output is dull; the value is on ARM64, where each line is
534 # either native or a known, listed exception.
535 Write-Step "Architecture audit (host: $HostArch)"
537 # Resolve against the PATH a NEW shell would get, not this process's.
539 # The steps above write the HKCU PATH, which a running process never sees -
540 # so auditing $env:PATH would report the state from before this script ran and
541 # warn about a problem it had just fixed. Compose machine + user from the
542 # registry (the order Windows itself uses), then append anything extra this
543 # process happens to carry: that tail is where a Developer Command Prompt's VS
544 # directories live, and keeping it last mirrors how VsDevCmd appends them.
546 foreach ($scope in 'Machine', 'User') {
547 $v = [Environment]::GetEnvironmentVariable('Path', $scope)
548 if ($v) { $composed += ($v -split ';' | Where-Object { $_.Trim() }) }
550 $composed += ($env:PATH -split ';' | Where-Object { $_.Trim() })
551 $seen = New-Object 'System.Collections.Generic.HashSet[string]' ([StringComparer]::OrdinalIgnoreCase)
552 $searchPath = @($composed | Where-Object { $seen.Add($_.Trim().TrimEnd('\')) })
554 function Resolve-OnPath([string]$Exe) {
555 foreach ($d in $searchPath) {
556 $p = Join-Path $d $Exe
557 if (Test-Path $p -PathType Leaf) { return $p }
562 # Tools with no native ARM64 build available anywhere, with the reason. These
563 # print as expected rather than as problems - see the README's ARM64 section.
565 # Shorter than it was: BinSkim, OpenCppCoverage and NASM used to be listed
566 # here as accepted emulation, and are now simply not installed on ARM64. That
567 # is the whole shape of the change - the exceptions that were tolerable one at
568 # a time added up to a VM full of x64 binaries.
570 # rsync came off this list when the release started publishing an arm64
571 # asset. An x64 rsync.exe on an ARM64 box is now a leftover from a run before
572 # that, not an accepted exception, so it warns and gets a remedy below.
574 'iperf3.exe' = 'no ARM64 build published; network-bound anyway'
575 'py.exe' = 'python.org ships the launcher shim as x86; it execs the native python.exe'
576 'vswhere.exe' = 'Microsoft ships x86 only; runs once per script'
579 # Fixable cases: a native build DOES exist, something just resolved ahead of
580 # it. Printed with the finding so the log carries the remedy, not just the
583 # ninja is the one that actually bites: Visual Studio bundles an x64 ninja.exe
584 # even on ARM64, and it is re-invoked for every edge in the build graph, so
585 # an emulated one is paid over and over rather than once. The NinjaPath step
586 # puts the native copy first; this is the check that it worked.
588 # Only two left, and both are for tools ARM64 still installs. The clang-cl and
589 # WinMerge remedies were removed with their rows: advising an install that the
590 # x64-only set has just declined to do would be the audit arguing with the
593 '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.'
594 'cmake.exe' = 'Install the native build with: winget install Kitware.CMake (its MSI is machine-scope, so it needs an administrator).'
595 '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.'
599 $vsWhereExe = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe'
600 if (Test-Path $vsWhereExe) {
601 $vs = & $vsWhereExe -products '*' -property installationPath -format value | Select-Object -First 1
604 # name -> extra candidate paths searched when the name is not on the PATH.
605 $targets = [ordered]@{
606 'git.exe' = @("$env:LOCALAPPDATA\Programs\Git\cmd\git.exe", (Join-Path $env:ProgramFiles 'Git\cmd\git.exe'))
608 # Both homes of the launcher: C:\Windows for an all-users install, the
609 # per-user Launcher directory otherwise. Often neither - it is a separate
610 # component from the interpreter, and "- not installed" here next to a
611 # native python.exe is the normal result of an unelevated Python install.
612 'py.exe' = @("$env:WINDIR\py.exe", "$env:LOCALAPPDATA\Programs\Python\Launcher\py.exe")
614 'cmake.exe' = @((Join-Path $env:ProgramFiles 'CMake\bin\cmake.exe'))
616 # Upstream LLVM. The Documents path is not a typo - see Add-LlvmToUserPath
617 # for why an unelevated install lands there.
619 (Join-Path $env:ProgramFiles 'LLVM\bin\clang-cl.exe')
620 (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin\clang-cl.exe')
621 (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin\clang-cl.exe')
623 'dotnet.exe' = @((Join-Path $env:ProgramFiles 'dotnet\dotnet.exe'))
624 'WinMergeU.exe' = @((Join-Path $env:ProgramFiles 'WinMerge\WinMergeU.exe'), (Join-Path ${env:ProgramFiles(x86)} 'WinMerge\WinMergeU.exe'))
625 'BinSkim.exe' = @((Join-Path $BinSkimDir 'BinSkim.exe'))
626 'rsync.exe' = @((Join-Path $RsyncDir 'rsync.exe'))
627 'ssh.exe' = @((Join-Path $env:WINDIR 'System32\OpenSSH\ssh.exe'))
630 'OpenCppCoverage.exe' = @((Join-Path $env:ProgramFiles 'OpenCppCoverage\OpenCppCoverage.exe'), (Join-Path ${env:ProgramFiles(x86)} 'OpenCppCoverage\OpenCppCoverage.exe'))
631 'vswhere.exe' = @($vsWhereExe)
632 'xperf.exe' = @((Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'))
635 $targets['MSBuild.exe'] = @((Join-Path $vs 'MSBuild\Current\Bin\arm64\MSBuild.exe'), (Join-Path $vs 'MSBuild\Current\Bin\MSBuild.exe'))
636 # The MSVC and VS-Clang compilers, under whichever MSVC version is present.
637 $msvc = Get-ChildItem (Join-Path $vs 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue |
638 Sort-Object Name | Select-Object -Last 1
640 $hostDir = if ($IsArm64) { 'Hostarm64\arm64' } else { 'Hostx64\x64' }
641 $targets['cl.exe (MSVC)'] = @((Join-Path $msvc.FullName "bin\$hostDir\cl.exe"))
643 $llvmHost = if ($IsArm64) { 'ARM64\bin' } else { 'x64\bin' }
644 $targets['clang-cl.exe (VS)'] = @((Join-Path $vs "VC\Tools\Llvm\$llvmHost\clang-cl.exe"))
647 # Tools this box does not provision on ARM64. Dropped from the audit rather
648 # than left to print "- not installed", because that line reads as a gap in
649 # the provisioning when it is the provisioning working as intended - and a
650 # dull audit is one you keep reading.
652 # The rows survive on x64, where all of these are installed and expected.
653 # Anything still on disk from before the split shows up in the winget list,
656 foreach ($gone in 'WinMergeU.exe', 'BinSkim.exe', 'nasm.exe',
657 'OpenCppCoverage.exe', 'clang-cl.exe', 'clang-cl.exe (VS)') {
658 $targets.Remove($gone)
662 $native = if ($IsArm64) { 'ARM64' } else { 'x64' }
664 foreach ($name in $targets.Keys) {
665 # A LABELLED entry - "clang-cl.exe (VS)" - names one specific copy, so it
666 # is resolved ONLY from its explicit candidates. Falling back to the PATH
667 # there would silently answer with a different installation of the same
668 # tool: with upstream LLVM on the PATH, the "(VS)" row reported the
669 # upstream compiler and so claimed Visual Studio's was present when it was
670 # not. Unlabelled entries still resolve PATH-first, because for those the
671 # question is which binary a build would actually invoke.
672 $exe = ($name -split ' ')[0]
673 $isPinned = $name -ne $exe
675 $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1
677 $path = Resolve-OnPath $exe
678 if (-not $path) { $path = $targets[$name] | Where-Object { $_ -and (Test-Path $_) } | Select-Object -First 1 }
680 if (-not $path) { Write-Host (" {0,-22} {1}" -f $name, '- not installed') -ForegroundColor DarkGray; continue }
682 $mach = Get-PEMachine $path
683 if (-not $mach) { continue }
684 if ($mach -eq $native) {
685 Write-Host (" {0,-22} {1,-6} native" -f $name, $mach) -ForegroundColor Green
686 } elseif ($KnownEmulated.ContainsKey($exe)) {
687 Write-Host (" {0,-22} {1,-6} expected: {2}" -f $name, $mach, $KnownEmulated[$exe]) -ForegroundColor DarkGray
689 Write-Host (" {0,-22} {1,-6} NOT NATIVE - $path" -f $name, $mach) -ForegroundColor Yellow
690 if ($Remedies.ContainsKey($exe)) {
691 Write-Host (" {0,-22} {1,-6} -> {2}" -f '', '', $Remedies[$exe]) -ForegroundColor Yellow
693 $unexpected += "$name ($mach)"
698 Write-Warning "Running under emulation with no listed reason: $($unexpected -join ', ')."
699 Write-Warning 'If a native build exists, prefer it (see the -> lines above); otherwise add it to $KnownEmulated with the reason.'
701 Write-Host ' Everything resolved to a native build, or to a listed exception.' -ForegroundColor Green
705 # ---------------------------------------------------------------------------
707 # ---------------------------------------------------------------------------
708 Write-Host "Host architecture: $HostArch" -ForegroundColor Cyan
710 if (([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(
711 [Security.Principal.WindowsBuiltInRole]::Administrator)) {
712 Write-Warning 'Running elevated. The user PATH and .gitconfig changes below will apply to the administrator profile, not yours.'
716 WinMerge = { Add-WinMergeToUserPath }
717 VsWhere = { Add-VsWhereToUserPath }
718 BinSkim = { Install-BinSkim }
719 GitConfig = { Set-GlobalGitConfig }
720 NinjaPath = { Set-NativeNinjaFirst }
721 LlvmPath = { Add-LlvmToUserPath }
722 # Last on purpose: it reports on what the steps above (and the winget installs
723 # in setup-windows.bat) actually put on the box.
724 ArchAudit = { Invoke-ArchAudit }
728 foreach ($name in $steps.Keys) {
729 if ($Skip -contains $name) {
730 Write-Host "`n==> $name (skipped)" -ForegroundColor DarkGray
733 if ($IsArm64 -and $Arm64Dropped.Contains($name)) {
734 Write-Host "`n==> $name (skipped: $($Arm64Dropped[$name]))" -ForegroundColor DarkGray
740 # One broken step must not cost the others. Collect and report at the end.
741 Write-Warning "$name failed: $($_.Exception.Message)"
747 Write-Host "`n[setup-windows-no-uac] FAILED: $($failed -join ', ')" -ForegroundColor Red
750 Write-Host "`n[setup-windows-no-uac] All steps completed." -ForegroundColor Green