fix(windows): reserve 8 MiB main-thread stack on ARM64 (#13918)

This commit is contained in:
Acd-kk authored and GitHub committed 2026-10-30 00:45:14 +08:00
1 parent 50d5ef4b51
commit 9400c0cd0b
10 files changed
+249 -42

No files matched your search

+5
View File
@@ -24,6 +24,11 @@ linker = "rust-lld"
# paths pull in deep serde/driver call stacks. This embeds the size in the PE.
rustflags = ["-C", "link-arg=/STACK:8388608"]
# Native ARM64 builds need the same main-thread stack as x64. Without this,
# opening a query can exhaust the linker's 1 MiB default stack (#13917).
[target.aarch64-pc-windows-msvc]
rustflags = ["-C", "link-arg=/STACK:8388608"]
# The legacy Windows 7 / Server 2012 R2 target keeps the same 8 MiB main-thread
# stack. CI builds it with an explicit RUSTFLAGS env (static CRT), which
# replaces this table, so the same link arg is repeated in those workflows and
+3 -34
View File
@@ -70,37 +70,6 @@ if ($violations.Count -gt 0) {
Write-Host "Windows 7 PE import audit passed: $BinaryPath"
# Main-thread stack reserve audit. The app needs the 8 MiB stack that
# .cargo/config.toml applies to the standard Windows target; the legacy target is
# built with an explicit env RUSTFLAGS (static CRT), which replaces the config
# rustflags, so the workflow repeats `-C link-arg=/STACK:8388608`. Without it the
# PE keeps the 1 MiB linker default and deep connect/serde call stacks abort with
# 0xC00000FD ("DBX 已停止工作"), which users reported on Windows 7 / Server 2012 R2.
$minimumStackReserve = 8 * 1024 * 1024
$image = [System.IO.File]::ReadAllBytes($BinaryPath)
if ($image.Length -lt 0x100) {
throw "Windows 7 PE audit target is truncated: $BinaryPath"
}
$peOffset = [System.BitConverter]::ToInt32($image, 0x3C)
if ($peOffset -le 0 -or $peOffset + 24 -gt $image.Length) {
throw "Invalid PE header offset in ${BinaryPath}"
}
$peSignature = [System.BitConverter]::ToUInt32($image, $peOffset)
if ($peSignature -ne 0x00004550) {
throw "Invalid PE signature in ${BinaryPath}"
}
$optionalHeaderOffset = $peOffset + 24
$optionalHeaderMagic = [System.BitConverter]::ToUInt16($image, $optionalHeaderOffset)
$stackReserveOffset = $optionalHeaderOffset + 72
$stackReserve = if ($optionalHeaderMagic -eq 0x20B) {
[System.BitConverter]::ToUInt64($image, $stackReserveOffset)
} elseif ($optionalHeaderMagic -eq 0x10B) {
[System.BitConverter]::ToUInt32($image, $stackReserveOffset)
} else {
throw ("Unsupported PE optional header magic 0x{0:X4} in {1}" -f $optionalHeaderMagic, $BinaryPath)
}
if ($stackReserve -lt $minimumStackReserve) {
throw ("Windows 7 main-thread stack reserve is {0} bytes, below the {1}-byte minimum. Add -C link-arg=/STACK:8388608 to the build RUSTFLAGS. Binary: {2}" -f $stackReserve, $minimumStackReserve, $BinaryPath)
}
Write-Host "Windows 7 PE stack reserve audit passed: $stackReserve bytes ($BinaryPath)"
# The legacy env RUSTFLAGS also needs /STACK:8388608. Share the same audit as
# standard x64/ARM64 releases so every Windows desktop target keeps this guard.
& (Join-Path $PSScriptRoot "assert-windows-stack-reserve.ps1") -BinaryPath $BinaryPath
@@ -0,0 +1,58 @@
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string[]]$BinaryPath
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$minimumStackReserve = [uint64](8 * 1024 * 1024)
foreach ($path in $BinaryPath) {
if (!(Test-Path -LiteralPath $path -PathType Leaf)) {
throw "Windows PE stack audit target does not exist: $path"
}
# Read only the headers: release executables can be hundreds of MiB.
$image = [System.IO.File]::OpenRead((Get-Item -LiteralPath $path).FullName)
$reader = [System.IO.BinaryReader]::new($image)
try {
if ($image.Length -lt 0x40 -or $reader.ReadUInt16() -ne 0x5A4D) {
throw "Invalid or truncated DOS header in ${path}"
}
[void]$image.Seek(0x3C, [System.IO.SeekOrigin]::Begin)
$peOffset = [long]$reader.ReadUInt32()
if ($peOffset -lt 0x40 -or $peOffset + 24 -gt $image.Length) {
throw "Invalid PE header offset in ${path}"
}
[void]$image.Seek($peOffset, [System.IO.SeekOrigin]::Begin)
if ($reader.ReadUInt32() -ne 0x00004550) {
throw "Invalid PE signature in ${path}"
}
$machine = $reader.ReadUInt16()
[void]$image.Seek($peOffset + 20, [System.IO.SeekOrigin]::Begin)
$optionalHeaderSize = $reader.ReadUInt16()
$optionalHeaderOffset = $peOffset + 24
if ($optionalHeaderSize -lt 2 -or $optionalHeaderOffset + $optionalHeaderSize -gt $image.Length) {
throw "Invalid or truncated PE optional header in ${path}"
}
[void]$image.Seek($optionalHeaderOffset, [System.IO.SeekOrigin]::Begin)
$magic = $reader.ReadUInt16()
$stackFieldSize = switch ($magic) {
0x20B { 8 } # PE32+: x64 and ARM64.
0x10B { 4 } # PE32.
default { throw ("Unsupported PE optional header magic 0x{0:X4} in {1}" -f $magic, $path) }
}
if ($optionalHeaderSize -lt 72 + $stackFieldSize) {
throw "PE optional header does not contain SizeOfStackReserve in ${path}"
}
[void]$image.Seek($optionalHeaderOffset + 72, [System.IO.SeekOrigin]::Begin)
$stackReserve = if ($stackFieldSize -eq 8) { $reader.ReadUInt64() } else { [uint64]$reader.ReadUInt32() }
if ($stackReserve -lt $minimumStackReserve) {
throw ("Windows main-thread stack reserve is {0} bytes, below the {1}-byte minimum. Add -C link-arg=/STACK:8388608 to the build RUSTFLAGS. Binary: {2}" -f $stackReserve, $minimumStackReserve, $path)
}
Write-Host ("Windows PE stack reserve audit passed: {0} bytes, machine 0x{1:X4} ({2})" -f $stackReserve, $machine, $path)
} finally {
$reader.Dispose()
}
}
@@ -0,0 +1,86 @@
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$audit = Join-Path $PSScriptRoot "assert-windows-stack-reserve.ps1"
$temporaryRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
$directory = Join-Path $temporaryRoot "dbx-stack-reserve-tests-$([guid]::NewGuid())"
New-Item -ItemType Directory -Path $directory | Out-Null
$passed = 0
function New-TestImage {
param([int]$Machine = 0x8664, [int]$Magic = 0x20B, [uint64]$StackReserve = 8388608)
$bytes = [byte[]]::new(512)
[BitConverter]::GetBytes([uint16]0x5A4D).CopyTo($bytes, 0)
[BitConverter]::GetBytes([uint32]0x80).CopyTo($bytes, 0x3C)
[BitConverter]::GetBytes([uint32]0x4550).CopyTo($bytes, 0x80)
[BitConverter]::GetBytes([uint16]$Machine).CopyTo($bytes, 0x84)
[BitConverter]::GetBytes([uint16]0xF0).CopyTo($bytes, 0x94)
[BitConverter]::GetBytes([uint16]$Magic).CopyTo($bytes, 0x98)
if ($Magic -eq 0x10B) {
[BitConverter]::GetBytes([uint32]$StackReserve).CopyTo($bytes, 0xE0)
} else {
[BitConverter]::GetBytes($StackReserve).CopyTo($bytes, 0xE0)
}
return ,$bytes
}
function Test-Image {
param([string]$Name, [byte[]]$Bytes, [string]$ExpectedError = "")
$path = Join-Path $directory "$Name.exe"
[IO.File]::WriteAllBytes($path, $Bytes)
$before = (Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash
$failure = $null
try { & $audit -BinaryPath $path } catch { $failure = $_.Exception.Message }
if ($ExpectedError) {
if (!$failure -or $failure -notlike "*$ExpectedError*") { throw "${Name}: expected '$ExpectedError', got '$failure'" }
} elseif ($failure) {
throw "${Name}: unexpected failure: $failure"
}
if ((Get-FileHash -LiteralPath $path -Algorithm SHA256).Hash -ne $before) { throw "${Name}: audit modified the executable" }
$script:passed++
}
try {
foreach ($machine in @(0x8664, 0xAA64)) {
Test-Image "minimum-$machine" (New-TestImage -Machine $machine)
Test-Image "larger-$machine" (New-TestImage -Machine $machine -StackReserve 16777216)
Test-Image "default-$machine" (New-TestImage -Machine $machine -StackReserve 1048576) "below the 8388608-byte minimum"
}
Test-Image "pe32" (New-TestImage -Machine 0x14C -Magic 0x10B)
Test-Image "pe32-default" (New-TestImage -Machine 0x14C -Magic 0x10B -StackReserve 1048576) "below the 8388608-byte minimum"
Test-Image "below-minimum" (New-TestImage -StackReserve 8388607) "below the 8388608-byte minimum"
Test-Image "large-pe64-reserve" (New-TestImage -StackReserve 4294967296)
Test-Image "empty" ([byte[]]::new(0)) "DOS header"
Test-Image "truncated-dos" ([byte[]]::new(32)) "DOS header"
$bytes = New-TestImage; $bytes[0] = 0
Test-Image "bad-dos-signature" $bytes "DOS header"
$bytes = New-TestImage; [BitConverter]::GetBytes([uint32]4294967280).CopyTo($bytes, 0x3C)
Test-Image "out-of-range-pe-offset" $bytes "PE header offset"
$bytes = New-TestImage; [BitConverter]::GetBytes([uint32]32).CopyTo($bytes, 0x3C)
Test-Image "pe-offset-inside-dos" $bytes "PE header offset"
$bytes = New-TestImage; $bytes[0x80] = 0
Test-Image "bad-pe-signature" $bytes "PE signature"
$bytes = New-TestImage
Test-Image "truncated-optional-header" ([byte[]]$bytes[0..180]) "truncated PE optional header"
$bytes = New-TestImage; [BitConverter]::GetBytes([uint16]1).CopyTo($bytes, 0x94)
Test-Image "missing-optional-magic" $bytes "PE optional header"
$bytes = New-TestImage; [BitConverter]::GetBytes([uint16]72).CopyTo($bytes, 0x94)
Test-Image "missing-stack-field" $bytes "SizeOfStackReserve"
$bytes = New-TestImage; [BitConverter]::GetBytes([uint16]79).CopyTo($bytes, 0x94)
Test-Image "truncated-pe64-stack-field" $bytes "SizeOfStackReserve"
$bytes = New-TestImage -Magic 0x10B; [BitConverter]::GetBytes([uint16]75).CopyTo($bytes, 0x94)
Test-Image "truncated-pe32-stack-field" $bytes "SizeOfStackReserve"
Test-Image "unknown-magic" (New-TestImage -Magic 0x999) "optional header magic"
& $audit -BinaryPath @((Join-Path $directory "minimum-34404.exe"), (Join-Path $directory "minimum-43620.exe"))
$passed++
$missing = Join-Path $directory "missing.exe"
try { & $audit -BinaryPath $missing; throw "Missing target was accepted" } catch {
if ($_.Exception.Message -notlike "*target does not exist*") { throw }
}
$passed++
Write-Host "Windows stack reserve audit tests passed: $passed cases"
} finally {
$resolved = [IO.Path]::GetFullPath($directory)
if (!$resolved.StartsWith((Join-Path $temporaryRoot "dbx-stack-reserve-tests-"), [StringComparison]::OrdinalIgnoreCase)) { throw "Unexpected cleanup path: $resolved" }
Remove-Item -LiteralPath $resolved -Recurse -Force
}
+2 -1
View File
@@ -6,6 +6,7 @@ import { goAgents, integrationCases, rustAgents, rustGroups } from "./ci-config.
const win7InfrastructureFiles = new Set([
".github/scripts/assert-win7-pe-compat.ps1",
".github/scripts/assert-windows-stack-reserve.ps1",
".github/scripts/assert-webview2-win7-loader.ps1",
".github/scripts/assert-win7-installer-content.ps1",
".github/scripts/assert-webview2-win7-runtime.ps1",
@@ -145,7 +146,7 @@ export function planCi({ files, metadata, root, eventName = "pull_request", rust
agent_integration_changed: liveMatrix.length > 0,
duckdb_changed: nativeChanges.has("duckdb"),
duckdb_windows: sharedRust || files.some((file) => file.startsWith("agents/drivers/duckdb/")),
windows_standard: windowsWin7Candidate,
windows_standard: windowsWin7Candidate || files.some((file) => file === ".github/scripts/assert-windows-stack-reserve.test.ps1" || file === ".github/scripts/test-windows-stack-reserve.ps1"),
windows_win7_bundle: win7InfrastructureChanged || win7DependencyChanged || unknownRust || (rust && unknownMember),
windows_win7_candidate: windowsWin7Candidate,
windows_win7_affected_packages: [...win7Affected].sort(),
+9
View File
@@ -142,6 +142,7 @@ test("old Win7 Rust paths remain candidates through the dependency graph", () =>
test("Win7 infrastructure changes remain candidates outside the Cargo graph", () => {
for (const file of [
".github/scripts/assert-win7-pe-compat.ps1",
".github/scripts/assert-windows-stack-reserve.ps1",
".github/scripts/assert-webview2-win7-loader.ps1",
".github/scripts/assert-win7-installer-content.ps1",
".github/scripts/assert-webview2-win7-runtime.ps1",
@@ -173,6 +174,14 @@ test("Win7 infrastructure changes remain candidates outside the Cargo graph", ()
}
});
test("Windows stack test changes run the standard Windows checks", () => {
for (const file of [".github/scripts/assert-windows-stack-reserve.test.ps1", ".github/scripts/test-windows-stack-reserve.ps1"]) {
const result = plan([file]);
assert.equal(result.windows_standard, true, file);
assert.equal(result.windows_win7_bundle, false, file);
}
});
test("Win7 dependency inputs fail open", () => {
for (const file of ["Cargo.toml", "Cargo.lock", "src-tauri/Cargo.toml", "crates/dbx-cli/Cargo.toml"]) {
assert.equal(plan([file]).windows_win7_candidate, true, file);
-6
View File
@@ -513,9 +513,3 @@ test("legacy Windows builds keep the 8 MiB main-thread stack", () => {
}
assert.match(job("build-windows-7-x64", sqlServerUserTest), stackFlag, "the SQL Server 2000 Win7 test build must keep the 8 MiB main-thread stack");
});
test("the Win7 PE audit fails when the stack reserve regresses", () => {
const audit = readFileSync(new URL("./assert-win7-pe-compat.ps1", import.meta.url), "utf8");
assert.ok(audit.includes("minimumStackReserve"));
assert.ok(audit.includes("link-arg=/STACK:8388608"));
});
@@ -0,0 +1,69 @@
[CmdletBinding()]
param(
[string[]]$Targets = @("x86_64-pc-windows-msvc", "aarch64-pc-windows-msvc")
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$repositoryRoot = Split-Path (Split-Path $PSScriptRoot -Parent) -Parent
$audit = Join-Path $PSScriptRoot "assert-windows-stack-reserve.ps1"
$temporaryRoot = [IO.Path]::GetFullPath([IO.Path]::GetTempPath())
$directory = Join-Path $temporaryRoot "dbx-stack-reserve-probe-$([guid]::NewGuid())"
New-Item -ItemType Directory -Path (Join-Path $directory "src") | Out-Null
$originalRustflags = [Environment]::GetEnvironmentVariable("RUSTFLAGS", "Process")
$originalEncodedRustflags = [Environment]::GetEnvironmentVariable("CARGO_ENCODED_RUSTFLAGS", "Process")
$hadRustflags = Test-Path Env:RUSTFLAGS
$hadEncodedRustflags = Test-Path Env:CARGO_ENCODED_RUSTFLAGS
function Restore-RustflagEnvironment {
if ($hadRustflags) { $env:RUSTFLAGS = $originalRustflags }
else { Remove-Item Env:RUSTFLAGS -ErrorAction SilentlyContinue }
if ($hadEncodedRustflags) { $env:CARGO_ENCODED_RUSTFLAGS = $originalEncodedRustflags }
else { Remove-Item Env:CARGO_ENCODED_RUSTFLAGS -ErrorAction SilentlyContinue }
}
# A real PE produced by Cargo verifies effective linker flags, including when
# an environment override takes precedence over the repository's target config.
# no_std keeps the cross-architecture probe independent of Windows SDK libraries.
[IO.File]::WriteAllText((Join-Path $directory "Cargo.toml"), @'
[package]
name = "stack-reserve-probe"
version = "0.0.0"
edition = "2021"
[workspace]
[profile.release]
panic = "abort"
'@)
[IO.File]::WriteAllText((Join-Path $directory "src/main.rs"), @'
#![no_std]
#![no_main]
#[no_mangle]
pub extern "C" fn mainCRTStartup() {}
#[panic_handler]
fn panic(_: &core::panic::PanicInfo<'_>) -> ! { loop {} }
'@)
Push-Location $repositoryRoot
try {
foreach ($mode in @("target-config", "environment")) {
if ($mode -eq "environment") {
if (!$hadRustflags -and !$hadEncodedRustflags) { continue }
Restore-RustflagEnvironment
} else {
# An empty variable still overrides Cargo config in current PowerShell.
Remove-Item Env:RUSTFLAGS, Env:CARGO_ENCODED_RUSTFLAGS -ErrorAction SilentlyContinue
}
foreach ($target in $Targets) {
Write-Host "Verifying Windows stack reserve: $target ($mode)"
& cargo rustc --offline --release --manifest-path (Join-Path $directory "Cargo.toml") --target $target --target-dir (Join-Path $directory "target") -- -C linker=rust-lld -C link-arg=/ENTRY:mainCRTStartup -C link-arg=/SUBSYSTEM:CONSOLE -C link-arg=/NODEFAULTLIB
if ($LASTEXITCODE -ne 0) { throw "Failed to build the Windows stack probe for $target ($mode)" }
& $audit -BinaryPath (Join-Path $directory "target/$target/release/stack-reserve-probe.exe")
}
}
} finally {
Restore-RustflagEnvironment
Pop-Location
$resolved = [IO.Path]::GetFullPath($directory)
if (!$resolved.StartsWith((Join-Path $temporaryRoot "dbx-stack-reserve-probe-"), [StringComparison]::OrdinalIgnoreCase)) { throw "Unexpected cleanup path: $resolved" }
Remove-Item -LiteralPath $resolved -Recurse -Force
}
+11 -1
View File
@@ -316,7 +316,7 @@ jobs:
# An env RUSTFLAGS replaces .cargo/config.toml target rustflags, so the
# 8 MiB main-thread stack must be repeated here: without it the Windows PE
# keeps the 1 MiB linker default and deep connect/serde call stacks abort
# with 0xC00000FD ("DBX 已停止工作"). Guarded by assert-win7-pe-compat.ps1.
# with 0xC00000FD ("DBX 已停止工作"). Verified below for x64 and ARM64.
RUSTFLAGS: -C debuginfo=line-tables-only -C target-feature=+crt-static -C link-arg=/STACK:8388608
RUSTC_WRAPPER: sccache
# Prefer S3 when available; GitHub's 10 GB cache quota evicts the shared
@@ -328,6 +328,12 @@ jobs:
- name: Setup Rust for standard Windows
uses: dtolnay/rust-toolchain@1.97.1
with:
targets: aarch64-pc-windows-msvc
- name: Windows PE stack reserve audit tests
shell: pwsh
run: ./.github/scripts/assert-windows-stack-reserve.test.ps1
- name: MCP replacement temporary file cleanup tests
shell: pwsh
@@ -372,6 +378,10 @@ jobs:
echo "SCCACHE_IDLE_TIMEOUT=0"
} >> "$GITHUB_ENV"
- name: Verify x64 and ARM64 executable stack reserves
shell: pwsh
run: ./.github/scripts/test-windows-stack-reserve.ps1
- name: Check standard Windows dependency path
run: cargo check --locked --package dbx --no-default-features --target x86_64-pc-windows-msvc
+6
View File
@@ -337,6 +337,8 @@ jobs:
runs-on: windows-2022
env:
CARGO_INCREMENTAL: "0"
# Environment flags override target rustflags; retain the 8 MiB stack.
RUSTFLAGS: -C link-arg=/STACK:8388608
RUSTC_WRAPPER: sccache
SCCACHE_GHA_ENABLED: ${{ secrets.SCCACHE_S3_BUCKET == '' && 'true' || 'false' }}
VSIGN_CERT_HASH: ${{ vars.VSIGN_CERT_HASH }}
@@ -458,6 +460,10 @@ jobs:
# DBX_[version]_x64/arm64-setup.exe and keep the _en-US.msi names.
args: --target ${{ matrix.target }} --config src-tauri/tauri.vsign.conf.json
- name: Verify Windows executable stack reserve
shell: pwsh
run: ./.github/scripts/assert-windows-stack-reserve.ps1 -BinaryPath "target/${{ matrix.target }}/release/dbx.exe"
- name: Verify Windows bundles
shell: pwsh
run: |