]> vilimpoc.org git repositories - dotfiles/blobdiff - setup-windows-with-uac.ps1
dotfiles: add iperf3 and nasm to the per-user winget installs
[dotfiles] / setup-windows-with-uac.ps1
index 8d990f5de3dfc43d7fc621c3040773d18400975e..17d02ee05db79fab0f63aa213e3746076020f27e 100644 (file)
     - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX,\r
       Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset)\r
     - Windows Driver Kit 10.0.26100\r
+    - Windows Performance Toolkit - xperf, wpr and Windows Performance Analyzer\r
+      (wpa.exe) - on the machine PATH\r
+    - Performance Log Users membership for one ordinary account, so it can run\r
+      user-mode ETW sessions (xperf -start ... -on <provider>) without elevation.\r
+      Kernel traces are NOT covered - the NT Kernel Logger is admin-only; see the\r
+      step for what was measured.\r
 \r
   Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed:\r
     Professional : https://aka.ms/vs/17/release/vs_professional.exe\r
     Enterprise   : https://aka.ms/vs/17/release/vs_enterprise.exe\r
 #>\r
 \r
+param(\r
+    # Account to put in Performance Log Users (see the "ETW session control"\r
+    # step, which runs first). Defaults to the interactive console user, but\r
+    # setup-windows.bat passes it explicitly: with over-the-shoulder elevation\r
+    # THIS script runs as the administrator whose credentials went into the UAC\r
+    # prompt, not as the user who started the batch file, so $env:USERNAME here\r
+    # is the wrong answer.\r
+    #\r
+    # Pass an empty string to skip it; adding an account later is one\r
+    # `net localgroup` away.\r
+    [string] $TraceUser = '',\r
+\r
+    # Do the ETW step and nothing else. It is a group membership and no\r
+    # downloads, where a full run is dominated by the three Visual Studio\r
+    # passes, which take minutes even when they have nothing to do. It is why\r
+    # that step runs FIRST: -EtwRightsOnly is then just an early exit rather\r
+    # than a set of guards down the rest of the script.\r
+    [switch] $EtwRightsOnly\r
+)\r
+\r
 $ErrorActionPreference = 'Stop'\r
 \r
 function Write-Step([string]$Msg) {\r
@@ -106,6 +132,121 @@ try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {}
 \r
 try {\r
 \r
+# ---------------------------------------------------------------------------\r
+# ETW session control for an ordinary account\r
+#\r
+# Creating or controlling an event tracing session - even a user-mode one naming\r
+# a single provider - is checked against the security descriptor ETW keeps per\r
+# provider GUID under HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The\r
+# default grants the session-control rights (TRACELOG_CREATE_ONDISK,\r
+# TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to SYSTEM,\r
+# Administrators, the service accounts and BUILTIN\Performance Log Users, and to\r
+# nobody else. Its own description says members "may ... enable trace providers,\r
+# and collect event traces", and that is what membership buys:\r
+#\r
+#     xperf -start MySession -on Microsoft-Windows-Kernel-Process -f trace.etl\r
+#     xperf -stop MySession\r
+#\r
+# runs unelevated for a member and is "Access is denied. (0x5)" for everyone\r
+# else. Enough to trace your own application's providers without a UAC prompt.\r
+#\r
+# Membership is read into the access token at LOGON, so the account has to sign\r
+# out and back in. Any NEW logon does it - an ssh login into this box is one,\r
+# which is the quick way to check without dropping the desktop.\r
+#\r
+# WHAT THIS DOES NOT BUY: system-wide kernel traces. `xperf -on base` and\r
+# `wpr -start` drive the NT Kernel Logger, which is reserved for Administrators\r
+# and LocalSystem - Microsoft documents Performance Log Users access as\r
+# explicitly NOT extending to it. Measured here, so that nobody repeats it: with\r
+# the account in the group, SeSystemProfilePrivilege ("Profile system\r
+# performance") granted to that group, and an explicit ACE giving the group\r
+# TRACELOG_ACCESS_KERNEL_LOGGER on SystemTraceControlGuid - all three in place,\r
+# across a reboot - xperf still answered\r
+#\r
+#     xperf: error: NT Kernel Logger: Access is denied. (0x5).\r
+#\r
+# It is not a check an ACE overrides. Those two grants were dropped again rather\r
+# than left on the box earning nothing, and CPU sampling and whole-system traces\r
+# are elevated work: run xperf, wpr or VTune from an Administrator prompt.\r
+#\r
+# Analysis needs none of this either way - wpa.exe opens an existing .etl as a\r
+# plain user.\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'ETW session control (non-elevated user-mode tracing)'\r
+$PerfLogUsersSid = 'S-1-5-32-559'   # BUILTIN\Performance Log Users\r
+try {\r
+    # Fall back to the console user when the caller did not name one: with\r
+    # over-the-shoulder elevation that is the person who started\r
+    # setup-windows.bat, which is who wants to trace.\r
+    $target = $TraceUser\r
+    if (-not $target) {\r
+        $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName\r
+        if ($target) { Write-Host "    No -TraceUser given; using the console user $target" }\r
+    }\r
+\r
+    if (-not $target) {\r
+        Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).'\r
+        Write-Warning 'To do it later:'\r
+        Write-Warning '    net localgroup "Performance Log Users" DOMAIN\user /add'\r
+    } else {\r
+        # Resolve to a SID first: it validates the name, and it is what the\r
+        # membership check compares, so a member spelled ".\claude" in one place\r
+        # and "LATISLAB\claude" in another is still recognised as the same account.\r
+        $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate(\r
+                        [System.Security.Principal.SecurityIdentifier])\r
+\r
+        # By SID, never by name: "Performance Log Users" is localised, and\r
+        # Get-LocalGroup -SID is how this stays correct on a non-English box.\r
+        $group = Get-LocalGroup -SID $PerfLogUsersSid\r
+\r
+        # Get-LocalGroupMember throws on a group holding a SID that no longer\r
+        # resolves (a known Windows 10 bug), so a failure to READ the membership\r
+        # must not stop us from writing it - fall through and let the add report.\r
+        $already = $false\r
+        try {\r
+            $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid |\r
+                         Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0\r
+        } catch {\r
+            Write-Host "    (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray\r
+        }\r
+\r
+        if ($already) {\r
+            Write-Host "    OK: $target is already in $($group.Name)"\r
+        } else {\r
+            try {\r
+                Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value\r
+            } catch {\r
+                # "already a member" is only reachable when the enumeration above\r
+                # failed, and is not an error. Matched on the type NAME rather\r
+                # than in a typed catch clause: catch types are resolved when the\r
+                # script is PARSED, before the LocalAccounts module has been\r
+                # autoloaded, so naming the type there is a parse error that\r
+                # would take the whole script down.\r
+                if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw }\r
+            }\r
+            Write-Host "    Added $target to $($group.Name)"\r
+        }\r
+\r
+        Write-Host ''\r
+        Write-Host "    $target must sign out and back in before this takes effect." -ForegroundColor Yellow\r
+        Write-Host '    Then, from that account (NOT elevated):' -ForegroundColor Yellow\r
+        Write-Host '        xperf -start T -on Microsoft-Windows-Kernel-Process -f trace.etl' -ForegroundColor Yellow\r
+        Write-Host '        xperf -stop T' -ForegroundColor Yellow\r
+    }\r
+} catch {\r
+    Write-Warning "Performance Log Users membership failed: $($_.Exception.Message)"\r
+    Write-Warning 'Do it by hand with:'\r
+    Write-Warning '    net localgroup "Performance Log Users" <user> /add'\r
+}\r
+\r
+if ($EtwRightsOnly) {\r
+    # `exit` inside the try still runs the finally below, so the transcript is\r
+    # stopped and the log is left readable by the non-elevated caller.\r
+    Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green\r
+    exit 0\r
+}\r
+\r
+\r
 # ---------------------------------------------------------------------------\r
 # Base tools via winget\r
 # ---------------------------------------------------------------------------\r
@@ -448,30 +589,48 @@ if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)
 }\r
 \r
 # ---------------------------------------------------------------------------\r
-# Windows Performance Toolkit (xperf / WPA / wpr) -- ETW CPU + loader profiling,\r
-# used by the perf/ measurement scripts. WPT is an OPTIONAL Windows SDK feature\r
-# that the VS "Windows 11 SDK" component does NOT select, so a fresh box lacks it.\r
-# The Windows ADK bundles WPT and winget owns the (versioned) download URL, so it\r
-# is the most reliable source. Idempotent (skips if xperf is already present in\r
-# either the SDK or ADK location) and non-fatal so it never aborts provisioning.\r
-# Lighter alternative if you don't want the full ADK: install the Windows SDK's\r
-# "Windows Performance Toolkit" optional feature via winsdksetup.exe /features\r
-# OptionId.WindowsPerformanceToolkit.\r
+# Windows Performance Toolkit: xperf, wpr, and Windows Performance Analyzer\r
+# (wpa.exe) -- ETW CPU + loader profiling and the GUI that reads the traces.\r
+#\r
+# WPA is NOT a Visual Studio component and has no relationship to VS's own\r
+# Performance Profiler (a separate, .diagsession-based tool that cannot open an\r
+# .etl). It ships in exactly two places: as an optional FEATURE of the Windows\r
+# SDK ("Windows Performance Toolkit", OptionId.WindowsPerformanceToolkit), and\r
+# in the Windows ADK, which bundles the same toolkit. Whether the SDK install\r
+# that Visual Studio performs happens to select that feature varies with the VS\r
+# and SDK version - when it does, WPT lands in\r
+# %ProgramFiles(x86)%\Windows Kits\10\Windows Performance Toolkit and the SDK\r
+# puts that directory on the machine PATH itself - so this step DETECTS first\r
+# and only falls back to installing the ADK (winget owns the versioned download\r
+# URL, which makes it the reliable source) when nothing is there. That fallback\r
+# is a large download; to install just the toolkit instead, run the standalone\r
+# SDK setup with\r
+#     winsdksetup.exe /features OptionId.WindowsPerformanceToolkit /q\r
+#\r
+# There is also a newer WPA in the Microsoft Store (`winget install --id\r
+# 9N0W1B2BXGNZ --source msstore`), which updates independently of the SDK. It is\r
+# not installed here: the Store package needs an interactive, signed-in session,\r
+# which is exactly what this elevated, unattended half does not have.\r
+#\r
+# Idempotent and non-fatal - it never aborts provisioning.\r
 # ---------------------------------------------------------------------------\r
-Write-Step 'Windows Performance Toolkit (xperf / WPA)'\r
-$wptRoots = @(\r
-    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
-    (Join-Path $env:ProgramFiles          'Windows Kits\10\Windows Performance Toolkit\xperf.exe'),\r
-    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit\xperf.exe')\r
+Write-Step 'Windows Performance Toolkit (xperf / wpr / WPA)'\r
+$WptDirs = @(\r
+    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Windows Performance Toolkit'),\r
+    (Join-Path $env:ProgramFiles        'Windows Kits\10\Windows Performance Toolkit'),\r
+    (Join-Path ${env:ProgramFiles(x86)} 'Windows Kits\10\Assessment and Deployment Kit\Windows Performance Toolkit')\r
 )\r
-$xperf = $wptRoots | Where-Object { Test-Path $_ } | Select-Object -First 1\r
-if ($xperf) {\r
-    Write-Host "    OK: WPT already present ($xperf)" -ForegroundColor Green\r
+function Find-WptDir { $script:WptDirs | Where-Object { Test-Path (Join-Path $_ 'xperf.exe') } | Select-Object -First 1 }\r
+\r
+$WptDir = Find-WptDir\r
+if ($WptDir) {\r
+    Write-Host "    OK: WPT already present ($WptDir)" -ForegroundColor Green\r
 } else {\r
     try {\r
         winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity `\r
             --accept-source-agreements --accept-package-agreements\r
         Write-Host '    Windows ADK (includes Windows Performance Toolkit) installed.'\r
+        $WptDir = Find-WptDir\r
     } catch {\r
         Write-Warning "WPT install failed: $($_.Exception.Message)"\r
         Write-Warning 'Install manually: winget install Microsoft.WindowsADK, or add the'\r
@@ -479,6 +638,78 @@ if ($xperf) {
     }\r
 }\r
 \r
+if ($WptDir) {\r
+    # Report what actually landed. wpa.exe is the piece people come looking for\r
+    # and it is the one that is absent if a trimmed toolkit ever shows up.\r
+    foreach ($tool in 'xperf.exe', 'wpr.exe', 'wpa.exe', 'wpaexporter.exe') {\r
+        $p = Join-Path $WptDir $tool\r
+        if (Test-Path $p) {\r
+            Write-Host "    $tool $((Get-Item $p).VersionInfo.ProductVersion)"\r
+        } else {\r
+            Write-Warning "$tool is missing from $WptDir"\r
+        }\r
+    }\r
+\r
+    # The WPT installer normally adds this to the machine PATH itself (and the\r
+    # Start Menu gets "Windows Kits > Windows Performance Toolkit" shortcuts for\r
+    # WPA and WPR). Re-assert it anyway: on the machine PATH rather than a user\r
+    # one so it also resolves for the non-interactive sshd sessions this box is\r
+    # driven through, which build their environment from the registry PATH.\r
+    # Compared trailing-backslash-insensitively - the installer's own entry has\r
+    # one, and adding a second spelling of the same directory is just noise.\r
+    $m = [Environment]::GetEnvironmentVariable('Path', 'Machine')\r
+    if (-not $m) { $m = '' }\r
+    $have = ($m -split ';') | Where-Object { $_.TrimEnd('\') -eq $WptDir.TrimEnd('\') }\r
+    if ($have) {\r
+        Write-Host "    OK: $WptDir already in the machine PATH"\r
+    } else {\r
+        $new = if ($m.Trim()) { $m.TrimEnd(';') + ';' + $WptDir } else { $WptDir }\r
+        [Environment]::SetEnvironmentVariable('Path', $new, 'Machine')\r
+        Write-Host "    Added $WptDir to the machine PATH (restart shells to pick it up)."\r
+    }\r
+}\r
+\r
+\r
+# ---------------------------------------------------------------------------\r
+# Intel VTune Profiler - reported, not installed\r
+#\r
+# Deliberately NOT automated, unlike everything above. The offline installer is\r
+# a ~750 MB download from a URL carrying a per-release GUID\r
+# (registrationcenter-download.intel.com/akdlm/IRC_NAS/<guid>/intel-vtune-<ver>_offline.exe)\r
+# with no "latest" redirect behind it, so every new build means editing a\r
+# hard-coded link in here - and it is only worth having on Intel silicon, since\r
+# hardware event-based sampling reads Intel PMU counters. Not a good trade for a\r
+# script that has to keep working unattended on any box.\r
+#\r
+# So this step only reports. To install it, take the Windows offline installer\r
+# from\r
+#     https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html\r
+# and run it elevated; it installs unattended with\r
+#     intel-vtune-<version>_offline.exe -a --silent --cli --eula accept\r
+# ---------------------------------------------------------------------------\r
+Write-Step 'Intel VTune Profiler (status only)'\r
+$UninstallKeys = @(\r
+    'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*'\r
+    'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'\r
+)\r
+$vtune = Get-ItemProperty $UninstallKeys -ErrorAction SilentlyContinue |\r
+         Where-Object { $_.DisplayName -match 'VTune' } |\r
+         Select-Object -First 1\r
+if ($vtune) {\r
+    Write-Host "    Installed: $($vtune.DisplayName.Trim()) $($vtune.DisplayVersion)" -ForegroundColor Green\r
+    # The oneAPI layout keeps a `latest` junction beside the versioned directory,\r
+    # so this path stays right across upgrades.\r
+    $VTuneCli = Join-Path $vtune.InstallLocation 'vtune\latest\bin64\vtune.exe'\r
+    if (Test-Path $VTuneCli) { Write-Host "    CLI: $VTuneCli" }\r
+} else {\r
+    Write-Host '    Not installed.' -ForegroundColor Yellow\r
+    Write-Host '    https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html' -ForegroundColor Yellow\r
+    $cpu = (Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1).Manufacturer\r
+    if ($cpu -and $cpu -notmatch 'Intel') {\r
+        Write-Host "    (This CPU reports itself as '$cpu' - VTune's hardware event-based sampling wants Intel silicon.)" -ForegroundColor Yellow\r
+    }\r
+}\r
+\r
 # ---------------------------------------------------------------------------\r
 Write-Host "`nAll done." -ForegroundColor Green\r
 Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.'\r