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