Compare commits

..
Author SHA1 Message Date
Nwflower f827f4c3e5 packaging: omit MSYS2 sources and symbols on default alpha previews [skip ci] 2026-12-05 01:12:44 -07:00
Nwflower 1aa6a2f701 packaging: exclude qemu-system-aarch64w, strip ARM64/restore binaries, enable zstd --long=27 [skip ci] 2026-12-05 00:54:31 -07:00
Nwflower 4121508711 ci: throttle upstream sync, deduplicate artifacts, and bound compiler cache 2026-12-05 00:28:17 -07:00
千川白浪 4cca3b9020 Merge pull request #21 from reims-go/windows-runtime-pack-fixes
windows-runtime: pack patches with binary files and mode changes
2026-12-05 13:51:23 +08:00
NwflowerandClaude Opus 5.5 2c64ad41aa windows-runtime: keep the patch queue empty
Leave the reims-vgpu performance patch and the QEMU prealloc patch out of
the series: their changes go to their own repositories as reviewed pull
requests, and the prebuilt kexts are rebuilt from reviewed sources. The
packer's handling of binary hunks and index modes stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 22:46:13 -07:00
千川白浪 456be59b47 Merge pull request #14 from yxc0915/codex/runtime-publish-cache
Cache Windows runtime builds and batch MSYS2 package metadata
2026-12-05 13:44:38 +08:00
Xiaochi You 55e2902258 Merge pull request #17 from yxc0915/steelbrain/restore-pci-gpu-name
🐛 Restore the host GPU name in System Information
2026-12-04 22:52:39 +08:00
YXC0915 2d100e48da 🐛 Restore the host GPU name in System Information
Publish the host GPU name as the guest's PCI model so System Information
can display the actual chipset name.

Keep the x86-64 Metal name and vendor compatibility rules used by
WindowServer and applications. Cover the PCI name in the guest tests
and regenerate both prebuilt kext sets.
2026-12-04 22:42:15 +08:00
sitxovski f13f143001 windows-runtime: pack patches with binary files and mode changes
- pack-runtime.ps1 reads a patch's paths from its "diff --git" headers,
  so binary files (prebuilt kexts) are declared too, and compares
  "index" lines without their file mode.
- series.txt: the local performance patch for reims-vgpu and the
  multithreaded Windows prealloc patch for vendor/qemu.
2026-12-04 16:58:34 +03:00
YXC0915 4f31eee07b Route native Ninja compiler calls through ccache
Windows searches the launching executable directory before PATH. Stage the CI copy of Ninja alongside the installed ccache shims and point ccache at the original CLANG64 toolchain. Log the detailed compiler counters.
2026-12-04 19:27:10 +08:00
YXC0915 9a8a776418 Cache Windows runtime compilation and batch MSYS2 package lookups
Reuse compiler objects and Cargo downloads across Alpha jobs, then link and package the exact runtime inputs on every build. Query package ownership, versions and licenses in batches and avoid recompressing the uploaded archives.

Checked the workflow with actionlint and checked the MSYS2 lookup with mock and installed-package tests.
2026-12-04 18:45:23 +08:00
Xiaochi You abc65fdbf9 Merge pull request #7 from cosimawei/feat/configurable-input-release-pr
Support configurable SDL input release shortcuts and pointer exit.
2026-12-04 16:06:30 +08:00
YXC0915 d427f1bd86 📝 Register SDL input release settings [ci skip]
List the new configuration switches and the window tests that guard them.
2026-12-04 15:50:25 +08:00
YXC0915 76791eb6b6 Merge current runtime master into capture shortcut validation 2026-12-04 15:47:59 +08:00
YXC0915 4f7c54c458 🆕 Package runtimes from the organization dependency pins [skip ci]
Read the source URLs and revisions directly from the selected runtime. Retire the six patches now in the organization forks and record the resolved URLs in the manifest and source package.
2026-12-03 02:54:20 +08:00
YXC0915 28457772f4 🐛 Isolate Places allocations from buffer address replay
Keep texture blocks in non-replay Vulkan allocations while preserving exact-address replay for captured buffers.
2026-12-03 01:02:03 +08:00
YXC0915 116ef68ae8 🐛 Resolve a working zstd for Windows runtime archives 2026-12-03 01:02:03 +08:00
Xiaochi You 1bc441947c Merge pull request #5 from yxc0915/steelbrain/static-attachment-feedback
🐛 Use static Vulkan attachment feedback for Windows
2026-12-03 00:41:50 +08:00
YXC0915 c0b03faa85 🐛 Use static Vulkan attachment feedback for Windows
Fix the dark desktop after FileVault unlock on RTX A5000 by setting the color attachment feedback flag at pipeline creation. Retain the existing feature gate and the shadow-copy fallback.
2026-12-03 00:40:40 +08:00
hanyewei 5f5995e9fb Configure SDL capture release shortcuts and pointer exit 2026-12-02 23:44:07 +08:00
YXC0915 57024d3ab1 Handle retired maintenance refs during Alpha publication [ci skip]
A branch rename can remove the ref while a runtime build is running. Keep the verified artifact and skip automatic publication when Git succeeds with no match. Preserve the checks for a failed query or a superseded commit.
2026-12-02 19:41:01 +08:00
YXC0915 e8083c97ea 🐛 Update maintenance branch references [ci skip]
Keep automation and documentation aligned with the renamed branch.
The source pins and build steps stay the same.
2026-12-02 19:27:53 +08:00
YXC0915 3bbf37b149 Build Windows runtimes with the AMD Vulkan startup fixes
Apply the GPU address carry and dynamic attachment feedback backports after the snapshot replay patch. The runtime source archive records both patches alongside their pinned upstream base.
2026-12-02 18:59:10 +08:00
YXC0915 98f1677b5f 🆕 Select Alpha versions by suspend compatibility [ci skip]
Publish the version planner and compatibility manifest contract.
Wait for a new runtime baseline before building the next Alpha.
2026-12-02 03:22:02 +08:00
YXC0915 9a6ace7a3a 📝 Define Alpha suspend compatibility versions [ci skip]
Document patch revisions, compatibility boundaries, and the client
validation required to restore older saved state.
2026-12-02 02:47:03 +08:00
YXC0915 add539cd0f 🐛 Replace unfinished Alpha builds on push
Cancel older builds only for new automatic updates. Resolve stale
dispatches before taking the build lock and check published versions
inside it so queued runs skip work that already finished.
2026-12-02 02:05:31 +08:00
YXC0915 3cb5384b33 🆕 Build and publish Alpha on runtime changes
Build a new Alpha when packaging inputs change and queue an Alpha for
each upstream merge into the runtime maintenance branch.
2026-12-02 01:57:47 +08:00
35 changed files with 1148 additions and 1359 deletions

No files matched your search

+3 -2
View File
@@ -2,7 +2,7 @@ name: Merge upstream updates
on:
schedule:
- cron: '37 */4 * * *'
- cron: '37 2 * * *'
workflow_dispatch:
permissions:
@@ -16,9 +16,10 @@ jobs:
sync:
if: github.repository == 'reims-go/reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 20
timeout-minutes: 10
steps:
- name: Merge upstream into the maintenance branch
id: merge
shell: bash
env:
GH_TOKEN: ${{ github.token }}
+174 -91
View File
@@ -1,6 +1,10 @@
name: Publish Runtime Preview
on:
push:
branches: [master]
paths:
- "packaging/windows-runtime/**"
schedule:
- cron: "23 3 * * *"
workflow_dispatch:
@@ -13,21 +17,25 @@ on:
description: "Publish the verified preview as a GitHub prerelease"
type: boolean
default: true
supersede:
description: "Replace older builds for an automatic maintenance-branch push"
type: boolean
default: false
rebuild:
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
description: "Plan a rebuild of an already published runtime using verified compatibility"
type: boolean
default: false
include_sources:
description: "Include MSYS2 copyleft source archive and detached debug symbols (for stable promotion)"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: build-runtime
cancel-in-progress: false
env:
UPSTREAM_URL: ${{ github.server_url }}/${{ github.repository }}.git
UPSTREAM_BRANCH: codex/win32-disk-aio
UPSTREAM_BRANCH: intel-vm-suspend
jobs:
resolve:
@@ -35,57 +43,30 @@ jobs:
outputs:
commit: ${{ steps.r.outputs.commit }}
skip: ${{ steps.r.outputs.skip }}
suffix: ${{ steps.r.outputs.suffix }}
steps:
- id: r
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
WANT: ${{ inputs.upstream_commit }}
REBUILD: ${{ inputs.rebuild }}
CURRENT_ONLY: ${{ inputs.supersede }}
run: |
set -euo pipefail
git clone -q --filter=blob:none --no-checkout --single-branch --branch "$UPSTREAM_BRANCH" "$UPSTREAM_URL" up
commit="$(git -C up rev-parse --verify "${WANT:-HEAD}^{commit}")"
git -C up cat-file -e "$commit:reims-go-runtime.json"
echo "commit=$commit" >> "$GITHUB_OUTPUT"
# Already published (alpha or stable) under any short-hash length or -pN revision?
max_rev=0
for tag in $(gh release list -R "$GITHUB_REPOSITORY" --limit 1000 --json tagName -q '.[].tagName' | grep '^runtime-' || true); do
rest="${tag#runtime-}"
base="${rest%%-p*}"
case "$commit" in
"$base"*)
rev=1
if [ "$rest" != "$base" ]; then
num="${rest#"$base"-p}"
case "$num" in
''|*[!0-9]*) ;;
*) rev="$num" ;;
esac
fi
if [ "$rev" -gt "$max_rev" ]; then max_rev="$rev"; fi
echo "Upstream $commit is already released as $tag (rev $rev)"
;;
esac
done
skip=false
suffix=""
if [ "$max_rev" -gt 0 ]; then
if [ "$REBUILD" = "true" ]; then
suffix="-p$((max_rev + 1))"
echo "Rebuild requested: will publish with suffix $suffix"
else
skip=true
fi
if [[ "$CURRENT_ONLY" == true && "$commit" != "$(git -C up rev-parse HEAD)" ]]; then
echo "Skipping superseded runtime commit $commit"
echo "skip=true" >> "$GITHUB_OUTPUT"
fi
echo "skip=$skip" >> "$GITHUB_OUTPUT"
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
build:
needs: resolve
if: needs.resolve.outputs.skip != 'true'
concurrency:
group: build-runtime
cancel-in-progress: ${{ github.event_name == 'push' || inputs.supersede }}
runs-on: windows-latest
timeout-minutes: 150
timeout-minutes: 90
permissions:
contents: write
steps:
@@ -93,66 +74,84 @@ jobs:
with:
persist-credentials: false
# Select the version inside the build lock, including queued runs.
- name: Plan Alpha release
id: plan
shell: pwsh
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
RUNTIME_COMMIT: ${{ needs.resolve.outputs.commit }}
REBUILD: ${{ github.event_name == 'push' || inputs.rebuild }}
PACKAGING_PUSH: ${{ github.event_name == 'push' }}
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
git config --global core.autocrlf false
git clone -q --filter=blob:none --no-checkout --single-branch --branch $env:UPSTREAM_BRANCH $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'runtime clone failed' }
$plan = & ./packaging/windows-runtime/scripts/plan-runtime-release.ps1 `
-RuntimeRepo $work -RuntimeCommit $env:RUNTIME_COMMIT `
-PackagingRepo $env:GITHUB_WORKSPACE -PackagingCommit $env:GITHUB_SHA `
-Repository $env:GITHUB_REPOSITORY -Rebuild:($env:REBUILD -eq 'true') `
-PackagingPush:($env:PACKAGING_PUSH -eq 'true')
"skip=$($plan.Skip.ToString().ToLowerInvariant())" >> $env:GITHUB_OUTPUT
if ($plan.Skip) { return }
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"RELEASE_ID=$($plan.ReleaseId)" >> $env:GITHUB_ENV
"SUSPEND_COMPAT_ID=$($plan.SuspendCompatID)" >> $env:GITHUB_ENV
"SUSPEND_VERIFICATION=$($plan.Evidence)" >> $env:GITHUB_ENV
"SUSPEND_PREDECESSOR=$($plan.Predecessor)" >> $env:GITHUB_ENV
- name: Setup MSYS2 CLANG64
if: steps.plan.outputs.skip != 'true'
id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: CLANG64
update: true
install: >-
git zstd tar mingw-w64-clang-x86_64-toolchain
git curl diffutils make zstd tar mingw-w64-clang-x86_64-toolchain
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-usbredir
mingw-w64-clang-x86_64-gnutls mingw-w64-clang-x86_64-dtc
mingw-w64-clang-x86_64-libva mingw-w64-clang-x86_64-zstd
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
mingw-w64-clang-x86_64-ccache mingw-w64-clang-x86_64-sccache
- name: Check out the runtime forks and apply dependency patches
if: steps.plan.outputs.skip != 'true'
id: patches
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
$work = $env:UPSTREAM_DIR
foreach ($d in 'cargo', 'xdg-data', 'xdg-cache') { New-Item -ItemType Directory -Force -Path (Join-Path $env:RUNNER_TEMP $d) | Out-Null }
# The runner's git defaults to core.autocrlf=true; LF patches need an LF
# checkout (upstream also rewrites CRLF files to LF, install-ctl.sh).
git config --global core.autocrlf false
git clone -q --single-branch --branch $env:UPSTREAM_BRANCH $env:UPSTREAM_URL $work
if ($LASTEXITCODE) { throw 'clone failed' }
git -C $work checkout -q '${{ needs.resolve.outputs.commit }}'
if ($LASTEXITCODE) { throw 'checkout failed' }
git -C $work submodule update --init --depth 1 vendor/qemu
if ($LASTEXITCODE) { git -C $work submodule update --init vendor/qemu }
if ($LASTEXITCODE) { throw 'vendor/qemu submodule failed' }
$utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util'
$utilPin = Get-Content -Raw -LiteralPath (Join-Path $work 'crates/reims-ctl/src/reims_util.rs')
if ($utilPin -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found' }
$utilRev = $Matches[1]
git init -q $utilRepo
if ($LASTEXITCODE) { throw 'reims-util init failed' }
git -C $utilRepo fetch -q --depth 1 https://github.com/steelbrain/reims-util.git $utilRev
if ($LASTEXITCODE) { throw 'reims-util fetch failed' }
git -C $utilRepo checkout -q --detach FETCH_HEAD
if ($LASTEXITCODE) { throw 'reims-util checkout failed' }
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.toml')
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
$m2vRev = $Matches[1]
} else {
$lockTxt = Get-Content -Raw -LiteralPath (Join-Path $work 'Cargo.lock')
if ($lockTxt -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
$m2vRev = $Matches[1]
$pins = & ./packaging/windows-runtime/scripts/read-runtime-dependencies.ps1 -RuntimeRepo $work
function Get-DependencyCheckout($pin, [string]$path) {
git init -q $path
if ($LASTEXITCODE) { throw "Could not initialize $path" }
git -C $path remote add origin $pin.Url
if ($LASTEXITCODE) { throw "Could not add origin for $path" }
git -C $path fetch -q --depth 1 origin $pin.Rev
if ($LASTEXITCODE) { throw "Could not fetch $($pin.Url)@$($pin.Rev)" }
git -C $path checkout -q --detach $pin.Rev
if ($LASTEXITCODE) { throw "Could not check out $($pin.Url)@$($pin.Rev)" }
Write-Host "Using $($pin.Url)@$($pin.Rev)"
}
git init -q $m2vRepo
if ($LASTEXITCODE) { throw 'metal2vulkan init failed' }
git -C $m2vRepo fetch -q --depth 1 https://github.com/steelbrain/metal2vulkan.git $m2vRev
if ($LASTEXITCODE) { throw 'metal2vulkan fetch failed' }
git -C $m2vRepo checkout -q --detach FETCH_HEAD
if ($LASTEXITCODE) { throw 'metal2vulkan checkout failed' }
$utilRepo = Join-Path $env:RUNNER_TEMP 'reims-util'
$m2vRepo = Join-Path $env:RUNNER_TEMP 'metal2vulkan'
Get-DependencyCheckout $pins.Util $utilRepo
Get-DependencyCheckout $pins.Metal $m2vRepo
$short = (git -C $work rev-parse --short=7 HEAD).Trim()
$releaseId = "$short${{ needs.resolve.outputs.suffix }}"
# Applies what applies, skips what upstream already has, stops on a
# conflict without touching the patch (AGENTS.md rule 4).
@@ -169,29 +168,77 @@ jobs:
}
if (-not $ok) { throw 'patch queue does not apply' }
$cargoHome = Join-Path $env:RUNNER_TEMP 'cargo'
$m2vFwd = $m2vRepo.Replace('\', '/')
$cargoCfg = @"
[patch."https://github.com/steelbrain/metal2vulkan"]
$m2vChanges = git -C $m2vRepo status --porcelain
if ($LASTEXITCODE) { throw 'Could not read metal2vulkan checkout status' }
if ($m2vChanges) {
$m2vFwd = $m2vRepo.Replace('\', '/')
$cargoCfg = @"
[patch."$($pins.Metal.Url)"]
metal2vulkan = { path = "$m2vFwd/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "$m2vFwd/crates/metal2vulkan-runtime" }
"@ -replace '(?m)^ ', ''
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
"UPSTREAM_DIR=$work" >> $env:GITHUB_ENV
"@
[IO.File]::WriteAllText((Join-Path $cargoHome 'config.toml'), ($cargoCfg.Replace("`r`n", "`n") + "`n"), [Text.UTF8Encoding]::new($false))
}
"REIMS_UTIL_DIR=$utilRepo" >> $env:GITHUB_ENV
"METAL2VULKAN_DIR=$m2vRepo" >> $env:GITHUB_ENV
"SHORT_COMMIT=$short" >> $env:GITHUB_ENV
"RELEASE_ID=$releaseId" >> $env:GITHUB_ENV
"CARGO_HOME=$cargoHome" >> $env:GITHUB_ENV
"XDG_DATA_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-data')" >> $env:GITHUB_ENV
"XDG_CACHE_HOME=$(Join-Path $env:RUNNER_TEMP 'xdg-cache')" >> $env:GITHUB_ENV
- name: Build upstream runtime in MSYS2 CLANG64
- name: Identify the Windows build toolchain
if: steps.plan.outputs.skip != 'true'
id: toolchain
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
fingerprint="$({ LC_ALL=C pacman -Q; cat rust-toolchain.toml; } | sha256sum)"
week="$(date -u +%G-W%V)"
echo "fingerprint=${fingerprint%% *}" >> "$GITHUB_OUTPUT"
echo "week=$week" >> "$GITHUB_OUTPUT"
echo "Build toolchain: ${fingerprint%% *} (cache bucket: $week)"
- name: Cache compiler objects and Cargo downloads
if: steps.plan.outputs.skip != 'true'
uses: actions/cache@v5
with:
path: |
${{ runner.temp }}/compiler-cache/ccache
${{ runner.temp }}/compiler-cache/sccache
${{ runner.temp }}/cargo/registry/index
${{ runner.temp }}/cargo/registry/cache
${{ runner.temp }}/cargo/git/db
key: runtime-build-v2-${{ runner.arch }}-${{ steps.toolchain.outputs.fingerprint }}-${{ steps.toolchain.outputs.week }}
restore-keys: |
runtime-build-v2-${{ runner.arch }}-${{ steps.toolchain.outputs.fingerprint }}-
- name: Build upstream runtime in MSYS2 CLANG64
if: steps.plan.outputs.skip != 'true'
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
CCACHE_MAXSIZE: 400M
CCACHE_COMPILERCHECK: content
SCCACHE_CACHE_SIZE: 500M
SCCACHE_ALLOW_INCREMENTAL: "1"
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
# Native Ninja searches its own directory for the installer's bare
# clang/clang++ names before PATH. Put the cache shims beside its CI copy.
temp_dir="$(cygpath -u "$RUNNER_TEMP")"
tools_dir="$temp_dir/compiler-tools"
mkdir -p "$tools_dir"
cp "$MINGW_PREFIX/bin/ninja.exe" "$MINGW_PREFIX/lib/ccache/bin/"clang{,++}.exe "$tools_dir/"
export PATH="$tools_dir:$PATH"
export CCACHE_PATH="$(cygpath -m "$MINGW_PREFIX/bin")"
export CCACHE_DIR="$(cygpath -m "$temp_dir")/compiler-cache/ccache"
export SCCACHE_DIR="$(cygpath -m "$temp_dir")/compiler-cache/sccache"
export RUSTC_WRAPPER="$(cygpath -m "$MINGW_PREFIX/bin/sccache.exe")"
ccache --zero-stats
sccache --start-server
trap 'ccache --show-stats --verbose; sccache --stop-server' EXIT
# Upstream's own non-interactive CLANG64 build script.
bash scripts/install-ctl.sh --yes
util_repo="$(cygpath -u "$REIMS_UTIL_DIR")"
@@ -203,6 +250,9 @@ jobs:
fi
- name: Package alpha runtime and source archives
if: steps.plan.outputs.skip != 'true'
env:
INCLUDE_FULL_SOURCES: ${{ inputs.include_sources }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
@@ -211,6 +261,7 @@ jobs:
# In-process call, so an empty list (every patch already upstream) binds
# as an empty array rather than being dropped as an empty argument.
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
$full = $env:INCLUDE_FULL_SOURCES -eq 'true'
& ./packaging/windows-runtime/scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-UtilRepo $env:REIMS_UTIL_DIR `
@@ -222,43 +273,72 @@ jobs:
-TempRoot $env:RUNNER_TEMP `
-Channel alpha `
-ReleaseId $env:RELEASE_ID `
-Patches $applied
-SuspendCompatID $env:SUSPEND_COMPAT_ID `
-PackagingCommit $env:GITHUB_SHA `
-Patches $applied `
-SkipMsys2Sources:(-not $full) `
-SkipSymbols:(-not $full)
- name: Alpha entry gate
if: steps.plan.outputs.skip != 'true'
env:
INCLUDE_FULL_SOURCES: ${{ inputs.include_sources }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$full = $env:INCLUDE_FULL_SOURCES -eq 'true'
& ./packaging/windows-runtime/scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID -RequireSlim -RequiredCapability vm-suspend `
-RequiredSuspendCompatID $env:SUSPEND_COMPAT_ID -RequiredPackagingCommit $env:GITHUB_SHA `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) `
-SkipMsys2Sources:(-not $full) `
-SkipSymbols:(-not $full)
- name: Upload alpha artifacts
- name: Upload alpha artifacts (non-release debug runs only)
if: steps.plan.outputs.skip != 'true' && !(github.event_name == 'push' || github.event_name == 'schedule' || inputs.publish)
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
path: |
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
${{ runner.temp }}/releases/SHA256SUMS.txt
retention-days: 14
compression-level: 0
retention-days: 3
- name: Publish alpha prerelease (never stable)
if: github.event_name == 'schedule' || inputs.publish
if: steps.plan.outputs.skip != 'true' && (github.event_name == 'push' || github.event_name == 'schedule' || inputs.publish)
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CURRENT_ONLY: ${{ github.event_name == 'push' || inputs.supersede }}
MERGED: ${{ steps.patches.outputs.merged }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
if ($env:CURRENT_ONLY -eq 'true') {
$ref = "refs/heads/$env:UPSTREAM_BRANCH"
$remote = git ls-remote $env:UPSTREAM_URL $ref
if ($LASTEXITCODE -ne 0) { throw "Could not query the runtime maintenance ref $ref" }
if (!$remote) {
Write-Warning "Skipping Alpha publication because $ref no longer exists. The verified archives are available in the workflow artifact."
return
}
if (($remote -split '\s+')[0] -ne '${{ needs.resolve.outputs.commit }}') {
Write-Host 'Skipping Alpha publication for a superseded runtime commit.'
return
}
}
$c = $env:RELEASE_ID
$short = $env:SHORT_COMMIT
$sourceRepo = $env:UPSTREAM_URL -replace '\.git$', ''
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
ForEach-Object { Join-Path $dir $_ } |
Where-Object { Test-Path -LiteralPath $_ -PathType Leaf }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
$compatibility = if ($env:SUSPEND_PREDECESSOR) { "`nVerified against $env:SUSPEND_PREDECESSOR. $env:SUSPEND_VERIFICATION" } else { '' }
$notes = @"
**Alpha** runtime (``$c``), built from [the Reims vGPU fork@$short]($sourceRepo/commit/${{ needs.resolve.outputs.commit }}).
@@ -269,7 +349,10 @@ jobs:
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
Packaging commit: ``$env:GITHUB_SHA``
Suspend compatibility ID: ``$env:SUSPEND_COMPAT_ID``$compatibility
Build: $env:GITHUB_SERVER_URL/$env:GITHUB_REPOSITORY/actions/runs/$env:GITHUB_RUN_ID
"@
gh release create "runtime-$c" @assets --repo $env:GITHUB_REPOSITORY --target '${{ needs.resolve.outputs.commit }}' --prerelease --title "Portable Runtime runtime-$c (alpha)" --notes $notes
gh release create "runtime-$c" @assets --repo $env:GITHUB_REPOSITORY --target '${{ needs.resolve.outputs.commit }}' --prerelease --latest=false --title "Portable Runtime runtime-$c (alpha)" --notes $notes
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
+15
View File
@@ -28,6 +28,8 @@ them; its `manual` checks are on a Linux host's guest boot.
| `displays=2` | the reims-graphics device's displays, 1 to 4, a window each (QEMU's reims-graphics-pci property; 1 by default) |
| `REIMS_VGPU_WINDOW_IMPL=sdl` | macOS, built with the `macos-sdl` feature (on by default): SDL3's window in place of AppKit's ("On macOS through SDL3" below) |
| `REIMS_VGPU_WINDOW_CAPTURE=0` | capture off: no window ever captures the keyboard or the pointer ("Capture off" below); reims-ctl sets it for a VM whose capture setting is off |
| `REIMS_VGPU_WINDOW_RELEASE_KEYS=Ctrl+Shift+F12` | additional release shortcut for SDL windows on Windows and Linux; when unset, `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS` can supply it |
| `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE=1` | on Windows and Linux, allow the pointer to leave a captured SDL window and release input when it leaves |
Unset or unparsable values give the defaults below.
`test: env::unset_or_unparsable_values_are_the_defaults`,
@@ -700,6 +702,19 @@ runtime's own device. The switches above apply, and `resolution=` too.
`test: sdl::shell::the_end_lets_go_of_the_grab_and_the_holds`,
`test: sdl::shell::the_pointer_is_held_over_the_image_in_whole_points`,
`manual` (the grab and the hold)
- An additional release shortcut uses at least one modifier and one to three
ordinary keys. The captured title shows the shortcut, and an empty or
invalid setting uses the default. The built-in release chord still works
with an additional shortcut set.
`test: native::sdl_thread::input::custom_shortcut_releases_capture_without_forwarding_its_final_key`,
`test: native::sdl_thread::input::custom_shortcut_can_hold_two_regular_keys`,
`test: native::sdl_thread::input::invalid_shortcut_keeps_the_default`
- With release on mouse leave enabled, capture allows the pointer out of the
window. The SDL mouse-leave event lifts held keys and buttons and releases
capture. This setting also turns off relative pointer locks in games and
at a shared display edge.
`test: native::sdl_thread::input::leaving_the_window_releases_mouse_and_keyboard_when_enabled`,
`manual` (move the pointer out of a captured SDL window)
- Scrolling: the wheel's notches, or, where the host takes smooth
scrolling, its lines at 10 points each, in no gesture (SDL gives no
phases); the guest gets the device's own direction.
+18
View File
@@ -14,6 +14,9 @@
//! no window ever captures the keyboard or the pointer ([`crate::capture`]). `1`, `true`,
//! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's
//! settings.
//! - `REIMS_VGPU_WINDOW_RELEASE_KEYS`: an additional SDL window capture release shortcut,
//! such as `Ctrl+Shift+F12`. Reims-Go's capture shortcut plugin can supply it through its
//! own namespace. The original release chord remains available.
use std::sync::OnceLock;
@@ -25,6 +28,11 @@ pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL";
/// The capture switch's variable.
pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE";
/// The extra release shortcut for Windows and Linux SDL windows.
pub const RELEASE_KEYS_VAR: &str = "REIMS_VGPU_WINDOW_RELEASE_KEYS";
/// The same shortcut supplied through the Reims-Go capture shortcut plugin.
const PLUGIN_RELEASE_KEYS_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS";
const PLUGIN_RELEASE_ON_LEAVE_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE";
/// Whether a click into the image captures input where the capture switch is unset.
pub const CAPTURE_DEFAULT: bool = true;
@@ -40,6 +48,10 @@ pub struct Settings {
pub window_impl: WindowImpl,
/// Whether a click into the image captures input; off, nothing ever does.
pub capture: bool,
/// Additional shortcut text for the SDL window.
pub release_keys: Option<String>,
/// Let the mouse leave the SDL window and release input when it does.
pub release_on_leave: bool,
}
impl Default for Settings {
@@ -49,6 +61,8 @@ impl Default for Settings {
screens: Vec::new(),
window_impl: WindowImpl::AppKit,
capture: CAPTURE_DEFAULT,
release_keys: None,
release_on_leave: false,
}
}
}
@@ -126,6 +140,10 @@ pub fn settings() -> &'static Settings {
Settings {
window_impl: parse_impl(var(IMPL_VAR).as_deref()),
capture: parse_capture(var(CAPTURE_VAR).as_deref()),
release_keys: var(RELEASE_KEYS_VAR).or_else(|| var(PLUGIN_RELEASE_KEYS_VAR)),
release_on_leave: var(PLUGIN_RELEASE_ON_LEAVE_VAR)
.as_deref()
.is_some_and(parse_switch),
..parse(borderless.as_deref(), screens.as_deref())
}
})
@@ -81,7 +81,7 @@ use crate::config::{
};
use crate::game::Game;
use crate::geometry::{self, Rect};
use crate::keys::{KeyEvent, KeyState};
use crate::keys::{KeyEvent, KeyState, Modifiers};
use crate::scroll::POINTS_PER_LINE;
/// How soon after the window gains the keyboard a click is the one that focused it, in
@@ -180,6 +180,99 @@ fn fixed(points: f64) -> i32 {
}
}
/// An additional release shortcut, using USB key positions like SDL's keyboard path.
#[derive(Debug)]
pub(crate) struct ReleaseShortcut {
modifiers: Modifiers,
keys: Vec<u16>,
name: String,
}
impl ReleaseShortcut {
pub(crate) fn parse(value: &str) -> Option<Self> {
let parts = value.split('+').map(str::trim).map(str::to_ascii_uppercase);
let mut modifiers = Modifiers::default();
let mut keys = Vec::new();
let mut key_names = Vec::new();
for part in parts {
let held = match part.as_str() {
"CTRL" => &mut modifiers.control,
"ALT" => &mut modifiers.option,
"SHIFT" => &mut modifiers.shift,
"WIN" | "SUPER" => &mut modifiers.command,
_ => {
let key = Self::parse_key(&part)?;
if keys.len() == 3 || keys.contains(&key) {
return None;
}
keys.push(key);
key_names.push(part);
continue;
}
};
if std::mem::replace(held, true) {
return None;
}
}
if modifiers == Modifiers::default() || keys.is_empty() {
return None;
}
let mut name = String::new();
for (held, label) in [
(modifiers.control, "Ctrl+"),
(modifiers.option, "Alt+"),
(modifiers.shift, "Shift+"),
(
modifiers.command,
if cfg!(windows) { "Win+" } else { "Super+" },
),
] {
if held {
name.push_str(label);
}
}
name.push_str(&key_names.join("+"));
Some(Self {
modifiers,
keys,
name,
})
}
fn parse_key(key_name: &str) -> Option<u16> {
let key = match key_name.as_bytes() {
[letter @ b'A'..=b'Z'] => u16::from(*letter - b'A') + 0x04,
[digit @ b'1'..=b'9'] => u16::from(*digit - b'1') + 0x1e,
[b'0'] => 0x27,
_ => {
let number = key_name.strip_prefix('F')?.parse::<u16>().ok()?;
if !matches!(
key_name,
"F1" | "F2"
| "F3"
| "F4"
| "F5"
| "F6"
| "F7"
| "F8"
| "F9"
| "F10"
| "F11"
| "F12"
) {
return None;
}
0x3a + number - 1
}
};
Some(key)
}
pub(crate) fn name(&self) -> &str {
&self.name
}
}
/// One window's input decisions (the module doc).
#[derive(Default)]
pub(crate) struct Input {
@@ -187,6 +280,8 @@ pub(crate) struct Input {
keys: KeyState,
/// Who gets the keyboard.
capture: Capture,
release_shortcut: Option<ReleaseShortcut>,
release_on_leave: bool,
/// The `BUTTON_*` bits of the buttons the guest was told are down.
buttons: u32,
/// The pointer event last sent.
@@ -249,6 +344,30 @@ impl Input {
Input { capture, ..self }
}
/// Sets an additional shortcut for releasing captured input.
pub(crate) fn with_release_shortcut(self, release_shortcut: Option<ReleaseShortcut>) -> Input {
Input {
release_shortcut,
..self
}
}
pub(crate) fn with_release_on_leave(self, release_on_leave: bool) -> Input {
Input {
release_on_leave,
..self
}
}
/// Let the host have the keyboard and pointer when the mouse leaves the window.
pub(crate) fn mouse_left(&mut self) -> Reaction {
if !self.release_on_leave || !self.is_captured() {
return Reaction::default();
}
self.lift_buttons();
self.release_capture()
}
/// Whether the captured pointer has gone past the image's edge.
#[cfg(test)]
pub(crate) fn is_away(&self) -> bool {
@@ -307,13 +426,26 @@ impl Input {
/// Where the pointer is held over `image`, the image's rectangle in the window's points: the
/// image while captured ([`Capture::pointer_confinement`]).
pub(crate) fn pointer_confinement(&self, image: Rect) -> Option<Rect> {
self.capture.pointer_confinement(image)
if self.release_on_leave {
None
} else {
self.capture.pointer_confinement(image)
}
}
/// What the title ends with: the release chord while captured, in the host's OS's names for
/// its keys, and that a click captures while not ([`Capture::title_suffix`]).
pub(crate) fn title_suffix(&self) -> &'static str {
self.capture.title_suffix(HOST_OS)
pub(crate) fn title_suffix(&self) -> std::borrow::Cow<'_, str> {
if self.is_captured()
&& let Some(shortcut) = &self.release_shortcut
{
return format!(
" \u{2014} input captured (press {} to release)",
shortcut.name
)
.into();
}
self.capture.title_suffix(HOST_OS).into()
}
/// What to send, taken.
@@ -345,7 +477,8 @@ impl Input {
return;
}
if let (Some(point), Some(mode)) = (at.point, guest_mode(at)) {
if self.capture.is_captured()
if !self.release_on_leave
&& self.capture.is_captured()
&& let Some(motion) = self.motion.clone()
&& let Some(hold) = self.game.begin(motion.as_ref(), point)
{
@@ -356,7 +489,8 @@ impl Input {
Some(ToHost::Pointer { at, .. }) => Some(at),
_ => None,
};
if self.capture.is_captured()
if !self.release_on_leave
&& self.capture.is_captured()
&& let Some(beyond) = self.beyond.clone()
&& let Some(hold) =
self.away
@@ -552,6 +686,18 @@ impl Input {
}
return Reaction::default();
}
if self.is_captured()
&& let Some(shortcut) = &self.release_shortcut
&& shortcut.keys.contains(&usage)
&& shortcut
.keys
.iter()
.all(|&key| key == usage || self.keys.is_held(key))
&& shortcut.modifiers == self.keys.held_modifiers()
&& !repeat
{
return self.release_capture();
}
if let Some(event) = self.keys.key_down(usage, repeat) {
self.out.push(ToHost::Key(event));
}
@@ -865,6 +1011,80 @@ mod tests {
assert_eq!(input.title_suffix(), UNCAPTURED_SUFFIX);
}
#[test]
fn custom_shortcut_releases_capture_without_forwarding_its_final_key() {
let mut input =
focused().with_release_shortcut(ReleaseShortcut::parse(" shift + ctrl + f12 "));
input.button_down(BUTTON_LEFT, 1_000_000_000, &at((10.0, 10.0)));
input.button_up(BUTTON_LEFT, &at((10.0, 10.0)));
assert!(input.title_suffix().contains("Ctrl+Shift+F12"));
input.take();
input.key(0xE0, true, false);
input.key(0xE1, true, false);
let reaction = input.key(0x45, true, false);
assert!(reaction.capture_changed && !input.is_captured());
assert_eq!(
input.take(),
vec![
ToHost::Key(KeyEvent::down(0xE0)),
ToHost::Key(KeyEvent::down(0xE1)),
ToHost::Key(KeyEvent::up(0xE1)),
ToHost::Key(KeyEvent::up(0xE0)),
]
);
}
#[test]
fn invalid_shortcut_keeps_the_default() {
for value in [
"",
"F12",
"Ctrl+Shift",
"Ctrl+Ctrl+F12",
"Ctrl+F13",
"Ctrl+F01",
] {
assert!(ReleaseShortcut::parse(value).is_none(), "{value:?}");
}
}
#[test]
fn custom_shortcut_can_hold_two_regular_keys() {
let mut input = focused().with_release_shortcut(ReleaseShortcut::parse("Ctrl+A+Z"));
let point = at((10.0, 10.0));
input.button_down(BUTTON_LEFT, 1_000_000_000, &point);
input.button_up(BUTTON_LEFT, &point);
assert!(input.title_suffix().contains("Ctrl+A+Z"));
assert!(!input.key(0xe0, true, false).capture_changed);
assert!(!input.key(0x04, true, false).capture_changed);
assert!(input.key(0x1d, true, false).capture_changed);
}
#[test]
fn leaving_the_window_releases_mouse_and_keyboard_when_enabled() {
for enabled in [false, true] {
let mut input = focused().with_release_on_leave(enabled);
let point = at((10.0, 10.0));
input.button_down(BUTTON_LEFT, 1_000_000_000, &point);
input.key(0x04, true, false);
assert!(input.is_captured());
assert_eq!(input.pointer_confinement(point.image).is_none(), enabled);
input.take();
assert_eq!(input.mouse_left().capture_changed, enabled);
assert_eq!(input.is_captured(), !enabled);
if enabled {
let events = input.take();
assert!(events.contains(&ToHost::Key(KeyEvent::up(0x04))));
assert!(
events
.iter()
.any(|event| matches!(event, ToHost::Pointer { buttons: 0, .. }))
);
assert!(!input.mouse_left().capture_changed);
}
}
}
/// With capture off, a click in the image is sent but captures nothing, so nothing holds the
/// pointer; the pointer outside the image is sent only in a drag; Ctrl, Alt and the GUI key
/// are the guest's keys and release nothing; the title says capture is off
@@ -113,6 +113,10 @@ impl Input {
self.0.focus_lost().capture_changed
}
pub(crate) fn mouse_left(&mut self) -> bool {
self.0.mouse_left().capture_changed
}
/// Whether input, the keyboard and the pointer, is captured.
pub(crate) fn is_captured(&self) -> bool {
self.0.is_captured()
@@ -124,7 +128,7 @@ impl Input {
}
/// What the title ends with in the current capture state.
pub(crate) fn title_suffix(&self) -> &'static str {
pub(crate) fn title_suffix(&self) -> std::borrow::Cow<'_, str> {
self.0.title_suffix()
}
@@ -211,6 +215,25 @@ pub(crate) fn open(window: &Arc<Window>, borderless: bool, _taken: &[Frame]) ->
display.0
);
let callbacks = window.callbacks();
let settings = crate::env::settings();
let release_shortcut = settings
.release_keys
.as_deref()
.and_then(input::ReleaseShortcut::parse);
if settings
.release_keys
.as_deref()
.is_some_and(|keys| !keys.trim().is_empty())
&& release_shortcut.is_none()
{
log::warn!(target: "reims_vgpu_window", "invalid input release shortcut; using the default");
}
log::info!(target: "reims_vgpu_window",
"input settings: capture={}, release shortcut={}, release on mouse leave={}",
settings.capture,
release_shortcut.as_ref().map_or("default", input::ReleaseShortcut::name),
settings.release_on_leave,
);
Some(Opened {
sdl,
asked: size,
@@ -221,7 +244,9 @@ pub(crate) fn open(window: &Arc<Window>, borderless: bool, _taken: &[Frame]) ->
.and_then(|callbacks| callbacks.beyond.clone()),
callbacks.and_then(|callbacks| callbacks.motion),
)
.with_capture(Capture::with_setting(crate::env::settings().capture)),
.with_capture(Capture::with_setting(settings.capture))
.with_release_shortcut(release_shortcut)
.with_release_on_leave(settings.release_on_leave),
),
state: State {
display,
+5 -1
View File
@@ -388,7 +388,11 @@ impl Shell {
// SDL's cursor is the process's: another window may have hidden it.
self.over_image = false;
self.refresh_cursor();
false
#[cfg(any(target_os = "linux", target_os = "windows"))]
let released = k == SDL_EVENT_WINDOW_MOUSE_LEAVE.0 && self.input.mouse_left();
#[cfg(target_os = "macos")]
let released = false;
released
}
_ => os::input_event(self, kind, event),
};
+1 -2
View File
@@ -212,8 +212,7 @@ std::string rgfxFamilyNameOf(const char *name);
std::string rgfxVendorNameOf(const char *name);
/// The `name` an x86-64 guest's Metal device answers where the host names its GPU `hostName`
/// (the device info's name, NUL-terminated): the kext's x86-64 name (rgfxX86Name,
/// guest/kext/src/RgfxDeviceName.hpp), which the kext states as the GPU's `model` too. That is
/// (the device info's name, NUL-terminated): rgfxX86Name (guest/kext/src/RgfxDeviceName.hpp). It is
/// "AMD - " and the host's name with the vendor words "Intel" and "NVIDIA" taken out, in any
/// case, each with a mark directly after it ("(R)", "(TM)", "®", "™") and then one space, on
/// every type of GPU (integrated, discrete, virtual, CPU, other): "AMD - Iris(R) Xe Graphics
+1 -1
View File
@@ -1519,7 +1519,7 @@ static NSString *rgfxHostNameOf(const RgfxCaps &caps)
return @"reims-graphics";
}
// On an x86-64 guest the x86-64 name, the kext's `model` there (rgfxMetalNameOf): "AMD - " and the
// On an x86-64 guest the Metal compatibility name (rgfxMetalNameOf): "AMD - " and the
// host's name without "Intel" and "NVIDIA", on every type of GPU: "AMD - GeForce RTX 3090",
// "AMD - Iris(R) Xe Graphics (RPL-P)". On an arm64 guest the host's name.
- (NSString *)name
+1 -3
View File
@@ -551,9 +551,7 @@ bool RgfxAccelerator::start(IOService *provider)
setProperty("VRAM,totalMB", memory.vramMB, 32);
}
}
// The GPU's name, as a Mac's GPU states it (RgfxDeviceName.hpp): `model` on the PCI device,
// which System Information shows as its Chipset Model. On an arm64 guest a host that gave no
// name has none stated.
// The host GPU's name as the PCI `model` that System Information shows as its Chipset Model.
{
uint8_t model[kRgfxDeviceModelMax];
const size_t length = readDeviceModel(model);
+1 -1
View File
@@ -432,7 +432,7 @@ public:
// false where the region is not mapped.
bool readMemorySize(RgfxMemorySize *out) const;
// The GPU's `model` bytes, from the host's device name (RgfxDeviceName.hpp): how many, 0
// where the region is not mapped or, on an arm64 guest, the host gave no name.
// where the region is not mapped or the host gave no name.
size_t readDeviceModel(uint8_t (&out)[kRgfxDeviceModelMax]) const;
// Shared events' ports (RgfxSharedEventUserClient.hpp): the client of ours that holds context
+13 -30
View File
@@ -1,9 +1,7 @@
// RgfxDeviceName: the GPU name the kext states to the guest, from the host's device name in the
// device info (RgfxDeviceInfo's name_len and name, written at RGFX_DEVICE_INFO_OFFSET when the
// device is made). On an arm64 guest it is the host's name whole. On an x86-64 guest it is the
// x86-64 name (rgfxX86Name): "AMD - " and the host's name without the vendor words "Intel" and
// "NVIDIA", on every host GPU. The bundle's Metal device answers the same name as its `name`
// on either guest (rgfxMetalNameOf, guest/bundle/src/RgfxCaps.hpp).
// RgfxDeviceName: the PCI model the kext states to the guest and the compatibility name the
// x86-64 Metal bundle answers. Both use the host's name from RgfxDeviceInfo. The PCI model
// keeps the host's name on both architectures. The x86-64 Metal name adds "AMD - " and drops
// the vendor words "Intel" and "NVIDIA" (rgfxX86Name, used by the bundle's rgfxMetalNameOf).
//
// A Mac's GPU states its name as its IOPCIDevice's `model`, an OSData of the name's bytes, which
// System Information shows as the GPU's "Chipset Model"; without one it shows "Graphics" and the
@@ -11,9 +9,8 @@
// 630's `model` is its 22 bytes and a NUL, the AMD Radeon Pro 5300M's its 20 bytes with none,
// and System Information names both. So the kext sets `model` as the Intel's is: the name's
// bytes, then a NUL. The host's name is its first name_len bytes (at most RGFX_DEVICE_NAME_LEN),
// cut at a NUL among them. On an arm64 guest, a host that gave no name (name_len 0, or a NUL
// first) has none stated; on an x86-64 guest it has "AMD - reims-graphics", as the bundle
// answers.
// cut at a NUL among them. The kext publishes no model when the host supplies no name
// (name_len 0 or a NUL first).
//
// Why the x86-64 name holds no vendor word: WindowServer's compositor (SkyLight, read from its
// code) takes a Metal device whose name holds "Intel" for an Intel GPU, and then scales a
@@ -25,9 +22,8 @@
// macOS 26.7.2 and 15.8.2. The compositor's other test, a name holding "NVIDIA", is the other
// vendor word: without either, every host takes the path of an AMD GPU's Mac.
//
// Header-only and free of the kernel's headers, so its native tests (tests/device_name_test.cpp,
// built for the x86-64 kext's rules and, as device_name_arm64_test, the arm64e kext's) build it
// as the kext does, and the bundle builds rgfxX86Name as the kext does.
// Header-only and free of the kernel's headers, so the native tests and Metal bundle can
// build it too.
//
// Our own code; it depends only on the committed wire header.
#ifndef RGFX_DEVICE_NAME_HPP_
@@ -38,10 +34,6 @@
#include <stddef.h>
#include <stdint.h>
#ifndef RGFX_GUEST_ARM64
#define RGFX_GUEST_ARM64 0
#endif
// The bytes of RgfxDeviceInfo the kext reads for the name: from name_len to the name's end.
static constexpr uint64_t kRgfxDeviceNameFirst = offsetof(RgfxDeviceInfo, name_len);
static constexpr uint64_t kRgfxDeviceNameEnd = offsetof(RgfxDeviceInfo, name) + RGFX_DEVICE_NAME_LEN;
@@ -54,8 +46,8 @@ static constexpr size_t kRgfxX86NamePrefixLen = sizeof(kRgfxX86NamePrefix) - 1;
// The most bytes of an x86-64 name: the prefix, a whole name field and a NUL.
static constexpr size_t kRgfxX86NameMax = kRgfxX86NamePrefixLen + RGFX_DEVICE_NAME_LEN + 1;
// The most bytes of `model`: the x86-64 name's, the longer of the two guests'.
static constexpr size_t kRgfxDeviceModelMax = kRgfxX86NameMax;
// The most bytes of `model`: the full name field and a NUL.
static constexpr size_t kRgfxDeviceModelMax = RGFX_DEVICE_NAME_LEN + 1;
// The vendor words the x86-64 name holds none of, and the marks it takes out with one directly
// before them: "(R)" and "(TM)", and the UTF-8 of "®" and "™". In lower case: each matches in
@@ -138,7 +130,7 @@ inline size_t rgfxX86Name(const uint8_t *name, size_t length, char (&out)[kRgfxX
return kRgfxX86NamePrefixLen + n;
}
// `model`'s bytes on an arm64 guest into `out`, from a name_len and the name field's
// `model`'s bytes into `out`, from a name_len and the name field's
// RGFX_DEVICE_NAME_LEN bytes: the host's name and a NUL. How many, its NUL counted, or 0 when
// the host gave no name.
inline size_t rgfxDeviceModel(uint32_t nameLen, const uint8_t *name, uint8_t (&out)[kRgfxDeviceModelMax])
@@ -155,23 +147,14 @@ inline size_t rgfxDeviceModel(uint32_t nameLen, const uint8_t *name, uint8_t (&o
return n + 1;
}
// `model`'s bytes on an x86-64 guest into `out`, from a name_len and the name field's
// RGFX_DEVICE_NAME_LEN bytes: the x86-64 name (rgfxX86Name) and a NUL. How many, its NUL
// counted; never 0.
inline size_t rgfxDeviceModelX86(uint32_t nameLen, const uint8_t *name, uint8_t (&out)[kRgfxDeviceModelMax])
{
return rgfxX86Name(name, nameLen, reinterpret_cast<char (&)[kRgfxX86NameMax]>(out)) + 1;
}
// `model`'s bytes out of the device info's bytes from kRgfxDeviceNameFirst to kRgfxDeviceNameEnd,
// as the kext's guest takes them (RGFX_GUEST_ARM64).
// `model`'s bytes out of the device info span.
inline size_t rgfxDeviceModelFrom(const uint8_t *span, uint8_t (&out)[kRgfxDeviceModelMax])
{
uint32_t nameLen = 0;
for (unsigned i = 0; i < sizeof(nameLen); i++)
nameLen |= static_cast<uint32_t>(span[i]) << (8 * i);
const uint8_t *name = span + (offsetof(RgfxDeviceInfo, name) - kRgfxDeviceNameFirst);
return RGFX_GUEST_ARM64 ? rgfxDeviceModel(nameLen, name, out) : rgfxDeviceModelX86(nameLen, name, out);
return rgfxDeviceModel(nameLen, name, out);
}
#endif // RGFX_DEVICE_NAME_HPP_
+4 -74
View File
@@ -1,10 +1,5 @@
// The native test of RgfxDeviceName.hpp: the `model` bytes the kext states on the PCI device, from
// the host's device name, as each guest's kext takes it (built twice: device_name_test for the
// x86-64 kext, device_name_arm64_test with RGFX_GUEST_ARM64 for the arm64e kext). Both cut the
// host's name at its length, at the field and at a NUL, and end it with a NUL, as an Intel Mac's
// Intel UHD Graphics 630 states its own (measured, macOS 26.7.1). The arm64e kext states the
// host's name whole, and none for no name. The x86-64 kext states the x86-64 name, "AMD - " and
// the host's name without "Intel" and "NVIDIA", and "AMD - reims-graphics" for no name.
// The native test of the PCI model bytes the kext publishes on either architecture.
// The bytes come from the host name, bounded by its length, field size, and any NUL.
#include "RgfxDeviceName.hpp"
#include <cstdio>
@@ -43,40 +38,18 @@ bool is(const uint8_t *model, size_t n, const char *want)
return n == len + 1 && !std::memcmp(model, want, len) && model[len] == 0;
}
#if !RGFX_GUEST_ARM64
// Whether `s` holds "intel" or "nvidia" in any ASCII case.
bool holdsVendorWord(const uint8_t *s, size_t n)
{
for (size_t i = 0; i < n; i++) {
for (const char *vendor : kRgfxVendorWords) {
if (rgfxMatchAnyCase(s + i, n - i, vendor))
return true;
}
}
return false;
}
// The x86-64 name of `host` through the device info.
bool x86NameIs(const char *host, const char *want)
{
uint8_t model[kRgfxDeviceModelMax];
const size_t n = fromDeviceInfo(static_cast<uint32_t>(std::strlen(host)), host, std::strlen(host), model);
return is(model, n, want) && !holdsVendorWord(model, n);
}
#endif
} // namespace
int main()
{
uint8_t model[kRgfxDeviceModelMax];
const char intel[] = "Intel UHD Graphics 630";
const char nvidia[] = "NVIDIA GeForce RTX 5080 Laptop GPU";
const char nvidia[] = "NVIDIA GeForce RTX 5090";
uint8_t full[RGFX_DEVICE_NAME_LEN];
for (size_t i = 0; i < sizeof(full); i++)
full[i] = static_cast<uint8_t>('A' + i % 26);
size_t n = 0;
#if RGFX_GUEST_ARM64
// A host GPU's name: its bytes and a NUL, as the Intel GPU's 23 bytes of `model`.
n = fromDeviceInfo(22, intel, 22, model);
check(n == 23, "a 22-byte name is 23 bytes of model");
@@ -108,49 +81,6 @@ int main()
// A NUL inside the length: the name up to it.
n = fromDeviceInfo(10, "AMD\0Radeon", 10, model);
check(is(model, n, "AMD"), "a NUL inside the length ends the name");
#else
// A host GPU's name: "AMD - " and the name without its vendor words, then a NUL.
check(x86NameIs(intel, "AMD - UHD Graphics 630"), "Intel's word and its space go");
check(x86NameIs(nvidia, "AMD - GeForce RTX 5080 Laptop GPU"), "NVIDIA's word and its space go");
check(x86NameIs("Intel(R) Iris(R) Xe Graphics (RPL-P)", "AMD - Iris(R) Xe Graphics (RPL-P)"),
"a mark after the word goes with it; a later one stays");
check(x86NameIs("Intel(R) UHD Graphics 630 (CFL GT2)", "AMD - UHD Graphics 630 (CFL GT2)"),
"the UHD 630 on Linux");
check(x86NameIs("Intel(R) Arc(tm) A770 Graphics (DG2)", "AMD - Arc(tm) A770 Graphics (DG2)"),
"the A770");
check(x86NameIs("NVIDIA GeForce RTX 3090", "AMD - GeForce RTX 3090"), "the 3090");
check(x86NameIs("AMD Radeon 780M Graphics (RADV PHOENIX)",
"AMD - AMD Radeon 780M Graphics (RADV PHOENIX)"),
"an AMD GPU's name whole");
check(x86NameIs("intel(tm) nViDiA\xc2\xae X\xe2\x84\xa2", "AMD - X\xe2\x84\xa2"),
"any case and either UTF-8 mark; a mark after no word stays");
check(x86NameIs("InNVIDIAtel(R) X", "AMD - X"), "a word that taking one out leaves goes too");
check(x86NameIs("Mesa Intel", "AMD - Mesa "), "a word at the end; the space before it stays");
// No name, or nothing left: "reims-graphics" after the prefix; a NUL first is no name.
check(fromDeviceInfo(0, intel, 22, model) == 21 && is(model, 21, "AMD - reims-graphics"),
"name_len 0 is AMD - reims-graphics");
n = fromDeviceInfo(5, "\0abcd", 5, model);
check(is(model, n, "AMD - reims-graphics"), "a NUL first is no name");
check(x86NameIs("NVIDIA", "AMD - reims-graphics"), "a name of a vendor word alone leaves none");
check(x86NameIs("Intel(R) ", "AMD - reims-graphics"), "a word, its mark and its space leave none");
// A whole field, 256 bytes and no NUL in it: the prefix, all of them, then a NUL.
n = fromDeviceInfo(RGFX_DEVICE_NAME_LEN, full, sizeof(full), model);
check(n == kRgfxDeviceModelMax, "a full field is the prefix, 256 bytes and a NUL");
check(!std::memcmp(model, "AMD - ", 6) && !std::memcmp(model + 6, full, sizeof(full)) &&
model[kRgfxDeviceModelMax - 1] == 0,
"every byte of a full field after the prefix, NUL-ended");
// A length past the field reads the field alone, never the bytes after it (architecture_name).
n = fromDeviceInfo(UINT32_MAX, full, sizeof(full), model);
check(n == kRgfxDeviceModelMax && model[kRgfxDeviceModelMax - 1] == 0, "a length past the field is cut to it");
// A length short of the name: its first bytes; a NUL inside the length ends it.
n = fromDeviceInfo(11, nvidia, sizeof(nvidia) - 1, model);
check(is(model, n, "AMD - GeFo"), "name_len bounds the name before its words go");
n = fromDeviceInfo(10, "AMD\0Radeon", 10, model);
check(is(model, n, "AMD - AMD"), "a NUL inside the length ends the name");
#endif
// The span the kext reads holds name_len and the whole field, and lies inside the device info.
check(kRgfxDeviceNameFirst == offsetof(RgfxDeviceInfo, name_len), "the span starts at name_len");
@@ -158,6 +88,6 @@ int main()
"the span ends at the name field's end");
check(kRgfxDeviceNameEnd <= sizeof(RgfxDeviceInfo), "the span ends inside the device info");
std::printf("device_name_test: OK (%d checks, %s kext)\n", checks, RGFX_GUEST_ARM64 ? "arm64e" : "x86-64");
std::printf("device_name_test: OK (%d checks)\n", checks);
return 0;
}
+1 -1
View File
@@ -24,7 +24,7 @@ Arch = "arm64e"
MinKernel = "23.0.0"
MaxKernel = ""
Comment = "The reims-graphics display and accelerator"
sha256 = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
sha256 = "efacd163e0b230f95ce7a43c05c87771e504137ffd6d675a14468cddc7865605"
[[kext]]
BundlePath = "RgfxGate.kext"
+9 -9
View File
@@ -3,8 +3,8 @@
# when a source or an output differs from its SHA-256 here (guest/tools/prebuilt.py).
# [built] records the local toolchain; every input is in the tree.
[built]
xcode = "Xcode 27.2 Build version 27B52"
sdk = "MacOSX27.2.sdk"
xcode = "unknown"
sdk = "MacOSX.sdk"
clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
[sources]
@@ -27,7 +27,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxBuffer.h" = "4b54841a30b0559c424b8aed06fcd5edd7c172cda1bf9fd5c892e30dc066ec7d"
"guest/bundle/src/RgfxBuffer.mm" = "360a494bb58668c4c66ce468b8ac39a10ccdad16e97a538ef48a6c8fa7cadbec"
"guest/bundle/src/RgfxCaps.cpp" = "d6020aeff1adcef0b74e9bbc51dea8d849f88355e019927ee9e8fb96a3007d12"
"guest/bundle/src/RgfxCaps.hpp" = "7063a6821533fdf44d66b4363aa14ba3a4d5321b2f3df62e2e3ff16ea9764a48"
"guest/bundle/src/RgfxCaps.hpp" = "4c8e0dba604b37d4509f54518f24337090fab595c5ed12c15d13298ad195f5dd"
"guest/bundle/src/RgfxClMode.cpp" = "c5d5127ef251d119cb104015676d16a475f615680b83d48eba32c48b76e39a5c"
"guest/bundle/src/RgfxClMode.hpp" = "138c803295021645c2854f3e9cb34dac96d485719d5447151ff9168c698e7a1a"
"guest/bundle/src/RgfxCommandObjects.h" = "cd504d3df8e3560758a926d31742e052bdda77e76c2c2c23e2dc6ae07346b9bc"
@@ -111,7 +111,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxMetalDevice+Unsupported.mm" = "a424349b2a969a53609b34ae3f4b72cc2e2c9378605ba780520eeb22643c535c"
"guest/bundle/src/RgfxMetalDevice+Video.mm" = "aa53c5a15243b11155c9342ab1c7867ff5e19ced9272471f9ea76e95db01d9af"
"guest/bundle/src/RgfxMetalDevice.h" = "92708ff70a7693edebc6402a8c68fa16ed1982c27d885a74ac56f6a92b4a10a9"
"guest/bundle/src/RgfxMetalDevice.mm" = "420bd3f1c54f87eb33d27e62427b4b1c967af8976193dd8f01b02794839e3fe8"
"guest/bundle/src/RgfxMetalDevice.mm" = "f1fa5b4c56b61766dd0f89f63be3eeeef51d927b51eef0065c7c79f3de50bcdc"
"guest/bundle/src/RgfxMetalError.h" = "e4440b3c0d0617ad118f16aa56fc9cfb0e7ebbf0ef2d3f8e16b27df9fd1f9803"
"guest/bundle/src/RgfxMetalPrivate.h" = "18196f21ce0808a37c8d8913fab72e16e032c7c73064b6a81618bb9f06a478f2"
"guest/bundle/src/RgfxMetallibWriter.cpp" = "a9f0e9a4a2ef80729470051130d201806f59d0c4d1803129a3662e4afc389f13"
@@ -333,8 +333,8 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
"guest/kext/src/RgfxAccelerator.cpp" = "e05bf13fb97b0e2fbc133dc83c451dd6b063323c8f2b26d67e82b8de9912ecd4"
"guest/kext/src/RgfxAccelerator.hpp" = "148d63554b5a5eaaaf280651d0f493b3741dbaf444808554f88af0e6bc670ce8"
"guest/kext/src/RgfxAcceleratorContexts.cpp" = "77f39e6d4750dfb0f1ff5a614b9d419362f159a8eac48b18673181a01d3f0451"
"guest/kext/src/RgfxAcceleratorLocks.cpp" = "171e708b5fb87abbf39423aa08fb0343ca8dd1777f47e125288a296940667124"
"guest/kext/src/RgfxAcceleratorSurfaces.cpp" = "54c72029acb78f19cc41e80ab1e646b1bb402af45ec0f073dc07eb2236f5baa0"
@@ -358,7 +358,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxDeferredAnswers.hpp" = "b7b62b567e38da8ce27d89aa47b1001f56f8f7afeda0def2b550b1f7ad9b18c6"
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
"guest/kext/src/RgfxDeviceName.hpp" = "7085045ea0c9ca3215e58ea43f0a23309a9ba8145e9c2d5ede541093a293f9c1"
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"Graft-arm64e.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
"Graft-arm64e.kext/Contents/MacOS/Graft" = "2f405e84ddd1414b6ac32e813a4369a6d4681d9c6e7331b933bb719761b1a31a"
"ReimsGraphics.kext/Contents/Info.plist" = "9683153587659c4bd4d5c52167eff1f3d2ae51dae575f60c15a27d89240f46c5"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "efacd163e0b230f95ce7a43c05c87771e504137ffd6d675a14468cddc7865605"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
"set.toml" = "a4da2409f25dd7bf12260de752c38c474b60d4b2d993810a44de0f4b07cb6dfd"
"set.toml" = "a0be05b8801df322a6d2276bb41821682c473157227fa29c7aef46e5ff171868"
+1 -1
View File
@@ -24,7 +24,7 @@ Arch = "x86_64"
MinKernel = "20.0.0"
MaxKernel = ""
Comment = "The reims-graphics display, accelerator and device control"
sha256 = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
sha256 = "c8b23bcde87d6d0415d09cbdf47ad444afe0c0ea2f51dca1a4583be8bea75f6e"
[[kext]]
BundlePath = "RgfxGate.kext"
+9 -9
View File
@@ -3,8 +3,8 @@
# when a source or an output differs from its SHA-256 here (guest/tools/prebuilt.py).
# [built] records the local toolchain; every input is in the tree.
[built]
xcode = "Xcode 27.2 Build version 27B52"
sdk = "MacOSX27.2.sdk"
xcode = "unknown"
sdk = "MacOSX.sdk"
clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
[sources]
@@ -27,7 +27,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxBuffer.h" = "4b54841a30b0559c424b8aed06fcd5edd7c172cda1bf9fd5c892e30dc066ec7d"
"guest/bundle/src/RgfxBuffer.mm" = "360a494bb58668c4c66ce468b8ac39a10ccdad16e97a538ef48a6c8fa7cadbec"
"guest/bundle/src/RgfxCaps.cpp" = "d6020aeff1adcef0b74e9bbc51dea8d849f88355e019927ee9e8fb96a3007d12"
"guest/bundle/src/RgfxCaps.hpp" = "7063a6821533fdf44d66b4363aa14ba3a4d5321b2f3df62e2e3ff16ea9764a48"
"guest/bundle/src/RgfxCaps.hpp" = "4c8e0dba604b37d4509f54518f24337090fab595c5ed12c15d13298ad195f5dd"
"guest/bundle/src/RgfxClMode.cpp" = "c5d5127ef251d119cb104015676d16a475f615680b83d48eba32c48b76e39a5c"
"guest/bundle/src/RgfxClMode.hpp" = "138c803295021645c2854f3e9cb34dac96d485719d5447151ff9168c698e7a1a"
"guest/bundle/src/RgfxCommandObjects.h" = "cd504d3df8e3560758a926d31742e052bdda77e76c2c2c23e2dc6ae07346b9bc"
@@ -111,7 +111,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxMetalDevice+Unsupported.mm" = "a424349b2a969a53609b34ae3f4b72cc2e2c9378605ba780520eeb22643c535c"
"guest/bundle/src/RgfxMetalDevice+Video.mm" = "aa53c5a15243b11155c9342ab1c7867ff5e19ced9272471f9ea76e95db01d9af"
"guest/bundle/src/RgfxMetalDevice.h" = "92708ff70a7693edebc6402a8c68fa16ed1982c27d885a74ac56f6a92b4a10a9"
"guest/bundle/src/RgfxMetalDevice.mm" = "420bd3f1c54f87eb33d27e62427b4b1c967af8976193dd8f01b02794839e3fe8"
"guest/bundle/src/RgfxMetalDevice.mm" = "f1fa5b4c56b61766dd0f89f63be3eeeef51d927b51eef0065c7c79f3de50bcdc"
"guest/bundle/src/RgfxMetalError.h" = "e4440b3c0d0617ad118f16aa56fc9cfb0e7ebbf0ef2d3f8e16b27df9fd1f9803"
"guest/bundle/src/RgfxMetalPrivate.h" = "18196f21ce0808a37c8d8913fab72e16e032c7c73064b6a81618bb9f06a478f2"
"guest/bundle/src/RgfxMetallibWriter.cpp" = "a9f0e9a4a2ef80729470051130d201806f59d0c4d1803129a3662e4afc389f13"
@@ -333,8 +333,8 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
"guest/kext/src/RgfxAccelerator.cpp" = "e05bf13fb97b0e2fbc133dc83c451dd6b063323c8f2b26d67e82b8de9912ecd4"
"guest/kext/src/RgfxAccelerator.hpp" = "148d63554b5a5eaaaf280651d0f493b3741dbaf444808554f88af0e6bc670ce8"
"guest/kext/src/RgfxAcceleratorContexts.cpp" = "77f39e6d4750dfb0f1ff5a614b9d419362f159a8eac48b18673181a01d3f0451"
"guest/kext/src/RgfxAcceleratorLocks.cpp" = "171e708b5fb87abbf39423aa08fb0343ca8dd1777f47e125288a296940667124"
"guest/kext/src/RgfxAcceleratorSurfaces.cpp" = "54c72029acb78f19cc41e80ab1e646b1bb402af45ec0f073dc07eb2236f5baa0"
@@ -358,7 +358,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxDeferredAnswers.hpp" = "b7b62b567e38da8ce27d89aa47b1001f56f8f7afeda0def2b550b1f7ad9b18c6"
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
"guest/kext/src/RgfxDeviceName.hpp" = "7085045ea0c9ca3215e58ea43f0a23309a9ba8145e9c2d5ede541093a293f9c1"
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"Graft.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
"Graft.kext/Contents/MacOS/Graft" = "04a1d44c0c80c20a71f3a662c46b56a1732b8134f095fb2ac57ec790f72baf72"
"ReimsGraphics.kext/Contents/Info.plist" = "ae0dafd3b6c36c24d1c92467d8203d76360eb6e4f6ad5c496167a21033b2c209"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "c8b23bcde87d6d0415d09cbdf47ad444afe0c0ea2f51dca1a4583be8bea75f6e"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
"set.toml" = "49182c19c3d961b251901e19a09016df684f1f102527a0d3274697eaaf3dbab5"
"set.toml" = "dcdad1148a389c4be577c0641f3f3942031df313983e09f5a445cb783a7e6a42"
+7 -10
View File
@@ -6,19 +6,16 @@
| :--- | :--- | :--- |
| Reims vGPU | [`reims-go/reims-vgpu`](https://github.com/reims-go/reims-vgpu/tree/intel-vm-suspend) | GPU 挂起重放、窗口和 CLI 兼容性修复 |
| QEMU | [`reims-go/qemu-reims-vgpu`](https://github.com/reims-go/qemu-reims-vgpu/tree/intel-vm-suspend) | Windows WHPX、文件迁移和设备状态保存恢复 |
| metal2vulkan | [`reims-go/metal2vulkan`](https://github.com/reims-go/metal2vulkan/tree/development) | Vulkan 渲染、附件反馈和 GPU 地址重放 |
| reims-util | [`reims-go/reims-util`](https://github.com/reims-go/reims-util/tree/development) | OpenCore 和 macOS 安装介质,包括并发离线下载 |
Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runtime.json` 声明运行时能力。更新 QEMU 时先把新提交推到 QEMU fork,再更新 Reims vGPU 的子模块指针。Reims-Go 构建据此记录两个源码仓库及提交号。
Reims vGPU 用 `vendor/qemu` 固定 QEMU 提交,用 `Cargo.toml` 和 `Cargo.lock` 固定 metal2vulkan,用 `crates/reims-ctl/src/reims_util.rs` 固定 reims-util。CI 根据这些固定值检出依赖,在运行时清单和对应源码包中记录四个组件的仓库及实际提交。
Alpha 编号与挂起兼容判定见 [Alpha 运行时编号与挂起兼容性规范](../versioning.md)。
## 构建时应用的依赖补丁
[`series.txt`](series.txt) 是可执行清单。依赖检出版本由 Reims vGPU 源码固定。补丁冲突会停止构建。
| 补丁 | 依赖 | 作用 |
| :--- | :--- | :--- |
| [`reims-util-parallel-offline-download.patch`](reims-util-parallel-offline-download.patch) | `steelbrain/reims-util` | 有 Apple 分块校验数据时并发下载离线安装包,按顺序验证并写入镜像。 |
| [`metal2vulkan-snapshot-replay.patch`](metal2vulkan-snapshot-replay.patch) | `steelbrain/metal2vulkan` | 读取和恢复缓冲、纹理及事件状态,为 GPU 挂起重放提供依赖。 |
构建通过 Cargo 的本地源码覆盖使用已打补丁的 `metal2vulkan`。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
[`series.txt`](series.txt) 目前为空。临时补丁按清单顺序应用,冲突会停止构建。客户端的运行时包格式见[便携运行时规范](https://github.com/Nwflower/Reims-Go/blob/main/docs/portable-runtime-spec.md)。
---
@@ -43,5 +40,5 @@ Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runt
每日构建会跳过已合入的等价补丁,并在日志中报告。确认后按以下步骤清理。
1. 删除 `patches/` 下对应的 `.patch` 文件,并同步更新 [`series.txt`](series.txt) 与本文件。
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml)。
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/reims-go/reims-vgpu/actions/workflows/runtime-preview.yml)。
3. 在真实宿主运行 [`smoke-runtime.ps1`](../scripts/smoke-runtime.ps1) 完成冒烟并人工确认后,将对应 Release 升级为 `stable`。
@@ -1,525 +0,0 @@
diff --git a/crates/metal2vulkan-runtime/src/block.rs b/crates/metal2vulkan-runtime/src/block.rs
index 0ac77ecac0f3abb9e9b76fb82d17c3536e22f4f5..426d025513a2f04e97f31efa66d1632635f7254d 100644
--- a/crates/metal2vulkan-runtime/src/block.rs
+++ b/crates/metal2vulkan-runtime/src/block.rs
@@ -54,6 +54,12 @@ impl Block {
Block { claim }
}
+ /// Returns capture/replay address metadata for this block (if supported).
+ pub fn capture_info(&self) -> Option<memory::BlockCaptureInfo> {
+ let (core, block) = self.held().ok()?;
+ core.pool.capture_info(&block.memory)
+ }
+
/// Whether the block is of `core`'s device.
pub(crate) fn is_of(&self, core: &Arc<Core>) -> bool {
Weak::as_ptr(&self.claim.core) == Arc::as_ptr(core)
diff --git a/crates/metal2vulkan-runtime/src/device.rs b/crates/metal2vulkan-runtime/src/device.rs
index 8edf1f27202f9a19b19cc4a4484d1e31341b8ab1..68f79440cc7727f2fae6063756380fe7a85ce7f9 100644
--- a/crates/metal2vulkan-runtime/src/device.rs
+++ b/crates/metal2vulkan-runtime/src/device.rs
@@ -273,6 +273,7 @@ pub(crate) struct Core {
/// every render pipeline takes its colour flag, and a draw reads an attachment of its pass
/// with the image in the feedback layout.
pub(crate) feedback_loop: bool,
+ pub(crate) capture_replay: bool,
/// `VK_EXT_device_fault`'s command, where device creation enabled it (where the device lists
/// it): a lost device's fault report, read once, at its first loss (`crate::fault`).
pub(crate) fault: Option<ash::ext::device_fault::Device>,
@@ -860,6 +861,7 @@ impl Device {
ticks,
calibrated,
feedback_loop: capabilities.feedback_loop,
+ capture_replay: capabilities.buffer_device_address_capture_replay,
fault,
indirect,
attachment_reads: capabilities.attachment_reads,
@@ -1140,6 +1142,41 @@ impl Device {
/// allocation past the device's count; [`Limit::AllocationNotMapped`](crate::Limit::AllocationNotMapped)
/// where the consumer did not map the allocation the take made; [`Error::Vulkan`] where the
/// device is out of memory or lost; [`Error::Quiesced`].
+ /// Whether Vulkan `bufferDeviceAddressCaptureReplay` is enabled on this device.
+ pub fn buffer_device_address_capture_replay(&self) -> bool {
+ self.shared.core.capture_replay
+ }
+
+ /// Waits non-destructively until all in-flight GPU work has completed and retired.
+ pub fn wait_idle(&self) -> Result<(), Error> {
+ let core = &self.shared.core;
+ if core.closed() {
+ return Err(Error::Quiesced);
+ }
+ // Wait for submitted command buffers to retire on the completion thread.
+ let deadline = Instant::now() + Duration::from_secs(10);
+ while core.pool.in_flight() > 0 && Instant::now() < deadline {
+ std::thread::sleep(Duration::from_millis(1));
+ }
+ // SAFETY: `device` is live and wait_idle synchronizes all host queues.
+ let _q = lock(&core.queues.runtime);
+ unsafe { core.device.device_wait_idle() }.map_err(Error::vulkan("vkDeviceWaitIdle"))?;
+ Ok(())
+ }
+
+ /// Replays a previously captured block at its exact Vulkan device address.
+ pub fn take_block_replayed(&self, capture: memory::BlockCaptureInfo) -> Result<Block, Error> {
+ let core = &self.shared.core;
+ if core.closed() {
+ return Err(Error::Quiesced);
+ }
+ let memory = core.pool.take_replayed(core, capture, crate::counters::Site::take(capture.class))?;
+ let info = memory.info();
+ let block = memory::Block::new(memory, Arc::clone(core));
+ Ok(Block::claim(core, info, block))
+ }
+
+ /// Allocates a new GPU memory block of `class` and `len` bytes.
pub fn take_block(&self, class: MemoryClass, len: u64) -> Result<Block, Error> {
let core = &self.shared.core;
if core.closed() {
diff --git a/crates/metal2vulkan-runtime/src/event.rs b/crates/metal2vulkan-runtime/src/event.rs
index fe95046625fb1d1c81e2925458c22c4dd3641197..8b47e5604f50dec0549733c515ce80e02dbe348e 100644
--- a/crates/metal2vulkan-runtime/src/event.rs
+++ b/crates/metal2vulkan-runtime/src/event.rs
@@ -140,6 +140,35 @@ impl Event {
}
}
+impl Event {
+ /// Reads the current signaled value of this timeline event (for checkpointing).
+ pub fn signaled_value(&self) -> u64 {
+ let inner = &self.inner;
+ let state = lock(&inner.state);
+ let floor = state.observed.max(state.floor);
+ inner.reached(None).map_or(floor, |reached| reached.max(floor))
+ }
+
+ /// Restores the timeline semaphore and CPU floor to `value` on a freshly created event.
+ pub fn restore_signaled_value(&self, value: u64) -> Result<(), Error> {
+ if value == 0 {
+ return Ok(());
+ }
+ let inner = &self.inner;
+ let info = vk::SemaphoreSignalInfo::default()
+ .semaphore(inner.semaphore)
+ .value(value);
+ // SAFETY: `semaphore` is a live timeline semaphore on `inner.core.device`.
+ unsafe { inner.core.device.signal_semaphore(&info) }
+ .map_err(Error::vulkan("vkSignalSemaphore"))?;
+ let mut state = lock(&inner.state);
+ state.floor = state.floor.max(value);
+ state.observed = state.observed.max(value);
+ inner.changed.notify_all();
+ Ok(())
+ }
+}
+
impl SharedEvent {
/// `signaledValue`: the higher of the semaphore's value and the host's floor, the semaphore's
/// value being one a host wait confirmed: a counter read finds it, and a wait with a timeout
diff --git a/crates/metal2vulkan-runtime/src/floor.rs b/crates/metal2vulkan-runtime/src/floor.rs
index 0e165934f4b7534d0a093b1a22bcd763a47db8d7..90c7f9e354af205aa5a6b2fbeb506e58fbba1ab8 100644
--- a/crates/metal2vulkan-runtime/src/floor.rs
+++ b/crates/metal2vulkan-runtime/src/floor.rs
@@ -1079,6 +1079,8 @@ pub struct Capabilities {
/// [`ATTACHMENT_READ_EXTENSIONS`]: a draw reads an attachment through the attachment feedback
/// loop, the feedback layout its image moves to and the flag every render pipeline takes.
pub feedback_loop: bool,
+ /// Whether `bufferDeviceAddressCaptureReplay` is enabled for checkpoint/restore.
+ pub buffer_device_address_capture_replay: bool,
/// The features device creation enables: every one the floor requires, each of the optional,
/// step-rate, min-LOD, fill-mode, alpha-to-one, quad-control, pixel-interlock, linear-attachment
/// and fault-report ones the device reports, the attachment-read ones where
@@ -1425,6 +1427,10 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
let Some((queue_family, _)) = family.filter(|_| missing.is_empty()) else {
return Err(BelowFloor { missing });
};
+ let capture_replay = reported.vulkan12.buffer_device_address_capture_replay == vk::TRUE;
+ if capture_replay {
+ features.vulkan12.buffer_device_address_capture_replay = vk::TRUE;
+ }
for feature in (OPTIONAL.iter().chain(STEP_RATES))
.chain(MIN_LOD_CLAMPS)
.chain(FILL_MODES)
@@ -1491,6 +1497,7 @@ pub(crate) fn decide(device: &Queried) -> Result<Capabilities, BelowFloor> {
texel_offset_operand: features.maintenance8.maintenance8 == vk::TRUE,
attachment_reads,
feedback_loop,
+ buffer_device_address_capture_replay: capture_replay,
features,
extensions: DEVICE_EXTENSIONS
.iter()
diff --git a/crates/metal2vulkan-runtime/src/lib.rs b/crates/metal2vulkan-runtime/src/lib.rs
index a2d59cc6f31eb64307c1a886fe7cf75f401511b1..557a1a4b213773df976895f703cd4c037ad2602b 100644
--- a/crates/metal2vulkan-runtime/src/lib.rs
+++ b/crates/metal2vulkan-runtime/src/lib.rs
@@ -100,7 +100,7 @@ pub use host_bytes::HostBytes;
pub use import::ImportHandle;
pub use indirect::{IndirectCommandBuffer, IndirectCommandBufferDescriptor, IndirectCommandType};
pub use instance::{Instance, PhysicalDevice};
-pub use memory::{AllocationId, AllocationInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
+pub use memory::{AllocationId, AllocationInfo, BlockCaptureInfo, BlockId, BlockInfo, BlockMappings, MemoryClass};
/// `MTLLibrary`: the translator's, read from AIR or a metallib.
/// `MTLSamplerDescriptor`: the translator's.
pub use metal2vulkan::bind::SamplerDescriptor;
diff --git a/crates/metal2vulkan-runtime/src/memory.rs b/crates/metal2vulkan-runtime/src/memory.rs
index 173e0858f2e6d07660cafd5f7893aee280f2dcdc..2864f4ba6b48a4892e6d9651548c75a4babcf395 100644
--- a/crates/metal2vulkan-runtime/src/memory.rs
+++ b/crates/metal2vulkan-runtime/src/memory.rs
@@ -235,8 +235,28 @@ impl AllocationId {
/// device is torn down. It is a range of one allocation, whose one `VkBuffer`, with every buffer
/// usage and a device address, spans it; an imported or exported block is the whole of an
/// allocation of its own. Only an exported block is exportable.
+/// Capture/replay address metadata for restoring a block at its exact Vulkan device address.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct BlockCaptureInfo {
+ /// Storage mode (`Shared` or `Private`).
+ pub class: MemoryClass,
+ /// Full parent Vulkan allocation length in bytes.
+ pub alloc_len: u64,
+ /// Offset of this block inside its parent allocation.
+ pub offset: u64,
+ /// Block length in bytes.
+ pub len: u64,
+ /// Guest-visible `VkDeviceAddress` of this block's first byte.
+ pub gpu_address: u64,
+ /// Opaque capture address of the parent `VkBuffer`.
+ pub opaque_buffer_address: u64,
+ /// Opaque capture address of the parent `VkDeviceMemory`.
+ pub opaque_memory_address: u64,
+}
+
#[non_exhaustive]
#[derive(Clone, Copy, Debug)]
+/// Metadata describing an allocated GPU memory block.
pub struct BlockInfo {
/// The block's number.
pub id: BlockId,
@@ -611,6 +631,10 @@ struct Allocation {
buffer: vk::Buffer,
/// The device address of its first byte.
address: u64,
+ /// Opaque capture address of `buffer` (0 if capture-replay unsupported).
+ opaque_buffer_address: u64,
+ /// Opaque capture address of `memory` (0 if capture-replay unsupported).
+ opaque_memory_address: u64,
len: u64,
mapping: Option<Mapping>,
device_local: bool,
@@ -823,6 +847,8 @@ struct State {
/// The internal the block-maker thread took up and is making ([`run`]).
making: Option<Internal>,
stop: bool,
+ replaying: bool,
+ making_ahead: bool,
next_id: u32,
next_allocation: u32,
/// The allocations [`BlockMappings::map`] accepted whose unmap has not run.
@@ -952,6 +978,8 @@ impl Pool {
asked: [true; INTERNALS],
making: None,
stop: false,
+ replaying: false,
+ making_ahead: false,
next_id: 1,
next_allocation: 1,
mapped: HashSet::new(),
@@ -1368,6 +1396,158 @@ impl Pool {
}
}
+ /// Returns capture/replay info for a pool block, if capture-replay is enabled.
+ pub(crate) fn capture_info(&self, memory: &Memory) -> Option<BlockCaptureInfo> {
+ if memory.own.is_some() {
+ return None;
+ }
+ let state = self.lock();
+ let alloc = state.allocations[memory.class.index()]
+ .iter()
+ .find(|a| a.memory == memory.memory)?;
+
+ Some(BlockCaptureInfo {
+ class: memory.class,
+ alloc_len: alloc.len,
+ offset: memory.base,
+ len: memory.len,
+ gpu_address: memory.address,
+ opaque_buffer_address: alloc.opaque_buffer_address,
+ opaque_memory_address: alloc.opaque_memory_address,
+ })
+ }
+
+ /// Replays a previously captured pool block at its exact Vulkan device address.
+ pub(crate) fn take_replayed(
+ &self,
+ core: &Core,
+ cap: BlockCaptureInfo,
+ site: Site,
+ ) -> Result<Memory, Error> {
+ let index = cap.class.index();
+ // 1. Check if the parent allocation is already present (e.g. another sub-block restored it,
+ // or a pre-stocked idle reserve landed at the exact same address!).
+ {
+ let mut state = self.lock();
+ if state.stop {
+ return Err(Error::Quiesced);
+ }
+ let id = number(&mut state)?;
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
+ if let Some(alloc) = state.allocations[index].iter_mut().find(|a| {
+ a.address == want_base
+ && a.opaque_buffer_address == cap.opaque_buffer_address
+ && a.opaque_memory_address == cap.opaque_memory_address
+ && a.len == cap.alloc_len
+ }) {
+ if alloc.free.take_at(cap.offset, cap.len) {
+ let carve = alloc.carve(cap.offset);
+ alloc.live += 1;
+ alloc.placed += cap.len;
+ alloc.ahead = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ return Ok(carve.block(id, cap.class, cap.len));
+ }
+ }
+ }
+ // 2. Pause block-maker ahead allocations, wait for any in-flight ahead make,
+ // and purge idle reserve slabs so none collide with the target opaque VA!
+ let idle_allocs: Vec<Allocation> = {
+ let mut state = self.lock();
+ state.replaying = true;
+ while state.making_ahead {
+ state = self.wait(state);
+ }
+ // Re-check if an ahead allocation that just finished landed at the exact target VA!
+ let want_base = cap.gpu_address.saturating_sub(cap.offset);
+ let hit = state.allocations[index].iter_mut().find_map(|a| {
+ if a.address == want_base
+ && a.opaque_buffer_address == cap.opaque_buffer_address
+ && a.opaque_memory_address == cap.opaque_memory_address
+ && a.len == cap.alloc_len
+ && a.free.take_at(cap.offset, cap.len)
+ {
+ let carve = a.carve(cap.offset);
+ a.live += 1;
+ a.placed += cap.len;
+ a.ahead = false;
+ Some(carve)
+ } else {
+ None
+ }
+ });
+ if let Some(carve) = hit {
+ let id = number(&mut state)?;
+ state.replaying = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ return Ok(carve.block(id, cap.class, cap.len));
+ }
+ let mut drained = Vec::new();
+ for c in MemoryClass::ALL {
+ let ci = c.index();
+ let mut kept = Vec::new();
+ for a in state.allocations[ci].drain(..) {
+ if a.live == 0 {
+ drained.push(a);
+ } else {
+ kept.push(a);
+ }
+ }
+ state.allocations[ci] = kept;
+ self.settle(&mut state, c);
+ }
+ drained
+ };
+ for a in idle_allocs {
+ free_idle(core, a);
+ }
+ // 3. Allocate at the exact captured opaque buffer + memory addresses.
+ let alloc_res = make_allocation_ex(
+ core,
+ cap.class,
+ cap.alloc_len,
+ Some(site),
+ Some((cap.opaque_buffer_address, cap.opaque_memory_address)),
+ );
+ let mut allocation = match alloc_res {
+ Ok(a) => a,
+ Err(e) => {
+ let mut state = self.lock();
+ state.replaying = false;
+ self.changed.notify_all();
+ return Err(e);
+ }
+ };
+ let mapped = self.map(&allocation, cap.class, true);
+ if !mapped {
+ free_allocation(core, allocation);
+ let mut state = self.lock();
+ state.replaying = false;
+ self.changed.notify_all();
+ return Err(Error::Limit(Limit::AllocationNotMapped {
+ class: cap.class,
+ len: cap.alloc_len,
+ }));
+ }
+ let ok = allocation.free.take_at(cap.offset, cap.len);
+ debug_assert!(ok, "fresh allocation must contain captured block range");
+ let mut state = self.lock();
+ let id = number(&mut state)?;
+ let memory = allocation.carve(cap.offset).block(id, cap.class, cap.len);
+ allocation.live = 1;
+ allocation.placed = cap.len;
+ state.allocations[index].push(allocation);
+ state.replaying = false;
+ self.counters.rise_by(cap.class.placed_gauge(), cap.len);
+ self.settle(&mut state, cap.class);
+ self.changed.notify_all();
+ Ok(memory)
+ }
+
/// Takes back a block taken with [`take`](Self::take): its bytes are a free range of its
/// allocation at once.
pub(crate) fn give_back(&self, memory: Memory) {
@@ -1788,12 +1968,16 @@ pub(crate) fn run(core: Arc<Core>) {
state = pool.lock();
continue;
}
- let wanted = (MemoryClass::ALL.into_iter())
- .find(|&class| !state.failed[class.index()] && !state.whole(class));
+ let wanted = (!state.replaying).then(|| {
+ (MemoryClass::ALL.into_iter())
+ .find(|&class| !state.failed[class.index()] && !state.whole(class))
+ }).flatten();
if let Some(class) = wanted {
+ state.making_ahead = true;
drop(state);
let made = ahead(&core, class);
state = pool.lock();
+ state.making_ahead = false;
match made {
// Idle from now: the reserve, which the idle rule does not weigh.
Some(mut allocation) => {
@@ -2022,6 +2206,16 @@ fn make_allocation(
class: MemoryClass,
len: u64,
site: Option<Site>,
+) -> Result<Allocation, Error> {
+ make_allocation_ex(core, class, len, site, None)
+}
+
+fn make_allocation_ex(
+ core: &Core,
+ class: MemoryClass,
+ len: u64,
+ site: Option<Site>,
+ replay: Option<(u64, u64)>,
) -> Result<Allocation, Error> {
let device = &core.device;
let (id, freed_at) = {
@@ -2031,22 +2225,38 @@ fn make_allocation(
state.freed_at[class.index()],
)
};
- let info = vk::BufferCreateInfo::default()
+ let mut buf_opaque = vk::BufferOpaqueCaptureAddressCreateInfo::default()
+ .opaque_capture_address(replay.map_or(0, |(b, _)| b));
+ let mut info = vk::BufferCreateInfo::default()
.size(len)
.usage(floor::BUFFER_USAGE)
.sharing_mode(vk::SharingMode::EXCLUSIVE);
+ if core.capture_replay {
+ info = info.flags(vk::BufferCreateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY);
+ if replay.is_some_and(|(b, _)| b != 0) {
+ info = info.push_next(&mut buf_opaque);
+ }
+ }
// SAFETY: the device is live, and the create info valid: `len` is at most its
// `maxBufferSize`.
let buffer =
unsafe { device.create_buffer(&info, None) }.map_err(Error::vulkan("vkCreateBuffer"))?;
// SAFETY: the buffer is the device's.
let requirements = unsafe { device.get_buffer_memory_requirements(buffer) };
- let mut flags =
- vk::MemoryAllocateFlagsInfo::default().flags(vk::MemoryAllocateFlags::DEVICE_ADDRESS);
- let allocate_info = vk::MemoryAllocateInfo::default()
+ let mut mem_flags = vk::MemoryAllocateFlags::DEVICE_ADDRESS;
+ if core.capture_replay {
+ mem_flags |= vk::MemoryAllocateFlags::DEVICE_ADDRESS_CAPTURE_REPLAY;
+ }
+ let mut flags = vk::MemoryAllocateFlagsInfo::default().flags(mem_flags);
+ let mut mem_opaque = vk::MemoryOpaqueCaptureAddressAllocateInfo::default()
+ .opaque_capture_address(replay.map_or(0, |(_, m)| m));
+ let mut allocate_info = vk::MemoryAllocateInfo::default()
.allocation_size(requirements.size.max(len))
.memory_type_index(core.memory_type(class))
.push_next(&mut flags);
+ if core.capture_replay && replay.is_some_and(|(_, m)| m != 0) {
+ allocate_info = allocate_info.push_next(&mut mem_opaque);
+ }
let bits = requirements.memory_type_bits;
// SAFETY: the floor chose the memory type for buffers of this usage on this device, and
// `bufferDeviceAddress` is enabled; a spill takes a type the buffer's requirements allow.
@@ -2065,6 +2275,8 @@ fn make_allocation(
memory,
buffer,
address: 0,
+ opaque_buffer_address: 0,
+ opaque_memory_address: 0,
len,
mapping: None,
device_local: !spilled && core.device_local & (1 << core.memory_type(class)) != 0,
@@ -2101,6 +2313,13 @@ fn make_allocation(
let of = vk::BufferDeviceAddressInfo::default().buffer(buffer);
// SAFETY: the buffer has device-address usage and is bound.
allocation.address = unsafe { device.get_buffer_device_address(&of) };
+ if core.capture_replay {
+ allocation.opaque_buffer_address =
+ unsafe { device.get_buffer_opaque_capture_address(&of) };
+ let mof = vk::DeviceMemoryOpaqueCaptureAddressInfo::default().memory(memory);
+ allocation.opaque_memory_address =
+ unsafe { device.get_device_memory_opaque_capture_address(&mof) };
+ }
(core.spans).made(
buffer,
allocation.address,
diff --git a/crates/metal2vulkan-runtime/src/places.rs b/crates/metal2vulkan-runtime/src/places.rs
index 137fb5790de850552affd179497df69d9912266a..3d679bbaa5285e87d1639a7cc140e0025b49e84f 100644
--- a/crates/metal2vulkan-runtime/src/places.rs
+++ b/crates/metal2vulkan-runtime/src/places.rs
@@ -248,6 +248,33 @@ impl Ranges {
Some(at)
}
+ /// Takes the exact range `at..at + len` if it is completely free.
+ pub(crate) fn take_at(&mut self, at: u64, len: u64) -> bool {
+ let Some(stop) = at.checked_add(len) else {
+ return false;
+ };
+ let Some(index) = self
+ .free
+ .iter()
+ .position(|&(start, end)| start <= at && stop <= end)
+ else {
+ return false;
+ };
+ let (start, end) = self.free[index];
+ match (start < at, stop < end) {
+ (false, false) => {
+ self.free.remove(index);
+ }
+ (true, false) => self.free[index] = (start, at),
+ (false, true) => self.free[index] = (stop, end),
+ (true, true) => {
+ self.free[index] = (start, at);
+ self.free.insert(index + 1, (stop, end));
+ }
+ }
+ true
+ }
+
/// Frees `offset..offset + len`, taken before, joining it to the free ranges beside it.
pub(crate) fn give(&mut self, offset: u64, len: u64) {
let end = offset + len;
@@ -1,524 +0,0 @@
diff --git a/src/http.rs b/src/http.rs
index 69aeb817b8dc1ff2cebb91bbcad5d4ad749b1540..777a7d8adf65faaff0f08e228a4165ed48984e42 100644
--- a/src/http.rs
+++ b/src/http.rs
@@ -13,13 +13,15 @@
use crate::progress::{self, Reporter};
use anyhow::{Context, Result, bail};
use std::fs::{File, OpenOptions};
-use std::io::{Read, Seek, SeekFrom, Write};
+use std::io::{Cursor, Read, Seek, SeekFrom, Write};
use std::path::{Path, PathBuf};
+use std::thread;
use std::time::Duration;
use ureq::Agent;
/// The most each request asks for.
pub const SEGMENT: u64 = 64 << 20;
+const PARALLEL_REQUESTS: usize = 4;
/// How long a request may take to send its range: a stall is noticed within this. (On a
/// connection too slow to send a whole range in it, each request sends what it can.)
pub const SEGMENT_BUDGET: Duration = Duration::from_secs(180);
@@ -124,6 +126,8 @@ pub struct Download<'a> {
/// For requests the server refuses (401, 403): new headers, such as a fresh asset token.
pub refresh: Option<&'a mut dyn FnMut() -> Result<Headers>>,
pub user_agent: Option<&'static str>,
+ /// Fetch the public installer package in parallel within each checked segment.
+ pub parallel: bool,
/// Failed requests in a row, with no byte received between them, before it gives up:
/// [`MAX_FAILURES`], or fewer when there is another place to download the file from.
pub tries: u32,
@@ -138,6 +142,7 @@ impl Download<'_> {
size: None,
refresh: None,
user_agent: None,
+ parallel: false,
tries: MAX_FAILURES,
}
}
@@ -229,6 +234,8 @@ pub fn download(
let mut failures = 0u32;
let mut bad_chunks = 0u32;
let mut buf = vec![0u8; 1 << 18];
+ let mut parallel =
+ d.parallel && check.verifies() && d.headers.is_empty() && d.user_agent.is_none();
r.progress(have, total);
'requests: loop {
@@ -240,94 +247,116 @@ pub fn download(
Some(t) => (have + SEGMENT).min(t) - 1,
None => have + SEGMENT - 1,
};
- let mut req = agent
- .get(&d.url)
- .header("Range", format!("bytes={have}-{end}"));
- for (k, v) in &d.headers {
- req = req.header(k, v);
- }
- let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
- if let Some(ua) = d.user_agent {
- cfg = cfg.user_agent(ua);
- }
- let resp = match cfg.build().call() {
- Ok(resp) => resp,
- Err(e) => {
- failures += 1;
- retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?;
- continue;
+ // Keep one segment in memory and commit it through the same ordered
+ // writer and chunk checker used by serial downloads.
+ let batch = if parallel
+ && let Some(size) = total
+ && end - have >= (PARALLEL_REQUESTS - 1) as u64
+ {
+ match read_parallel_segment(agent, &d.url, have, end, size, r) {
+ Ok(bytes) => Some(bytes),
+ Err(_) => {
+ progress::check(r)?;
+ parallel = false;
+ r.note("Parallel ranges could not be read. Continuing with one connection.");
+ None
+ }
}
+ } else {
+ None
};
- let status = resp.status().as_u16();
- match status {
- 206 => {
- let range = resp
- .headers()
- .get("content-range")
- .and_then(|v| v.to_str().ok())
- .and_then(content_range)
- .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
- if range.0 != have {
- bail!(
- "{} sent bytes from {} when asked for {have}",
- d.url,
- range.0
- );
+ let mut body: Box<dyn Read> = if let Some(bytes) = batch {
+ Box::new(Cursor::new(bytes))
+ } else {
+ let mut req = agent
+ .get(&d.url)
+ .header("Range", format!("bytes={have}-{end}"));
+ for (k, v) in &d.headers {
+ req = req.header(k, v);
+ }
+ let mut cfg = req.config().timeout_recv_body(Some(SEGMENT_BUDGET));
+ if let Some(ua) = d.user_agent {
+ cfg = cfg.user_agent(ua);
+ }
+ let resp = match cfg.build().call() {
+ Ok(resp) => resp,
+ Err(e) => {
+ failures += 1;
+ retry_or_fail(&mut failures, d.tries, &format!("{e}"), &d.url, r)?;
+ continue;
+ }
+ };
+ let status = resp.status().as_u16();
+ match status {
+ 206 => {
+ let range = resp
+ .headers()
+ .get("content-range")
+ .and_then(|v| v.to_str().ok())
+ .and_then(content_range)
+ .with_context(|| format!("{} sent a range without Content-Range", d.url))?;
+ if range.0 != have {
+ bail!(
+ "{} sent bytes from {} when asked for {have}",
+ d.url,
+ range.0
+ );
+ }
+ match (total, range.1) {
+ (Some(t), Some(rt)) if t != rt => bail!(
+ "{} is {} long, not the expected {}: it changed on the server",
+ d.url,
+ rt,
+ t
+ ),
+ (None, Some(rt)) => {
+ total = Some(rt);
+ r.progress(have, total);
+ }
+ _ => {}
+ }
}
- match (total, range.1) {
- (Some(t), Some(rt)) if t != rt => bail!(
- "{} is {} long, not the expected {}: it changed on the server",
- d.url,
- rt,
- t
- ),
- (None, Some(rt)) => {
- total = Some(rt);
- r.progress(have, total);
+ 200 => {
+ // The whole file: the server ignored the range.
+ if have > 0 {
+ cut(file, 0)?;
+ have = 0;
+ check.restart_at(0);
+ }
+ if total.is_none() {
+ total = resp.body().content_length();
}
- _ => {}
}
- }
- 200 => {
- // The whole file: the server ignored the range.
- if have > 0 {
+ 416 if total.is_some_and(|t| have >= t) => break,
+ 416 => {
+ // Past the end: the file on the server is shorter than what we have.
+ if have == 0 {
+ bail!("{} refused every range", d.url);
+ }
+ r.note("The file changed on the server: starting over");
cut(file, 0)?;
have = 0;
check.restart_at(0);
+ continue;
}
- if total.is_none() {
- total = resp.body().content_length();
- }
- }
- 416 if total.is_some_and(|t| have >= t) => break,
- 416 => {
- // Past the end: the file on the server is shorter than what we have.
- if have == 0 {
- bail!("{} refused every range", d.url);
+ 401 | 403 if d.refresh.is_some() && failures < 3 => {
+ failures += 1;
+ if let Some(f) = d.refresh.as_mut() {
+ d.headers = f()?;
+ }
+ continue;
}
- r.note("The file changed on the server: starting over");
- cut(file, 0)?;
- have = 0;
- check.restart_at(0);
- continue;
- }
- 401 | 403 if d.refresh.is_some() && failures < 3 => {
- failures += 1;
- if let Some(f) = d.refresh.as_mut() {
- d.headers = f()?;
+ 408 | 429 | 500..=599 => {
+ failures += 1;
+ retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?;
+ continue;
}
- continue;
- }
- 408 | 429 | 500..=599 => {
- failures += 1;
- retry_or_fail(&mut failures, d.tries, &format!("HTTP {status}"), &d.url, r)?;
- continue;
+ _ => bail!("{} answered HTTP {status}", d.url),
}
- _ => bail!("{} answered HTTP {status}", d.url),
- }
+ Box::new(resp.into_body().into_reader())
+ };
file.seek(SeekFrom::Start(base + have))?;
- let mut body = resp.into_body().into_reader();
let start = have;
loop {
if r.cancelled() {
@@ -389,6 +418,79 @@ pub fn download(
Ok(())
}
+fn read_parallel_segment(
+ agent: &Agent,
+ url: &str,
+ start: u64,
+ end: u64,
+ total: u64,
+ r: &dyn Reporter,
+) -> Result<Vec<u8>> {
+ let mut segment = vec![0; (end - start + 1) as usize];
+ let request_size = segment.len().div_ceil(PARALLEL_REQUESTS);
+ thread::scope(|scope| -> Result<()> {
+ let mut requests = Vec::with_capacity(PARALLEL_REQUESTS);
+ for (index, chunk) in segment.chunks_mut(request_size).enumerate() {
+ let first = start + (index * request_size) as u64;
+ let request = thread::Builder::new().spawn_scoped(scope, move || {
+ read_exact_range(agent, url, first, total, chunk, r)
+ })?;
+ requests.push(request);
+ }
+ for request in requests {
+ request
+ .join()
+ .map_err(|_| anyhow::anyhow!("range worker failed"))??;
+ }
+ Ok(())
+ })?;
+ Ok(segment)
+}
+
+fn read_exact_range(
+ agent: &Agent,
+ url: &str,
+ start: u64,
+ total: u64,
+ mut remaining: &mut [u8],
+ r: &dyn Reporter,
+) -> Result<()> {
+ let end = start + remaining.len() as u64 - 1;
+ progress::check(r)?;
+ let response = agent
+ .get(url)
+ .header("Range", format!("bytes={start}-{end}"))
+ .header("Accept-Encoding", "identity")
+ .config()
+ .timeout_recv_body(Some(SEGMENT_BUDGET))
+ .build()
+ .call()?;
+ let expected = format!("bytes {start}-{end}/{total}");
+ if response.status().as_u16() != 206
+ || response
+ .headers()
+ .get("Content-Range")
+ .and_then(|value| value.to_str().ok())
+ != Some(expected.as_str())
+ {
+ bail!("server did not return the requested byte range");
+ }
+ let mut body = response.into_body().into_reader();
+ while !remaining.is_empty() {
+ progress::check(r)?;
+ let n = body.read(remaining)?;
+ if n == 0 {
+ bail!("range body ended before its declared length");
+ }
+ remaining = &mut remaining[n..];
+ }
+ progress::check(r)?;
+ if body.read(&mut [0u8; 1])? != 0 {
+ bail!("range body exceeded its declared length");
+ }
+ Ok(())
+}
+
fn retry_or_fail(
failures: &mut u32,
tries: u32,
@@ -455,6 +557,173 @@ pub fn hex(b: &[u8]) -> String {
#[cfg(test)]
mod tests {
use super::*;
+ use std::io::{BufRead, BufReader};
+ use std::net::{TcpListener, TcpStream};
+
+ struct Silent;
+
+ impl Reporter for Silent {
+ fn event(&self, _: progress::Event) {}
+ }
+
+ fn read_request(stream: &TcpStream) -> Result<String> {
+ stream.set_read_timeout(Some(Duration::from_secs(5)))?;
+ let mut reader = BufReader::new(stream);
+ let mut range = String::new();
+ loop {
+ let mut line = String::new();
+ if reader.read_line(&mut line)? == 0 || line == "\r\n" {
+ break;
+ }
+ if let Some((name, value)) = line.split_once(':')
+ && name.eq_ignore_ascii_case("range")
+ {
+ range = value.trim().to_string();
+ }
+ }
+ Ok(range)
+ }
+
+ #[test]
+ fn sends_four_ranges_before_waiting_for_their_bodies() -> Result<()> {
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ listener.set_nonblocking(true)?;
+ let url = format!("http://{}", listener.local_addr()?);
+ let server = thread::spawn(move || -> Result<()> {
+ let deadline = std::time::Instant::now() + Duration::from_secs(5);
+ let mut requests = std::collections::BTreeMap::new();
+ while requests.len() < 4 {
+ match listener.accept() {
+ Ok((stream, _)) => {
+ let range = read_request(&stream)?;
+ requests.insert(range, stream);
+ }
+ Err(e)
+ if e.kind() == std::io::ErrorKind::WouldBlock
+ && std::time::Instant::now() < deadline =>
+ {
+ thread::sleep(Duration::from_millis(5));
+ }
+ Err(e) => {
+ return Err(e).context("waiting for four simultaneous range requests");
+ }
+ }
+ }
+ // No worker gets a response until all four requests have arrived.
+ let data = b"abcdefghijklmnop";
+ for offset in (0..data.len()).step_by(4).rev() {
+ let mut stream = requests
+ .remove(&format!("bytes={offset}-{}", offset + 3))
+ .context("missing requested range")?;
+ write!(
+ stream,
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes {offset}-{}/16\r\nConnection: close\r\n\r\n",
+ offset + 3
+ )?;
+ stream.write_all(&data[offset..offset + 4])?;
+ }
+ Ok(())
+ });
+ let data = read_parallel_segment(&test_agent(), &url, 0, 15, 16, &Silent);
+ server
+ .join()
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
+ assert_eq!(data?, b"abcdefghijklmnop");
+ Ok(())
+ }
+
+ #[test]
+ fn rejects_ignored_misaligned_and_truncated_ranges() -> Result<()> {
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ let url = format!("http://{}", listener.local_addr()?);
+ let server = thread::spawn(move || -> Result<()> {
+ for reply in [
+ "HTTP/1.1 200 OK\r\nContent-Length: 4\r\nConnection: close\r\n\r\nabcd",
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 4\r\nContent-Range: bytes 5-8/16\r\nConnection: close\r\n\r\nabcd",
+ "HTTP/1.1 206 Partial Content\r\nContent-Length: 3\r\nContent-Range: bytes 4-7/16\r\nConnection: close\r\n\r\nabc",
+ ] {
+ let (mut stream, _) = listener.accept()?;
+ read_request(&stream)?;
+ stream.write_all(reply.as_bytes())?;
+ }
+ Ok(())
+ });
+ let agent = test_agent();
+ for _ in 0..3 {
+ assert!(read_exact_range(&agent, &url, 4, 16, &mut [0; 4], &Silent).is_err());
+ }
+ server
+ .join()
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
+ Ok(())
+ }
+
+ #[test]
+ fn falls_back_to_a_single_request_from_the_verified_prefix() -> Result<()> {
+ use crate::chunklist::{ChunkCheck, Chunklist, Signature};
+ use sha2::{Digest, Sha256};
+
+ let data = b"abcdefghijklmnop";
+ let listener = TcpListener::bind("127.0.0.1:0")?;
+ let url = format!("http://{}", listener.local_addr()?);
+ let server = thread::spawn(move || -> Result<()> {
+ for _ in 0..PARALLEL_REQUESTS {
+ let (mut stream, _) = listener.accept()?;
+ read_request(&stream)?;
+ stream.write_all(
+ b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
+ )?;
+ }
+ let (mut stream, _) = listener.accept()?;
+ assert_eq!(read_request(&stream)?, "bytes=4-15");
+ stream.write_all(
+ b"HTTP/1.1 206 Partial Content\r\nContent-Length: 12\r\nContent-Range: bytes 4-15/16\r\nConnection: close\r\n\r\n",
+ )?;
+ stream.write_all(&data[4..])?;
+ Ok(())
+ });
+ let dir = std::env::temp_dir().join(format!("reims-util-fallback-{}", std::process::id()));
+ std::fs::create_dir_all(&dir)?;
+ let path = dir.join("download");
+ std::fs::write(part_path(&path), &data[..4])?;
+ let chunks = data
+ .chunks_exact(4)
+ .map(|chunk| (4, Sha256::digest(chunk).into()))
+ .collect();
+ let mut check = ChunkCheck::new(Chunklist {
+ chunks,
+ signature: Signature::Digest,
+ });
+ let mut request = Download::new(&url, "Test download".into());
+ request.size = Some(data.len() as u64);
+ request.parallel = true;
+ let result = download(
+ &test_agent(),
+ request,
+ Dest::File(&path),
+ &mut check,
+ &Silent,
+ );
+ let actual = std::fs::read(&path);
+ let _ = std::fs::remove_file(&path);
+ let _ = std::fs::remove_file(part_path(&path));
+ let _ = std::fs::remove_dir(&dir);
+ result?;
+ server
+ .join()
+ .map_err(|_| anyhow::anyhow!("test server failed"))??;
+ assert_eq!(actual?, data);
+ Ok(())
+ }
+
+ fn test_agent() -> Agent {
+ Agent::config_builder()
+ .proxy(None)
+ .http_status_as_error(false)
+ .timeout_global(Some(Duration::from_secs(5)))
+ .build()
+ .into()
+ }
#[test]
fn parses_content_range() {
diff --git a/src/installer.rs b/src/installer.rs
index 7c17423300c153fd24fe9e031de3a835dcda57e1..265031a5d2ff54e0b8c9b752bad579c5927c5ef1 100644
--- a/src/installer.rs
+++ b/src/installer.rs
@@ -475,6 +475,7 @@ pub fn offline_installer(inst: &Installer, dir: &Path, r: &dyn Reporter) -> Resu
progress::check(r)?;
let mut d = Download::new(&inst.url, format!("Downloading {}", inst.label()));
d.size = Some(inst.size);
+ d.parallel = true;
let pkg = Dest::Region {
file: &mut f,
offset: pkg_at,
@@ -746,6 +747,7 @@ mod tests {
/// macOS 12's and 26's do, through `<target>Applications`), and where it fails after placing
/// the app (as Big Sur's does, needing zsh), the app gets the package as SharedSupport.dmg
/// and the script starts its startosinstall on the volume.
+ #[cfg(unix)]
#[test]
fn install_script_runs_without_dirname_or_zsh() {
use std::os::unix::fs::{PermissionsExt, symlink};
diff --git a/src/recovery.rs b/src/recovery.rs
index fe4eadc745ac4867802254a53197821acac3d411..11406e790884549b7e4e6b297f29c3a0285c606f 100644
--- a/src/recovery.rs
+++ b/src/recovery.rs
@@ -311,6 +311,7 @@ impl Image {
size: Some(self.size()),
refresh: Some(&mut refresh),
user_agent: Some(USER_AGENT),
+ parallel: false,
tries: http::MAX_FAILURES,
};
http::download(&self.agent, d, dest, check, r)
+2 -4
View File
@@ -1,8 +1,6 @@
# Patch queue, in the order the patches are applied (see patches/README.md).
# One patch per line: <target> <file>.
# The runtime forks contain the Reims vGPU and QEMU changes.
# This queue applies additional patches to their pinned dependencies.
# Runtime components are built from the pinned Reims-Go organization forks.
# The queue is reserved for temporary patches to those pinned checkouts.
# CI (runtime-preview.yml via scripts/apply-patch-series.ps1) and
# scripts/pack-runtime.ps1 both read this file; add or retire patches here.
reims-util reims-util-parallel-offline-download.patch
metal2vulkan metal2vulkan-snapshot-replay.patch
@@ -27,7 +27,11 @@ param(
[string]$Zstd,
[string[]]$AppliedPatches = @(),
[string]$RequiredCapability = '',
[string]$RequiredSuspendCompatID = '',
[string]$RequiredPackagingCommit = '',
[switch]$RequireSlim,
[switch]$SkipMsys2Sources,
[switch]$SkipSymbols,
# Only for checking packages built before the 2026-11-28 rename ("candidate").
[string]$ExpectChannel = 'alpha',
[string]$TempRoot = $env:RUNNER_TEMP
@@ -39,12 +43,14 @@ $AppliedPatches = @($AppliedPatches | ForEach-Object { $_ -split ',' } | ForEach
$names = @{
runtime = "reims-runtime-win-x64-$Commit.tar.zst"
source = "reims-runtime-src-$Commit.tar.zst"
msys2 = "reims-runtime-msys2-src-$Commit.tar.zst"
sums = 'SHA256SUMS.txt'
}
if (-not $SkipMsys2Sources) {
$names.msys2 = "reims-runtime-msys2-src-$Commit.tar.zst"
}
$symbolsName = "reims-runtime-symbols-$Commit"
if ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst"))) {
if ((-not $SkipSymbols) -and ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst")))) {
$names.symbols = "$symbolsName.tar.zst"
}
# 1. All assets for this layout.
@@ -86,6 +92,13 @@ try {
if ($m.channel -ne $ExpectChannel) { throw "manifest channel is $($m.channel), expected $ExpectChannel" }
if ($m.source_package -ne $names.source) { throw "manifest source_package is $($m.source_package), expected $($names.source)" }
if ($RequiredCapability -and $RequiredCapability -notin $m.capabilities) { throw "manifest lacks capability $RequiredCapability" }
if ($RequiredSuspendCompatID -and ($m.suspend_compat_id -cne $RequiredSuspendCompatID -or
$Commit -cnotmatch ('^' + [regex]::Escape($RequiredSuspendCompatID) + '(?:-p[1-9][0-9]*)?$'))) {
throw "manifest suspend_compat_id is $($m.suspend_compat_id), expected $RequiredSuspendCompatID for $Commit"
}
if ($RequiredPackagingCommit -and $m.packaging_commit -cne $RequiredPackagingCommit) {
throw "manifest packaging_commit is $($m.packaging_commit), expected $RequiredPackagingCommit"
}
$files = @(Get-ChildItem -LiteralPath $root -Recurse -File)
if ($m.file_count -ne $files.Count) { throw "manifest file_count is $($m.file_count), actual $($files.Count)" }
$rawBytes = [int64](($files | Measure-Object Length -Sum).Sum)
@@ -112,6 +125,15 @@ try {
if (!(Test-Path -LiteralPath (Join-Path $root $rel) -PathType Leaf)) { throw "Missing runtime dependency: $rel" }
}
Write-Host 'PASS stripped executable hashes, detached debug members and video driver files'
} elseif ($RequireSlim) {
foreach ($rel in 'bin/reims-ctl.exe','bin/reims-util.exe','qemu/bin/qemu-system-x86_64.exe','qemu/bin/qemu-img.exe','qemu/bin/reims-vgpu-compile.exe') {
$hash = (Get-FileHash -LiteralPath (Join-Path $root $rel) -Algorithm SHA256).Hash
if ($hash -ne $m.sha256.$rel) { throw "Manifest hash mismatch for $rel" }
}
foreach ($rel in 'qemu/bin/libva.dll','qemu/bin/libva_win32.dll','qemu/bin/vaon12_drv_video.dll','NOTICE.md','MSYS2-PACKAGES.txt') {
if (!(Test-Path -LiteralPath (Join-Path $root $rel) -PathType Leaf)) { throw "Missing runtime dependency: $rel" }
}
Write-Host 'PASS stripped executable hashes and video driver files (light alpha)'
}
# 4. QEMU runs from the bundle alone and has the reims device.
@@ -130,7 +152,7 @@ try {
if ($proc.ExitCode -ne 0) { throw "qemu -device help exited $($proc.ExitCode): $err" }
if ($out -notmatch 'reims-graphics-pci') { throw "qemu -device help does not list reims-graphics-pci`n$out`n$err" }
Write-Host 'PASS qemu-system-x86_64 -device help lists reims-graphics-pci (no MSYS2 on PATH)'
if ($names.symbols) {
if ($names.symbols -or $RequireSlim) {
$oldPath = $env:PATH
$img = Join-Path $qemuBin 'qemu-img.exe'
try {
@@ -33,9 +33,10 @@ param(
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
$localDb = Join-Path $Msys2 'var\lib\pacman\local'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$zstd = Join-Path $Msys2 'usr\bin\zstd.exe'
$zstd = Resolve-Zstd -Msys2 $Msys2
function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
@@ -49,12 +49,22 @@ param(
# Release identifier for archive names and manifest.commit (defaults to short
# upstream commit; e.g. "3731afd-p2" for a patch-queue rebuild of 3731afd).
[string]$ReleaseId = '',
[ValidatePattern('^(?:[0-9a-f]{7,40})?$')]
[string]$SuspendCompatID = '',
[ValidatePattern('^(?:[0-9a-f]{40})?$')]
[string]$PackagingCommit = '',
# Names from patches/series.txt actually applied. Not given: all of them.
# Given but empty: none (every patch already upstream).
[string[]]$Patches = @()
[string[]]$Patches = @(),
# Omit the 110 MB MSYS2 copyleft source bundle (e.g. for frequent alpha previews;
# include for stable releases or dedicated toolchain source releases).
[switch]$SkipMsys2Sources,
# Omit the ~95 MB detached debug symbols archive (binaries are still stripped).
[switch]$SkipSymbols
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$CargoBin = Join-Path $CargoHome 'bin'
@@ -93,20 +103,12 @@ function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Resolve-Zstd {
@(
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
(Join-Path $Msys2 'usr\bin\zstd.exe'),
(Join-Path $Msys2 'clang64\bin\zstd.exe')
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
}
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
$zstd = Resolve-Zstd
if (-not $zstd) { throw 'zstd not found (install MSYS2 zstd or put zstd.exe on PATH)' }
$tar = Join-Path $TempRoot "$name.tar"
Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name)
Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
# --long=27 (128 MiB window) deduplicates shared QEMU code across x86_64 and aarch64
# binaries while staying within default zstd CLI and Go decoder window limits.
Invoke-Native $zstd @('-T0', '--long=27', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
Remove-Item -LiteralPath $tar -Force
}
@@ -128,6 +130,9 @@ foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
$commit = (git -C $ReimsRepo rev-parse --short HEAD).Trim()
$fullCommit = (git -C $ReimsRepo rev-parse HEAD).Trim()
$id = if ($ReleaseId -and $ReleaseId.Trim()) { $ReleaseId.Trim() } else { $commit }
if ($SuspendCompatID -and $id -cnotmatch ('^' + [regex]::Escape($SuspendCompatID) + '(?:-p[1-9][0-9]*)?$')) {
throw "Suspend compatibility ID $SuspendCompatID does not match release $id"
}
$qemuRepo = Join-Path $ReimsRepo 'vendor\qemu'
$qemuCommit = (git -C $qemuRepo rev-parse HEAD).Trim()
$reimsOrigin = git -C $ReimsRepo config --get remote.origin.url 2>$null
@@ -140,10 +145,9 @@ if (Test-Path -LiteralPath $runtimeFeatures) {
$capabilities = @((Get-Content -Raw -LiteralPath $runtimeFeatures | ConvertFrom-Json).capabilities)
}
# reims-util's pinned commit is a constant in reims-ctl (crates/reims-ctl/src/reims_util.rs, REV).
$utilSrc = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'crates\reims-ctl\src\reims_util.rs')
if ($utilSrc -notmatch 'pub const REV: &str = "([0-9a-f]{40})"') { throw 'reims-util REV not found in reims_util.rs' }
$utilCommit = $Matches[1]
$pins = & (Join-Path $PSScriptRoot 'read-runtime-dependencies.ps1') -RuntimeRepo $ReimsRepo
$utilCommit = $pins.Util.Rev
$m2vCommit = $pins.Metal.Rev
$checkouts = Join-Path $CargoHome 'git\checkouts'
$utilTree = if ($UtilRepo) {
(Resolve-Path -LiteralPath $UtilRepo).Path
@@ -156,15 +160,6 @@ if (-not $utilTree) { throw "reims-util source at $utilCommit not found" }
$actualUtil = git -C $utilTree rev-parse HEAD
if ($LASTEXITCODE -ne 0 -or $actualUtil -ne $utilCommit) { throw "reims-util checkout must be at $utilCommit" }
# metal2vulkan's pinned commit (workspace Cargo.toml, falling back to Cargo.lock).
$cargoToml = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.toml')
if ($cargoToml -match 'metal2vulkan\s*=\s*\{[^}]*rev\s*=\s*"([0-9a-f]{40})"') {
$m2vCommit = $Matches[1]
} else {
$lock = Get-Content -Raw -LiteralPath (Join-Path $ReimsRepo 'Cargo.lock')
if ($lock -notmatch 'metal2vulkan\?rev=([0-9a-f]{40})') { throw 'metal2vulkan rev not found in Cargo.toml or Cargo.lock' }
$m2vCommit = $Matches[1]
}
$m2vTree = if ($Metal2VulkanRepo) {
(Resolve-Path -LiteralPath $Metal2VulkanRepo).Path
} else {
@@ -204,9 +199,11 @@ foreach ($e in $series) {
if ($usePatchList -and $e.Name -notin $Patches) { continue }
$file = Join-Path $patchesDir $e.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
# Files the patch touches ("--- a/x" / "+++ b/x"), to scope the diff checks.
# Files the patch touches ("--- a/x" / "+++ b/x", and each "diff --git a/x b/y" header, which a
# binary patch has alone), to scope the diff checks.
$paths = @(Get-Content -LiteralPath $file | ForEach-Object {
if ($_ -match '^(?:---|\+\+\+) [ab]/(.+?)\s*$') { $Matches[1] }
elseif ($_ -match '^diff --git a/(.+?) b/(.+?)\s*$') { $Matches[1]; $Matches[2] }
} | Select-Object -Unique)
$patchSpecs += @{
Name = $e.Name
@@ -238,7 +235,12 @@ foreach ($targetName in $byTarget.Keys) {
# object count between the upstream clone and the single-commit verify repo.
$diffArgs = @('-C', $repo, '-c', 'core.autocrlf=false', 'diff', '--full-index')
if ($paths.Count) { $diffArgs += '--'; $diffArgs += $paths }
$treeDiff = (& git @diffArgs | Out-String).Replace("`r`n", "`n").TrimEnd()
# The mode on an "index" line is the file's, not the change's: the verify tree is extracted by
# tar on Windows, which keeps no executable bit, so a changed executable (a prebuilt kext) reads
# 100644 there and 100755 here. A change of mode has its own "old mode"/"new mode" lines, which
# stay compared.
$indexMode = '(?m)^(index [0-9a-f]+\.\.[0-9a-f]+) [0-7]{6}$'
$treeDiff = ((& git @diffArgs | Out-String).Replace("`r`n", "`n") -replace $indexMode, '$1').TrimEnd()
# Apply the declared patch stack to a clean temporary clone of HEAD and compare diffs byte-for-byte.
$verifyDir = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid())
@@ -282,7 +284,7 @@ foreach ($targetName in $byTarget.Keys) {
Invoke-GitApply $verifyDir $patchText
Remove-Item -LiteralPath $patchLf -Force
}
$expectedDiff = (& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n").TrimEnd()
$expectedDiff = ((& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n") -replace $indexMode, '$1').TrimEnd()
if ($treeDiff -ne $expectedDiff) {
$treeStat = (& git -C $repo diff --stat -- @paths | Out-String).Trim()
$expStat = (& git -C $verifyDir diff --stat | Out-String).Trim()
@@ -372,16 +374,51 @@ if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) {
Write-Host '==> Listing MSYS2 packages of bundled DLLs'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$dlls = @(Get-ChildItem -LiteralPath "$bundleDir\qemu\bin" -Filter '*.dll' -File | Sort-Object Name)
$metadataScript = (Join-Path $PSScriptRoot 'read-msys2-package-metadata.sh').Replace('\', '/')
$dllPaths = @($dlls | ForEach-Object { "/clang64/bin/$($_.Name)" })
$expectedPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
foreach ($path in $dllPaths) { [void]$expectedPaths.Add($path) }
$rows = @(& $bash -lc 'script=$1; shift; source "$script"' -- $metadataScript @dllPaths)
if ($LASTEXITCODE -ne 0) { throw "MSYS2 package metadata lookup failed ($LASTEXITCODE)" }
$owners = @{}
$licensesByPackage = @{}
foreach ($row in $rows) {
$type, $key, $value, $version = $row -split "`t", 4
switch ($type) {
'owned' {
if (!$expectedPaths.Remove($key) -or !$value -or !$version) {
throw "Unexpected MSYS2 ownership row: $row"
}
$owners[$key] = [pscustomobject]@{ Package = $value; Version = $version }
}
'unowned' {
if (!$expectedPaths.Remove($key) -or $value) {
throw "Unexpected MSYS2 ownership row: $row"
}
}
'license' {
if (!$key -or !$value -or !$value.StartsWith('/clang64/share/licenses/', [StringComparison]::Ordinal) -or $version) {
throw "Unexpected MSYS2 license row: $row"
}
if (!$licensesByPackage.ContainsKey($key)) {
$licensesByPackage[$key] = [Collections.Generic.List[string]]::new()
}
$licensesByPackage[$key].Add($value)
}
default { throw "Unexpected MSYS2 package metadata row: $row" }
}
}
if ($expectedPaths.Count -ne 0) { throw "MSYS2 ownership lookup did not answer for $($expectedPaths -join ', ')" }
$pkgLines = [Collections.Generic.List[string]]::new()
$pkgSet = [ordered]@{}
$pkgNames = [ordered]@{}
foreach ($d in $dlls) {
$owner = (& $bash -lc "LC_ALL=C pacman -Qqo /clang64/bin/$($d.Name) 2>/dev/null" | Select-Object -First 1)
$owner = $owners["/clang64/bin/$($d.Name)"]
if ($owner) {
$ver = (& $bash -lc "LC_ALL=C pacman -Q $owner" | Select-Object -First 1).Split(' ')[1]
$pkgLines.Add("$($d.Name)`t$owner`t$ver")
$pkgSet["$owner $ver"] = $true
$pkgNames[$owner] = $true
$pkgLines.Add("$($d.Name)`t$($owner.Package)`t$($owner.Version)")
$pkgSet["$($owner.Package) $($owner.Version)"] = $true
$pkgNames[$owner.Package] = $true
} else {
$pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-")
}
@@ -389,9 +426,7 @@ foreach ($d in $dlls) {
# Bundle each MSYS2 package's installed license texts under licenses/msys2/.
$msysLicRoot = Join-Path $bundleDir 'licenses\msys2'
foreach ($owner in $pkgNames.Keys) {
$licFiles = @(& $bash -lc "LC_ALL=C pacman -Ql $owner 2>/dev/null" | ForEach-Object {
if ($_ -match '^\S+\s+(/clang64/share/licenses/.+)$' -and -not $Matches[1].EndsWith('/')) { $Matches[1] }
})
$licFiles = $licensesByPackage[$owner]
foreach ($lf in $licFiles) {
$rel = $lf.Substring('/clang64/share/licenses/'.Length)
$srcFile = Join-Path $Msys2 ($lf.TrimStart('/') -replace '/', '\')
@@ -455,7 +490,9 @@ foreach ($extra in @(
}
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
Copy-Item -Path "$bundleDir\patches\*" -Destination "$srcDir\patches\"
foreach ($ps in $patchSpecs) {
Copy-Item -LiteralPath (Join-Path "$bundleDir\patches" $ps.Name) -Destination "$srcDir\patches\"
}
Copy-Item -LiteralPath "$bundleDir\MSYS2-PACKAGES.txt" -Destination "$srcDir\MSYS2-PACKAGES.txt"
Copy-Item -LiteralPath "$bundleDir\NOTICE.md" -Destination "$srcDir\NOTICE.md"
$m2vBuildSteps = if ($byTarget.Contains('metal2vulkan')) {
@@ -468,7 +505,7 @@ and point Cargo at the patched checkout via ```$CARGO_HOME/config.toml``:
$m2vApply
cat >> "`${CARGO_HOME:-`$HOME/.cargo}/config.toml" <<EOF
[patch."https://github.com/steelbrain/metal2vulkan"]
[patch."$($pins.Metal.Url)"]
metal2vulkan = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan-runtime" }
EOF
@@ -491,6 +528,14 @@ $utilApply
"@
}
$applyRuntimePatches = @(
foreach ($ps in $patchSpecs) {
switch ($ps.Target) {
'reims-vgpu' { " git -C reims-vgpu-$commit apply ../patches/$($ps.Name)" }
'vendor/qemu' { " git -C reims-vgpu-$commit/vendor/qemu apply ../../../patches/$($ps.Name)" }
}
}
)
Write-Utf8 "$srcDir\README.md" @"
# Source for $bundleName
@@ -500,21 +545,18 @@ Corresponding source for the binaries in ``$bundleName.tar.zst``.
| :-- | :-- | :-- |
| ``reims-vgpu-$commit/`` | $reimsSource | ``$fullCommit`` |
| ``reims-vgpu-$commit/vendor/qemu/`` | $qemuSource | ``$qemuCommit`` |
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | https://github.com/steelbrain/reims-util | ``$utilCommit`` |
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | https://github.com/steelbrain/metal2vulkan | ``$m2vCommit`` |
| ``reims-util-$($utilCommit.Substring(0, 7))/`` | $($pins.Util.Url) | ``$utilCommit`` |
| ``metal2vulkan-$($m2vCommit.Substring(0, 7))/`` | $($pins.Metal.Url) | ``$m2vCommit`` |
The archive exports the commits above. Apply the patches in ``patches/``
before compiling:
$(
if ($applyRuntimePatches) {
"Apply the runtime patches from the archive root.`n`n" + ($applyRuntimePatches -join "`n")
}
)
cd reims-vgpu-$commit
$((($patchSpecs | Where-Object { $_.Target -eq 'reims-vgpu' } | ForEach-Object { " git apply ../patches/$($_.Name)" }) -join "`n"))
cd vendor/qemu
$((($patchSpecs | Where-Object { $_.Target -eq 'vendor/qemu' } | ForEach-Object { " git apply ../../../patches/$($_.Name)" }) -join "`n"))
(``patch -p1`` works too.)
$m2vBuildSteps
Then build as upstream documents (``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell). The DLLs in ``qemu/bin`` come from the MSYS2
From ``reims-vgpu-$commit/``, run ``scripts/install-ctl.sh``
in an MSYS2 CLANG64 shell. The DLLs in ``qemu/bin`` come from the MSYS2
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
$utilBuildSteps
"@
@@ -534,13 +576,14 @@ $manifest = [ordered]@{
full_commit = $fullCommit
vendor_qemu_repo = $qemuSource
vendor_qemu_commit = $qemuCommit
util_repo = $pins.Util.Url
util_commit = $utilCommit
metal2vulkan_repo = $pins.Metal.Url
metal2vulkan_commit = $m2vCommit
patches = $patchEntries
capabilities = $capabilities
channel = $Channel
source_package = "$srcName.tar.zst"
symbols_package = "$symbolsName.tar.zst"
qemu_version = $qemuVersionLine
util_version = $utilVersionLine
built_at = (Get-Date).ToString('o')
@@ -549,27 +592,40 @@ $manifest = [ordered]@{
raw_bytes = [int64]((Get-ChildItem -LiteralPath $bundleDir -Recurse -File | Measure-Object Length -Sum).Sum) # Add the manifest's own size after writing it below.
sha256 = $hashes
}
if (-not $SkipSymbols) { $manifest['symbols_package'] = "$symbolsName.tar.zst" }
if ($SuspendCompatID) { $manifest['suspend_compat_id'] = $SuspendCompatID }
if ($PackagingCommit) { $manifest['packaging_commit'] = $PackagingCommit }
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
$manifest.raw_bytes += (Get-Item -LiteralPath "$bundleDir\manifest.json").Length
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
# ── 6. Archives and sums ─────────────────────────────────────
$zstd = Resolve-Zstd -Msys2 $Msys2
Write-Host '==> Compressing runtime'
$runtimeArchive = Join-Path $OutDir "$bundleName.tar.zst"
New-TarZst $stageRoot $bundleName $runtimeArchive
Write-Host '==> Compressing sources'
$srcArchive = Join-Path $OutDir "$srcName.tar.zst"
New-TarZst $stageRoot $srcName $srcArchive
$symbolsArchive = Join-Path $OutDir "$symbolsName.tar.zst"
New-TarZst $stageRoot $symbolsName $symbolsArchive
$rtHash = Get-Sha256 $runtimeArchive
$srcHash = Get-Sha256 $srcArchive
Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n$(Get-Sha256 $symbolsArchive) $symbolsName.tar.zst`n"
$sumsLines = @(
"$rtHash $bundleName.tar.zst"
"$srcHash $srcName.tar.zst"
)
if (-not $SkipSymbols) {
$symbolsArchive = Join-Path $OutDir "$symbolsName.tar.zst"
New-TarZst $stageRoot $symbolsName $symbolsArchive
$sumsLines += "$(Get-Sha256 $symbolsArchive) $symbolsName.tar.zst"
}
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') (($sumsLines -join "`n") + "`n")
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
if (-not $SkipMsys2Sources) {
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
}
Remove-Item -Recurse -Force -LiteralPath $stageRoot
@@ -0,0 +1,141 @@
[CmdletBinding()]
param(
[Parameter(Mandatory)][string]$RuntimeRepo,
[Parameter(Mandatory)][ValidatePattern('^[0-9a-f]{40}$')][string]$RuntimeCommit,
[Parameter(Mandatory)][string]$PackagingRepo,
[Parameter(Mandatory)][ValidatePattern('^[0-9a-f]{40}$')][string]$PackagingCommit,
[Parameter(Mandatory)][string]$Repository,
[switch]$Rebuild,
[switch]$PackagingPush
)
$ErrorActionPreference = 'Stop'
$tagPattern = '^runtime-(?<base>[0-9a-f]{7,40})(?:-p(?<revision>[1-9][0-9]*))?$'
function Invoke-VersionCommand([string]$command, [string[]]$argv) {
$result = & $command @argv
if ($LASTEXITCODE -ne 0) { throw "$command $($argv -join ' ') failed ($LASTEXITCODE)" }
return $result
}
function Test-InputsChanged([string]$Repo, [string]$From, [string]$To, [string[]]$Paths) {
& git -C $Repo diff --quiet $From $To -- @Paths
if ($LASTEXITCODE -gt 1) { throw "Could not compare suspend inputs from $From to $To" }
return $LASTEXITCODE -eq 1
}
function New-VersionPlan([string]$ReleaseId, [string]$Family, [string]$Evidence = '', [string]$Predecessor = '') {
return [pscustomobject]@{
Skip = $false
ReleaseId = $ReleaseId
SuspendCompatID = $Family
Evidence = $Evidence
Predecessor = $Predecessor
}
}
$remoteTags = @{}
foreach ($line in (Invoke-VersionCommand git @('-C', $RuntimeRepo, 'ls-remote', '--tags', 'origin', 'refs/tags/runtime-*'))) {
if ($line -match '^(?<sha>[0-9a-f]{40})\s+refs/tags/(?<tag>runtime-[^\s^]+)(?<peeled>\^\{\})?$') {
if ($Matches.peeled -or !$remoteTags.ContainsKey($Matches.tag)) {
$remoteTags[$Matches.tag] = $Matches.sha
}
}
}
$pages = (Invoke-VersionCommand gh @('api', '--paginate', '--slurp', "repos/$Repository/releases?per_page=100")) -join "`n"
$releasePages = $pages | ConvertFrom-Json -NoEnumerate
$published = @(foreach ($page in $releasePages) {
foreach ($release in $page) {
if ($release.draft -or $release.tag_name -notmatch $tagPattern) { continue }
$family = $Matches.base
$revision = if ($Matches.revision) { [int]$Matches.revision } else { 0 }
$tag = $release.tag_name
if (!$remoteTags.ContainsKey($tag)) { throw "Published runtime tag $tag was not found in Git" }
$packaging = if ($release.body -match '(?m)^Packaging commit: `([0-9a-f]{40})`\s*$') { $Matches[1] } else { '' }
$verifiedFamily = if ($release.body -match '(?m)^Suspend compatibility ID: `([0-9a-f]{7,40})`\s*$') { $Matches[1] } else { '' }
[pscustomobject]@{
Tag = $tag
RuntimeCommit = $remoteTags[$tag]
Packaging = $packaging
Family = $family
Revision = $revision
VerifiedFamily = $verifiedFamily
PublishedAt = [DateTimeOffset]$release.published_at
}
}
})
$sameRuntime = @($published | Where-Object RuntimeCommit -eq $RuntimeCommit)
if ($sameRuntime.Count -and (!$Rebuild -or ($PackagingPush -and ($sameRuntime | Where-Object Packaging -eq $PackagingCommit)))) {
Write-Host "Skipping the already published runtime $RuntimeCommit."
return [pscustomobject]@{ Skip = $true }
}
# The verification belongs to the changed commit and names its exact other input.
$approvalRepo = if ($PackagingPush -or $Rebuild) { $PackagingRepo } else { $RuntimeRepo }
$approvalCommit = if ($PackagingPush -or $Rebuild) { $PackagingCommit } else { $RuntimeCommit }
$otherInput = if ($PackagingPush -or $Rebuild) { $RuntimeCommit } else { $PackagingCommit }
$message = (Invoke-VersionCommand git @('-C', $approvalRepo, 'show', '-s', '--format=%B', $approvalCommit)) -join "`n"
$trailers = $message | git interpret-trailers --parse
if ($LASTEXITCODE -ne 0) { throw 'Could not read suspend compatibility trailers' }
$approval = @{}
foreach ($line in $trailers) {
if ($line -match '^(Suspend-Compatible-With|Suspend-Verified-Inputs|Suspend-Verification):\s+(.+)$') {
if ($approval.ContainsKey($Matches[1])) { throw "Repeated compatibility trailer: $($Matches[1])" }
$approval[$Matches[1]] = $Matches[2].Trim()
}
}
if ($approval.Count) {
$previous = $published | Where-Object Tag -eq $approval['Suspend-Compatible-With']
$evidence = $approval['Suspend-Verification']
if (!$previous -or !$previous.Packaging -or $previous.VerifiedFamily -ne $previous.Family -or
$approval['Suspend-Verified-Inputs'] -ne $otherInput -or $evidence -notmatch '^https://[^\s<>]+$') {
Write-Warning 'Compatibility evidence does not match these inputs and a published compatibility baseline.'
} else {
$latest = $published | Sort-Object PublishedAt, Revision -Descending | Select-Object -First 1
$familyTip = $published | Where-Object Family -eq $previous.Family | Sort-Object Revision -Descending | Select-Object -First 1
& git -C $RuntimeRepo merge-base --is-ancestor $previous.RuntimeCommit $RuntimeCommit
if ($LASTEXITCODE -gt 1) { throw 'Could not verify the runtime baseline ancestry' }
$ancestor = $LASTEXITCODE -eq 0
# Direct changes to these inputs require a fresh family even with a trailer.
$runtimePaths = @(
'vendor/qemu', 'guest', 'firmware', ':(glob)crates/reims-vgpu*/**',
'.cargo', 'Cargo.toml', 'Cargo.lock', 'rust-toolchain.toml', 'reims-go-runtime.json',
'scripts/install-ctl.sh', 'scripts/install.ps1',
'crates/reims-ctl/Cargo.toml', 'crates/reims-ctl/Cargo.lock',
'crates/reims-ctl/src/qemu.rs', 'crates/reims-ctl/src/runtime.rs',
'crates/reims-ctl/src/main.rs', 'crates/reims-ctl/src/cli.rs', 'crates/reims-ctl/src/vm.rs',
'crates/reims-ctl/src/opencore.rs', 'crates/reims-ctl/src/reims_util.rs',
'crates/reims-ctl/src/host.rs', 'crates/reims-ctl/src/os'
)
$packagingPaths = @(
':(glob)packaging/windows-runtime/patches/*.patch',
'packaging/windows-runtime/patches/series.txt',
'packaging/windows-runtime/scripts/apply-patch-series.ps1'
)
if ($ancestor -and $previous.Tag -eq $latest.Tag -and $previous.Tag -eq $familyTip.Tag) {
& git -C $PackagingRepo cat-file -e "$($previous.Packaging)^{commit}" 2>$null
if ($LASTEXITCODE -ne 0) {
Invoke-VersionCommand git @('-C', $PackagingRepo, 'fetch', '-q', '--no-tags', 'origin', $previous.Packaging)
}
$runtimeChange = Test-InputsChanged $RuntimeRepo $previous.RuntimeCommit $RuntimeCommit $runtimePaths
$packagingChange = Test-InputsChanged $PackagingRepo $previous.Packaging $PackagingCommit $packagingPaths
if (!$runtimeChange -and !$packagingChange) {
$id = "$($previous.Family)-p$($familyTip.Revision + 1)"
if ($remoteTags.ContainsKey("runtime-$id")) { throw "Runtime tag runtime-$id is already reserved" }
return New-VersionPlan $id $previous.Family $evidence $previous.Tag
}
Write-Warning 'Suspend inputs changed. A new runtime family is required.'
} else {
Write-Warning 'The verification must cover the latest published runtime and its highest family revision.'
}
}
}
$base = (Invoke-VersionCommand git @('-C', $RuntimeRepo, 'rev-parse', '--short=7', $RuntimeCommit)).Trim()
if ($sameRuntime.Count -or $remoteTags.ContainsKey("runtime-$base")) {
throw 'A new runtime baseline commit is required, or record verified compatibility for these exact build inputs.'
}
return New-VersionPlan $base $base
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Pacman's ownership query returns the owner and installed version together.
set -euo pipefail
export LC_ALL=C
if (($# == 0)); then
exit 0
fi
status=0
ownership=$(pacman -Qo -- "$@" 2>&1) || status=$?
owned='^(/clang64/bin/.+) is owned by ([^[:space:]]+) ([^[:space:]]+)$'
unowned='^error: No package owns (/clang64/bin/.+)$'
declare -A seen=()
packages=()
missing=0
while IFS= read -r line; do
if [[ $line =~ $owned ]]; then
path=${BASH_REMATCH[1]}
package=${BASH_REMATCH[2]}
version=${BASH_REMATCH[3]}
printf 'owned\t%s\t%s\t%s\n' "$path" "$package" "$version"
if [[ -z ${seen[$package]+yes} ]]; then
seen[$package]=1
packages+=("$package")
fi
elif [[ $line =~ $unowned ]]; then
printf 'unowned\t%s\n' "${BASH_REMATCH[1]}"
((missing += 1))
else
printf 'Unexpected pacman ownership response: %s\n' "$line" >&2
exit 1
fi
done <<< "$ownership"
if ((status != missing % 256)); then
printf 'pacman ownership query exited with %d for %d unowned files\n' "$status" "$missing" >&2
exit 1
fi
if ((${#packages[@]})); then
pacman -Ql -- "${packages[@]}" | awk '
{
package = $1
sub(/^[^[:space:]]+[[:space:]]+/, "")
if ($0 ~ /^\/clang64\/share\/licenses\/.+/ && $0 !~ /\/$/)
printf "license\t%s\t%s\n", package, $0
}
'
fi
@@ -0,0 +1,31 @@
param([Parameter(Mandatory)][string]$RuntimeRepo)
$ErrorActionPreference = 'Stop'
$githubUrl = 'https://github\.com/[\w.-]+/[\w.-]+'
$util = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'crates/reims-ctl/src/reims_util.rs')
$utilUrl = [regex]::Match($util, "pub const REPO: &str = ""($githubUrl)"";").Groups[1].Value
$utilRev = [regex]::Match($util, 'pub const REV: &str = "([0-9a-f]{40})";').Groups[1].Value
if (-not $utilUrl -or -not $utilRev) { throw 'reims-util REPO or REV is missing from reims_util.rs' }
$cargo = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'Cargo.toml')
$metal = foreach ($name in 'metal2vulkan', 'metal2vulkan-runtime') {
$entry = [regex]::Match($cargo, "(?m)^$name\s*=\s*\{([^}]+)\}").Groups[1].Value
$url = [regex]::Match($entry, "git\s*=\s*""($githubUrl)""").Groups[1].Value
if (-not $url) { throw "$name git URL is missing from Cargo.toml" }
$rev = [regex]::Match($entry, 'rev\s*=\s*"([0-9a-f]{40})"').Groups[1].Value
if (-not $rev) {
$lock = Get-Content -Raw -LiteralPath (Join-Path $RuntimeRepo 'Cargo.lock')
$pin = '(?m)^source = "git\+' + [regex]::Escape($url) + '\?rev=([0-9a-f]{40})#[0-9a-f]{40}"'
$rev = [regex]::Match($lock, $pin).Groups[1].Value
}
if (-not $rev) { throw "$name revision is missing from Cargo.toml and Cargo.lock" }
[pscustomobject]@{ Url = $url; Rev = $rev }
}
if ($metal[0].Url -cne $metal[1].Url -or $metal[0].Rev -cne $metal[1].Rev) {
throw 'metal2vulkan and metal2vulkan-runtime must use the same repository and commit'
}
[pscustomobject]@{
Util = [pscustomobject]@{ Url = $utilUrl; Rev = $utilRev }
Metal = $metal[0]
}
@@ -0,0 +1,25 @@
function Resolve-Zstd([string]$Msys2) {
$candidates = @(
Get-Command zstd.exe -CommandType Application -All -ErrorAction SilentlyContinue |
Select-Object -ExpandProperty Source
Join-Path $Msys2 'usr\bin\zstd.exe'
Join-Path $Msys2 'clang64\bin\zstd.exe'
)
$failures = @()
foreach ($candidate in ($candidates | Select-Object -Unique)) {
if (-not (Test-Path -LiteralPath $candidate -PathType Leaf)) { continue }
# A binary can exist but fail to load its DLLs outside the MSYS2 shell.
try {
& $candidate --version *> $null
if ($LASTEXITCODE -eq 0) { return $candidate }
$failures += "$candidate (exit $LASTEXITCODE)"
} catch {
$failures += "$candidate ($($_.Exception.Message))"
}
}
if ($failures.Count) { throw "Could not run zstd.exe: $($failures -join '; ')" }
throw "zstd.exe not found on PATH or in MSYS2 at $Msys2"
}
@@ -10,23 +10,27 @@ param(
$ErrorActionPreference = 'Stop'
$programs = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe',
'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
# Additional executables that may be built alongside x64 (e.g. ARM64 guest support).
# Strip their debug info into the detached symbols archive whenever present.
$optionalPrograms = @('qemu/bin/qemu-system-aarch64.exe', 'qemu/bin/reims-restore.exe')
$allStripped = $programs + $optionalPrograms
# Omit only the paths tested with the x64 launcher. Keep new upstream files,
# in particular dynamically loaded video drivers, ROMs, and license notices.
$tools = @('bin/qemu-system-x86_64w.exe', 'bin/elf2dmp.exe', 'bin/qemu-edid.exe',
'bin/qemu-io.exe', 'bin/qemu-nbd.exe', 'bin/qemu-storage-daemon.exe')
$tools = @('bin/qemu-system-x86_64w.exe', 'bin/qemu-system-aarch64w.exe', 'bin/elf2dmp.exe',
'bin/qemu-edid.exe', 'bin/qemu-io.exe', 'bin/qemu-nbd.exe', 'bin/qemu-storage-daemon.exe')
foreach ($file in Get-ChildItem -LiteralPath $QemuDir -Recurse -Force -File) {
$rel = [IO.Path]::GetRelativePath($QemuDir, $file.FullName).Replace('\', '/')
if ($rel -in $tools) { continue }
if ($rel -match '^share/edk2-(aarch64|riscv64|loongarch64)-(code|vars)\.fd$' -or
$rel -match '^share/firmware/\d+-edk2-(aarch64|riscv64|loongarch64)\.json$') { continue }
if ("qemu/$rel" -in $programs) { continue }
if ("qemu/$rel" -in $allStripped) { continue }
$dest = Join-Path $BundleDir "qemu/$rel"
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
Copy-Item -LiteralPath $file.FullName -Destination $dest
}
foreach ($rel in $programs) {
function Copy-StrippedBinary([string]$rel) {
$src = if ($rel.StartsWith('qemu/')) { Join-Path $QemuDir $rel.Substring(5) }
else { Join-Path $CargoBin (Split-Path -Leaf $rel) }
$dest = Join-Path $BundleDir $rel
@@ -38,5 +42,15 @@ foreach ($rel in $programs) {
& $Objcopy --strip-debug "--add-gnu-debuglink=$debug" $src $dest | Out-Null
if ($LASTEXITCODE) { throw "Stripping $src failed ($LASTEXITCODE)" }
}
foreach ($rel in $programs) {
Copy-StrippedBinary $rel
}
foreach ($rel in $optionalPrograms) {
$src = Join-Path $QemuDir $rel.Substring(5)
if (Test-Path -LiteralPath $src -PathType Leaf) {
Copy-StrippedBinary $rel
}
}
# The packer hashes these final, stripped bytes for manifest.json.
$programs
@@ -0,0 +1,117 @@
[CmdletBinding()]
param([Parameter(Mandatory)][string]$TempRoot)
$ErrorActionPreference = 'Stop'
$root = (Resolve-Path -LiteralPath $TempRoot).Path
$fixture = Join-Path $root ("alpha-version-test-" + [guid]::NewGuid())
$planner = Join-Path $PSScriptRoot 'plan-runtime-release.ps1'
$source = Join-Path $fixture 'runtime'
$packaging = Join-Path $fixture 'packaging'
$fixtureReleases = [System.Collections.Generic.List[hashtable]]::new()
$testRepo = 'test/runtime'
function gh {
$global:LASTEXITCODE = 0
'[' + (ConvertTo-Json -InputObject $fixtureReleases.ToArray() -Depth 5 -Compress) + ']'
}
function Test-Git([string]$repo, [string[]]$argv) {
$result = & git -C $repo @argv
if ($LASTEXITCODE) { throw "git $($argv -join ' ') failed in fixture" }
return $result
}
function Write-Commit([string]$repo, [string]$path, [string]$content, [string]$message = 'Fixture update') {
$file = Join-Path $repo $path
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $file) | Out-Null
Set-Content -LiteralPath $file -Encoding utf8NoBOM -Value $content
Test-Git $repo @('add', '--', $path) | Out-Null
Test-Git $repo @('commit', '-q', '-m', $message) | Out-Null
return Test-Git $repo @('rev-parse', 'HEAD')
}
function Add-Published([string]$id, [string]$commit, [string]$pack, [string]$family) {
$tag = "runtime-$id"
Test-Git $source @('tag', $tag, $commit) | Out-Null
$fixtureReleases.Add(@{
tag_name = $tag
draft = $false
published_at = [DateTimeOffset]::UnixEpoch.AddMinutes($fixtureReleases.Count).ToString('o')
body = "Packaging commit: ``$pack```nSuspend compatibility ID: ``$family``"
})
}
function Approval([string]$predecessor, [string]$other) {
return "Fixture verified`n`nSuspend-Compatible-With: $predecessor`nSuspend-Verified-Inputs: $other`nSuspend-Verification: https://example.invalid/runtime-test"
}
function Plan([string]$commit, [string]$pack, [switch]$PackagingPush) {
& $planner -RuntimeRepo $source -RuntimeCommit $commit -PackagingRepo $packaging -PackagingCommit $pack `
-Repository $testRepo -Rebuild:$PackagingPush -PackagingPush:$PackagingPush
}
function Assert-Version($plan, [string]$id, [string]$family) {
if ($plan.Skip -or $plan.ReleaseId -ne $id -or $plan.SuspendCompatID -ne $family) {
throw "Expected $id in family $family, got $($plan | ConvertTo-Json -Compress)"
}
}
try {
foreach ($repo in $source, $packaging) {
New-Item -ItemType Directory -Path $repo -Force | Out-Null
Test-Git $repo @('init', '-q') | Out-Null
Test-Git $repo @('config', 'user.name', 'Version Fixture') | Out-Null
Test-Git $repo @('config', 'user.email', 'fixture@example.invalid') | Out-Null
}
Test-Git $source @('remote', 'add', 'origin', $source) | Out-Null
$old = Write-Commit $source 'crates/reims-ctl/src/qemu.rs' 'original state path'
$pack = Write-Commit $packaging 'packaging/windows-runtime/patches/series.txt' 'original patch queue'
$base = Test-Git $source @('rev-parse', '--short=7', $old)
Assert-Version (Plan $old $pack) $base $base
Add-Published $base $old $pack $base
if (!(Plan $old $pack).Skip -or !(Plan $old $pack -PackagingPush).Skip) {
throw 'Already published build was not skipped'
}
$compatiblePack = Write-Commit $packaging 'packaging/windows-runtime/notice.txt' 'packaging adjustment' (Approval "runtime-$base" $old)
Assert-Version (Plan $old $compatiblePack -PackagingPush) "$base-p1" $base
$breakingPack = Write-Commit $packaging 'packaging/windows-runtime/patches/series.txt' 'changed snapshot patch queue' (Approval "runtime-$base" $old)
try {
$null = Plan $old $breakingPack -PackagingPush
throw 'Incompatible packaging change reused the old runtime commit'
} catch {
if ($_ -notmatch 'A new runtime baseline commit is required') { throw }
}
$compatible = Write-Commit $source 'docs/build.md' 'safe runtime change' (Approval "runtime-$base" $pack)
Assert-Version (Plan $compatible $pack) "$base-p1" $base
Add-Published "$base-p1" $compatible $pack $base
if (!(Plan $compatible $pack).Skip) {
throw 'A published revision with a different source prefix rebuilt'
}
$next = Write-Commit $source 'docs/build.md' 'another verified change' (Approval "runtime-$base-p1" $pack)
Assert-Version (Plan $next $pack) "$base-p2" $base
$breaking = Write-Commit $source 'crates/reims-ctl/src/qemu.rs' 'different state path' (Approval "runtime-$base-p1" $pack)
$breakingBase = Test-Git $source @('rev-parse', '--short=7', $breaking)
Assert-Version (Plan $breaking $pack) $breakingBase $breakingBase
Add-Published $breakingBase $breaking $pack $breakingBase
$reverted = Write-Commit $source 'crates/reims-ctl/src/qemu.rs' 'original state path' (Approval "runtime-$base-p1" $pack)
$revertedBase = Test-Git $source @('rev-parse', '--short=7', $reverted)
Assert-Version (Plan $reverted $pack) $revertedBase $revertedBase
$unverified = Write-Commit $source 'docs/build.md' 'unverified change'
$unverifiedBase = Test-Git $source @('rev-parse', '--short=7', $unverified)
Assert-Version (Plan $unverified $pack) $unverifiedBase $unverifiedBase
Write-Host 'PASS Alpha family selection, exact-source deduplication, and suspend input guards'
} finally {
if (Test-Path -LiteralPath $fixture) {
$resolved = (Resolve-Path -LiteralPath $fixture).Path
if ($resolved -ne $fixture -or (Split-Path -Parent $resolved) -ne $root) {
throw "Unexpected test fixture path: $resolved"
}
Remove-Item -LiteralPath $resolved -Recurse -Force
}
}
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Exercise the batched queries and their failure handling without a package database.
set -euo pipefail
helper="$(dirname "$0")/read-msys2-package-metadata.sh"
mode=ok
pacman() {
case "$*" in
'-Qo -- /clang64/bin/a.dll /clang64/bin/local.dll /clang64/bin/b.dll')
echo '/clang64/bin/a.dll is owned by same-package 2:1.0-3'
echo 'error: No package owns /clang64/bin/local.dll' >&2
echo '/clang64/bin/b.dll is owned by same-package 2:1.0-3'
case $mode in
query-failure) echo 'error: invalid local database' >&2; return 2 ;;
wrong-status) return 0 ;;
esac
return 1
;;
'-Ql -- same-package')
echo 'same-package /clang64/bin/a.dll'
echo 'same-package /clang64/share/licenses/example/'
echo 'same-package /clang64/share/licenses/example/<LICENSE> text'
if [[ $mode == list-failure ]]; then
echo 'error: failed to read package file list' >&2
return 1
fi
;;
*)
printf 'Unexpected pacman invocation: %s\n' "$*" >&2
return 255
;;
esac
}
read_metadata() (
source "$helper" "$@"
)
paths=(/clang64/bin/a.dll /clang64/bin/local.dll /clang64/bin/b.dll)
expected=$'owned\t/clang64/bin/a.dll\tsame-package\t2:1.0-3\nunowned\t/clang64/bin/local.dll\nowned\t/clang64/bin/b.dll\tsame-package\t2:1.0-3\nlicense\tsame-package\t/clang64/share/licenses/example/<LICENSE> text'
actual=$(read_metadata "${paths[@]}")
if [[ $actual != "$expected" ]]; then
printf 'Metadata did not match:\n%s\n' "$actual" >&2
exit 1
fi
[[ -z $(read_metadata) ]]
for mode in query-failure wrong-status list-failure; do
if read_metadata "${paths[@]}" >/dev/null 2>&1; then
printf 'Accepted an unexpected pacman failure: %s\n' "$mode" >&2
exit 1
fi
done
printf 'MSYS2 package metadata checks passed\n'
+54
View File
@@ -0,0 +1,54 @@
# Alpha 运行时编号与挂起兼容性规范
本规范用于 Windows 便携运行时的 Alpha 发布。主编号表示挂起兼容边界,`-pN` 表示同一主编号下的发布修订。
## 编号规则
| 变更判定 | 发布编号 | 旧挂起文件 |
| :--- | :--- | :--- |
| 同一主编号下首次发布 | `runtime-a1b2c3d` | 作为该主编号的兼容基线 |
| 交付内容有变更,旧挂起文件仍可用新版恢复 | `runtime-a1b2c3d-p1`、`runtime-a1b2c3d-p2`,按顺序递增 | 支持从该主编号下已验证的早期版本升级恢复 |
| 直接修改挂起或恢复逻辑、影响挂起功能,或暂时无法确认兼容 | `runtime-d4e5f6a`,使用新的主编号 | 新版拒绝加载上一主编号的挂起文件 |
同一版本的发布标识、归档名称和 `manifest.json` 的 `commit` 使用同一份编号。`full_commit` 和 `vendor_qemu_commit` 分别记录实际构建所用的运行时与 QEMU 完整提交。`-pN` 递增时,源码记录随实际构建更新。发布过的主编号和修订号不得换包或重新分配。
新主编号采用新兼容基线对应的运行时提交短 SHA。若不兼容变更来自打包仓库或依赖补丁,先在运行时维护分支提交新的兼容基线记录,再以该提交生成新主编号。
## 兼容性判定
发布前比较上一版实际交付的运行时、QEMU、依赖补丁、固件和启动参数。仅在确认新版能读取旧挂起状态,并验证恢复后虚拟机可继续运行时,才能沿用主编号。
- **可以沿用主编号的场景** 包括下载、日志或打包调整。前提是这些调整没有改变挂起所用的文件、启动配置或恢复行为,并通过跨版本恢复验证。
- **必须更换主编号的场景** 包括挂起保存、状态写入、恢复加载和相关校验逻辑的变更。迁移流或设备状态的格式、版本有变,以及 QEMU、WHPX、vGPU 或依赖调整会影响挂起功能时,也必须更换主编号。默认机型、CPU 特性、设备布局、固件、RAM 映射、磁盘控制器、QMP 恢复顺序和介质校验规则的变更也要纳入判定。
- **影响不明确时使用新主编号。** 目录名和提交标题可用于定位审查范围。变更实际触达的状态和跨版本恢复结果决定能否沿用主编号。
例如,网络修复需要核对它是否改动可迁移网卡、网络设备状态或恢复顺序。只修改网络相关文件仍需完成这项检查。
## 客户端恢复契约
客户端将发布标识用于下载、安装和定位归档。跨修订恢复使用清单中明确声明的挂起兼容标识,并在保存挂起时将该标识写入记录。获得同一兼容标识的发布必须符合本规范的同主编号规则。客户端仍要验证挂起记录的格式、虚拟硬件配置、附加介质和状态文件完整性。
清单和挂起记录使用 `suspend_compat_id` 保存挂起兼容标识,其值为发布编号中 `-pN` 前的主编号。打包提交记录在清单的 `packaging_commit` 中。
不兼容的挂起文件应在启动 QEMU 加载前被拦截。客户端保留原挂起状态,并提示用户选择原运行时重新恢复,或在用户明确放弃挂起后冷启动。
现有 Reims-Go 校验会比较 `vendor_qemu_commit` 和完整的运行时编号。即使 QEMU 提交相同,`a1b2c3d` 与 `a1b2c3d-p1` 的完整编号也会触发拒绝。客户端支持明确的兼容标识后,Alpha 才可向使用该客户端的用户承诺跨 `-pN` 恢复。缺少兼容标识的旧记录继续使用原有校验。若要承诺旧记录可以升级恢复,必须另行验证并明确列出可接受的旧运行时和 QEMU 提交组合。 [现有运行时校验](https://github.com/Nwflower/Reims-Go/blob/08b3089569b2f3a705e06fbe6d37846c7faf7d47/internal/macos/reims/suspend.go#L159-L189) · [挂起文件及介质校验](https://github.com/Nwflower/Reims-Go/blob/08b3089569b2f3a705e06fbe6d37846c7faf7d47/internal/macos/reims/suspend_transaction.go#L139-L184)
## 发布验证
1. **确认比较基线。** 记录旧包和新包的发布标识、运行时与 QEMU 完整提交、依赖和补丁变更,以及本次编号判定。
2. **沿用主编号。** 在虚拟机副本上,用旧包正常运行并挂起,再切到新版恢复。核对桌面和原应用状态、磁盘可写性及受影响的设备。验证上一修订和本系列最早承诺可升级的版本,并覆盖这次受影响的宿主或后端。
3. **更换主编号。** 用上一主编号的挂起记录确认新版在加载前拦截,并验证新版能冷启动及完成自己的挂起与恢复。保留测试证据和可用于恢复旧状态的原运行时。
4. **确认发布。** 核对编号与运行时清单、校验和、源码附件和 Release 说明。Alpha 经 CI 构建和检查后以预发布交付,正式版由人工确认和发布。 [Alpha 构建流程](../../.github/workflows/runtime-preview.yml)
## 自动编号的验证记录
沿用主编号前,在触发构建的提交末尾记录已验证的上一修订、另一侧的完整提交和验收记录链接。运行时分支提交记录打包提交,打包变更和手动重建由打包提交记录运行时提交。
```text
Suspend-Compatible-With: runtime-a1b2c3d-p2
Suspend-Verified-Inputs: 0123456789abcdef0123456789abcdef01234567
Suspend-Verification: https://example.com/runtime-resume-check
```
CI 使用最新已发布且声明兼容标识的运行时作为验证基线,该版本还必须是所属主编号下的最高修订。运行时和打包输入必须与该次验证对应。QEMU 指针、挂起相关源码或依赖补丁变化会要求新主编号。没有满足这些条件的验证记录时,CI 按新主编号处理。若运行时提交已发布且本次只是更换打包输入,先提交新的运行时基线,再发布。
+5
View File
@@ -0,0 +1,5 @@
{
"capabilities": [
"window-release-shortcut"
]
}