X-Git-Url: https://vilimpoc.org/repos/dotfiles/blobdiff_plain/0aec6243fab52a10889bd5052a4cf1496be80b0d..cd774a195092cd0ab4c8e92862d0c5cf7e04f195:/setup-windows-with-uac.ps1?ds=sidebyside diff --git a/setup-windows-with-uac.ps1 b/setup-windows-with-uac.ps1 index a546a0a..c935e2d 100644 --- a/setup-windows-with-uac.ps1 +++ b/setup-windows-with-uac.ps1 @@ -11,43 +11,49 @@ - OpenSSH Server (sshd) capability: automatic + started + inbound TCP 22 - rsync for Windows (nuket/rsync-windows) in C:\Tools\rsync, on the machine PATH: rsync.exe plus the ssh.exe it runs, out of the release zip for this - architecture - - Visual Studio 2022 Community (C++ desktop workload, Spectre libs, WDK VSIX, - Win11 SDK 26100, Clang/LLVM, and the v141 + Windows XP targeting toolset) + architecture (there is no ARM64 zip; ARM64 gets the x64 one, and the + ssh.exe is kept only if it actually starts) + - Visual Studio Community (C++ desktop workload, x86/x64 AND ARM64 build + tools, Spectre libs, WDK VSIX, Win11 SDK 26100, Clang/LLVM, and - on x64 + only - the v141 + Windows XP targeting toolset). VS 2022 on x64, VS 2026 + on ARM64; see $VsChannel. - Windows Driver Kit 10.0.26100 - Windows Performance Toolkit - xperf, wpr and Windows Performance Analyzer (wpa.exe) - on the machine PATH - - ETW collection rights for one ordinary account: Performance Log Users - membership plus the "Profile system performance" user right, so xperf and - wpr run WITHOUT elevation - Change $VsInstallerUrl below to the Professional or Enterprise bootstrapper if needed: - Professional : https://aka.ms/vs/17/release/vs_professional.exe - Enterprise : https://aka.ms/vs/17/release/vs_enterprise.exe -#> + Change $VsEdition below to Professional or Enterprise if needed. $VsChannel + picks the Visual Studio generation and is architecture-split by default: + 17 (VS 2022) on x64, where the v141 / Windows XP toolset is wanted, and + 18 (VS 2026) on ARM64, where that toolset cannot exist anyway. -param( - # Account to be granted non-elevated ETW collection rights (see the "ETW - # collection rights" step at the bottom). Defaults to the interactive - # console user, but setup-windows.bat passes it explicitly: with - # over-the-shoulder elevation THIS script runs as the administrator whose - # credentials went into the UAC prompt, not as the user who started the - # batch file, so $env:USERNAME here is the wrong answer. - # - # Pass an empty string to skip the group membership (the user right is still - # granted to the group, so adding an account later is one command). - [string] $TraceUser = '', - - # Do the ETW rights step and nothing else. That step is seconds of registry - # and LSA work with no downloads, where a full run is dominated by the three - # Visual Studio passes, which take minutes even when they have nothing to do. - # It is why the ETW step runs FIRST: -EtwRightsOnly is then just an early - # exit rather than a set of guards down the rest of the script. - [switch] $EtwRightsOnly -) + ARCHITECTURE. Runs on x64 and on ARM64 (Windows 11 on Arm). On ARM64 the + Visual Studio installer, MSVC and clang-cl are all native ARM64 and + cross-compile ARM64/x64/x86 targets; what changes is called out at each step, + and $HostArch below is what drives it. +#> $ErrorActionPreference = 'Stop' +# --------------------------------------------------------------------------- +# Host architecture +# +# RuntimeInformation.OSArchitecture rather than PROCESSOR_ARCHITECTURE: this +# script can be launched by a 32-bit or an emulated x64 PowerShell, either of +# which reports the emulated architecture in the environment variable while this +# API still reports the real one. Values seen here: X64, Arm64, X86. +# +# $IsArm64 gates: +# - which rsync-windows release zip is fetched (there is no ARM64 one) +# - which Visual Studio generation is driven ($VsChannel: 18 on Arm, 17 on x64) +# - the Visual Studio component groups (ARM64 build tools in; the v141/XP +# toolset out, because it has no ARM64-hosted compiler and Microsoft does not +# ship Windows XP targeting for Arm hosts. Clang/LLVM is installed on every +# architecture and is native on Arm, so it is NOT gated here) +# - what the VTune and WPT steps report +# --------------------------------------------------------------------------- +$HostArch = [Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString() +$IsArm64 = ($HostArch -eq 'Arm64') + function Write-Step([string]$Msg) { Write-Host "`n==> $Msg" -ForegroundColor Cyan } @@ -62,215 +68,6 @@ function Assert-ExitCode([int]$Code, [string]$Step) { } } -# --------------------------------------------------------------------------- -# User rights assignment (LSA account rights) -# -# Windows has no built-in cmdlet for "grant this SID this privilege". The two -# ways to script it are secedit (export the whole USER_RIGHTS area to an INF, -# edit one line, re-import) and the LSA API. The API is used here because it is -# surgical: LsaAddAccountRights adds exactly one right to exactly one SID and is -# a no-op when it is already held, where a secedit round-trip re-applies every -# user right on the box to fix one of them. The GUI equivalent, for a human, is -# secpol.msc > Local Policies > User Rights Assignment -# -# The type is compiled on first use; C# 5 only, since Windows PowerShell 5.1's -# Add-Type compiles with the in-box CodeDom compiler. -# --------------------------------------------------------------------------- -function Initialize-LsaRightsType { - if ('LsaRights' -as [type]) { return } - Add-Type -TypeDefinition @' -using System; -using System.ComponentModel; -using System.Runtime.InteropServices; - -public static class LsaRights -{ - [StructLayout(LayoutKind.Sequential)] - private struct LSA_UNICODE_STRING - { - public ushort Length; - public ushort MaximumLength; - public IntPtr Buffer; - } - - [StructLayout(LayoutKind.Sequential)] - private struct LSA_OBJECT_ATTRIBUTES - { - public int Length; - public IntPtr RootDirectory; - public IntPtr ObjectName; - public uint Attributes; - public IntPtr SecurityDescriptor; - public IntPtr SecurityQualityOfService; - } - - [DllImport("advapi32.dll", SetLastError = true)] - private static extern uint LsaOpenPolicy(IntPtr systemName, - ref LSA_OBJECT_ATTRIBUTES objectAttributes, uint desiredAccess, out IntPtr policyHandle); - - [DllImport("advapi32.dll", SetLastError = true)] - private static extern uint LsaAddAccountRights(IntPtr policyHandle, byte[] accountSid, - LSA_UNICODE_STRING[] userRights, uint countOfRights); - - [DllImport("advapi32.dll", SetLastError = true)] - private static extern uint LsaEnumerateAccountRights(IntPtr policyHandle, byte[] accountSid, - out IntPtr userRights, out uint countOfRights); - - [DllImport("advapi32.dll")] - private static extern uint LsaClose(IntPtr policyHandle); - - [DllImport("advapi32.dll")] - private static extern uint LsaFreeMemory(IntPtr buffer); - - [DllImport("advapi32.dll")] - private static extern int LsaNtStatusToWinError(uint status); - - private const uint POLICY_VIEW_LOCAL_INFORMATION = 0x00000001; - private const uint POLICY_CREATE_ACCOUNT = 0x00000010; - private const uint POLICY_LOOKUP_NAMES = 0x00000800; - - // Returned by LsaEnumerateAccountRights when the SID holds no rights at all, - // which is an empty list rather than an error. - private const uint STATUS_OBJECT_NAME_NOT_FOUND = 0xC0000034; - - private static IntPtr OpenPolicy() - { - LSA_OBJECT_ATTRIBUTES attrs = new LSA_OBJECT_ATTRIBUTES(); - attrs.Length = Marshal.SizeOf(typeof(LSA_OBJECT_ATTRIBUTES)); - IntPtr handle; - uint status = LsaOpenPolicy(IntPtr.Zero, ref attrs, - POLICY_VIEW_LOCAL_INFORMATION | POLICY_CREATE_ACCOUNT | POLICY_LOOKUP_NAMES, out handle); - if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); } - return handle; - } - - public static string[] Get(byte[] sid) - { - IntPtr policy = OpenPolicy(); - try - { - IntPtr rights; - uint count; - uint status = LsaEnumerateAccountRights(policy, sid, out rights, out count); - if (status == STATUS_OBJECT_NAME_NOT_FOUND) { return new string[0]; } - if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); } - try - { - string[] result = new string[count]; - int stride = Marshal.SizeOf(typeof(LSA_UNICODE_STRING)); - for (int i = 0; i < count; i++) - { - LSA_UNICODE_STRING s = (LSA_UNICODE_STRING)Marshal.PtrToStructure( - new IntPtr(rights.ToInt64() + (long)i * stride), typeof(LSA_UNICODE_STRING)); - result[i] = Marshal.PtrToStringUni(s.Buffer, s.Length / 2); - } - return result; - } - finally { LsaFreeMemory(rights); } - } - finally { LsaClose(policy); } - } - - public static void Add(byte[] sid, string right) - { - IntPtr policy = OpenPolicy(); - try - { - LSA_UNICODE_STRING[] rights = new LSA_UNICODE_STRING[1]; - rights[0].Buffer = Marshal.StringToHGlobalUni(right); - // Length counts BYTES and excludes the terminator; MaximumLength includes it. - rights[0].Length = (ushort)(right.Length * 2); - rights[0].MaximumLength = (ushort)(right.Length * 2 + 2); - try - { - uint status = LsaAddAccountRights(policy, sid, rights, 1); - if (status != 0) { throw new Win32Exception(LsaNtStatusToWinError(status)); } - } - finally { Marshal.FreeHGlobal(rights[0].Buffer); } - } - finally { LsaClose(policy); } - } -} -'@ -} - -function Get-SidBytes([string]$Sid) { - $s = New-Object System.Security.Principal.SecurityIdentifier($Sid) - $bytes = New-Object byte[] $s.BinaryLength - $s.GetBinaryForm($bytes, 0) - return ,$bytes -} - -function Get-AccountRight([string]$Sid) { - Initialize-LsaRightsType - return [LsaRights]::Get((Get-SidBytes $Sid)) -} - -function Grant-AccountRight([string]$Sid, [string]$Right) { - Initialize-LsaRightsType - [LsaRights]::Add((Get-SidBytes $Sid), $Right) -} - -# --------------------------------------------------------------------------- -# ETW provider-GUID access control -# -# ETW keeps a security descriptor per provider GUID under -# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security, and EventAccessControl is -# the documented way to edit one. Editing the registry value directly would work -# too - it is a self-relative SD in a REG_BINARY - but the API takes the SID and -# the rights mask and leaves the descriptor's shape to Windows. -# --------------------------------------------------------------------------- -function Initialize-EtwAclType { - if ('EtwAcl' -as [type]) { return } - Add-Type -TypeDefinition @' -using System; -using System.Runtime.InteropServices; - -public static class EtwAcl -{ - // ULONG EventAccessControl(LPGUID, ULONG Operation, PSID, ULONG Rights, BOOLEAN AllowOrDeny) - [DllImport("advapi32.dll", SetLastError = true)] - public static extern uint EventAccessControl(ref Guid guid, uint operation, byte[] sid, - uint rights, [MarshalAs(UnmanagedType.U1)] bool allowOrDeny); - - // ULONG EventAccessQuery(LPGUID, PSECURITY_DESCRIPTOR, PULONG BufferSize) - [DllImport("advapi32.dll", SetLastError = true)] - public static extern uint EventAccessQuery(ref Guid guid, byte[] buffer, ref uint bufferSize); -} -'@ -} - -# The rights a session controller needs, from evntrace.h: -# 0x0001 WMIGUID_QUERY 0x0100 TRACELOG_ACCESS_KERNEL_LOGGER -# 0x0020 TRACELOG_CREATE_REALTIME 0x0200 TRACELOG_LOG_EVENT -# 0x0040 TRACELOG_CREATE_ONDISK 0x0400 TRACELOG_ACCESS_REALTIME -# 0x0080 TRACELOG_GUID_ENABLE 0x0800 TRACELOG_REGISTER_GUIDS -# TRACELOG_ACCESS_KERNEL_LOGGER is the one that names the NT Kernel Logger -# specifically; the rest are what any controller needs to create a session, -# write it to disk and enable providers on it. -$EtwControllerRights = 0x0FE1 - -function Grant-EtwGuidAccess([string]$Guid, [string]$Sid, [uint32]$Rights) { - Initialize-EtwAclType - $g = [Guid]$Guid - # Operation 2 = EventSecurityAddDACL: add one ACE and leave every existing - # one in place. EventSecuritySetDACL (0) would REPLACE the descriptor, which - # on the kernel logger means removing the entries Windows itself relies on. - $rc = [EtwAcl]::EventAccessControl([ref]$g, 2, (Get-SidBytes $Sid), $Rights, $true) - if ($rc -ne 0) { throw (New-Object System.ComponentModel.Win32Exception([int]$rc)) } -} - -function Get-EtwGuidSddl([string]$Guid) { - Initialize-EtwAclType - $g = [Guid]$Guid - $size = [uint32]0 - [void][EtwAcl]::EventAccessQuery([ref]$g, $null, [ref]$size) - if ($size -eq 0) { return $null } - $buf = New-Object byte[] $size - if ([EtwAcl]::EventAccessQuery([ref]$g, $buf, [ref]$size) -ne 0) { return $null } - return (New-Object System.Security.AccessControl.RawSecurityDescriptor($buf, 0)).GetSddlForm('Access') -} - function Show-VsSetupLogs { # The VS Installer writes dd_*.log to the invoking user's %TEMP%. Because # this script runs elevated, that %TEMP% belongs to the elevated user and is @@ -295,15 +92,41 @@ function Show-VsSetupLogs { } } +function Get-VsInstallPath { + # The install path of a Visual Studio matching $script:VsChannel, or $null. + # + # -version is the point. A bare `vswhere -products *` returns EVERY Visual + # Studio on the box, newest first, and handing that path to a bootstrapper of + # a different generation is not a no-op: `vs_community.exe` (17.x) told to + # `modify --installPath ` is a 17.x engine pointed at an + # 18.x product. On a box that already has VS 2026 - increasingly the default - + # every pass below would target the wrong install. Scope the query to the + # generation this script is actually driving. + if (-not (Test-Path $script:VsWhere)) { return $null } + $range = "[$script:VsChannel.0,$($script:VsChannel + 1).0)" + & $script:VsWhere -products '*' -version $range -property installationPath -format value | + Select-Object -First 1 +} + function Invoke-VsModify { # Run one VS install/modify pass for a named group of components. Splitting # the install into separate passes makes it obvious WHICH group fails: each # call prints its label and exit code before Assert-ExitCode throws. + # + # -Optional downgrades a failure to a warning. Used for groups that are not + # available on every host architecture (the v141/XP toolset on ARM64) or that + # the rest of the box does not depend on, so one unavailable component cannot + # cost you the toolchain. param( [string] $Label, - [string[]] $Ids + [string[]] $Ids, + [switch] $Optional ) - Write-Step "VS2022: $Label" + Write-Step "Visual Studio: $Label" + if (-not $Ids) { + Write-Host ' (no components in this group for this architecture - skipping)' -ForegroundColor DarkGray + return + } $addStr = ($Ids | ForEach-Object { "--add $_" }) -join ' ' # --installPath must be quoted: it contains spaces ("C:\Program Files\..."). # Windows PowerShell 5.1's Start-Process does not quote array elements, so we @@ -318,14 +141,15 @@ function Invoke-VsModify { Write-Host " > $script:VsBootstrapper $argString" -ForegroundColor DarkGray $p = Start-Process -FilePath $script:VsBootstrapper -ArgumentList $argString -Wait -PassThru -NoNewWindow Write-Host " exit code: $($p.ExitCode)" - Assert-ExitCode $p.ExitCode "VS2022 ($Label)" + if ($Optional -and $p.ExitCode -notin @(0, 3010)) { + Write-Warning "Visual Studio ($Label) failed with exit code $($p.ExitCode); continuing (this group is optional)." + } else { + Assert-ExitCode $p.ExitCode "Visual Studio ($Label)" + } # After the first (fresh) install, re-detect the install path so subsequent # passes use `modify`. - if (-not $script:InstallPath -and (Test-Path $script:VsWhere)) { - $script:InstallPath = & $script:VsWhere -products '*' -property installationPath -format value | - Select-Object -First 1 - } + if (-not $script:InstallPath) { $script:InstallPath = Get-VsInstallPath } } # --------------------------------------------------------------------------- @@ -340,175 +164,22 @@ try { Start-Transcript -Path $LogFile -Force | Out-Null } catch {} try { -# --------------------------------------------------------------------------- -# ETW collection rights for an ordinary account -# -# Out of the box, xperf and wpr only work elevated. THREE separate things stand -# in a standard user's way, and each has its own error: -# -# xperf -on base -> "NT Kernel Logger: Access is denied. (0x5)" -# wpr -start GeneralProfile -# -> "Failed to enable the policy to profile system -# performance." (0xc5585011) -# -# 1. Creating or controlling ANY event tracing session - even a user-mode one -# naming a single provider - is checked against the security descriptor ETW -# keeps per provider GUID under -# HKLM\SYSTEM\CurrentControlSet\Control\WMI\Security. The DEFAULT descriptor -# grants the session-control rights (TRACELOG_CREATE_ONDISK, -# TRACELOG_CREATE_REALTIME, TRACELOG_GUID_ENABLE, TRACELOG_LOG_EVENT) to -# SYSTEM, Administrators, the service accounts, and BUILTIN\Performance Log -# Users - and to nobody else. That group is the supported hook; its own -# description says members "may ... enable trace providers, and collect event -# traces". -# -# 2. Switching on the kernel/system trace provider on top of that needs the -# SeSystemProfilePrivilege user right ("Profile system performance"), held by -# default only by Administrators and NT SERVICE\WdiServiceHost. That is the -# one wpr names in its error. -# -# 3. The kernel logger is not covered by that default descriptor. Its own GUID - -# SystemTraceControlGuid, the session both `xperf -on` and wpr drive - carries -# an explicit descriptor that does not mention Performance Log Users, so 1 and -# 2 are not enough by themselves. Measured on this box with both in place: a -# user-mode session starts (exit 0) and the account holds the privilege, and -# `xperf -on base` still answers "NT Kernel Logger: Access is denied" while -# wpr's error changes from the policy message above to a bare 0x80070005. -# Even READING that descriptor comes back access-denied, which is the tell. So -# add an ACE for the group with EventAccessControl; TRACELOG_ACCESS_KERNEL_LOGGER -# is the right that names this particular session. -# -# The privilege and the ACE both go to the GROUP, and the account then goes into -# the group: membership alone becomes the switch, and enabling the next account -# is one `net localgroup` away with no policy or registry edit. -# -# What this costs, stated plainly: a member of that group can capture -# system-wide kernel traces - process, image, file and registry activity across -# every account on the box, paths and command lines included. That is what the -# group is for, and it is the price of collecting a trace without a UAC prompt. -# -# Deliberately NOT granted: SeDebugPrivilege. xperf needs it for neither CPU -# sampling nor walking stacks in your own processes, and it is equivalent to -# handing out administrator. -# -# THIS ONLY HELPS A NON-ADMIN ACCOUNT. Both a privilege and a group membership -# are baked into the access token at LOGON, and UAC hands an administrator a -# filtered token that keeps just five harmless privileges - so an admin's -# ordinary shell still cannot trace, however the policy reads. Running as a -# standard user is what makes this work. -# -# For the same reason 1 and 2 do not take effect in an already-open session: the -# account has to sign out and back in. Any NEW logon does it - an ssh login into -# this box is one, which is the quick way to check without dropping the desktop. -# The ACE in 3 is machine state, read when a session is started, so that one -# applies immediately. -# -# Analysis never needed any of this: wpa.exe opens an existing .etl as a plain -# user. This step is only about collection. -# --------------------------------------------------------------------------- -Write-Step 'ETW collection rights (non-elevated xperf / wpr)' -$PerfLogUsersSid = 'S-1-5-32-559' # BUILTIN\Performance Log Users -# SystemTraceControlGuid: the NT Kernel Logger / system session that xperf -on -# and wpr both drive. Fixed by contract, from evntrace.h. -$SystemTraceControlGuid = '9e814aad-3204-11d2-9a82-006008a86939' -try { - # --- The user right, granted to the group --- - $existing = Get-AccountRight $PerfLogUsersSid - if ($existing -contains 'SeSystemProfilePrivilege') { - Write-Host ' OK: Performance Log Users already holds SeSystemProfilePrivilege' - } else { - Grant-AccountRight $PerfLogUsersSid 'SeSystemProfilePrivilege' - Write-Host ' Granted SeSystemProfilePrivilege ("Profile system performance") to Performance Log Users' - } - - # --- The kernel logger's own descriptor --- - # Idempotent: adding the ACE for a SID that already has it rewrites the same - # entry. Kept in its own try so that a failure here still leaves the group - # membership below to be done - user-mode sessions work without it. - try { - Grant-EtwGuidAccess $SystemTraceControlGuid $PerfLogUsersSid $EtwControllerRights - Write-Host (" Granted Performance Log Users the controller rights (0x{0:X4}, TRACELOG_ACCESS_KERNEL_LOGGER included) on SystemTraceControlGuid" -f $EtwControllerRights) - $sddl = Get-EtwGuidSddl $SystemTraceControlGuid - if ($sddl) { Write-Host " kernel logger DACL is now $sddl" -ForegroundColor DarkGray } - } catch { - Write-Warning "Could not add the ACE on SystemTraceControlGuid: $($_.Exception.Message)" - Write-Warning 'xperf -on will keep answering "NT Kernel Logger: Access is denied."' - } - - # --- The membership --- - # Fall back to the console user when the caller did not name one: with - # over-the-shoulder elevation that is the person who started - # setup-windows.bat, which is who wants to trace. - $target = $TraceUser - if (-not $target) { - $target = (Get-CimInstance Win32_ComputerSystem -ErrorAction SilentlyContinue).UserName - if ($target) { Write-Host " No -TraceUser given; using the console user $target" } - } - - if (-not $target) { - Write-Warning 'No account to add to Performance Log Users (pass -TraceUser DOMAIN\user).' - Write-Warning 'The user right is in place, so this is the only step left:' - Write-Warning ' net localgroup "Performance Log Users" DOMAIN\user /add' +Write-Step "Host architecture: $HostArch" +if ($IsArm64) { + # x64 emulation ("Prism") is what carries every x64-only tool this script + # installs - rsync.exe, the WDK and ADK installers, BinSkim in the + # non-elevated half. It is present on Windows 11 on Arm and absent on + # Windows 10 on Arm (x86-only there) and on some Server images, so check + # rather than assume: without it those steps install binaries that cannot + # start, and the failure would otherwise surface much later. + $Prism = Join-Path $env:WINDIR 'System32\xtajit64.dll' + if (Test-Path $Prism) { + Write-Host ' x64 emulation (Prism) present - x64-only tools will run.' -ForegroundColor Green } else { - # Resolve to a SID first: it validates the name, and it is what the - # membership check compares, so a member spelled ".\claude" in one place - # and "LATISLAB\claude" in another is still recognised as the same account. - $targetSid = (New-Object System.Security.Principal.NTAccount($target)).Translate( - [System.Security.Principal.SecurityIdentifier]) - - # By SID, never by name: "Performance Log Users" is localised, and - # Get-LocalGroup -SID is how this stays correct on a non-English box. - $group = Get-LocalGroup -SID $PerfLogUsersSid - - # Get-LocalGroupMember throws on a group holding a SID that no longer - # resolves (a known Windows 10 bug), so a failure to READ the membership - # must not stop us from writing it - fall through and let the add report. - $already = $false - try { - $already = @(Get-LocalGroupMember -SID $PerfLogUsersSid | - Where-Object { $_.SID.Value -eq $targetSid.Value }).Count -gt 0 - } catch { - Write-Host " (could not enumerate $($group.Name) members: $($_.Exception.Message))" -ForegroundColor DarkGray - } - - if ($already) { - Write-Host " OK: $target is already in $($group.Name)" - } else { - try { - Add-LocalGroupMember -SID $PerfLogUsersSid -Member $targetSid.Value - } catch { - # "already a member" is only reachable when the enumeration above - # failed, and is not an error. Matched on the type NAME rather - # than in a typed catch clause: catch types are resolved when the - # script is PARSED, before the LocalAccounts module has been - # autoloaded, so naming the type there is a parse error that - # would take the whole script down. - if ($_.Exception.GetType().Name -ne 'MemberExistsException') { throw } - } - Write-Host " Added $target to $($group.Name)" - } - - Write-Host '' - Write-Host " $target must sign out and back in before this takes effect." -ForegroundColor Yellow - Write-Host ' Then, from that account (NOT elevated):' -ForegroundColor Yellow - Write-Host ' whoami /priv | findstr SeSystemProfilePrivilege' -ForegroundColor Yellow - Write-Host ' xperf -on base ; xperf -stop C:\Temp\trace.etl' -ForegroundColor Yellow + Write-Warning "x64 emulation not found ($Prism is missing). rsync.exe, the WDK/ADK installers and BinSkim have no ARM64 build and will not run on this box." } -} catch { - Write-Warning "ETW rights setup failed: $($_.Exception.Message)" - Write-Warning 'Grant them by hand: secpol.msc > Local Policies > User Rights Assignment >' - Write-Warning '"Profile system performance" > add Performance Log Users, then' - Write-Warning ' net localgroup "Performance Log Users" /add' } -if ($EtwRightsOnly) { - # `exit` inside the try still runs the finally below, so the transcript is - # stopped and the log is left readable by the non-elevated caller. - Write-Host "`n-EtwRightsOnly: skipping the installs." -ForegroundColor Green - exit 0 -} - - # --------------------------------------------------------------------------- # Base tools via winget # --------------------------------------------------------------------------- @@ -637,7 +308,21 @@ try { # --------------------------------------------------------------------------- Write-Step 'rsync for Windows' $RsyncRepo = 'nuket/rsync-windows' -$RsyncAsset = if ([Environment]::Is64BitOperatingSystem) { 'rsync-windows-x64.zip' } else { 'rsync-windows-x86.zip' } +# The release publishes exactly two assets - x64 and x86 - and no ARM64 one, so +# on ARM64 the x64 build is the right pick: it runs under Prism, and an emulated +# x64 rsync still moves data far faster than the ~17MB/s stdin cap that the whole +# reason for using this build is to avoid. (The transfer is I/O-bound on the +# socket, not on emulated CPU.) Selected off $HostArch rather than +# Is64BitOperatingSystem, which answers "true" on ARM64 and so cannot tell the +# two 64-bit cases apart. +$RsyncAsset = switch ($HostArch) { + 'X64' { 'rsync-windows-x64.zip' } + 'Arm64' { 'rsync-windows-x64.zip' } + default { 'rsync-windows-x86.zip' } +} +if ($IsArm64) { + Write-Host ' ARM64: no native asset is published, using the x64 build under emulation.' -ForegroundColor Yellow +} # The /releases/latest/download/ redirect rather than the API: unauthenticated # API calls are rate-limited to 60/hour per IP, which a provisioning run behind a # shared NAT can genuinely exhaust, and the redirect costs none of that budget. @@ -650,7 +335,9 @@ try { $RsyncExe = Join-Path $RsyncDir 'rsync.exe' # Does the release's ssh.exe have the libcrypto it needs? Decided before the - # download so the answer can also gate what comes out of the zip. + # download so the answer can also gate what comes out of the zip. This is a + # cheap pre-filter only - the authoritative check is running the thing, which + # happens after the unpack below. $SysCrypto = Join-Path $env:WINDIR 'System32\libcrypto.dll' $WantSsh = Test-Path $SysCrypto if (-not $WantSsh) { @@ -660,6 +347,15 @@ try { if ($v -and ([version]($v -replace '[^0-9.]', '')) -lt [version]'3.8.2') { Write-Warning "$SysCrypto is LibreSSL $v; the release's ssh.exe is built against 3.8.2 (Windows OpenSSH Client 9.5). Update Windows, or expect ssh.exe not to start." } + if ($IsArm64) { + # On ARM64 the presence of libcrypto.dll proves less than it does on + # x64: System32 holds the ARM64 build of it, and the ssh.exe in the + # zip is x64. Whether an emulated x64 process can load that DLL comes + # down to whether it is a plain ARM64 binary or an ARM64X one - not + # something worth deciding by parsing the PE header, when running the + # binary answers it outright. Unpack it, then run it (below). + Write-Host ' ARM64: the x64 ssh.exe will be verified by running it, not by assuming.' -ForegroundColor Yellow + } } # Download and unpack beside the targets, not over them, so an interrupted @@ -707,6 +403,41 @@ try { Move-Item -Path $src -Destination (Join-Path $RsyncDir $f) -Force } Remove-Item -Recurse -Force $unpack + + # Prove the unpacked ssh.exe actually starts, and DELETE it if it does not. + # + # This matters more than it looks. rsync.exe prefers an ssh.exe sitting in its + # own directory, so a present-but-unstartable one does not degrade to the + # in-box client - it breaks rsync outright, and the error you get is a remote + # shell that died rather than anything naming ssh.exe. The two ways to land + # there are a missing/old System32 libcrypto.dll (x64 boxes) and an ARM64 box + # whose ARM64 libcrypto cannot be loaded by this x64 binary. Removing it is + # the repair in both cases: rsync then falls back to the ssh on the PATH, + # which on ARM64 is the native in-box client. + # + # EAP back to Continue for the call: ssh -V writes its version to STDERR, and + # under $ErrorActionPreference = 'Stop' a native command's stderr becomes a + # terminating error, so a WORKING client would look like a broken one. + # $global:LASTEXITCODE is cleared first because an exe that cannot start at + # all throws without setting one, and the stale 0 from the previous native + # command would otherwise read as success. + $SshExe = Join-Path $RsyncDir 'ssh.exe' + if ($WantSsh -and (Test-Path $SshExe)) { + $prevEap = $ErrorActionPreference + $ErrorActionPreference = 'Continue' + $global:LASTEXITCODE = $null + $sshVer = $null + try { $sshVer = (& $SshExe -V 2>&1 | Select-Object -First 1) } catch { } + finally { $ErrorActionPreference = $prevEap } + if ($LASTEXITCODE -eq 0) { + Write-Host " ssh.exe runs: $sshVer" + } else { + $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" } + Write-Warning "The release's ssh.exe does not run here ($why)$(if ($sshVer) { ": $sshVer" }). Removing it so rsync.exe falls back to the ssh on the PATH instead of failing on it." + Remove-Item $SshExe -Force -ErrorAction SilentlyContinue + $WantSsh = $false + } + } Write-Host " Installed $RsyncExe$(if ($WantSsh) { ' and the ssh.exe it runs' })" # Machine PATH (HKLM environment). Idempotent: only appends if absent. @@ -747,12 +478,26 @@ $BaseComponents = @( # Core C++ desktop workload 'Microsoft.VisualStudio.Workload.NativeDesktop' - # Spectre-mitigated MSVC runtime libs + # MSVC build tools. Named explicitly rather than left to --includeRecommended, + # because what that pulls in depends on the host: on an ARM64 machine the + # workload's recommended set is the ARM64-hosted toolchain targeting ARM64, + # and the x64 cross-compiler is NOT implied. Ask for both and the box builds + # every target it can, whichever architecture it is: + # on x64 -> x64-hosted, targeting x86/x64 and ARM64 + # on ARM64 -> ARM64-hosted, targeting ARM64 and x86/x64 + # Both are native toolchains; neither cross-compile runs under emulation. + 'Microsoft.VisualStudio.Component.VC.Tools.x86.x64' + 'Microsoft.VisualStudio.Component.VC.Tools.ARM64' + + # Spectre-mitigated MSVC runtime libs, for each target above 'Microsoft.VisualStudio.Component.VC.Runtimes.x86.x64.Spectre' 'Microsoft.VisualStudio.Component.VC.Runtimes.ARM64.Spectre' - # Spectre-mitigated ATL (needed for many driver/COM projects) + # Spectre-mitigated ATL (needed for many driver/COM projects). The x86/x64 and + # ARM64 ATL libraries are separate components; a driver or COM project built + # for ARM64 wants the second one, and it is not implied by the first. 'Microsoft.VisualStudio.Component.VC.ATL.Spectre' + 'Microsoft.VisualStudio.Component.VC.ATL.ARM64.Spectre' # Windows 11 SDK — build number must match the WDK below 'Microsoft.VisualStudio.Component.Windows11SDK.26100' @@ -764,6 +509,17 @@ $BaseComponents = @( # Clang/LLVM toolset (ClangCL, used in CMakePresets.json). Two parts: the Clang # compiler itself, plus the MSBuild integration providing the "ClangCL" toolset. +# +# Installed on every architecture, ARM64 included, and native there - not an +# emulated x64 compiler. Two things establish that: the VSIX is +# productArch=neutral with no chip/machineArch restriction, so the Arm installer +# offers it; and MSVC's VC\Tools\Llvm tree is partitioned by HOST architecture +# (bin = x86, x64\bin = x64, ARM64\bin = ARM64) with genuine ARM64 binaries +# already in ARM64\bin, which is where clang-cl.exe lands. Unlike the v141/XP +# group below, nothing technical is in the way. +# +# This is the compiler diversity the box is after: MSVC and clang-cl over the +# same sources, both native. $ClangComponents = @( 'Microsoft.VisualStudio.Component.VC.Llvm.Clang' 'Microsoft.VisualStudio.Component.VC.Llvm.ClangToolset' @@ -772,51 +528,186 @@ $ClangComponents = @( # Windows XP targeting (v141_xp toolset, used in CMakePresets.json). The v141 # (VS2017) build tools provide the 14.16 compiler that the XP toolset wraps; # WinXP layers the XP-compatible CRT/SDK on top of it. -$XpComponents = @( - 'Microsoft.VisualStudio.Component.VC.v141.x86.x64' - 'Microsoft.VisualStudio.Component.WinXP' -) +# +# NOT USED ON ARM64, and left empty there. The components are still listed in the +# catalog on Arm, so this is not strictly "unavailable" - but the 14.16 toolset +# predates Windows on Arm as a host and ships HostX86/HostX64 compilers only, so +# the best you could get is an x86-emulated compiler, and Microsoft does not +# support XP targeting from an Arm host. Nothing is lost that this box could have +# used: Windows XP never ran on ARM64, so an XP-targeting build from an ARM64 +# host has no purpose beyond producing x86 binaries, which the current toolset +# does natively via -A Win32. On x64 the group is installed exactly as before. +$XpComponents = if ($IsArm64) { @() } else { + @( + 'Microsoft.VisualStudio.Component.VC.v141.x86.x64' + 'Microsoft.VisualStudio.Component.WinXP' + ) +} -# Detect an existing VS install via vswhere (ships with the VS Installer). +# Which Visual Studio generation to drive: 17 = VS 2022, 18 = VS 2026. Both have +# native ARM64 installers and ARM64-hosted MSVC. This picks the bootstrapper URL, +# and - just as importantly - scopes the vswhere lookup below, so a box that +# already has a DIFFERENT generation installed is not mistaken for this one. +# +# Split by architecture on purpose: +# x64 -> 17. The v141 / Windows XP targeting toolset in $XpComponents is the +# reason; that group is the whole point of pinning a generation here. +# ARM64 -> 18. The XP group is skipped on Arm regardless (no ARM64-hosted 14.16 +# compiler), so nothing holds this back to 17, and VS 2026 brings the +# newer MSVC. Together with the native ARM64 clang-cl from +# $ClangComponents above, that is the compiler diversity on this box. +$VsChannel = if ($IsArm64) { 18 } else { 17 } +$VsEdition = 'community' # community | professional | enterprise + +# aka.ms path segment per generation. NOT the same word for both: VS 2022 is +# published under /release/, VS 2026 under /stable/. This is not cosmetic - +# https://aka.ms/vs/18/release/vs_community.exe is not a 404, it silently +# redirects to Bing and returns 200 with an HTML body, so a wrong guess here +# downloads a web page, names it vs_community.exe, and fails at Start-Process +# with something that looks nothing like a bad URL. +$VsChannelPath = if ($VsChannel -ge 18) { 'stable' } else { 'release' } + +# Detect an existing VS install via vswhere (ships with the VS Installer). Note +# that vswhere itself lives under the 32-bit Program Files on every architecture, +# ARM64 included - the VS Installer is x86-registered there by contract even +# though the installer binaries themselves are native. # These are referenced by Invoke-VsModify via $script: scope. $VsWhere = Join-Path ${env:ProgramFiles(x86)} 'Microsoft Visual Studio\Installer\vswhere.exe' -$InstallPath = $null +$InstallPath = Get-VsInstallPath + +# Report any OTHER Visual Studio generations on the box. They are left alone - +# the passes below only ever touch $InstallPath - but when none of them matches +# $VsChannel this script is about to download and install a second, largely +# redundant toolchain, and that should be a visible decision rather than a +# surprise 10GB. (On ARM64, where $VsChannel is 18, an existing VS 2026 IS the +# match and gets modified in place rather than duplicated.) if (Test-Path $VsWhere) { - $InstallPath = & $VsWhere -products '*' -property installationPath -format value | - Select-Object -First 1 + $others = & $VsWhere -products '*' -format value -property installationPath | + Where-Object { $_ -and $_ -ne $InstallPath } + if ($others) { + Write-Step 'Other Visual Studio installations detected' + foreach ($o in $others) { Write-Host " $o" -ForegroundColor Yellow } + Write-Host " Not modified. This script drives VS generation $VsChannel only." -ForegroundColor Yellow + Write-Host " To use one of the above instead, set `$VsChannel at the top of this step." -ForegroundColor Yellow + } } -Write-Step 'Downloading VS2022 Community bootstrapper' -$VsInstallerUrl = 'https://aka.ms/vs/17/release/vs_community.exe' -$VsBootstrapper = Join-Path $TempDir 'vs_community.exe' +Write-Step "Downloading VS $VsChannel $VsEdition bootstrapper (host: $HostArch)" +# aka.ms serves the bootstrapper for the requesting machine's architecture, so on +# ARM64 this is the native ARM64 installer - no --arch flag needed or offered. +$VsInstallerUrl = "https://aka.ms/vs/$VsChannel/$VsChannelPath/vs_$VsEdition.exe" +$VsBootstrapper = Join-Path $TempDir "vs_$VsEdition.exe" +Write-Host " $VsInstallerUrl" -ForegroundColor DarkGray Invoke-WebRequest -Uri $VsInstallerUrl -OutFile $VsBootstrapper -UseBasicParsing +# Prove we got an installer and not a web page. The Bing redirect described above +# returns 200 with HTML, and every other aka.ms typo behaves the same way, so a +# bad channel/edition combination is otherwise only discovered when the "exe" +# fails to start. 'MZ' is the DOS header every PE begins with. +$vsHead = [IO.File]::ReadAllBytes($VsBootstrapper) | Select-Object -First 2 +if (-not ($vsHead.Count -eq 2 -and $vsHead[0] -eq 0x4D -and $vsHead[1] -eq 0x5A)) { + throw "Visual Studio: $VsInstallerUrl did not return an executable (no MZ header; $((Get-Item $VsBootstrapper).Length) bytes). Check `$VsChannel / `$VsChannelPath / `$VsEdition." +} +Write-Host " OK: bootstrapper is a PE ($([math]::Round((Get-Item $VsBootstrapper).Length / 1MB, 2)) MB)" + # Install in three sequential passes. The base set is installed first (this is # the configuration that previously worked); Clang and the XP toolset are added # afterwards. If one fails, its label pinpoints which group is responsible. +# +# The last two are -Optional: neither the Clang toolset nor XP targeting is +# needed to build with MSVC, and on a host where one of them is simply not +# offered a hard failure here would cost you the whole toolchain over a component +# you can add later from the installer UI. Invoke-VsModify -Label 'base toolset + workload' -Ids $BaseComponents -Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents -Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents +Invoke-VsModify -Label 'Clang / LLVM' -Ids $ClangComponents -Optional +if ($IsArm64) { + Write-Step 'Visual Studio: Windows XP (v141 + WinXP)' + Write-Host ' Skipped on ARM64: the v141 (14.16) toolset ships x86/x64-hosted compilers only,' -ForegroundColor Yellow + Write-Host ' and Windows XP targeting is not offered for Arm hosts. Build x86 with the' -ForegroundColor Yellow + Write-Host ' current toolset instead (cmake -A Win32), which is native here.' -ForegroundColor Yellow +} else { + Invoke-VsModify -Label 'Windows XP (v141 + WinXP)' -Ids $XpComponents -Optional +} # --------------------------------------------------------------------------- -# Verify the v141 / XP toolset actually landed. Earlier runs silently skipped -# it and the failure only surfaced at build time, so check on disk and fail -# loudly here instead. +# Verify what actually landed, on disk. Earlier runs silently skipped the v141 +# toolset and the failure only surfaced at build time, so check here and say so +# loudly instead. Widened from that one check to every toolset worth naming, +# because the same "installed something, but not the thing you needed" failure is +# now possible per host architecture: this reports which MSVC host toolchains are +# present (HostARM64 is what proves the compiler is native rather than emulated), +# whether clang-cl is there, and - on x64 only - whether v141 is. +# +# Reporting, not throwing. A missing optional component is something to fix from +# the installer UI, not a reason to fail a provisioning run that installed a +# working compiler. # --------------------------------------------------------------------------- -Write-Step 'Verifying v141 / XP toolset' -$InstallPath = & $VsWhere -products '*' -property installationPath -format value | - Select-Object -First 1 -$V141 = if ($InstallPath) { - Get-ChildItem (Join-Path $InstallPath 'VC\Tools\MSVC') -Directory -ErrorAction SilentlyContinue | - Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1 -} -if ($V141) { - Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green +Write-Step 'Verifying the installed toolsets' +$InstallPath = Get-VsInstallPath +if (-not $InstallPath) { + Write-Warning "No Visual Studio $VsChannel installation found after the passes above; cannot verify toolsets." } else { - Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.' - Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:' - Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)' - Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools' + Write-Host " Install path: $InstallPath" + + # What MSVC versions landed, and which host toolchains each one carries. + # HostARM64 is the directory that proves the native ARM64 compiler is here + # rather than an x64 one that would run under emulation. + $msvcRoot = Join-Path $InstallPath 'VC\Tools\MSVC' + foreach ($v in (Get-ChildItem $msvcRoot -Directory -ErrorAction SilentlyContinue | Sort-Object Name)) { + $hosts = Get-ChildItem (Join-Path $v.FullName 'bin') -Directory -ErrorAction SilentlyContinue | + ForEach-Object { $_.Name } + Write-Host " MSVC $($v.Name): $(if ($hosts) { $hosts -join ', ' } else { '(no bin dir)' })" + } + if ($IsArm64) { + $armHost = Test-Path (Join-Path $msvcRoot '*\bin\HostARM64\ARM64\cl.exe') + if ($armHost) { + Write-Host ' OK: native ARM64-hosted cl.exe present.' -ForegroundColor Green + } else { + Write-Warning 'No HostARM64 cl.exe found - MSVC would run under x64 emulation. Add "MSVC v14x - VS 2022 C++ ARM64/ARM64EC build tools" in the installer.' + } + } + + # clang-cl, for the ClangCL toolset in CMakePresets.json. Checked per host + # directory, because the Llvm tree is partitioned by HOST architecture and + # only the matching one is a native compiler. + # + # Look for clang-cl.exe specifically, NOT for the directory. VC\Tools\Llvm\*\bin + # holds clang-format.exe and clang-tidy.exe on every host whether or not the + # Clang component was ever installed - those ship with the NativeDesktop + # workload - so a present ARM64\bin proves nothing on its own. That is the + # false positive to avoid when checking this by hand. + $llvmRoot = Join-Path $InstallPath 'VC\Tools\Llvm' + $clangArm = Test-Path (Join-Path $llvmRoot 'ARM64\bin\clang-cl.exe') + $clangX64 = Test-Path (Join-Path $llvmRoot 'x64\bin\clang-cl.exe') + $clangX86 = Test-Path (Join-Path $llvmRoot 'bin\clang-cl.exe') + if ($clangArm -or $clangX64 -or $clangX86) { + Write-Host " clang-cl: $(@(if ($clangArm) {'ARM64'}; if ($clangX64) {'x64'}; if ($clangX86) {'x86'}) -join ', ')" -ForegroundColor Green + # On ARM64 the x64 build would still run, under emulation - so say plainly + # whether the NATIVE one is the one that landed. + if ($IsArm64 -and -not $clangArm) { + Write-Warning 'No ARM64-hosted clang-cl - the x64 one would run under emulation. Re-run the Clang/LLVM pass, or add "C++ Clang tools for Windows" in the installer.' + } + } else { + Write-Warning 'clang-cl not found - the ClangCL presets will fail. Add the "C++ Clang tools for Windows" component.' + } + + # v141 / XP. Only meaningful where the toolset can exist at all; on ARM64 the + # group above was deliberately skipped, so warning here would be noise about + # a decision this script made on purpose two steps ago. + if ($IsArm64) { + Write-Host ' v141 / Windows XP toolset: n/a on ARM64 (not offered for Arm hosts).' -ForegroundColor DarkGray + } else { + $V141 = Get-ChildItem $msvcRoot -Directory -ErrorAction SilentlyContinue | + Where-Object { $_.Name -like '14.16.*' } | Select-Object -First 1 + if ($V141) { + Write-Host " OK: v141 toolset present ($($V141.Name))" -ForegroundColor Green + } else { + Write-Warning 'v141 (14.16.x) toolset NOT found - the XP build presets will fail.' + Write-Warning 'Add it via Visual Studio Installer > Modify > Individual components:' + Write-Warning ' - MSVC v141 - VS 2017 C++ x64/x86 build tools (v14.16)' + Write-Warning ' - C++ Windows XP Support for VS 2017 (v141) tools' + } + } } # --------------------------------------------------------------------------- @@ -826,8 +717,16 @@ if ($V141) { # linkid=2335869 -> WDK 26100.6584 (per Microsoft "Other WDK Downloads"). # --------------------------------------------------------------------------- $WdkVersion = '10.0.26100' -$WdkInstalledRoot = (Get-ItemProperty 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' ` - -ErrorAction SilentlyContinue).WdkBinRootVersioned +# Both hives. The WDK installer is a 32-bit program, so on x64 it writes under +# WOW6432Node - but which hive a given kit lands in has varied across kit +# versions and architectures, and reading only one of them makes an installed WDK +# look absent, which costs a needless multi-GB reinstall on every run. Check the +# native hive too and take whichever answers. +$WdkInstalledRoot = @( + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows Kits\Installed Roots' + 'HKLM:\SOFTWARE\Microsoft\Windows Kits\Installed Roots' +) | ForEach-Object { (Get-ItemProperty $_ -ErrorAction SilentlyContinue).WdkBinRootVersioned } | + Where-Object { $_ } | Select-Object -First 1 if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion)) { # Re-running wdksetup.exe for an already-present version returns exit code @@ -840,6 +739,10 @@ if ($WdkInstalledRoot -and $WdkInstalledRoot -match [regex]::Escape($WdkVersion) Invoke-WebRequest -Uri $WdkUrl -OutFile $WdkInstaller -UseBasicParsing Write-Step 'Installing WDK' + # wdksetup.exe is a 32-bit binary and runs under emulation on ARM64; the kit + # it lays down does include the ARM64 target headers, libs and tools (the + # signing/deployment tools under bin\arm64), so an ARM64 driver builds from + # an ARM64 host. Only the installer is emulated, not the toolchain. $proc = Start-Process -FilePath $WdkInstaller -ArgumentList '/quiet /norestart' -Wait -PassThru -NoNewWindow Write-Host " WDK installer exit code: $($proc.ExitCode)" if ($proc.ExitCode -eq 2008) { @@ -889,6 +792,14 @@ if ($WptDir) { Write-Host " OK: WPT already present ($WptDir)" -ForegroundColor Green } else { try { + # The ADK manifest offers no ARM64 installer, so on ARM64 winget fetches + # the x64 one; it runs under emulation and lays down a toolkit that does + # include the ARM64 binaries. The SDK feature is the lighter route on any + # architecture and is worth preferring if this fallback ever gives + # trouble - see the winsdksetup.exe line in the comment above. + if ($IsArm64) { + Write-Host ' ARM64: the ADK installer is x64 (emulated); the toolkit it installs is ARM64.' -ForegroundColor Yellow + } winget install --id Microsoft.WindowsADK --exact --silent --disable-interactivity ` --accept-source-agreements --accept-package-agreements Write-Host ' Windows ADK (includes Windows Performance Toolkit) installed.' @@ -932,8 +843,60 @@ if ($WptDir) { } +# --------------------------------------------------------------------------- +# Intel VTune Profiler - reported, not installed +# +# Deliberately NOT automated, unlike everything above. The offline installer is +# a ~750 MB download from a URL carrying a per-release GUID +# (registrationcenter-download.intel.com/akdlm/IRC_NAS//intel-vtune-_offline.exe) +# with no "latest" redirect behind it, so every new build means editing a +# hard-coded link in here - and it is only worth having on Intel silicon, since +# hardware event-based sampling reads Intel PMU counters. Not a good trade for a +# script that has to keep working unattended on any box. +# +# So this step only reports. To install it, take the Windows offline installer +# from +# https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html +# and run it elevated; it installs unattended with +# intel-vtune-_offline.exe -a --silent --cli --eula accept +# --------------------------------------------------------------------------- +Write-Step 'Intel VTune Profiler (status only)' +if ($IsArm64) { + # Not a "not installed yet" case - there is no Windows-on-Arm build of VTune, + # and there is nothing for it to sample: its whole value is reading Intel PMU + # counters. Say so plainly and point at what does work here, rather than + # printing a download link for a product this box cannot run. + Write-Host ' n/a on ARM64: Intel ships no Windows-on-Arm build, and hardware event-based' -ForegroundColor DarkGray + Write-Host ' sampling reads Intel PMU counters. Use the Windows Performance Toolkit above' -ForegroundColor DarkGray + Write-Host ' (wpr / xperf to collect, wpa to analyse) for profiling on this box.' -ForegroundColor DarkGray + Write-Host ' Arm also publishes Arm Performance Studio / Streamline for Arm PMU sampling.' -ForegroundColor DarkGray +} else { + $UninstallKeys = @( + 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*' + 'HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*' + ) + $vtune = Get-ItemProperty $UninstallKeys -ErrorAction SilentlyContinue | + Where-Object { $_.DisplayName -match 'VTune' } | + Select-Object -First 1 + if ($vtune) { + Write-Host " Installed: $($vtune.DisplayName.Trim()) $($vtune.DisplayVersion)" -ForegroundColor Green + # The oneAPI layout keeps a `latest` junction beside the versioned directory, + # so this path stays right across upgrades. + $VTuneCli = Join-Path $vtune.InstallLocation 'vtune\latest\bin64\vtune.exe' + if (Test-Path $VTuneCli) { Write-Host " CLI: $VTuneCli" } + } else { + Write-Host ' Not installed.' -ForegroundColor Yellow + Write-Host ' https://www.intel.com/content/www/us/en/developer/tools/oneapi/vtune-profiler-download.html' -ForegroundColor Yellow + $cpu = (Get-CimInstance Win32_Processor -ErrorAction SilentlyContinue | Select-Object -First 1).Manufacturer + if ($cpu -and $cpu -notmatch 'Intel') { + Write-Host " (This CPU reports itself as '$cpu' - VTune's hardware event-based sampling wants Intel silicon.)" -ForegroundColor Yellow + } + } +} + # --------------------------------------------------------------------------- Write-Host "`nAll done." -ForegroundColor Green +Write-Host "Host architecture was $HostArch." Write-Host 'If a reboot was flagged above, restart before opening VS or building drivers.' } @@ -944,7 +907,7 @@ catch { # Only fold in the VS Installer logs when a VS step actually failed; for other # steps (e.g. WDK) those logs are stale and misleading, so the message above # is what matters. - if ($_.Exception.Message -match 'VS2022') { + if ($_.Exception.Message -match 'Visual Studio') { try { Show-VsSetupLogs } catch {} } }