+function Set-NativeNinjaFirst {
+ # Make the native ninja.exe the one that wins, including inside a Visual
+ # Studio Developer Command Prompt.
+ #
+ # WHY THIS IS INSURANCE RATHER THAN THE FIX. VS ships an x64 ninja.exe even on
+ # ARM64 and puts it on the PATH from
+ # Common7\Tools\vsdevcmd\ext\cmake.bat, which does:
+ # set "PATH=%PATH%;...\CMake\bin;...\CMake\Ninja"
+ # That APPENDS - the VS directories land at the very end of the composed
+ # PATH, behind every machine and user entry. So a native ninja installed
+ # anywhere on the user PATH already beats it, and measurement on an ARM64 box
+ # confirms it does. (An earlier revision of this script claimed VsDevCmd
+ # prepends and that the VS copy therefore always won; that was wrong.)
+ #
+ # It is still worth pinning the order explicitly: winget appends its package
+ # directory to the user PATH, so the margin depends on nothing more than two
+ # append orders staying as they are, in a file Microsoft owns and revises.
+ # Putting the directory first costs nothing and removes the dependency.
+ #
+ # Ninja is worth this attention where a one-off tool would not be: it is
+ # re-invoked for every edge in the build graph, so it is the one place an
+ # emulated binary is paid over and over rather than once.
+ Write-Step 'Native ninja ahead of the Visual Studio copy'
+
+ $candidates = @()
+ $candidates += Get-ChildItem (Join-Path $env:LOCALAPPDATA 'Microsoft\WinGet\Packages') `
+ -Filter 'ninja.exe' -Recurse -Depth 2 -ErrorAction SilentlyContinue |
+ ForEach-Object { $_.FullName }
+ $candidates += @(
+ (Join-Path $env:ProgramFiles 'Ninja\ninja.exe')
+ (Join-Path $env:LOCALAPPDATA 'Programs\Ninja\ninja.exe')
+ )
+ # A ninja already on the PATH counts too - but only if it is not the VS one,
+ # which is the binary this step exists to get out in front of.
+ $onPath = (Get-Command ninja.exe -ErrorAction SilentlyContinue | Select-Object -First 1).Source
+ if ($onPath -and $onPath -notmatch 'CommonExtensions\\Microsoft\\CMake') { $candidates += $onPath }
+
+ $native = $null
+ foreach ($c in ($candidates | Where-Object { $_ -and (Test-Path $_) } | Select-Object -Unique)) {
+ $m = Get-PEMachine $c
+ if ($m -eq $(if ($IsArm64) { 'ARM64' } else { 'x64' })) { $native = $c; break }
+ }
+
+ if (-not $native) {
+ Write-Warning 'No native ninja.exe found. Install it with: winget install Ninja-build.Ninja'
+ Write-Warning 'Until then a build using the Ninja generator gets the x64 ninja Visual Studio bundles.'
+ return
+ }
+
+ Write-Host " native ninja: $native ($(Get-PEMachine $native))"
+ Add-ToUserPath (Split-Path $native -Parent) -Prepend
+}
+
+function Add-LlvmToUserPath {
+ # Put the upstream LLVM's bin directory on the user PATH.
+ #
+ # Two reasons this needs a step rather than trusting the installer:
+ #
+ # 1. WHERE IT LANDS. LLVM's NSIS installer targets %ProgramFiles%\LLVM, and
+ # when it cannot write there - a standard user, no elevation - it does not
+ # fail. It silently falls back to a per-user directory, observed as
+ # %USERPROFILE%\Documents\LLVM, and winget still reports "Successfully
+ # installed". So the package is registered, the compiler is genuinely
+ # there and native, and nothing can find it.
+ # 2. PATH. The installer's "add to PATH" option is not taken in a silent
+ # install, so clang-cl is not a command afterwards either way.
+ #
+ # Appended, not prepended: this is a second compiler kept deliberately
+ # alongside MSVC, and it should not quietly win a `clang-cl` that some script
+ # meant for Visual Studio's copy. Note VS does NOT put its own
+ # VC\Tools\Llvm on the PATH (its clang-cl is reached through CMake's
+ # -T ClangCL), so there is no collision to lose here.
+ Write-Step 'Upstream LLVM on the user PATH'
+ $candidates = @(
+ (Join-Path $env:ProgramFiles 'LLVM\bin')
+ (Join-Path ${env:ProgramFiles(x86)} 'LLVM\bin')
+ (Join-Path $env:LOCALAPPDATA 'Programs\LLVM\bin')
+ (Join-Path ([Environment]::GetFolderPath('MyDocuments')) 'LLVM\bin')
+ (Join-Path $env:USERPROFILE 'Documents\LLVM\bin')
+ )
+ $dir = $candidates | Where-Object { Test-Path (Join-Path $_ 'clang-cl.exe') } | Select-Object -First 1
+ if (-not $dir) {
+ Write-Host ' Not installed (winget install LLVM.LLVM); Visual Studio''s own clang-cl is unaffected.' -ForegroundColor DarkGray
+ return
+ }
+ $exe = Join-Path $dir 'clang-cl.exe'
+ $mach = Get-PEMachine $exe
+ Write-Host " $exe ($mach)"
+ if ($IsArm64 -and $mach -ne 'ARM64') {
+ Write-Warning "This LLVM is $mach, not ARM64. winget install LLVM.LLVM should resolve to the -woa64 build on this host."
+ }
+ if ($dir -notmatch [regex]::Escape($env:ProgramFiles)) {
+ Write-Host ' Note: not under Program Files - the installer fell back to a per-user' -ForegroundColor Yellow
+ Write-Host ' location because it could not write there. Re-run elevated for a machine-wide install.' -ForegroundColor Yellow
+ }
+ Add-ToUserPath $dir
+}
+
+function Get-RustupPath {
+ # winget installed rustup moments ago, but this process inherited its PATH
+ # before rustup-init added .cargo\bin to it, so Get-Command can miss it on a
+ # first run. Prefer one already on the PATH, then the cargo home.
+ $onPath = Get-Command rustup.exe -ErrorAction SilentlyContinue
+ if ($onPath) { return $onPath.Source }
+ $exe = Join-Path $CargoHome 'bin\rustup.exe'
+ if (Test-Path $exe) { return $exe }
+ $null
+}
+
+function Set-RustDefaultToolchain {
+ # Install Rust's stable MSVC toolchain for THIS host and make it the default:
+ # stable-x86_64-pc-windows-msvc on x64, stable-aarch64-pc-windows-msvc on
+ # ARM64.
+ #
+ # winget's rustup install mostly does this already - it runs
+ # `rustup-init -y -q`, which installs stable for the host rustup detects - so
+ # on a fresh box this step largely confirms it. It exists to make the answer
+ # explicit rather than inherited. rustup takes its default host from its own
+ # build, so an x64 rustup on an ARM64 box - an install from before the
+ # manifest had an arm64 rustup-init, or one started from an emulated x64
+ # shell - quietly sets up an x86_64 host and an emulated compiler. Naming the
+ # triple pins both the toolchain installed here and, through
+ # `set default-host`, what a bare `stable` means to rustup from then on.
+ #
+ # MSVC rather than GNU: the -msvc toolchains link with link.exe and the
+ # Windows SDK from the Visual Studio the elevated half installs - including
+ # the ARM64 build tools an aarch64 host links with. Those are needed to BUILD,
+ # not to install, so this step does not depend on the elevated half.
+ #
+ # Re-runs are cheap: `toolchain install` on an installed toolchain updates it
+ # to the current stable, or reports it unchanged. Setting the default each
+ # time is the point of the step - a default you changed by hand (to nightly,
+ # say) is put back to stable, so leave the step out of the plan to keep it.
+ Write-Step 'Rust: stable MSVC toolchain as the default'
+ if (-not $RustHost) {
+ Write-Warning "No Rust host toolchain is set up for host architecture '$HostArch'; skipping."
+ return
+ }
+ $rustup = Get-RustupPath
+ if (-not $rustup) {
+ Write-Warning 'rustup not found. Install it with: winget install Rustlang.Rustup'
+ return
+ }
+ Write-Host " using $rustup ($(Get-PEMachine $rustup))"
+
+ # EAP back to Continue for the calls: rustup reports progress on STDERR, and
+ # under $ErrorActionPreference = 'Stop' a native command's stderr can become
+ # a terminating error. Judged by the exit code instead - cleared first, as
+ # for ssh.exe above, so an exe that cannot start at all does not inherit the
+ # last one's 0.
+ $toolchain = "stable-$RustHost"
+ $calls = @(
+ @('set', 'default-host', $RustHost),
+ @('toolchain', 'install', $toolchain),
+ @('default', $toolchain)
+ )
+ $prevEap = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ foreach ($call in $calls) {
+ $global:LASTEXITCODE = $null
+ & $rustup @call
+ if ($LASTEXITCODE -ne 0) {
+ $why = if ($null -eq $LASTEXITCODE) { 'it would not start' } else { "exit $LASTEXITCODE" }
+ throw "rustup $($call -join ' ') failed ($why)"
+ }
+ }
+ } finally {
+ $ErrorActionPreference = $prevEap
+ }
+
+ # Report the compiler itself. .cargo\bin\rustc.exe is a rustup proxy - a copy
+ # of rustup.exe - so its architecture says nothing about the toolchain's.
+ $rustc = Join-Path $RustupHome "toolchains\$toolchain\bin\rustc.exe"
+ if (Test-Path $rustc) {
+ Write-Host " default: $toolchain - $(& $rustc -V) ($(Get-PEMachine $rustc))"
+ } else {
+ Write-Warning "rustup reported success, but $rustc is not there."
+ }
+
+ # An x86_64 host toolchain left on an ARM64 box - from before this step
+ # pinned the triple - is an emulated compiler that is no longer the default.
+ # Named rather than removed; whether it goes is your call. Building x64 code
+ # from here wants the x64 TARGET on the native toolchain, not an x64 host.
+ $x64Stable = Join-Path $RustupHome 'toolchains\stable-x86_64-pc-windows-msvc'
+ if ($IsArm64 -and (Test-Path $x64Stable)) {
+ Write-Host ' Also installed: stable-x86_64-pc-windows-msvc, an x64 compiler that runs emulated here.' -ForegroundColor Yellow
+ Write-Host " Remove it with 'rustup toolchain uninstall stable-x86_64-pc-windows-msvc'; to build" -ForegroundColor Yellow
+ Write-Host " x64 code from this box, use 'rustup target add x86_64-pc-windows-msvc' instead." -ForegroundColor Yellow
+ }
+}
+
+function Set-UserEnvironmentVariable([string] $Name, [string] $Value) {
+ # HKCU, like Add-ToUserPath, so it outlives the script; written only when it
+ # differs, so a re-run changes nothing.
+ if ([Environment]::GetEnvironmentVariable($Name, 'User') -eq $Value) {
+ Write-Host " $Name is already $Value"
+ return
+ }
+ [Environment]::SetEnvironmentVariable($Name, $Value, 'User')
+ Write-Host " Set $Name = $Value (restart your shell to pick it up)."
+}
+
+function Get-AndroidRevision($Package) {
+ # A package's revision from the index, as a [version]: <major>, optional
+ # <minor> and <micro>. [int] of a missing element is 0.
+ $r = $Package.revision
+ [version]('{0}.{1}.{2}' -f [int]$r.major, [int]$r.minor, [int]$r.micro)
+}
+
+function ConvertTo-Revision([string] $Text) {
+ # "23.0" as the same three-part [version] the index gives, so the two
+ # compare. [version]'23.0' has no third part - it reads as -1 - and so
+ # counted as OLDER than 23.0.0: an installed, current copy looked stale.
+ $parts = @($Text.Trim() -split '\.' | Where-Object { $_ -ne '' })
+ while ($parts.Count -lt 3) { $parts += '0' }
+ [version]($parts[0..2] -join '.')
+}
+
+function Invoke-AndroidCli {
+ # The Android CLI (cmdline-tools\latest\bin\android.exe) against this SDK,
+ # its output shown as it comes - a first install downloads well over 100 MB
+ # and should not look stalled. Returns the exit code, $null if it would not
+ # start. EAP Continue for the call, as for the other native tools here.
+ #
+ # stdin is one empty line, so it is closed rather than the console: a
+ # prompt nobody expected gets "no" instead of an unattended run waiting on
+ # it forever.
+ param([string[]] $Arguments)
+ $cli = Join-Path $AndroidSdkRoot 'cmdline-tools\latest\bin\android.exe'
+ $prevEap = $ErrorActionPreference
+ $ErrorActionPreference = 'Continue'
+ try {
+ $global:LASTEXITCODE = $null
+ # Its stderr becomes error records under 2>&1 in Windows PowerShell,
+ # which would print as red "NativeCommandError" noise; back to plain
+ # lines first. The one JVM warning dropped is the bundled Java noting,
+ # on every call, a flag this Windows 10 does not support.
+ '' | & $cli "--sdk=$AndroidSdkRoot" @Arguments 2>&1 | ForEach-Object { "$_" } |
+ Where-Object { $_ -notmatch 'UseAllWindowsProcessorGroups flag is not supported' } | Out-Host
+ $LASTEXITCODE
+ } finally {
+ $ErrorActionPreference = $prevEap
+ }
+}
+
+function Install-AndroidSdk {
+ # The Android SDK for building apps, per-user, in Android Studio's default
+ # location (%LOCALAPPDATA%\Android\Sdk) unless ANDROID_HOME names another:
+ # the command-line tools, platform-tools, and the newest stable platform and
+ # build-tools. That is what Android Studio's first-run wizard would set up,
+ # done without the wizard - on the x64 laptop Studio was installed and that
+ # wizard had never run, so there was no SDK at all. Gradle fetches any other
+ # platform or build-tools a project asks for by itself, once the licences are
+ # accepted, so this is the floor rather than the whole set.
+ #
+ # "Newest stable" comes from Google's package index, read here each run:
+ # channel-0 (stable) and no <preview> revision, the platform by API level
+ # (android-37.2 beats android-37.1 beats android-36), build-tools by version.
+ #
+ # THE COMMAND-LINE TOOLS ARE NOT WHAT THEY WERE. From 23.0, sdkmanager is
+ # deprecated and sdkmanager.bat is a shim over the new Android CLI
+ # (cmdline-tools\latest\bin\android.exe, `android sdk install ...`), which on
+ # first use installs itself into %USERPROFILE%\.android (bin\android-cli.exe,
+ # about 90 MB, and cli\ - a bundled Java runtime, and a metrics spool). So
+ # the CLI is called directly here, with its own "platforms/android-37.2"
+ # package paths: no deprecated shim, and no cmd parsing to split the old
+ # "platforms;android-37.2" at its semicolon. `sdk install` installs a
+ # package or, if it is there, updates it to the latest - so it is also the
+ # re-run path, downloading nothing when everything is current.
+ #
+ # ITS EXIT CODE IS NOT TRUSTED. CLI 1.0.16406183 finishes every `sdk`
+ # command and then crashes on the way out, 0xC0000409 (a fail-fast in
+ # ucrtbase) - on the x64 laptop's Windows 10, every time, in a console or
+ # not, while `--version` and `info` exit 0. So success is judged by the
+ # result: each package asked for must have the package.xml the CLI writes
+ # once a package is complete. A nonzero exit with everything present is a
+ # note, not a failure; anything missing is a failure, whatever the exit.
+ #
+ # The command-line tools themselves are bootstrapped from the index's own
+ # "cmdline-tools;latest" archive (SHA-1 from the index), and replaced only
+ # when the index has a newer revision than the one in source.properties.
+ # The CLI cannot do that for them: the archive calls itself
+ # cmdline-tools;23.0, a fixed version, so it would never "update" it.
+ #
+ # The SDK licences are accepted on your behalf; the plan says so before
+ # anything runs. The CLI does it as it installs - sdkmanager --licenses is
+ # now a no-op - writing licenses\android-sdk-license. Gradle needs it to
+ # build, and to fetch what a project asks for.
+ #
+ # The CLI brings its own Java, so the SDK needs no JDK. Gradle does: when
+ # there is no JAVA_HOME, the one Android Studio bundles (jbr) becomes the
+ # user's, so a command-line gradlew works. An existing JAVA_HOME is never
+ # changed.
+ Write-Step "Android SDK in $AndroidSdkRoot"
+
+ [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
+ # No progress bar for the downloads. Windows PowerShell 5.1's
+ # Invoke-WebRequest redraws it per chunk, and that - not the network - is
+ # what a large download then waits on: measured on the x64 laptop, the
+ # 148 MB command-line tools took about ten minutes and five minutes of CPU
+ # with it on. Local to this function, so nothing else changes.
+ $ProgressPreference = 'SilentlyContinue'
+ [xml]$index = (Invoke-WebRequest -UseBasicParsing -Uri $AndroidIndex).Content
+ $stable = @($index.DocumentElement.remotePackage |
+ Where-Object { $_.channelRef.ref -eq 'channel-0' -and -not $_.revision.preview })
+
+ # --- the command-line tools: bootstrapped, and kept current, from the index ---
+ $ct = @($stable | Where-Object { $_.path -eq 'cmdline-tools;latest' })[0]
+ if (-not $ct) { throw "No stable cmdline-tools;latest in $AndroidIndex." }
+ $ctWant = Get-AndroidRevision $ct
+ $ctDir = Join-Path $AndroidSdkRoot 'cmdline-tools\latest'
+ $ctHave = $null
+ $props = Join-Path $ctDir 'source.properties'
+ if (Test-Path $props) {
+ $m = [regex]::Match((Get-Content $props -Raw), '(?m)^Pkg\.Revision=(\d+(\.\d+){0,2})')
+ if ($m.Success) { $ctHave = ConvertTo-Revision $m.Groups[1].Value }
+ }
+ if ($ctHave -and $ctHave -ge $ctWant) {
+ Write-Host " command-line tools $ctHave are current."
+ } else {
+ $archive = @($ct.archives.archive | Where-Object { $_.'host-os' -eq 'windows' })[0]
+ $sum = $archive.complete.checksum
+ $sha1 = if ($sum -is [string]) { $sum } else { $sum.'#text' }
+ $url = $AndroidRepo + $archive.complete.url
+ Write-Host " command-line tools $(if ($ctHave) { "$ctHave -> " })$ctWant; downloading $($archive.complete.url)."
+ # PATH LENGTH. The archive nests deep - a guava jar in it sits well over
+ # 150 characters below its top - and Windows PowerShell 5.1 is bound by
+ # the 260-character MAX_PATH. So the temp directory's name is 8
+ # characters: %TEMP%\xxxxxxxx\cmdline-tools\... is then no deeper than
+ # %LOCALAPPDATA%\Android\Sdk\cmdline-tools\latest\..., and whenever the
+ # SDK's own path fits, unpacking it does too. (A 43-character name here
+ # made the unpack deeper than the SDK it was for.)
+ $tmp = Join-Path $env:TEMP ([guid]::NewGuid().ToString('N').Substring(0, 8))
+ New-Item -ItemType Directory -Force -Path $tmp | Out-Null
+ try {
+ $zip = Join-Path $tmp 'ct.zip'
+ Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $zip
+ $got = (Get-FileHash $zip -Algorithm SHA1).Hash.ToLower()
+ if ($sha1 -and $got -ne $sha1.ToLower()) { throw "SHA-1 mismatch for $url`: expected $sha1, got $got" }
+ Expand-Archive -Path $zip -DestinationPath $tmp -Force
+ # The archive holds a top-level cmdline-tools\ directory; the SDK
+ # layout wants it at cmdline-tools\latest. Replaced wholesale, as
+ # BinSkim is, so files dropped between releases do not linger - but
+ # the old copy is RENAMED aside first and deleted last. A rename is
+ # one operation whatever the depth below it; deleting walks every
+ # file and can trip over a path that is too long. Done this way, a
+ # delete that fails leaves a stray folder to report, not an SDK
+ # with no command-line tools in it. The aside name is six
+ # characters, like "latest", so the delete is no deeper either.
+ New-Item -ItemType Directory -Force -Path (Split-Path $ctDir) | Out-Null
+ $old = $null
+ if (Test-Path $ctDir) {
+ $old = Join-Path (Split-Path $ctDir) ('old' + [guid]::NewGuid().ToString('N').Substring(0, 3))
+ Rename-Item -Path $ctDir -NewName (Split-Path $old -Leaf)
+ }
+ Move-Item -Path (Join-Path $tmp 'cmdline-tools') -Destination $ctDir
+ if ($old) {
+ try { Remove-Item -Recurse -Force $old }
+ catch { Write-Warning "The new command-line tools are in place, but the old copy could not be removed: $old ($($_.Exception.Message))" }
+ }
+ } finally {
+ Remove-Item -Recurse -Force $tmp -ErrorAction SilentlyContinue
+ }
+ }
+
+ # --- the newest stable platform and build-tools, by the index ---
+ $platform = @($stable | ForEach-Object {
+ $m = [regex]::Match($_.path, '^platforms;android-(\d+)(?:\.(\d+))?$')
+ if ($m.Success) {
+ [pscustomobject]@{ Path = $_.path; Api = [version]('{0}.{1}' -f $m.Groups[1].Value, [int]$m.Groups[2].Value) }
+ }
+ } | Sort-Object Api)[-1].Path
+ $buildTools = @($stable | Where-Object { $_.path -match '^build-tools;\d+(\.\d+)*$' } |
+ Sort-Object { [version]($_.path -replace '^build-tools;', '') })[-1].path
+ if (-not $platform -or -not $buildTools) { throw "Could not find a stable platform and build-tools in $AndroidIndex." }
+
+ # The index names packages "platforms;android-37.2"; the CLI, and the SDK's
+ # directories, use "platforms/android-37.2".
+ $packages = @('platform-tools', ($platform -replace ';', '/'), ($buildTools -replace ';', '/'))
+ Write-Host " installing or updating: $($packages -join ', ')"
+ $rc = Invoke-AndroidCli -Arguments (@('sdk', 'install') + $packages)
+ $missing = @($packages | Where-Object { -not (Test-Path (Join-Path $AndroidSdkRoot (($_ -replace '/', '\') + '\package.xml'))) })
+ if ($missing) {
+ $why = if ($null -eq $rc) { 'it would not start' } else { "exit $rc" }
+ throw "android sdk install left out $($missing -join ', ') ($why)"
+ }
+ if ($null -eq $rc) {
+ Write-Warning 'The Android CLI would not start; the packages already installed were left as they were, not updated.'
+ } elseif ($rc -ne 0) {
+ Write-Host (" note: the Android CLI exited {0} (0x{0:X8}) after finishing - its crash on the way out, not a failed" -f $rc) -ForegroundColor DarkGray
+ Write-Host ' install: every package asked for is in place.' -ForegroundColor DarkGray
+ }
+
+ # Report what is there now, from each package's own source.properties.
+ foreach ($pkg in $packages) {
+ $p = Join-Path $AndroidSdkRoot (($pkg -replace '/', '\') + '\source.properties')
+ $rev = if (Test-Path $p) { [regex]::Match((Get-Content $p -Raw), '(?m)^Pkg\.Revision=(.*)$').Groups[1].Value.Trim() } else { '?' }
+ Write-Host (' {0,-28} {1}' -f $pkg, $rev)
+ }
+
+ Set-UserEnvironmentVariable 'ANDROID_HOME' $AndroidSdkRoot
+
+ # JAVA_HOME, for Gradle - only when there is none, and only to Android
+ # Studio's bundled JDK. Without Studio this just says what is missing.
+ if (-not [Environment]::GetEnvironmentVariable('JAVA_HOME', 'User') -and
+ -not [Environment]::GetEnvironmentVariable('JAVA_HOME', 'Machine')) {
+ $jbr = @((Join-Path $env:ProgramFiles 'Android\Android Studio\jbr'),
+ (Join-Path $env:LOCALAPPDATA 'Programs\Android Studio\jbr') |
+ Where-Object { Test-Path (Join-Path $_ 'bin\java.exe') })[0]
+ if ($jbr) {
+ Set-UserEnvironmentVariable 'JAVA_HOME' $jbr
+ } else {
+ Write-Warning 'No JAVA_HOME, and no Android Studio JDK to point it at: a command-line gradlew will need one. Install Android Studio (the AndroidStudio step) or a JDK.'
+ }
+ }
+
+ # The Android CLI (android), and the tools beside it (lint, d8, r8,
+ # apkanalyzer, the sdkmanager/avdmanager shims), in any shell.
+ # platform-tools is NOT added: the PlatformTools step already puts adb on the
+ # PATH, and two adb.exe on it would only make which one answers depend on
+ # the order.
+ Add-ToUserPath (Join-Path $ctDir 'bin')
+}
+