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