build: keep portable runtime tooling in the runtime repository

This commit is contained in:
YXC0915 committed 2026-12-01 11:19:50 +08:00
1 parent 5f96f4ab08
commit e6c8388c37
20 files changed
+27 -2670

No files matched your search

-288
View File
@@ -1,288 +0,0 @@
name: Build Portable Runtime (Alpha)
# The runtime fork calls this workflow to build and publish previews.
# A manual run in Reims-Go builds artifacts for verification.
on:
workflow_call:
inputs:
upstream_commit:
type: string
default: ""
publish:
type: boolean
default: false
rebuild:
type: boolean
default: false
workflow_dispatch:
inputs:
upstream_commit:
description: "Reims vGPU fork commit (empty = runtime branch HEAD)"
required: false
default: ""
publish:
description: "Publish a preview when run in the runtime fork"
type: boolean
default: false
rebuild:
description: "Build a new patch revision (runtime-<commit>-pN) even if this upstream commit is already released"
type: boolean
default: false
permissions:
contents: read
concurrency:
group: build-runtime
cancel-in-progress: false
env:
UPSTREAM_URL: https://github.com/yxc0915/reims-vgpu.git
UPSTREAM_BRANCH: codex/intel-vm-suspend
jobs:
resolve:
runs-on: ubuntu-latest
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 }}
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
fi
echo "skip=$skip" >> "$GITHUB_OUTPUT"
echo "suffix=$suffix" >> "$GITHUB_OUTPUT"
build:
needs: resolve
if: needs.resolve.outputs.skip != 'true'
runs-on: windows-latest
timeout-minutes: 150
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
repository: ${{ job.workflow_repository }}
ref: ${{ job.workflow_sha }}
persist-credentials: false
- name: Setup MSYS2 CLANG64
id: msys2
uses: msys2/setup-msys2@v2
with:
msystem: CLANG64
update: true
install: >-
git 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-mesa mingw-w64-clang-x86_64-vulkan-loader
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
- name: Check out the runtime forks and apply dependency patches
id: patches
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$work = Join-Path $env:RUNNER_TEMP 'reims-vgpu'
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]
}
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' }
$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).
$resultFile = Join-Path $env:RUNNER_TEMP 'patches.json'
try {
pwsh -NoProfile -File scripts/apply-patch-series.ps1 -ReimsRepo $work -UtilRepo $utilRepo -Metal2VulkanRepo $m2vRepo -ResultFile $resultFile
$ok = $LASTEXITCODE -eq 0
} finally {
if (Test-Path $resultFile) {
$r = Get-Content -Raw $resultFile | ConvertFrom-Json
"merged=$(@($r.merged) -join ',')" >> $env:GITHUB_OUTPUT
"APPLIED_PATCHES=$(@($r.applied) -join ',')" >> $env:GITHUB_ENV
}
}
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"]
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
"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
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
# Upstream's own non-interactive CLANG64 build script.
bash scripts/install-ctl.sh --yes
util_repo="$(cygpath -u "$REIMS_UTIL_DIR")"
if [[ -n "$(git -C "$util_repo" status --porcelain)" ]]; then
toolchain="$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)"
export PATH="$(cygpath -u "$CARGO_HOME")/bin:$PATH"
CC=clang CXX=clang++ AR=llvm-ar cargo +"$toolchain-x86_64-pc-windows-gnullvm" install \
--locked --force --root "$CARGO_HOME" --path "$REIMS_UTIL_DIR"
fi
- name: Package alpha runtime and source archives
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$outDir = Join-Path $env:RUNNER_TEMP 'releases'
New-Item -ItemType Directory -Force -Path $outDir | Out-Null
# 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 { $_ })
& ./scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-UtilRepo $env:REIMS_UTIL_DIR `
-Metal2VulkanRepo $env:METAL2VULKAN_DIR `
-CargoHome $env:CARGO_HOME `
-QemuDir (Join-Path $env:XDG_DATA_HOME 'reims-ctl\qemu\current') `
-Msys2 '${{ steps.msys2.outputs.msys2-location }}' `
-OutDir $outDir `
-TempRoot $env:RUNNER_TEMP `
-Channel alpha `
-ReleaseId $env:RELEASE_ID `
-Patches $applied
- name: Alpha entry gate
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
& ./scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID -RequireSlim -RequiredCapability vm-suspend `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
- name: Upload alpha artifacts
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
- name: Publish alpha prerelease (never stable)
if: github.repository == 'yxc0915/reims-vgpu' && inputs.publish
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
MERGED: ${{ steps.patches.outputs.merged }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$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 $_ }
$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 { '' }
$notes = @"
**Alpha** runtime (``$c``), built from [the Reims vGPU fork@$short]($sourceRepo/commit/${{ needs.resolve.outputs.commit }}).
Not smoke-tested on a real host. It becomes stable only after ``scripts/smoke-runtime.ps1`` passes on a real Windows host and a person approves (portable-runtime-spec.md section 6).
Local patches applied (sources and patches are in the attached source packages):
$applied$merged
The optional ``reims-runtime-symbols-$c.tar.zst`` contains matching debug files for crash analysis.
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
if ($LASTEXITCODE) { throw "gh release create failed ($LASTEXITCODE)" }
+4 -4
View File
@@ -8,7 +8,7 @@
与上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的分工:
- **`reims-vgpu`**:底层引擎(QEMU 分支、`reims-graphics-pci`、`metal2vulkan`、`reims-ctl`、`reims-util`)。
- **`reims-go`(本仓库)**:桌面应用、命令行包装与便携运行时打包/分发流水线,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
- **`reims-go`(本仓库)**:桌面应用、命令行包装与运行时下载管理,提供开箱即用的环境体检、离线装机、硬件调优、Guest Tools、恢复点与 CoW 派生能力。
## 存储与产物边界
@@ -32,7 +32,7 @@
- 用户显式要求工单,或任务需要跨会话恢复、多人/多 Agent 交接、持续积累验收证据时,再通过 `work.mjs` 建立或复用工单。
- 一次性产物用 `node scripts/debug/tmp.mjs new <label>` 或 `run <label> -- <command>`(向子进程注入 `REIMS_TMP_DIR`):正常结束(退出码 0)自动删除目录,失败保留证据供排查;超期(24 小时)且属主进程已退出的残留由 `gc --yes` 回收,存活进程与符号链接/Junction 受保护。
- 工单按 `draft → active → review → close` 流转;`close` 校验通过后删除整个工单目录。
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md`、`docs/` 与 `patches/README.md` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
- **持久文档零引用**:`README.md`、`README.en.md`、`CHANGELOG.md`、`AGENTS.md` 与 `docs/` 严禁引用具体工单 ID 或 `.debug/tmp/` 会话实例路径。
| 命令 | 用途 |
| :--- | :--- |
@@ -50,7 +50,7 @@
1. **上游行为以一手源码为准**:引用 `reims-ctl` / `reims-vgpu` 行为时核对对应上游 commit 与 `文件:行号`;未实测项显式标注「待验证」。
2. **人工确认红线**:UAC 提权启用 WHPX、重启 Windows、macOS 图形安装向导、向上游提交 PR、将运行时升级为 `stable` 正式发布,均须由人确认触发。自动化例外:Reims vGPU fork 的 Preview 工作流每天构建,通过 `alpha` 准入检查后在运行时仓库发布 GitHub 预发布。
3. **敏感与专有内容零入库**:严禁提交 SMC OSK、SMBIOS 真实序列号、MAC 地址、任何 Apple IPSW / BaseSystem / 解密固件或闭源二进制。
4. **运行时源码与依赖补丁**:Reims vGPU 和 QEMU 的源码修改由各自运行时 fork 维护。客户端构建使用 [`patches/series.txt`](patches/series.txt) 应用其余依赖补丁。源码入口、顺序与状态见 [`patches/README.md`](patches/README.md)。补丁打不上就停下报告,不要自动改写补丁。
4. **构建职责**:本仓库构建并发布客户端。便携运行时的编译、打包、依赖补丁和 Preview 发布由 [Reims vGPU fork 的 CI](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 负责。
5. **运行时包如实声明来源**:`manifest.json` 必须写清上游各仓库 commit 与实际应用的全部补丁;带补丁的包不得宣称为纯上游构建。
6. **默认用户只拿 `stable` 通道**:CI 产物先入 `alpha`,经真实宿主冒烟并人工确认后才升为 `stable`(见 [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md))。
7. **配置写入只走 `reims-ctl set`**:不直接改写 `vm.toml`,保证上游校验与 OpenCore 重建生效(见 [`docs/design-guidelines.md`](docs/design-guidelines.md))。
@@ -71,4 +71,4 @@
- [`docs/design-guidelines.md`](docs/design-guidelines.md) — 产品与界面设计规范(配置原语、状态模型、视觉与文案)
- [`docs/portable-runtime-spec.md`](docs/portable-runtime-spec.md) — 便携运行时打包、发布通道与合规规范
- [`docs/plugin-architecture.md`](docs/plugin-architecture.md) — 插件系统架构与扩展接口规范
- [`patches/README.md`](patches/README.md) — 上游临时补丁队列与 PR 跟踪
- [运行时补丁与上游跟踪](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md) — 运行时源码入口与依赖补丁
+3 -2
View File
@@ -3,8 +3,9 @@
`Reims-Go` itself (Go backend and desktop frontend) is licensed under the Apache
License, Version 2.0 (see `LICENSE`). That license applies to Reims-Go's own code
only and is separate from the portable runtime bundle it invokes as an external
child process. Local compatibility patches under `patches/` are licensed under
terms compatible with their target upstream projects (see `patches/LICENSE`).
child process. Compatibility patches in the runtime repository are licensed
under terms compatible with their target upstream projects (see [runtime patch
licenses](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/LICENSE)).
The Reims-Go desktop executable also incorporates open-source Go and frontend
libraries (including Wails, React, Radix UI, Lucide, Inter font, Go `golang.org/x`
-1
View File
@@ -70,7 +70,6 @@ flowchart TB
| `internal/config`、`internal/i18n` | 应用配置持久化(`reims-go.json`)、轻量 ICU 格式化引擎、多跳语言回退链与带稳定排障码的结构化错误(`CodedError`) |
| `internal/thumb`、`internal/tray`、`internal/version` | 4K 截屏行级缩放预览、Windows 系统托盘常驻、版本信息与新版本检查 |
| `frontend/src` | 桌面界面:`components/`(页面与对话框)、`ui/`(Radix 基件封装)、`lib/`(格式化、日志与任务)、`styles/`(设计令牌) |
| `patches/` | 上游临时补丁队列与 PR 跟踪,见 [`patches/README.md`](../patches/README.md) |
| `scripts/` | 便携运行时打包、二进制裁剪与符号分离、MSYS2 源码归档、`alpha` 准入与冒烟脚本,以及 `scripts/debug/` 本地调试目录管理与卫生校验脚本 |
---
+2 -2
View File
@@ -1,7 +1,7 @@
# 插件系统架构(Plugin Architecture)
> 状态:**核心内核、内置扩展、主题引擎、Sidecar 托管与 CLI/GUI 管理已落地**;市场远端索引与 L2 脚本层按需迭代。
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md) · [`patches/README.md`](../patches/README.md)
> 关联文档:[`architecture.md`](architecture.md) · [`design-guidelines.md`](design-guidelines.md) · [`portable-runtime-spec.md`](portable-runtime-spec.md)
---
@@ -276,7 +276,7 @@ UI 槽位采用「声明即占有」:宿主预定义 `vm.toolbar`、`vm.card`
| 类别 | 归属 | 原则 |
| :--- | :--- | :--- |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [`patches/`](../patches/)(编译期) | 外部插件无法等价替代;坚持上游 PR,合入即退役 |
| 引擎内部崩溃与 Hypervisor 层修复(WHPX 兼容、协程、构建锁文件等) | [运行时源码与补丁](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)(编译期) | 外部插件无法等价替代,修复交由运行时仓库维护 |
| 窗口内部消息循环拦截(如 SDL 窗口内字符消息) | `patches/`,宿主侧做部分补偿 | 跨进程拦截需 DLL 注入,杀软误报风险高,不做成插件 |
| 宿主侧绕过、兜底补偿与宿客桥接 | 内置扩展(§5.4) | 运行时缺少对应补丁时平滑降级;依据运行时 `capabilities` 判断 |
+14 -16
View File
@@ -39,7 +39,7 @@ reims-runtime-<commit>/
### 2.2 裁剪与调试符号分离
打包脚本 [`scripts/stage-runtime-binaries.ps1`](../scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
运行时仓库的 [`stage-runtime-binaries.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/stage-runtime-binaries.ps1) 执行两项体积优化,在缩小下载体积的同时保留完整调试能力:
1. **裁剪非必要工具与异架构固件**:仅移除 Windows x64 启动器不会调用的 `qemu-system-x86_64w.exe`、`elf2dmp.exe`、`qemu-edid.exe`、`qemu-io.exe`、`qemu-nbd.exe`、`qemu-storage-daemon.exe`,以及 ARM64、RISC-V、LoongArch64 的 EDK2 固件与描述文件;完整保留 x64 固件、BIOS、ROM、keymaps、动态加载的 `libva` 视频驱动与全部 DLL。
2. **独立发布调试符号**:使用 MSYS2 CLANG64 的 `llvm-objcopy` 从 5 个主可执行文件(`reims-ctl.exe`、`reims-util.exe`、`qemu-system-x86_64.exe`、`qemu-img.exe`、`reims-vgpu-compile.exe`)提取 `.debug` 符号并写入 GNU debug link,打包为同 Release 下的 `reims-runtime-symbols-<commit>.tar.zst`(客户端默认不下载符号包)。`manifest.json` 记录最终剥离后可执行文件的 SHA-256。
@@ -73,23 +73,23 @@ reims-runtime-<commit>/
## 3. 打包与 CI 自动构建
### 3.1 本地打包
运行 `pwsh -File scripts/pack-runtime.ps1 -Channel alpha` 一次产出以下发布附件:
### 3.1 运行时发布附件
运行时仓库的 [`pack-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-runtime.ps1) 产出以下发布附件。
1. `reims-runtime-win-x64-<commit>.tar.zst`(运行时主体)
2. `reims-runtime-symbols-<commit>.tar.zst`(独立调试符号包)
3. `reims-runtime-src-<commit>.tar.zst`(运行时源码、依赖补丁和重建说明)
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 生成)
4. `reims-runtime-msys2-src-<commit>.tar.zst`(MSYS2 copyleft DLL 源码包,由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 生成)
5. `SHA256SUMS.txt`(覆盖上述压缩包的统一校验清单)
打包前脚本会核对构建目录的 `git diff` 是否与声明的补丁逐字节一致;存在未声明修改或补丁不匹配时立即停止。
### 3.2 每日 CI 构建
Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 每日调用 [Reims-Go 的运行时构建工作流](../.github/workflows/build-runtime.yml),也支持手动指定提交。在 `windows-latest`(MSYS2 CLANG64)执行以下步骤。
Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/blob/master/.github/workflows/runtime-preview.yml) 每日构建,也支持手动指定提交。工作流从运行时仓库读取打包脚本和依赖补丁,在 `windows-latest`(MSYS2 CLANG64)执行以下步骤。
1. 读取 Reims vGPU fork 的运行时分支,并检出其中固定的 QEMU fork 提交。若该 Reims vGPU 提交已有运行时 Release,则跳过。
2. 按 [`patches/series.txt`](../patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。
3. 执行上游 `scripts/install-ctl.sh --yes` 编译,调用 `scripts/pack-runtime.ps1 -Channel alpha` 打包。
4. 运行 [`scripts/check-runtime-alpha.ps1`](../scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。
5. 通过后在 Reims vGPU fork 的 Releases 发布 Preview,标记为 GitHub 预发布(`alpha`)。从 Reims-Go 仓库发起的手动构建提供 CI 产物供验证。
2. 按 [`series.txt`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/series.txt) 顺序为固定的依赖版本应用补丁。已合入上游的补丁会跳过并报告,遇到冲突时中止构建。
3. 运行 Reims vGPU 源码中的 `scripts/install-ctl.sh --yes` 编译,再调用运行时仓库的打包脚本。
4. 运行 [`check-runtime-alpha.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/check-runtime-alpha.ps1) 校验附件哈希、许可证、挂起能力声明,以及在不含 MSYS2 的 `PATH` 下验证 vGPU 设备枚举、CLI 版本和 `qcow2` 创建读取。
5. 通过后在 Reims vGPU fork 的 Releases 发布 Preview,标记为 GitHub 预发布(`alpha`)。手动构建可通过 `publish=false` 仅下载 CI 产物进行验证。
> **CI 边界**:GitHub 托管的 Windows Server runner 不提供 WHPX,也无法复现 Windows 10 兼容性问题。CI 只验证可编译与控制面基本可用,实际能否启动 macOS 桌面必须经过第 5 节的真机冒烟。
@@ -100,9 +100,7 @@ Reims vGPU fork 的 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/bl
## 4. 补丁队列
Reims vGPU 和 QEMU 的修改由各自的运行时 fork 维护。客户端仓库在 [`patches/`](../patches/) 维护其他运行时依赖的补丁。源码和补丁入口如下。
- 机器清单:[`patches/series.txt`](../patches/series.txt)
- 维护文档:[`patches/README.md`](../patches/README.md)
Reims vGPU 和 QEMU 的修改由各自的 fork 维护。Reims vGPU fork 的 [依赖补丁目录](https://github.com/yxc0915/reims-vgpu/tree/master/packaging/windows-runtime/patches) 保存构建时应用的补丁与维护说明。
运行时包的 `manifest.json` 记录源码仓库、提交、运行时能力及打包时应用的依赖补丁和哈希。
@@ -114,8 +112,8 @@ Reims vGPU 和 QEMU 的修改由各自的运行时 fork 维护。客户端仓库
| 通道 | GitHub Release 形态 | 准入条件 |
| :--- | :--- | :--- |
| **`alpha`** | 预发布(Pre-release) | CI 每日自动构建并通过 `scripts/check-runtime-alpha.ps1` 全部校验 |
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升:在真实 Windows 10/11 宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
| **`alpha`** | 预发布(Pre-release) | 运行时 CI 自动构建并通过 Alpha 准入检查 |
| **`stable`** | 正式发布(Release) | 从 `alpha` 晋升。在真实 Windows 10/11 宿主运行 [`smoke-runtime.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/smoke-runtime.ps1),验证纯净目录 `doctor`、启动至 macOS 桌面、截屏与正常关机,经人工确认后晋升 |
- 客户端默认仅获取 `stable` 通道;`alpha` 需用户在界面开启「接收 Alpha 版」或在 CLI 传入 `--alpha`。
- 晋升 `stable` 时,在运行时仓库将已通过冒烟的 Preview 改为正式 Release,并移除标题中的 Alpha 标记。保留原资产、校验清单和 `manifest.json` 的构建通道。
@@ -129,6 +127,6 @@ Reims-Go 本体(Go 后端与前端外壳)采用 [Apache-2.0](../LICENSE) 协
由于便携运行时包含 GPLv2(QEMU)、`GPL-2.0-or-later OR LGPL-3.0-or-later`(`reims-vgpu` / `reims-ctl` / `metal2vulkan`)以及 MSYS2 CLANG64 / libva 动态库,每个公开运行时 Release **必须同处附带完整对应源码与许可证文本**:
1. **上游源码包(`reims-runtime-src-<commit>.tar.zst`)**:导出所用 commit 的四个上游仓库源码树、构建所需的 QEMU meson 子项目、`patches/` 中的全部补丁原文及重建说明。
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`scripts/pack-msys2-sources.ps1`](../scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](../NOTICE.md) 与 `licenses/` 全文。
2. **MSYS2 copyleft 源码包(`reims-runtime-msys2-src-<commit>.tar.zst`)**:由 [`pack-msys2-sources.ps1`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/scripts/pack-msys2-sources.ps1) 根据本机 pacman 元数据自动筛选全部无宽松替代协议的 GPL / LGPL / MPL 依赖包,下载官方 `.src.tar.zst` 并使用 `gpgv` 与 MSYS2 密钥逐一验签,同时附带 `MSYS2-PACKAGES.txt` 说明全部 DLL 归属与许可。
3. **许可证与声明**:运行时包根目录内置 [`NOTICE.md`](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/NOTICE.md) 与 `licenses/` 全文。
4. **不含 Apple 专有文件**:任何仓库目录或运行时 Release 均不包含 macOS 安装包、恢复镜像、解密固件或 SMC 密钥;系统安装包均由用户端直连 Apple 服务器获取。
+2 -2
View File
@@ -33,12 +33,12 @@
优先打磨和验证已有能力,在 P0 任务稳定前不堆砌新子系统。
### 1. 首次装机与发版闭环
- 在 GitHub Actions 上实跑 `build-runtime.yml` 每日构建与 `alpha` 准入流程,验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
- 在运行时仓库的 [Preview CI](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml) 验证公开资产的 `manifest.json`、补丁队列与源码包一致性。
- 在多种受支持的 Windows 10 / 11、GPU 与 macOS 组合上跑通完整开箱流程(干净目录 → 体检 → 安装运行时 → 下载离线包 → 装机 → 退出恢复模式)。
- 完善中断与异常场景的故障恢复(断网续传、磁盘不足、取消 UAC、运行时损坏),确保失败后可安全重试且不残留半配置虚拟机。
### 2. 日常主力体验与上游性能跟进
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`(跟踪明细见 [patches/README.md](../patches/README.md))。
- 持续跟进上游 [`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 的 Windows 图形与窗口改进(热切全屏、无黑边窗口缩放、原生 Windows Vulkan 后端、首帧延迟优化、自由指针 `Win → Command` 映射),合入后经 `alpha` 冒烟升级至 `stable`。跟踪明细见[运行时补丁文档](https://github.com/yxc0915/reims-vgpu/blob/master/packaging/windows-runtime/patches/README.md)。
- 推动当前本地兼容性补丁上游化,并逐步清零 `patches/` 队列。
- 在真实宿主完成长时间开发负载验证(编译、浏览器、多任务、图文剪贴板、WebDAV 挂载、Windows 盘符只读共享、音频/麦克风与休眠唤醒恢复)。
- 修复 WebDAV 共享目录可经 Junction 逃逸的路径校验缺陷,并把共享目录与只读盘统一到基于 `os.Root` 的路径安全层;随后按测量结果推进小文件 I/O 优化。
-11
View File
@@ -1,11 +0,0 @@
# Licensing for `patches/`
Unlike the rest of the Reims-Go repository (which is licensed under the Apache
License, Version 2.0), patch files in this directory are intended to be applied
to and contributed back to their respective upstream repositories. To maintain
strict license compatibility with each target codebase:
- `qemu-*.patch` (targeting `vendor/qemu` / QEMU) are licensed under
**GPL-2.0-or-later**.
- `reims-*.patch` (targeting `steelbrain/reims-vgpu` or `steelbrain/reims-util`) are
dual-licensed under **GPL-2.0-or-later OR LGPL-3.0-or-later**.
-47
View File
@@ -1,47 +0,0 @@
# 运行时源码与依赖补丁
Reims-Go 独立构建桌面客户端。便携运行时使用以下源码分支。
| 组件 | 源码 | 维护范围 |
| :--- | :--- | :--- |
| Reims vGPU | [`yxc0915/reims-vgpu`](https://github.com/yxc0915/reims-vgpu/tree/codex/intel-vm-suspend) | GPU 挂起重放、窗口和 CLI 兼容性修复 |
| QEMU | [`yxc0915/qemu-reims-vgpu`](https://github.com/yxc0915/qemu-reims-vgpu/tree/codex/intel-vm-suspend) | Windows WHPX、文件迁移和设备状态保存恢复 |
Reims vGPU 分支通过 `vendor/qemu` 固定 QEMU 提交,并在 `reims-go-runtime.json` 声明运行时能力。更新 QEMU 时先把新提交推到 QEMU fork,再更新 Reims vGPU 的子模块指针。Reims-Go 构建据此记录两个源码仓库及提交号。
## 构建时应用的依赖补丁
[`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`。打包和重建流程见[便携运行时规范](../docs/portable-runtime-spec.md)。
---
## 关注中的上游 PR 与演进
跟踪仓库:[`steelbrain/reims-vgpu`](https://github.com/steelbrain/reims-vgpu) 与 [`steelbrain/reims-util`](https://github.com/steelbrain/reims-util)。
| 上游方向 / PR | 价值与影响 | 合入后的跟进动作 |
| :--- | :--- | :--- |
| `#153` 图形呈现 | Windows NVIDIA MAILBOX/FIFO 首帧优化,改善高帧率与首帧延迟 | 随每日 `alpha` 构建进入冒烟验证 |
| `#152` 平台层 | 原生 Windows Vulkan 后端,降低图形适配开销 | 升级运行时并对比帧率与稳定性 |
| `#107` 图形内存 | 采样纹理回读就地消费,减少内存拷贝 | 随运行时升级纳入 |
| `#123` 窗口体验 | `Ctrl+Alt+Enter` 运行中热切全屏 | 同步界面快捷键提示 |
| `#172` 窗口体验 | Windows 拖动窗口动态贴合,消除缩放黑边 | 验证多显示器与高 DPI 缩放 |
| `Win → Command` | 自由指针模式下 Windows 键映射 macOS Command | 合入后移除前端相关提示 |
| `reims-util` 语言参数 | 支持 `opencore --lang` 并在重建 OpenCore 时保留 `prev-lang:kbd` | 合入后可逐步简化本仓 `internal/opencore` 补丁重写 |
---
## 补丁退役检查表
每日构建会跳过已合入的等价补丁,并在日志中报告。确认后按以下步骤清理。
1. 删除 `patches/` 下对应的 `.patch` 文件,并同步更新 [`series.txt`](series.txt) 与本文件。
2. 等待下一次定时构建,或在 Reims vGPU fork 手动触发 [Preview 工作流](https://github.com/yxc0915/reims-vgpu/actions/workflows/runtime-preview.yml)。
3. 在真实宿主运行 [`scripts/smoke-runtime.ps1`](../scripts/smoke-runtime.ps1) 完成冒烟并人工确认后,将对应 Release 升级为 `stable`。
-525
View File
@@ -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)
-8
View File
@@ -1,8 +0,0 @@
# 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.
# CI (build-runtime.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
-102
View File
@@ -1,102 +0,0 @@
<#
.SYNOPSIS
Apply the patch queue in patches/series.txt to the checked-out upstream sources.
.DESCRIPTION
For each patch, in series order:
- applies cleanly -> apply it;
- already in the tree -> skip it (git apply --reverse --check passes: on a
fresh upstream clone this means merged upstream);
- neither -> stop with an error. Patches are never edited
automatically (AGENTS.md rule 4).
Writes the result as JSON to -ResultFile:
{ "applied": ["a.patch", ...], "merged": ["b.patch", ...], "conflict": "c.patch" | null }
so CI can pass the applied list to pack-runtime.ps1 (manifest states only what
was really applied, AGENTS.md rule 5) and report merged or conflicting patches.
.EXAMPLE
pwsh -File scripts/apply-patch-series.ps1 -ReimsRepo $env:RUNNER_TEMP\reims-vgpu -UtilRepo $env:RUNNER_TEMP\reims-util -Metal2VulkanRepo $env:RUNNER_TEMP\metal2vulkan -ResultFile patches.json
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ReimsRepo,
[string]$ResultFile = '',
[string]$UtilRepo = '',
[string]$Metal2VulkanRepo = ''
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$repositories = @{
'reims-vgpu' = $ReimsRepo
'vendor/qemu' = Join-Path $ReimsRepo 'vendor\qemu'
'reims-util' = $UtilRepo
'metal2vulkan' = $Metal2VulkanRepo
}
function Read-PatchSeries {
$series = Join-Path $patchesDir 'series.txt'
foreach ($line in Get-Content -LiteralPath $series) {
$t = $line.Trim()
if (-not $t -or $t.StartsWith('#')) { continue }
$parts = $t -split '\s+'
if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) {
throw "Bad line in patches/series.txt: '$line'"
}
[pscustomobject]@{ Target = $parts[0]; Name = $parts[1] }
}
}
$result = [ordered]@{ applied = @(); merged = @(); conflict = $null }
function Save-Result {
if ($ResultFile) {
[IO.File]::WriteAllText($ResultFile, ($result | ConvertTo-Json -Depth 3), [Text.UTF8Encoding]::new($false))
}
}
$series = @(Read-PatchSeries)
if (-not $UtilRepo -and $series.Target -contains 'reims-util') {
throw 'Pass -UtilRepo with a checkout at the reims-util revision pinned by reims-ctl.'
}
if (-not $Metal2VulkanRepo -and $series.Target -contains 'metal2vulkan') {
throw 'Pass -Metal2VulkanRepo with a checkout at the metal2vulkan revision pinned by reims-vgpu.'
}
foreach ($p in $series) {
$file = Join-Path $patchesDir $p.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch listed in series.txt is missing: $file" }
$dir = $repositories[$p.Target]
# git -C into a missing or uninitialised submodule falls back to the outer
# repository, where "git apply" silently skips paths outside the current
# directory and reports success. Require $dir to be its own work tree.
$top = (& git -C $dir rev-parse --show-toplevel 2>$null)
if ($LASTEXITCODE -ne 0 -or -not $top -or
[IO.Path]::GetFullPath($top.Trim()).TrimEnd([char[]]'\/') -ne [IO.Path]::GetFullPath($dir).TrimEnd([char[]]'\/')) {
throw "$dir is not a checked-out git work tree for $($p.Target)"
}
& git -C $dir apply --check $file 2>$null
if ($LASTEXITCODE -eq 0) {
& git -C $dir apply $file
if ($LASTEXITCODE -ne 0) { throw "git apply $($p.Name) failed after a clean --check" }
Write-Host "applied $($p.Target) $($p.Name)"
$result.applied += $p.Name
continue
}
& git -C $dir apply --reverse --check $file 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host "merged $($p.Target) $($p.Name) (already in the tree: merged upstream? retire it per spec section 5 rule 4)"
$result.merged += $p.Name
continue
}
$result.conflict = $p.Name
Save-Result
# Show git's own reason in the log.
& git -C $dir apply --check $file
throw "$($p.Name) neither applies nor is already upstream in $dir. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
$global:LASTEXITCODE = 0
Save-Result
-152
View File
@@ -1,152 +0,0 @@
<#
.SYNOPSIS
Entry gate for the alpha channel (portable-runtime-spec.md section 6), run by
CI on the packed release files before anything is published.
.DESCRIPTION
Fails unless all of these hold:
1. The runtime, both source packages and SHA256SUMS.txt exist. Slim
releases also require the matching detached symbols archive.
2. SHA256SUMS.txt lists all release archives and every hash matches.
3. manifest.json in the runtime names -Commit, channel "alpha", the source
package, and exactly the patches in -AppliedPatches.
4. The runtime's own qemu-system-x86_64.exe, run with a PATH holding only
the runtime and Windows (no MSYS2), lists reims-graphics-pci in
"-device help".
This is not the stable gate: promotion to stable still needs the real-host
smoke test (scripts/smoke-runtime.ps1) and a person's approval.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$OutDir,
[Parameter(Mandatory = $true)]
[string]$Commit,
[Parameter(Mandatory = $true)]
[string]$Zstd,
[string[]]$AppliedPatches = @(),
[string]$RequiredCapability = '',
[switch]$RequireSlim,
# Only for checking packages built before the 2026-11-28 rename ("candidate").
[string]$ExpectChannel = 'alpha',
[string]$TempRoot = $env:RUNNER_TEMP
)
$ErrorActionPreference = 'Stop'
$AppliedPatches = @($AppliedPatches | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
$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'
}
$symbolsName = "reims-runtime-symbols-$Commit"
if ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst"))) {
$names.symbols = "$symbolsName.tar.zst"
}
# 1. All assets for this layout.
foreach ($k in $names.Keys) {
$p = Join-Path $OutDir $names[$k]
if (-not (Test-Path -LiteralPath $p)) { throw "Missing release asset: $($names[$k])" }
}
Write-Host "PASS $($names.Count) release assets present"
# 2. Sums cover the archives and match.
$sums = @{}
foreach ($line in Get-Content -LiteralPath (Join-Path $OutDir $names.sums)) {
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') { $sums[$Matches[2].Trim()] = $Matches[1].ToLowerInvariant() }
}
foreach ($k in ($names.Keys | Where-Object { $_ -ne 'sums' })) {
$n = $names[$k]
if (-not $sums.ContainsKey($n)) { throw "SHA256SUMS.txt has no entry for $n" }
$got = (Get-FileHash -Algorithm SHA256 -LiteralPath (Join-Path $OutDir $n)).Hash.ToLowerInvariant()
if ($got -ne $sums[$n]) { throw "SHA256 mismatch for ${n}: listed $($sums[$n]), actual $got" }
}
Write-Host 'PASS SHA256SUMS.txt covers and matches all archives'
# Extract the runtime.
$work = Join-Path $TempRoot ("alpha-gate-" + [guid]::NewGuid())
New-Item -ItemType Directory -Force -Path $work | Out-Null
try {
$tar = Join-Path $work 'runtime.tar'
& $Zstd -d -q -f (Join-Path $OutDir $names.runtime) -o $tar
if ($LASTEXITCODE -ne 0) { throw "zstd failed ($LASTEXITCODE)" }
# Windows' own bsdtar: GNU tar from Git/MSYS2 reads "D:" as a remote host.
& (Join-Path $env:SystemRoot 'System32\tar.exe') -xf $tar -C $work
if ($LASTEXITCODE -ne 0) { throw "tar failed ($LASTEXITCODE)" }
Remove-Item -LiteralPath $tar -Force
$root = Join-Path $work "reims-runtime-win-x64-$Commit"
# 3. Manifest states what was really built.
$m = Get-Content -Raw -LiteralPath (Join-Path $root 'manifest.json') | ConvertFrom-Json
if ($m.commit -ne $Commit) { throw "manifest commit is $($m.commit), expected $Commit" }
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" }
$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)
if ($m.raw_bytes -ne $rawBytes) { throw "manifest raw_bytes is $($m.raw_bytes), actual $rawBytes" }
$declared = @($m.patches | ForEach-Object { $_.name })
if (($declared -join ',') -ne ($AppliedPatches -join ',')) {
throw "manifest patches [$($declared -join ', ')] differ from those applied [$($AppliedPatches -join ', ')]"
}
Write-Host "PASS manifest: commit $Commit, channel $($m.channel), patches [$($declared -join ', ')]"
if ($m.symbols_package -or $names.symbols) {
if (!$names.symbols -or $m.symbols_package -ne $names.symbols) { throw 'Missing or mismatched symbols package' }
$symTar = Join-Path $work 'symbols.tar'
& $Zstd -d -q -f (Join-Path $OutDir $names.symbols) -o $symTar
if ($LASTEXITCODE) { throw 'Cannot decompress symbols package' }
$members = & (Join-Path $env:SystemRoot 'System32\tar.exe') -tf $symTar
if ($LASTEXITCODE) { throw 'Cannot list symbols package' }
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" }
if ("$symbolsName/$rel.debug" -notin $members) { throw "Missing debug file 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, detached debug members and video driver files'
}
# 4. QEMU runs from the bundle alone and has the reims device.
$qemuBin = Join-Path $root 'qemu\bin'
$psi = [Diagnostics.ProcessStartInfo]::new((Join-Path $qemuBin 'qemu-system-x86_64.exe'), '-device help')
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.WorkingDirectory = $qemuBin
$psi.Environment['PATH'] = "$qemuBin;$env:SystemRoot\System32;$env:SystemRoot"
$proc = [Diagnostics.Process]::Start($psi)
$errTask = $proc.StandardError.ReadToEndAsync()
$out = $proc.StandardOutput.ReadToEnd()
if (-not $proc.WaitForExit(120000)) { $proc.Kill(); throw 'qemu -device help timed out' }
$err = $errTask.Result
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) {
$oldPath = $env:PATH
$img = Join-Path $qemuBin 'qemu-img.exe'
try {
$env:PATH = $psi.Environment['PATH']
foreach ($exe in 'reims-ctl.exe','reims-util.exe') {
& (Join-Path $root "bin/$exe") --version
if ($LASTEXITCODE) { throw "$exe --version failed ($LASTEXITCODE)" }
}
$disk = Join-Path $work 'test.qcow2'
& $img create -f qcow2 $disk 32M
if ($LASTEXITCODE) { throw "qemu-img create failed ($LASTEXITCODE)" }
$info = & $img info --output=json $disk
if ($LASTEXITCODE -or (($info -join "`n" | ConvertFrom-Json).'virtual-size' -ne 32MB)) { throw 'qemu-img info failed' }
} finally { $env:PATH = $oldPath }
Write-Host 'PASS CLI versions and qcow2 creation / inspection (no MSYS2 on PATH)'
}
} finally {
Remove-Item -Recurse -Force -LiteralPath $work -ErrorAction SilentlyContinue
}
+1 -1
View File
@@ -72,7 +72,7 @@ function overlaps(left, right) {
}
export function collectDurableDocs(storage) {
const docs = ['README.md', 'README.en.md', 'CHANGELOG.md', 'AGENTS.md', 'patches/README.md']
const docs = ['README.md', 'README.en.md', 'CHANGELOG.md', 'AGENTS.md']
const docsDir = path.join(storage, 'docs')
if (fs.existsSync(docsDir)) {
const walk = (dir, prefix) => {
+1 -1
View File
@@ -21,7 +21,7 @@
## 退役
- [ ] 值得保留的探针已沉淀为 `*_test.go` 或 `scripts/` 正式脚本
- [ ] 需要同步的持久文档(`CHANGELOG.md`、`docs/`、`patches/README.md` 等)已更新,且不含本工单 ID
- [ ] 需要同步的持久文档(`CHANGELOG.md`、`docs/` 等)已更新,且不含本工单 ID
- [ ] 每条测量都有明确去处(`code`、`test`、`comment`、`doc` 或 `none`)
- [ ] `node scripts/debug/check.mjs` 通过,验证记录已补齐
- [ ] 本目录已由 `node scripts/debug/work.mjs close {{ID}}` 删除
-171
View File
@@ -1,171 +0,0 @@
<#
.SYNOPSIS
Pack the sources of the copyleft MSYS2 packages whose DLLs a runtime bundles,
as a separate release asset.
.DESCRIPTION
Reads the "# Packages" list from a runtime's MSYS2-PACKAGES.txt, looks up each
package's source name (%BASE%) and licenses in the local pacman database, and
keeps the packages whose license requires source (GPL / LGPL / MPL) unless an
alternative licence without those can be chosen (for example "GPL OR FTL").
For each kept package it downloads <base>-<version>.src.tar.zst and its .sig
from repo.msys2.org (cached in -CacheDir), checks the signature against the
MSYS2 keyring with gpgv, and packs them into
reims-runtime-msys2-src-<commit>.tar.zst in -OutDir. The archive's hash is
added to -OutDir\SHA256SUMS.txt (an existing line for it is replaced).
Published in the same GitHub Release as the runtime, so the sources are
offered from the same place as the binaries (GPLv2 §3, LGPL-2.1 §6).
.EXAMPLE
pwsh -File scripts/pack-msys2-sources.ps1 -PackagesFile MSYS2-PACKAGES.txt -Commit 3731afd -OutDir D:\Data\reims-go\releases\3731afd-candidate
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$PackagesFile,
[Parameter(Mandatory)] [string]$Commit,
[Parameter(Mandatory)] [string]$OutDir,
[string]$Msys2 = 'D:\DevTools\msys64',
[string]$CacheDir = 'D:\Data\reims-go\releases\msys2-sources-cache',
[string]$TempRoot = 'D:\Build\Temp',
[string]$Mirror = 'https://repo.msys2.org/mingw/sources'
)
$ErrorActionPreference = 'Stop'
$localDb = Join-Path $Msys2 'var\lib\pacman\local'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$zstd = Join-Path $Msys2 'usr\bin\zstd.exe'
function Write-Utf8([string]$path, [string]$text) {
[IO.File]::WriteAllText($path, $text.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Read-Desc([string]$name, [string]$version) {
$file = Join-Path $localDb "$name-$version\desc"
if (-not (Test-Path -LiteralPath $file)) {
throw "$name $version is not in the local pacman database ($file): was MSYS2 updated after the runtime was built?"
}
$fields = @{}
$key = $null
foreach ($line in Get-Content -LiteralPath $file) {
if ($line -match '^%(\w+)%$') { $key = $Matches[1]; $fields[$key] = @(); continue }
if ($key -and $line -ne '') { $fields[$key] += $line }
}
return $fields
}
# A licence entry needs source unless one OR-alternative is free of copyleft.
# Entries prefixed "documentation:" cover only docs, which aren't shipped.
function Test-NeedsSource([string[]]$licenses) {
foreach ($entry in $licenses) {
if ($entry -like 'documentation:*') { continue }
$expr = $entry -replace '^spdx:', ''
$alternatives = $expr -split '\s+OR\s+'
$allCopyleft = $true
foreach ($alt in $alternatives) {
if ($alt -notmatch 'GPL|MPL') { $allCopyleft = $false }
}
if ($allCopyleft) { return $true }
}
return $false
}
function To-MsysPath([string]$winPath) {
$p = $winPath -replace '\\', '/'
if ($p -match '^([A-Za-z]):(.*)$') { return '/' + $Matches[1].ToLower() + $Matches[2] }
return $p
}
# ── 1. Which packages need source ────────────────────────────
$text = Get-Content -Raw -LiteralPath $PackagesFile
$section = ($text -split '# Packages[^\n]*\n', 2)[1]
if (-not $section) { throw "No '# Packages' section in $PackagesFile" }
$packages = $section -split "`n" | Where-Object { $_ -match '^\S+ \S+$' } | ForEach-Object {
$n, $v = $_ -split ' '
$d = Read-Desc $n $v
[pscustomobject]@{
Name = $n
Version = $v
Base = $d['BASE'][0]
Licenses = $d['LICENSE']
Needs = (Test-NeedsSource $d['LICENSE'])
}
}
$needed = @($packages | Where-Object Needs | Sort-Object Base, Version -Unique)
Write-Host ("==> {0} of {1} packages need source; {2} source archives" -f @($packages | Where-Object Needs).Count, $packages.Count, $needed.Count)
# ── 2. Download and verify ───────────────────────────────────
New-Item -ItemType Directory -Force -Path $CacheDir, $OutDir | Out-Null
foreach ($p in $needed) {
$file = "$($p.Base)-$($p.Version).src.tar.zst"
foreach ($f in @($file, "$file.sig")) {
$dest = Join-Path $CacheDir $f
if (-not (Test-Path -LiteralPath $dest)) {
Write-Host " downloading $f"
Invoke-WebRequest -Uri "$Mirror/$f" -OutFile "$dest.part" -UserAgent 'reims-go-packager'
Move-Item -LiteralPath "$dest.part" -Destination $dest -Force
}
}
$cache = To-MsysPath $CacheDir
$out = & $bash -lc "LC_ALL=C gpgv --keyring /etc/pacman.d/gnupg/pubring.gpg '$cache/$file.sig' '$cache/$file' 2>&1"
if ($LASTEXITCODE -ne 0) { throw "Signature check failed for ${file}:`n$out" }
$signer = ($out | Select-String 'Good signature from "([^"]+)"').Matches.Groups[1].Value
$p | Add-Member -NotePropertyName File -NotePropertyValue $file
$p | Add-Member -NotePropertyName Signer -NotePropertyValue $signer
}
# ── 3. Pack ──────────────────────────────────────────────────
$name = "reims-runtime-msys2-src-$Commit"
$stage = Join-Path $TempRoot "pack-$name"
if (Test-Path -LiteralPath $stage) { Remove-Item -Recurse -Force -LiteralPath $stage }
$dir = Join-Path $stage $name
New-Item -ItemType Directory -Force -Path (Join-Path $dir 'sources') | Out-Null
foreach ($p in $needed) {
Copy-Item -LiteralPath (Join-Path $CacheDir $p.File) -Destination (Join-Path $dir 'sources')
Copy-Item -LiteralPath (Join-Path $CacheDir "$($p.File).sig") -Destination (Join-Path $dir 'sources')
}
$rows = foreach ($p in ($packages | Sort-Object Name)) {
$lic = ($p.Licenses -join '; ') -replace '\|', '/'
$src = if ($p.Needs) { "``sources/$("$($p.Base)-$($p.Version).src.tar.zst")``" } else { '— (permissive licence; text in the runtime''s licenses/)' }
"| ``$($p.Name -replace '^mingw-w64-clang-x86_64-', '')`` | $($p.Version) | $lic | $src |"
}
Write-Utf8 (Join-Path $dir 'README.md') @"
# MSYS2 package sources for reims-runtime-win-x64-$Commit
The runtime's ``qemu/bin`` bundles DLLs from MSYS2 CLANG64 packages. This archive
holds, unmodified, the source packages of every one whose licence requires source
(GPL, LGPL or MPL with no permissive alternative), exactly as MSYS2 publishes them
at $Mirror, each with its detached signature (``.sig``), checked with gpgv
against the MSYS2 keyring when this archive was made.
A ``.src.tar.zst`` contains the PKGBUILD, the upstream source tarball and MSYS2's
patches: ``makepkg-mingw`` in an MSYS2 shell rebuilds the package.
| Package | Version | Licence | Source |
| :-- | :-- | :-- | :-- |
$($rows -join "`n")
"@
$tar = Join-Path $TempRoot "$name.tar"
& tar.exe -cf $tar -C $stage $name
if ($LASTEXITCODE -ne 0) { throw 'tar failed' }
$archive = Join-Path $OutDir "$name.tar.zst"
& $zstd -T0 -3 -q -f $tar -o $archive # contents are already compressed
if ($LASTEXITCODE -ne 0) { throw 'zstd failed' }
Remove-Item -LiteralPath $tar -Force
Remove-Item -Recurse -Force -LiteralPath $stage
# ── 4. SHA256SUMS.txt ────────────────────────────────────────
$hash = (Get-FileHash -Algorithm SHA256 -LiteralPath $archive).Hash.ToLowerInvariant()
$sums = Join-Path $OutDir 'SHA256SUMS.txt'
$lines = @()
if (Test-Path -LiteralPath $sums) {
$lines = @(Get-Content -LiteralPath $sums | Where-Object { $_ -and $_ -notmatch " $([regex]::Escape("$name.tar.zst"))$" })
}
$lines += "$hash $name.tar.zst"
Write-Utf8 $sums (($lines -join "`n") + "`n")
Write-Host '==> Done' -ForegroundColor Green
'{0} {1:N1} MB ({2} source archives, all signatures good)' -f $archive, ((Get-Item $archive).Length / 1MB), $needed.Count
-580
View File
@@ -1,580 +0,0 @@
<#
.SYNOPSIS
Pack a portable reims-vgpu runtime for Windows x64, its matching source
package, and SHA256SUMS.txt, ready to publish as a GitHub Release.
.DESCRIPTION
Outputs, in -OutDir (all five are assets of one GitHub Release):
reims-runtime-win-x64-<commit>.tar.zst runtime (bin/, qemu/, manifest.json,
NOTICE.md, licenses/, patches/,
MSYS2-PACKAGES.txt)
reims-runtime-src-<commit>.tar.zst corresponding source: pristine upstream
trees at the built commits + patches/
reims-runtime-msys2-src-<commit>.tar.zst sources of the copyleft MSYS2 packages
whose DLLs are bundled (pack-msys2-sources.ps1)
reims-runtime-symbols-<commit>.tar.zst detached debug files for the five programs
SHA256SUMS.txt all four archives
manifest.json (schema 2) states what the package was really built from:
upstream commit, vendor/qemu commit, reims-util and metal2vulkan commits,
every local patch with its SHA256, and the channel. A package built with
patches is never described as pure upstream (AGENTS.md rule 5).
The patches come from patches/series.txt (in that order). -Patches narrows
them to the ones really applied to the build tree (CI passes the list from
apply-patch-series.ps1, which skips patches already merged upstream).
Before packing, the build tree's diff must equal the declared patches, so
the source package matches the binaries, and any other change in the
build trees is refused. A mismatch stops the script.
.EXAMPLE
pwsh -File scripts/pack-runtime.ps1 -Channel alpha
pwsh -File scripts/pack-runtime.ps1 -Patches reims-util-parallel-offline-download.patch,metal2vulkan-snapshot-replay.patch
#>
[CmdletBinding(PositionalBinding = $false)]
param(
[string]$ReimsRepo = 'D:\DevTools\reims-vgpu',
[string]$UtilRepo = '',
[string]$Metal2VulkanRepo = '',
[string]$CargoHome = 'D:\DevTools\cargo',
[string]$QemuDir = 'D:\Data\macos-vm-lab\reims\data\reims-ctl\qemu\current',
[string]$Msys2 = 'D:\DevTools\msys64',
[string]$OutDir = 'D:\Data\reims-go\releases',
[string]$TempRoot = 'D:\Build\Temp',
# Channel at build time. A runtime is promoted to stable by turning its
# GitHub prerelease into a release, never by repacking (spec section 6).
[ValidateSet('alpha', 'stable')]
[string]$Channel = 'alpha',
[int]$ZstdLevel = 15,
# 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 = '',
# Names from patches/series.txt actually applied. Not given: all of them.
# Given but empty: none (every patch already upstream).
[string[]]$Patches = @()
)
$ErrorActionPreference = 'Stop'
$repoRoot = Split-Path -Parent $PSScriptRoot
$patchesDir = Join-Path $repoRoot 'patches'
$CargoBin = Join-Path $CargoHome 'bin'
function Invoke-Native([string]$exe, [string[]]$argv) {
& $exe @argv
if ($LASTEXITCODE -ne 0) { throw "$exe $($argv -join ' ') failed ($LASTEXITCODE)" }
}
function Invoke-GitApply([string]$repo, [string]$patchText, [switch]$Check) {
$psi = [Diagnostics.ProcessStartInfo]::new()
$psi.FileName = (Get-Command git).Source
$psi.WorkingDirectory = $repo
$psi.UseShellExecute = $false
$psi.RedirectStandardInput = $true
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.ArgumentList.Add('apply')
if ($Check) { $psi.ArgumentList.Add('--check') }
$psi.ArgumentList.Add('-')
$proc = [Diagnostics.Process]::Start($psi)
$proc.StandardInput.NewLine = "`n"
$proc.StandardInput.Write($patchText)
$proc.StandardInput.Close()
$stdout = $proc.StandardOutput.ReadToEnd()
$stderr = $proc.StandardError.ReadToEnd()
$proc.WaitForExit()
if ($proc.ExitCode) { throw "git apply failed in $repo ($($proc.ExitCode)): $stdout$stderr" }
}
function Get-Sha256([string]$path) {
(Get-FileHash -Algorithm SHA256 -LiteralPath $path).Hash.ToLowerInvariant()
}
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)
Remove-Item -LiteralPath $tar -Force
}
# ── 1. Inputs and provenance ─────────────────────────────────
function Get-GitHubSource([string]$Url, [string]$Fallback) {
if ($Url -match '^(?:https://(?:[^/@]+@)?github\.com/|git@github\.com:)([\w.-]+/[\w.-]+?)(?:\.git)?/?$') {
return "https://github.com/$($Matches[1])"
}
return "https://github.com/$Fallback"
}
$ctlExe = Join-Path $CargoBin 'reims-ctl.exe'
$utilExe = Join-Path $CargoBin 'reims-util.exe'
$qemuExe = Join-Path $QemuDir 'bin\qemu-system-x86_64.exe'
foreach ($p in @($ctlExe, $utilExe, $qemuExe)) {
if (-not (Test-Path -LiteralPath $p)) { throw "Required runtime binary not found: $p" }
}
$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 }
$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
$qemuOrigin = git -C $ReimsRepo config --file .gitmodules --get submodule.vendor/qemu.url
$reimsSource = Get-GitHubSource $reimsOrigin 'steelbrain/reims-vgpu'
$qemuSource = Get-GitHubSource $qemuOrigin 'steelbrain/qemu-reims-vgpu'
$capabilities = @()
$runtimeFeatures = Join-Path $ReimsRepo 'reims-go-runtime.json'
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]
$checkouts = Join-Path $CargoHome 'git\checkouts'
$utilTree = if ($UtilRepo) {
(Resolve-Path -LiteralPath $UtilRepo).Path
} else {
Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'reims-util-*' |
ForEach-Object { Join-Path $_.FullName $utilCommit.Substring(0, 7) } |
Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
}
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 {
Get-ChildItem -LiteralPath $checkouts -Directory -Filter 'metal2vulkan-*' -ErrorAction SilentlyContinue |
ForEach-Object { Join-Path $_.FullName $m2vCommit.Substring(0, 7) } |
Where-Object { Test-Path -LiteralPath $_ } | Select-Object -First 1
}
if (-not $m2vTree) { throw "metal2vulkan source at $m2vCommit not found (pass -Metal2VulkanRepo or check $checkouts)" }
$actualM2v = (git -C $m2vTree rev-parse HEAD).Trim()
if ($LASTEXITCODE -ne 0 -or $actualM2v -ne $m2vCommit) { throw "metal2vulkan checkout must be at $m2vCommit (got $actualM2v)" }
$qemuVersionLine = (& $qemuExe --version | Select-Object -First 1).Trim()
$utilVersionLine = (& $utilExe --version | Select-Object -First 1).Trim()
# ── 2. Patches must equal the build tree's diffs ─────────────
$repositories = @{
'reims-vgpu' = $ReimsRepo
'vendor/qemu' = $qemuRepo
'reims-util' = $utilTree
'metal2vulkan' = $m2vTree
}
$series = @(foreach ($line in Get-Content -LiteralPath (Join-Path $patchesDir 'series.txt')) {
$t = $line.Trim()
if (-not $t -or $t.StartsWith('#')) { continue }
$parts = $t -split '\s+'
if ($parts.Count -ne 2 -or -not $repositories.ContainsKey($parts[0])) { throw "Bad line in patches/series.txt: '$line'" }
[pscustomobject]@{ Target = $parts[0]; Name = $parts[1] }
})
# PowerShell -File passes "a,b" as one string: accept both forms.
$Patches = @($Patches | ForEach-Object { $_ -split ',' } | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($n in $Patches) {
if ($n -notin $series.Name) { throw "-Patches names $n, which is not in patches/series.txt" }
}
$patchSpecs = @()
$usePatchList = $PSBoundParameters.ContainsKey('Patches')
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.
$paths = @(Get-Content -LiteralPath $file | ForEach-Object {
if ($_ -match '^(?:---|\+\+\+) [ab]/(.+?)\s*$') { $Matches[1] }
} | Select-Object -Unique)
$patchSpecs += @{
Name = $e.Name
Target = $e.Target
Repo = $repositories[$e.Target]
Paths = $paths
}
}
# Avoid colliding with the [string[]]$Patches parameter (PowerShell variable
# names are case-insensitive; reusing $patches coerces every entry to a string).
$patchEntries = @()
# Group patches by repo so multi-patch stacks (e.g. 2-3 QEMU WHPX patches) are
# verified together against a clean HEAD export with zero undeclared diff.
$byTarget = [ordered]@{}
foreach ($ps in $patchSpecs) {
$file = Join-Path $patchesDir $ps.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
if (-not $byTarget.Contains($ps.Target)) {
$byTarget[$ps.Target] = [Collections.Generic.List[hashtable]]::new()
}
$byTarget[$ps.Target].Add($ps)
$patchEntries += [ordered]@{ name = $ps.Name; target = $ps.Target; sha256 = (Get-Sha256 $file) }
}
foreach ($targetName in $byTarget.Keys) {
$group = $byTarget[$targetName]
$repo = $group[0].Repo
$paths = @($group | ForEach-Object { $_.Paths } | Where-Object { $_ } | Select-Object -Unique)
# Use --full-index so blob hash abbreviation lengths match regardless of
# 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()
# 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())
try {
New-Item -ItemType Directory -Force -Path $verifyDir | Out-Null
$headRev = (git -C $repo rev-parse HEAD).Trim()
Invoke-Native 'git' @('init', '-q', $verifyDir)
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.autocrlf', 'false')
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.eol', 'lf')
Invoke-Native 'git' @('-C', $verifyDir, 'config', 'core.filemode', 'false')
Write-Utf8 (Join-Path $verifyDir '.gitattributes') '* text eol=lf`n'
$tar = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $headRev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $verifyDir)
Remove-Item -LiteralPath $tar -Force
# bsdtar expands the upstream LF bytes, but Windows text tools used
# during extraction must not decide the comparison's line endings.
foreach ($file in Get-ChildItem -LiteralPath $verifyDir -Recurse -File) {
if ($file.LinkType) { continue }
$bytes = [IO.File]::ReadAllBytes($file.FullName)
$text = [Text.Encoding]::UTF8.GetString($bytes)
if ($text.Contains([char]0)) { continue }
$lf = $text.Replace("`r`n", "`n")
if ($lf -cne $text) {
[IO.File]::WriteAllText($file.FullName, $lf, [Text.UTF8Encoding]::new($false))
}
}
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'add', '-A')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '-m', 'base')
Invoke-Native 'git' @('-C', $verifyDir, 'add', '--renormalize', '.')
Invoke-Native 'git' @('-C', $verifyDir, '-c', 'user.name=verify', '-c', 'user.email=verify@local', 'commit', '-q', '--allow-empty', '-m', 'normalize-lf')
foreach ($ps in $group) {
$pf = Join-Path $patchesDir $ps.Name
# .patch files may be checked out with CRLF on Windows. Keep the
# authoritative file intact while comparing its LF representation
# with a Git tree archived and indexed with LF line endings.
$patchLf = Join-Path $TempRoot ("patch-lf-" + [guid]::NewGuid() + '.patch')
$patchText = [IO.File]::ReadAllText($pf).Replace("`r`n", "`n")
[IO.File]::WriteAllText($patchLf, $patchText, [Text.UTF8Encoding]::new($false))
Invoke-GitApply $verifyDir $patchText -Check
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()
if ($treeDiff -ne $expectedDiff) {
$treeStat = (& git -C $repo diff --stat -- @paths | Out-String).Trim()
$expStat = (& git -C $verifyDir diff --stat | Out-String).Trim()
Write-Host "Build tree diff --stat:`n$treeStat"
Write-Host "Expected patch stack diff --stat:`n$expStat"
throw "Patch stack ($(($group | ForEach-Object { $_.Name }) -join ', ')) does not match the build tree's diff in $repo. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
# Also verify newly created (untracked) files added by patches byte-for-byte.
$addedFiles = @(& git -C $verifyDir ls-files --others --exclude-standard | Where-Object { $_ })
foreach ($rel in $addedFiles) {
$expPath = Join-Path $verifyDir ($rel -replace '/', '\')
$treePath = Join-Path $repo ($rel -replace '/', '\')
if (-not (Test-Path -LiteralPath $treePath -PathType Leaf)) {
throw "Patch stack expected new file $rel in $repo, but it is missing."
}
$expText = [IO.File]::ReadAllText($expPath).Replace("`r`n", "`n")
$treeText = [IO.File]::ReadAllText($treePath).Replace("`r`n", "`n")
if ($treeText -cne $expText) {
throw "New file $rel in $repo does not match the declared patch stack. Stop: don't edit patches automatically (AGENTS.md rule 4)."
}
}
} finally {
if (Test-Path -LiteralPath $verifyDir) { Remove-Item -Recurse -Force -LiteralPath $verifyDir }
}
}
# Anything else changed in the build trees is undeclared: refuse.
function Get-Undeclared([string]$repo, [string]$target, [string[]]$statusArgs) {
$declared = @($patchSpecs | Where-Object { $_.Target -eq $target } | ForEach-Object { $_.Paths })
@(& git -C $repo status --porcelain @statusArgs | Where-Object {
$path = $_.Substring(3).Trim('"')
$path -notin $declared
})
}
$otherCtl = Get-Undeclared $ReimsRepo 'reims-vgpu' @('--ignore-submodules=all')
$otherQemu = Get-Undeclared $qemuRepo 'vendor/qemu' @('--untracked-files=no')
$utilStatusArgs = if ($UtilRepo) { '--untracked-files=all' } else { '--untracked-files=no' }
$otherUtil = Get-Undeclared $utilTree 'reims-util' @($utilStatusArgs)
$m2vStatusArgs = if ($Metal2VulkanRepo) { '--untracked-files=all' } else { '--untracked-files=no' }
$otherM2v = Get-Undeclared $m2vTree 'metal2vulkan' @($m2vStatusArgs)
if ($otherCtl.Count -or $otherQemu.Count -or $otherUtil.Count -or $otherM2v.Count) {
throw "Undeclared changes in the build trees:`n$($otherCtl + $otherQemu + $otherUtil + $otherM2v -join "`n")"
}
$bundleName = "reims-runtime-win-x64-$id"
$srcName = "reims-runtime-src-$id"
$symbolsName = "reims-runtime-symbols-$id"
$stageRoot = Join-Path $TempRoot "pack-$id"
$bundleDir = Join-Path $stageRoot $bundleName
$srcDir = Join-Path $stageRoot $srcName
if (Test-Path -LiteralPath $stageRoot) { Remove-Item -Recurse -Force -LiteralPath $stageRoot }
New-Item -ItemType Directory -Force -Path "$bundleDir\bin", "$bundleDir\qemu", "$bundleDir\licenses", "$bundleDir\patches", $srcDir, $OutDir | Out-Null
# ── 3. Runtime bundle ────────────────────────────────────────
Write-Host "==> Staging $bundleName ($Channel)"
$resolvedQemu = (Get-Item -LiteralPath $QemuDir).Target
if (-not $resolvedQemu) { $resolvedQemu = $QemuDir }
$keyFiles = @(& (Join-Path $PSScriptRoot 'stage-runtime-binaries.ps1') -CargoBin $CargoBin -QemuDir $resolvedQemu `
-BundleDir $bundleDir -SymbolsDir (Join-Path $stageRoot $symbolsName) -Objcopy (Join-Path $Msys2 'clang64/bin/llvm-objcopy.exe') | ForEach-Object { $_ })
$expectedKeyFiles = @('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')
if ($keyFiles.Count -ne 5 -or (Compare-Object $expectedKeyFiles $keyFiles)) {
$keyFiles | ForEach-Object { Write-Host "Unexpected stager output [$($_.GetType().FullName)]: $_" }
throw 'Binary stager did not return exactly the five expected executable paths'
}
Copy-Item -LiteralPath (Join-Path $repoRoot 'NOTICE.md') -Destination "$bundleDir\NOTICE.md"
foreach ($ps in $patchSpecs) { Copy-Item -LiteralPath (Join-Path $patchesDir $ps.Name) -Destination "$bundleDir\patches\" }
Copy-Item -LiteralPath (Join-Path $patchesDir 'README.md') -Destination "$bundleDir\patches\README.md"
if (Test-Path -LiteralPath (Join-Path $patchesDir 'LICENSE')) {
Copy-Item -LiteralPath (Join-Path $patchesDir 'LICENSE') -Destination "$bundleDir\patches\LICENSE"
}
# The order the patches above were applied in (only those really applied).
Write-Utf8 "$bundleDir\patches\series.txt" ((($patchSpecs | ForEach-Object { '{0,-12} {1}' -f $_.Target, $_.Name }) -join "`n") + "`n")
$licenses = @{
'reims-vgpu-LICENSE.txt' = (Join-Path $ReimsRepo 'LICENSE')
'qemu-COPYING.txt' = (Join-Path $qemuRepo 'COPYING')
'qemu-COPYING.LIB.txt' = (Join-Path $qemuRepo 'COPYING.LIB')
}
foreach ($k in $licenses.Keys) {
if (Test-Path -LiteralPath $licenses[$k]) { Copy-Item -LiteralPath $licenses[$k] -Destination (Join-Path "$bundleDir\licenses" $k) }
}
if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) {
Copy-Item -Path (Join-Path $ReimsRepo 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force
}
# MSYS2 CLANG64 DLLs: owning package and version, and where its source is.
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)
$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)
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
} else {
$pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-")
}
}
# 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] }
})
foreach ($lf in $licFiles) {
$rel = $lf.Substring('/clang64/share/licenses/'.Length)
$srcFile = Join-Path $Msys2 ($lf.TrimStart('/') -replace '/', '\')
if (Test-Path -LiteralPath $srcFile -PathType Leaf) {
$dstFile = Join-Path $msysLicRoot ($rel -replace '/', '\')
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dstFile))
Copy-Item -LiteralPath $srcFile -Destination $dstFile -Force
}
}
}
$msysText = @"
# DLLs bundled in qemu/bin and the MSYS2 CLANG64 packages they come from
# (pacman -Qo on the build machine, $(Get-Date -Format 'yyyy-MM-dd')).
#
# Sources: every package whose licence requires source (GPL / LGPL / MPL) is in
# reims-runtime-msys2-src-$id.tar.zst, published beside this runtime.
# The same files are also at:
# https://repo.msys2.org/mingw/sources/ (<package>-<version>.src.tar.zst, by pkgbase)
# https://github.com/msys2/MINGW-packages (build recipes)
# Licenses: bundled under licenses/msys2/ from each package's /clang64/share/licenses/ in MSYS2.
DLL`tPACKAGE`tVERSION
$($pkgLines -join "`n")
# Packages ($($pkgSet.Count))
$($pkgSet.Keys -join "`n")
"@
Write-Utf8 "$bundleDir\MSYS2-PACKAGES.txt" $msysText
# ── 4. Source bundle ─────────────────────────────────────────
Write-Host "==> Staging $srcName"
function Export-GitTree([string]$repo, [string]$rev, [string]$dest) {
New-Item -ItemType Directory -Force -Path $dest | Out-Null
$tar = Join-Path $TempRoot ("git-export-" + [guid]::NewGuid() + '.tar')
Invoke-Native 'git' @('-C', $repo, 'archive', '--format=tar', '-o', $tar, $rev)
Invoke-Native 'tar.exe' @('-xf', $tar, '-C', $dest)
Remove-Item -LiteralPath $tar -Force
}
Export-GitTree $ReimsRepo $fullCommit (Join-Path $srcDir "reims-vgpu-$commit")
Export-GitTree $qemuRepo $qemuCommit (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu")
# QEMU's meson wraps downloaded for this build (dtc, keycodemapdb, ...): part of what was built.
Get-ChildItem -LiteralPath (Join-Path $qemuRepo 'subprojects') -Directory |
Where-Object { $_.Name -ne 'packagecache' -and -not (Test-Path -LiteralPath (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\$($_.Name)")) } |
ForEach-Object { Copy-Item -LiteralPath $_.FullName -Destination (Join-Path $srcDir "reims-vgpu-$commit\vendor\qemu\subprojects\") -Recurse -Force }
Export-GitTree $utilTree $utilCommit (Join-Path $srcDir "reims-util-$($utilCommit.Substring(0, 7))")
Export-GitTree $m2vTree $m2vCommit (Join-Path $srcDir "metal2vulkan-$($m2vCommit.Substring(0, 7))")
foreach ($extra in @(
@{ Name = 'reims-util'; Tree = $utilTree },
@{ Name = 'metal2vulkan'; Tree = $m2vTree }
)) {
foreach ($lf in @('LICENSE', 'LICENSE.txt', 'LICENSE.md', 'COPYING', 'COPYING.LIB')) {
$srcLic = Join-Path $extra.Tree $lf
if (Test-Path -LiteralPath $srcLic -PathType Leaf) {
Copy-Item -LiteralPath $srcLic -Destination (Join-Path "$bundleDir\licenses" "$($extra.Name)-$lf") -Force
}
}
if (Test-Path -LiteralPath (Join-Path $extra.Tree 'LICENSES') -PathType Container) {
Copy-Item -Path (Join-Path $extra.Tree 'LICENSES\*') -Destination "$bundleDir\licenses\" -Recurse -Force
}
}
New-Item -ItemType Directory -Force -Path "$srcDir\patches" | Out-Null
Copy-Item -Path "$bundleDir\patches\*" -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')) {
$m2vDir = "metal2vulkan-$($m2vCommit.Substring(0, 7))"
$m2vApply = ($byTarget['metal2vulkan'] | ForEach-Object { " git -C $m2vDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n"
@"
Before running ``scripts/install-ctl.sh``, apply the ``metal2vulkan`` patches
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"]
metal2vulkan = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan" }
metal2vulkan-runtime = { path = "`$(cygpath -m "`$(pwd)/$m2vDir")/crates/metal2vulkan-runtime" }
EOF
"@
}
$utilBuildSteps = if ($byTarget.Contains('reims-util')) {
$utilDir = "reims-util-$($utilCommit.Substring(0, 7))"
$utilApply = ($byTarget['reims-util'] | ForEach-Object { " git -C $utilDir apply `"`$(pwd)/patches/$($_.Name)`"" }) -join "`n"
@"
After the upstream build, run these commands from the extracted source
archive's root in the same MSYS2 CLANG64 shell. They apply the reims-util
patches and replace the stock reims-util executable with this build:
$utilApply
cd reims-vgpu-$commit
toolchain=`$(sed -n 's/^channel *= *"\([^"]*\)".*/\1/p' rust-toolchain.toml)
CC=clang CXX=clang++ AR=llvm-ar cargo +"`$toolchain-x86_64-pc-windows-gnullvm" install --locked --force --path ../$utilDir
"@
}
Write-Utf8 "$srcDir\README.md" @"
# Source for $bundleName
Corresponding source for the binaries in ``$bundleName.tar.zst``.
| Directory | Source repository | Commit |
| :-- | :-- | :-- |
| ``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`` |
The archive exports the commits above. Apply the patches in ``patches/``
before compiling:
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
packages listed in ``MSYS2-PACKAGES.txt``, with links to their sources.
$utilBuildSteps
"@
# ── 5. Manifest (schema 2) ───────────────────────────────────
$hashes = [ordered]@{}
foreach ($rel in $keyFiles) {
$fp = Join-Path $bundleDir ($rel -replace '/', '\')
$hashes[$rel] = Get-Sha256 $fp
}
$manifest = [ordered]@{
schema_version = 2
name = $bundleName
platform = 'windows-x86_64'
upstream_repo = $reimsSource
commit = $id
full_commit = $fullCommit
vendor_qemu_repo = $qemuSource
vendor_qemu_commit = $qemuCommit
util_commit = $utilCommit
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')
file_count = (Get-ChildItem -LiteralPath $bundleDir -Recurse -File).Count + 1
dll_count = $dlls.Count
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
}
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 ─────────────────────────────────────
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"
# 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
Remove-Item -Recurse -Force -LiteralPath $stageRoot
Write-Host ''
Write-Host '==> Done' -ForegroundColor Green
'{0,-10} {1} {2:N1} MB' -f 'runtime', $runtimeArchive, ((Get-Item $runtimeArchive).Length / 1MB)
'{0,-10} {1} {2:N1} MB' -f 'source', $srcArchive, ((Get-Item $srcArchive).Length / 1MB)
"channel $Channel; patches: $(($patchEntries | ForEach-Object { $_.name }) -join ', '); DLLs: $($dlls.Count)"
-191
View File
@@ -1,191 +0,0 @@
<#
.SYNOPSIS
Real-host smoke test for an alpha portable reims-vgpu runtime archive.
.DESCRIPTION
Implements docs/portable-runtime-spec.md section 6 (alpha -> stable gate):
1. Verifies SHA256 against SHA256SUMS.txt (when provided).
2. Extracts the runtime into an isolated directory under -TempRoot (never C:).
3. Verifies manifest.json provenance, NOTICE.md, licenses/, and core binaries.
4. Runs `reims-ctl doctor` and `reims-ctl list --json` in a clean environment
stripped of MSYS2 / Cargo paths to prove true portability.
5. Writes a Markdown report for human review before promoting to `stable`.
.EXAMPLE
powershell -ExecutionPolicy Bypass -File scripts/smoke-runtime.ps1 `
-ArchivePath D:\Data\reims-go\releases\reims-runtime-win-x64-3731afd.tar.zst `
-Sha256File D:\Data\reims-go\releases\SHA256SUMS.txt
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true)]
[string]$ArchivePath,
[string]$Sha256File = '',
[string]$TempRoot = 'D:\Build\Temp',
[string]$ReportOut = ''
)
$ErrorActionPreference = 'Stop'
if (-not (Test-Path -LiteralPath $ArchivePath)) {
throw "Archive not found: $ArchivePath"
}
$archiveFile = Get-Item -LiteralPath $ArchivePath
$actualHash = (Get-FileHash -Algorithm SHA256 -LiteralPath $ArchivePath).Hash.ToLowerInvariant()
$hashStatus = 'skipped (no -Sha256File provided)'
if ($Sha256File -ne '') {
if (-not (Test-Path -LiteralPath $Sha256File)) {
throw "SHA256SUMS file not found: $Sha256File"
}
$matched = $false
foreach ($line in (Get-Content -LiteralPath $Sha256File)) {
if ($line -match '^([0-9a-fA-F]{64})\s+\*?(.+)$') {
$h = $Matches[1].ToLowerInvariant()
$n = $Matches[2].Trim()
if ($n -eq $archiveFile.Name) {
if ($h -ne $actualHash) {
throw "SHA256 mismatch for $($archiveFile.Name): expected $h, got $actualHash"
}
$matched = $true
break
}
}
}
if (-not $matched) {
throw "Entry for $($archiveFile.Name) not found in $Sha256File"
}
$hashStatus = "PASS ($actualHash)"
}
$stamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$smokeDir = Join-Path $TempRoot "smoke-$stamp"
$extractDir = Join-Path $smokeDir 'runtime'
$dataDir = Join-Path $smokeDir 'data'
New-Item -ItemType Directory -Force -Path $extractDir, $dataDir | Out-Null
function Resolve-Zstd {
@(
(Get-Command zstd.exe -ErrorAction SilentlyContinue | Select-Object -ExpandProperty Source),
'D:\DevTools\msys64\usr\bin\zstd.exe',
'C:\msys64\usr\bin\zstd.exe'
) | Where-Object { $_ -and (Test-Path -LiteralPath $_) } | Select-Object -First 1
}
try {
Write-Host "[1/5] Extracting $($archiveFile.Name) into $extractDir..."
if ($archiveFile.Name.EndsWith('.tar.zst')) {
$zstd = Resolve-Zstd
if (-not $zstd) { throw 'zstd.exe not found to extract .tar.zst' }
$tarPath = Join-Path $smokeDir 'runtime.tar'
& $zstd -d -f -q $ArchivePath -o $tarPath
if ($LASTEXITCODE -ne 0) { throw "zstd decompress failed ($LASTEXITCODE)" }
& tar.exe -xf $tarPath -C $extractDir
if ($LASTEXITCODE -ne 0) { throw "tar extract failed ($LASTEXITCODE)" }
Remove-Item -LiteralPath $tarPath -Force
} elseif ($archiveFile.Name.EndsWith('.zip')) {
Expand-Archive -LiteralPath $ArchivePath -DestinationPath $extractDir -Force
} else {
throw "Unsupported archive format: $($archiveFile.Name)"
}
# Handle single top-level folder inside archive.
$rootDir = $extractDir
$children = @(Get-ChildItem -LiteralPath $extractDir)
if ($children.Count -eq 1 -and $children[0].PSIsContainer) {
$rootDir = $children[0].FullName
}
Write-Host "[2/5] Checking manifest.json, compliance files, and core binaries..."
$required = @(
'manifest.json',
'NOTICE.md',
'licenses',
'bin\reims-ctl.exe',
'bin\reims-util.exe',
'qemu\bin\qemu-system-x86_64.exe',
'qemu\bin\qemu-img.exe'
)
foreach ($rel in $required) {
$p = Join-Path $rootDir $rel
if (-not (Test-Path -LiteralPath $p)) {
throw "Missing required runtime asset: $rel"
}
}
$manifest = Get-Content -Raw -LiteralPath (Join-Path $rootDir 'manifest.json') | ConvertFrom-Json
$patchList = @()
if ($manifest.patches) {
$patchList = @($manifest.patches | ForEach-Object { $_.name })
}
Write-Host "[3/5] Running reims-ctl doctor in a clean MSYS2-free environment..."
$cleanEnv = @{
'XDG_CONFIG_HOME' = (Join-Path $dataDir 'config')
'XDG_DATA_HOME' = (Join-Path $dataDir 'data')
'XDG_CACHE_HOME' = (Join-Path $dataDir 'cache')
'TEMP' = (Join-Path $dataDir 'tmp')
'TMP' = (Join-Path $dataDir 'tmp')
'REIMS_CTL_QEMU' = (Join-Path $rootDir 'qemu')
'PATH' = "$($env:SystemRoot)\System32;$($env:SystemRoot)"
}
New-Item -ItemType Directory -Force -Path $cleanEnv['XDG_CONFIG_HOME'], $cleanEnv['XDG_DATA_HOME'], $cleanEnv['XDG_CACHE_HOME'], $cleanEnv['TEMP'] | Out-Null
function Invoke-CleanCtl([string[]]$ctlArgs) {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = (Join-Path $rootDir 'bin\reims-ctl.exe')
$psi.Arguments = ($ctlArgs -join ' ')
$psi.UseShellExecute = $false
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.CreateNoWindow = $true
foreach ($k in $cleanEnv.Keys) {
$psi.EnvironmentVariables[$k] = $cleanEnv[$k]
}
$proc = [System.Diagnostics.Process]::Start($psi)
$stdout = $proc.StandardOutput.ReadToEnd()
$stderr = $proc.StandardError.ReadToEnd()
$proc.WaitForExit()
return @{ Code = $proc.ExitCode; Stdout = $stdout; Stderr = $stderr }
}
$doctorRes = Invoke-CleanCtl @('doctor')
Write-Host "[4/5] Running reims-ctl list --json..."
$listRes = Invoke-CleanCtl @('list', '--json')
if ($listRes.Code -ne 0) {
throw "reims-ctl list --json failed ($($listRes.Code)): $($listRes.Stderr)"
}
Write-Host "[5/5] Generating smoke report..."
$reportLines = @(
"# Runtime Smoke Test Report",
"",
"- **Tested at**: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss zzz')",
"- **Host**: $([Environment]::MachineName) ($([Environment]::OSVersion.VersionString))",
"- **Archive**: $($archiveFile.Name) ($([math]::Round($archiveFile.Length / 1MB, 1)) MB)",
"- **SHA256 check**: $hashStatus",
"- **Upstream commit**: $($manifest.commit) (channel: $($manifest.channel))",
"- **vendor/qemu commit**: $($manifest.vendor_qemu_commit)",
"- **Patches**: $(if ($patchList.Count -gt 0) { $patchList -join ', ' } else { 'none (pure upstream)' })",
"- **Source package declared**: $($manifest.source_package)",
"- **reims-ctl list --json**: PASS (exit $($listRes.Code))",
"- **reims-ctl doctor exit code**: $($doctorRes.Code)",
"",
"## reims-ctl doctor output",
'```text',
$doctorRes.Stdout.TrimEnd(),
'```'
)
$report = $reportLines -join "`n"
if ($ReportOut -ne '') {
New-Item -ItemType Directory -Force -Path (Split-Path -Parent $ReportOut) | Out-Null
[IO.File]::WriteAllText($ReportOut, $report + "`n", [Text.UTF8Encoding]::new($false))
Write-Host "Smoke report written to: $ReportOut"
} else {
Write-Host "`n$report"
}
Write-Host "`nSmoke test finished. Human review required before promoting alpha -> stable."
} finally {
if (Test-Path -LiteralPath $smokeDir) {
Remove-Item -LiteralPath $smokeDir -Recurse -Force -ErrorAction SilentlyContinue
}
}
-42
View File
@@ -1,42 +0,0 @@
# Stage the Windows x64 payload and matching GNU debug files. Inputs are read-only.
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string]$CargoBin,
[Parameter(Mandatory)] [string]$QemuDir,
[Parameter(Mandatory)] [string]$BundleDir,
[Parameter(Mandatory)] [string]$SymbolsDir,
[Parameter(Mandatory)] [string]$Objcopy
)
$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')
# 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')
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 }
$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) {
$src = if ($rel.StartsWith('qemu/')) { Join-Path $QemuDir $rel.Substring(5) }
else { Join-Path $CargoBin (Split-Path -Leaf $rel) }
$dest = Join-Path $BundleDir $rel
$debug = Join-Path $SymbolsDir "$rel.debug"
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $debug))
& $Objcopy --only-keep-debug $src $debug | Out-Null
if ($LASTEXITCODE) { throw "Extracting symbols from $src failed ($LASTEXITCODE)" }
& $Objcopy --strip-debug "--add-gnu-debuglink=$debug" $src $dest | Out-Null
if ($LASTEXITCODE) { throw "Stripping $src failed ($LASTEXITCODE)" }
}
# The packer hashes these final, stripped bytes for manifest.json.
$programs