Compare commits

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

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

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

Checked the workflow with actionlint and checked the MSYS2 lookup with mock and installed-package tests.
2026-12-04 18:45:23 +08:00
Xiaochi You abc65fdbf9 Merge pull request #7 from cosimawei/feat/configurable-input-release-pr
Support configurable SDL input release shortcuts and pointer exit.
2026-12-04 16:06:30 +08:00
YXC0915 d427f1bd86 📝 Register SDL input release settings [ci skip]
List the new configuration switches and the window tests that guard them.
2026-12-04 15:50:25 +08:00
YXC0915 76791eb6b6 Merge current runtime master into capture shortcut validation 2026-12-04 15:47:59 +08:00
hanyewei 5f5995e9fb Configure SDL capture release shortcuts and pointer exit 2026-12-02 23:44:07 +08:00
34 changed files with 621 additions and 1800 deletions

No files matched your search

+2 -22
View File
@@ -2,7 +2,7 @@ name: Merge upstream updates
on:
schedule:
- cron: '37 */4 * * *'
- cron: '37 2 * * *'
workflow_dispatch:
permissions:
@@ -16,9 +16,7 @@ jobs:
sync:
if: github.repository == 'reims-go/reims-vgpu'
runs-on: ubuntu-latest
timeout-minutes: 20
outputs:
runtime_commit: ${{ steps.merge.outputs.runtime_commit }}
timeout-minutes: 10
steps:
- name: Merge upstream into the maintenance branch
id: merge
@@ -91,22 +89,4 @@ jobs:
echo "::add-mask::$auth"
git -c "http.https://github.com/.extraheader=AUTHORIZATION: basic $auth" \
push origin "$merged:refs/heads/$TARGET_BRANCH"
printf 'runtime_commit=%s\n' "$merged" >> "$GITHUB_OUTPUT"
summary "Merged upstream commit $source into $TARGET_BRANCH at $merged."
alpha:
# Pushes made by GITHUB_TOKEN do not start push-triggered workflows.
needs: sync
if: needs.sync.outputs.runtime_commit != ''
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Queue Alpha for the merged commit
env:
GH_TOKEN: ${{ github.token }}
RUNTIME_COMMIT: ${{ needs.sync.outputs.runtime_commit }}
run: |
gh workflow run runtime-preview.yml --repo "$GITHUB_REPOSITORY" --ref master \
-f upstream_commit="$RUNTIME_COMMIT" -f publish=true -f supersede=true
+73 -9
View File
@@ -25,6 +25,10 @@ on:
description: "Plan a rebuild of an already published runtime using verified compatibility"
type: boolean
default: false
include_sources:
description: "Include MSYS2 copyleft source archive and detached debug symbols (for stable promotion)"
type: boolean
default: false
permissions:
contents: read
@@ -62,7 +66,7 @@ jobs:
group: build-runtime
cancel-in-progress: ${{ github.event_name == 'push' || inputs.supersede }}
runs-on: windows-latest
timeout-minutes: 150
timeout-minutes: 90
permissions:
contents: write
steps:
@@ -106,14 +110,17 @@ jobs:
msystem: CLANG64
update: true
install: >-
git zstd tar mingw-w64-clang-x86_64-toolchain
git curl diffutils make zstd tar mingw-w64-clang-x86_64-toolchain
mingw-w64-clang-x86_64-cmake mingw-w64-clang-x86_64-meson
mingw-w64-clang-x86_64-ninja mingw-w64-clang-x86_64-pkgconf
mingw-w64-clang-x86_64-glib2 mingw-w64-clang-x86_64-pixman
mingw-w64-clang-x86_64-gtk3 mingw-w64-clang-x86_64-libslirp
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-libva
mingw-w64-clang-x86_64-libusb mingw-w64-clang-x86_64-usbredir
mingw-w64-clang-x86_64-gnutls mingw-w64-clang-x86_64-dtc
mingw-w64-clang-x86_64-libva mingw-w64-clang-x86_64-zstd
mingw-w64-clang-x86_64-mesa mingw-w64-clang-x86_64-vulkan-loader
mingw-w64-clang-x86_64-python mingw-w64-clang-x86_64-python-pip
mingw-w64-clang-x86_64-ccache mingw-w64-clang-x86_64-sccache
- name: Check out the runtime forks and apply dependency patches
if: steps.plan.outputs.skip != 'true'
@@ -179,14 +186,59 @@ jobs:
"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: Identify the Windows build toolchain
if: steps.plan.outputs.skip != 'true'
id: toolchain
shell: msys2 {0}
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
fingerprint="$({ LC_ALL=C pacman -Q; cat rust-toolchain.toml; } | sha256sum)"
week="$(date -u +%G-W%V)"
echo "fingerprint=${fingerprint%% *}" >> "$GITHUB_OUTPUT"
echo "week=$week" >> "$GITHUB_OUTPUT"
echo "Build toolchain: ${fingerprint%% *} (cache bucket: $week)"
- name: Cache compiler objects and Cargo downloads
if: steps.plan.outputs.skip != 'true'
uses: actions/cache@v5
with:
path: |
${{ runner.temp }}/compiler-cache/ccache
${{ runner.temp }}/compiler-cache/sccache
${{ runner.temp }}/cargo/registry/index
${{ runner.temp }}/cargo/registry/cache
${{ runner.temp }}/cargo/git/db
key: runtime-build-v2-${{ runner.arch }}-${{ steps.toolchain.outputs.fingerprint }}-${{ steps.toolchain.outputs.week }}
restore-keys: |
runtime-build-v2-${{ runner.arch }}-${{ steps.toolchain.outputs.fingerprint }}-
- name: Build upstream runtime in MSYS2 CLANG64
if: steps.plan.outputs.skip != 'true'
shell: msys2 {0}
env:
REIMS_INSTALL_SKIP_HOST_CHECKS: "1"
CCACHE_MAXSIZE: 400M
CCACHE_COMPILERCHECK: content
SCCACHE_CACHE_SIZE: 500M
SCCACHE_ALLOW_INCREMENTAL: "1"
run: |
set -euo pipefail
cd "$(cygpath -u "$UPSTREAM_DIR")"
# Native Ninja searches its own directory for the installer's bare
# clang/clang++ names before PATH. Put the cache shims beside its CI copy.
temp_dir="$(cygpath -u "$RUNNER_TEMP")"
tools_dir="$temp_dir/compiler-tools"
mkdir -p "$tools_dir"
cp "$MINGW_PREFIX/bin/ninja.exe" "$MINGW_PREFIX/lib/ccache/bin/"clang{,++}.exe "$tools_dir/"
export PATH="$tools_dir:$PATH"
export CCACHE_PATH="$(cygpath -m "$MINGW_PREFIX/bin")"
export CCACHE_DIR="$(cygpath -m "$temp_dir")/compiler-cache/ccache"
export SCCACHE_DIR="$(cygpath -m "$temp_dir")/compiler-cache/sccache"
export RUSTC_WRAPPER="$(cygpath -m "$MINGW_PREFIX/bin/sccache.exe")"
ccache --zero-stats
sccache --start-server
trap 'ccache --show-stats --verbose; sccache --stop-server' EXIT
# Upstream's own non-interactive CLANG64 build script.
bash scripts/install-ctl.sh --yes
util_repo="$(cygpath -u "$REIMS_UTIL_DIR")"
@@ -199,6 +251,8 @@ jobs:
- name: Package alpha runtime and source archives
if: steps.plan.outputs.skip != 'true'
env:
INCLUDE_FULL_SOURCES: ${{ inputs.include_sources }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
@@ -207,6 +261,7 @@ jobs:
# In-process call, so an empty list (every patch already upstream) binds
# as an empty array rather than being dropped as an empty argument.
$applied = @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
$full = $env:INCLUDE_FULL_SOURCES -eq 'true'
& ./packaging/windows-runtime/scripts/pack-runtime.ps1 `
-ReimsRepo $env:UPSTREAM_DIR `
-UtilRepo $env:REIMS_UTIL_DIR `
@@ -220,29 +275,37 @@ jobs:
-ReleaseId $env:RELEASE_ID `
-SuspendCompatID $env:SUSPEND_COMPAT_ID `
-PackagingCommit $env:GITHUB_SHA `
-Patches $applied
-Patches $applied `
-SkipMsys2Sources:(-not $full) `
-SkipSymbols:(-not $full)
- name: Alpha entry gate
if: steps.plan.outputs.skip != 'true'
env:
INCLUDE_FULL_SOURCES: ${{ inputs.include_sources }}
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$full = $env:INCLUDE_FULL_SOURCES -eq 'true'
& ./packaging/windows-runtime/scripts/check-runtime-alpha.ps1 `
-OutDir (Join-Path $env:RUNNER_TEMP 'releases') `
-Commit $env:RELEASE_ID -RequireSlim -RequiredCapability vm-suspend `
-RequiredSuspendCompatID $env:SUSPEND_COMPAT_ID -RequiredPackagingCommit $env:GITHUB_SHA `
-Zstd (Join-Path '${{ steps.msys2.outputs.msys2-location }}' 'usr\bin\zstd.exe') `
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ })
-AppliedPatches @($env:APPLIED_PATCHES -split ',' | Where-Object { $_ }) `
-SkipMsys2Sources:(-not $full) `
-SkipSymbols:(-not $full)
- name: Upload alpha artifacts
if: steps.plan.outputs.skip != 'true'
- name: Upload alpha artifacts (non-release debug runs only)
if: steps.plan.outputs.skip != 'true' && !(github.event_name == 'push' || github.event_name == 'schedule' || inputs.publish)
uses: actions/upload-artifact@v4
with:
name: reims-runtime-win-x64-${{ env.RELEASE_ID }}-alpha
path: |
${{ runner.temp }}/releases/reims-runtime-*.tar.zst
${{ runner.temp }}/releases/SHA256SUMS.txt
retention-days: 14
compression-level: 0
retention-days: 3
- name: Publish alpha prerelease (never stable)
if: steps.plan.outputs.skip != 'true' && (github.event_name == 'push' || github.event_name == 'schedule' || inputs.publish)
@@ -271,7 +334,8 @@ jobs:
$sourceRepo = $env:UPSTREAM_URL -replace '\.git$', ''
$dir = Join-Path $env:RUNNER_TEMP 'releases'
$assets = @("reims-runtime-win-x64-$c.tar.zst", "reims-runtime-src-$c.tar.zst", "reims-runtime-msys2-src-$c.tar.zst", "reims-runtime-symbols-$c.tar.zst", 'SHA256SUMS.txt') |
ForEach-Object { Join-Path $dir $_ }
ForEach-Object { Join-Path $dir $_ } |
Where-Object { Test-Path -LiteralPath $_ -PathType Leaf }
$applied = if ($env:APPLIED_PATCHES) { ($env:APPLIED_PATCHES -split ',' | ForEach-Object { "- ``$_``" }) -join "`n" } else { '- (none)' }
$merged = if ($env:MERGED) { "`n`nAlready upstream, skipped (retire from patches/): $env:MERGED" } else { '' }
$compatibility = if ($env:SUSPEND_PREDECESSOR) { "`nVerified against $env:SUSPEND_PREDECESSOR. $env:SUSPEND_VERIFICATION" } else { '' }
+15
View File
@@ -28,6 +28,8 @@ them; its `manual` checks are on a Linux host's guest boot.
| `displays=2` | the reims-graphics device's displays, 1 to 4, a window each (QEMU's reims-graphics-pci property; 1 by default) |
| `REIMS_VGPU_WINDOW_IMPL=sdl` | macOS, built with the `macos-sdl` feature (on by default): SDL3's window in place of AppKit's ("On macOS through SDL3" below) |
| `REIMS_VGPU_WINDOW_CAPTURE=0` | capture off: no window ever captures the keyboard or the pointer ("Capture off" below); reims-ctl sets it for a VM whose capture setting is off |
| `REIMS_VGPU_WINDOW_RELEASE_KEYS=Ctrl+Shift+F12` | additional release shortcut for SDL windows on Windows and Linux; when unset, `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS` can supply it |
| `REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE=1` | on Windows and Linux, allow the pointer to leave a captured SDL window and release input when it leaves |
Unset or unparsable values give the defaults below.
`test: env::unset_or_unparsable_values_are_the_defaults`,
@@ -700,6 +702,19 @@ runtime's own device. The switches above apply, and `resolution=` too.
`test: sdl::shell::the_end_lets_go_of_the_grab_and_the_holds`,
`test: sdl::shell::the_pointer_is_held_over_the_image_in_whole_points`,
`manual` (the grab and the hold)
- An additional release shortcut uses at least one modifier and one to three
ordinary keys. The captured title shows the shortcut, and an empty or
invalid setting uses the default. The built-in release chord still works
with an additional shortcut set.
`test: native::sdl_thread::input::custom_shortcut_releases_capture_without_forwarding_its_final_key`,
`test: native::sdl_thread::input::custom_shortcut_can_hold_two_regular_keys`,
`test: native::sdl_thread::input::invalid_shortcut_keeps_the_default`
- With release on mouse leave enabled, capture allows the pointer out of the
window. The SDL mouse-leave event lifts held keys and buttons and releases
capture. This setting also turns off relative pointer locks in games and
at a shared display edge.
`test: native::sdl_thread::input::leaving_the_window_releases_mouse_and_keyboard_when_enabled`,
`manual` (move the pointer out of a captured SDL window)
- Scrolling: the wheel's notches, or, where the host takes smooth
scrolling, its lines at 10 points each, in no gesture (SDL gives no
phases); the guest gets the device's own direction.
+18
View File
@@ -14,6 +14,9 @@
//! no window ever captures the keyboard or the pointer ([`crate::capture`]). `1`, `true`,
//! `yes` or `on` turns it on. Default: [`CAPTURE_DEFAULT`]. reims-ctl sets it from a VM's
//! settings.
//! - `REIMS_VGPU_WINDOW_RELEASE_KEYS`: an additional SDL window capture release shortcut,
//! such as `Ctrl+Shift+F12`. Reims-Go's capture shortcut plugin can supply it through its
//! own namespace. The original release chord remains available.
use std::sync::OnceLock;
@@ -25,6 +28,11 @@ pub const SCREENS_VAR: &str = "REIMS_VGPU_WINDOW_SCREENS";
pub const IMPL_VAR: &str = "REIMS_VGPU_WINDOW_IMPL";
/// The capture switch's variable.
pub const CAPTURE_VAR: &str = "REIMS_VGPU_WINDOW_CAPTURE";
/// The extra release shortcut for Windows and Linux SDL windows.
pub const RELEASE_KEYS_VAR: &str = "REIMS_VGPU_WINDOW_RELEASE_KEYS";
/// The same shortcut supplied through the Reims-Go capture shortcut plugin.
const PLUGIN_RELEASE_KEYS_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_KEYS";
const PLUGIN_RELEASE_ON_LEAVE_VAR: &str = "REIMS_PLUGIN_LOCAL_CAPTURE_SHORTCUT_RELEASE_ON_LEAVE";
/// Whether a click into the image captures input where the capture switch is unset.
pub const CAPTURE_DEFAULT: bool = true;
@@ -40,6 +48,10 @@ pub struct Settings {
pub window_impl: WindowImpl,
/// Whether a click into the image captures input; off, nothing ever does.
pub capture: bool,
/// Additional shortcut text for the SDL window.
pub release_keys: Option<String>,
/// Let the mouse leave the SDL window and release input when it does.
pub release_on_leave: bool,
}
impl Default for Settings {
@@ -49,6 +61,8 @@ impl Default for Settings {
screens: Vec::new(),
window_impl: WindowImpl::AppKit,
capture: CAPTURE_DEFAULT,
release_keys: None,
release_on_leave: false,
}
}
}
@@ -126,6 +140,10 @@ pub fn settings() -> &'static Settings {
Settings {
window_impl: parse_impl(var(IMPL_VAR).as_deref()),
capture: parse_capture(var(CAPTURE_VAR).as_deref()),
release_keys: var(RELEASE_KEYS_VAR).or_else(|| var(PLUGIN_RELEASE_KEYS_VAR)),
release_on_leave: var(PLUGIN_RELEASE_ON_LEAVE_VAR)
.as_deref()
.is_some_and(parse_switch),
..parse(borderless.as_deref(), screens.as_deref())
}
})
@@ -81,7 +81,7 @@ use crate::config::{
};
use crate::game::Game;
use crate::geometry::{self, Rect};
use crate::keys::{KeyEvent, KeyState};
use crate::keys::{KeyEvent, KeyState, Modifiers};
use crate::scroll::POINTS_PER_LINE;
/// How soon after the window gains the keyboard a click is the one that focused it, in
@@ -180,6 +180,99 @@ fn fixed(points: f64) -> i32 {
}
}
/// An additional release shortcut, using USB key positions like SDL's keyboard path.
#[derive(Debug)]
pub(crate) struct ReleaseShortcut {
modifiers: Modifiers,
keys: Vec<u16>,
name: String,
}
impl ReleaseShortcut {
pub(crate) fn parse(value: &str) -> Option<Self> {
let parts = value.split('+').map(str::trim).map(str::to_ascii_uppercase);
let mut modifiers = Modifiers::default();
let mut keys = Vec::new();
let mut key_names = Vec::new();
for part in parts {
let held = match part.as_str() {
"CTRL" => &mut modifiers.control,
"ALT" => &mut modifiers.option,
"SHIFT" => &mut modifiers.shift,
"WIN" | "SUPER" => &mut modifiers.command,
_ => {
let key = Self::parse_key(&part)?;
if keys.len() == 3 || keys.contains(&key) {
return None;
}
keys.push(key);
key_names.push(part);
continue;
}
};
if std::mem::replace(held, true) {
return None;
}
}
if modifiers == Modifiers::default() || keys.is_empty() {
return None;
}
let mut name = String::new();
for (held, label) in [
(modifiers.control, "Ctrl+"),
(modifiers.option, "Alt+"),
(modifiers.shift, "Shift+"),
(
modifiers.command,
if cfg!(windows) { "Win+" } else { "Super+" },
),
] {
if held {
name.push_str(label);
}
}
name.push_str(&key_names.join("+"));
Some(Self {
modifiers,
keys,
name,
})
}
fn parse_key(key_name: &str) -> Option<u16> {
let key = match key_name.as_bytes() {
[letter @ b'A'..=b'Z'] => u16::from(*letter - b'A') + 0x04,
[digit @ b'1'..=b'9'] => u16::from(*digit - b'1') + 0x1e,
[b'0'] => 0x27,
_ => {
let number = key_name.strip_prefix('F')?.parse::<u16>().ok()?;
if !matches!(
key_name,
"F1" | "F2"
| "F3"
| "F4"
| "F5"
| "F6"
| "F7"
| "F8"
| "F9"
| "F10"
| "F11"
| "F12"
) {
return None;
}
0x3a + number - 1
}
};
Some(key)
}
pub(crate) fn name(&self) -> &str {
&self.name
}
}
/// One window's input decisions (the module doc).
#[derive(Default)]
pub(crate) struct Input {
@@ -187,6 +280,8 @@ pub(crate) struct Input {
keys: KeyState,
/// Who gets the keyboard.
capture: Capture,
release_shortcut: Option<ReleaseShortcut>,
release_on_leave: bool,
/// The `BUTTON_*` bits of the buttons the guest was told are down.
buttons: u32,
/// The pointer event last sent.
@@ -249,6 +344,30 @@ impl Input {
Input { capture, ..self }
}
/// Sets an additional shortcut for releasing captured input.
pub(crate) fn with_release_shortcut(self, release_shortcut: Option<ReleaseShortcut>) -> Input {
Input {
release_shortcut,
..self
}
}
pub(crate) fn with_release_on_leave(self, release_on_leave: bool) -> Input {
Input {
release_on_leave,
..self
}
}
/// Let the host have the keyboard and pointer when the mouse leaves the window.
pub(crate) fn mouse_left(&mut self) -> Reaction {
if !self.release_on_leave || !self.is_captured() {
return Reaction::default();
}
self.lift_buttons();
self.release_capture()
}
/// Whether the captured pointer has gone past the image's edge.
#[cfg(test)]
pub(crate) fn is_away(&self) -> bool {
@@ -307,13 +426,26 @@ impl Input {
/// Where the pointer is held over `image`, the image's rectangle in the window's points: the
/// image while captured ([`Capture::pointer_confinement`]).
pub(crate) fn pointer_confinement(&self, image: Rect) -> Option<Rect> {
self.capture.pointer_confinement(image)
if self.release_on_leave {
None
} else {
self.capture.pointer_confinement(image)
}
}
/// What the title ends with: the release chord while captured, in the host's OS's names for
/// its keys, and that a click captures while not ([`Capture::title_suffix`]).
pub(crate) fn title_suffix(&self) -> &'static str {
self.capture.title_suffix(HOST_OS)
pub(crate) fn title_suffix(&self) -> std::borrow::Cow<'_, str> {
if self.is_captured()
&& let Some(shortcut) = &self.release_shortcut
{
return format!(
" \u{2014} input captured (press {} to release)",
shortcut.name
)
.into();
}
self.capture.title_suffix(HOST_OS).into()
}
/// What to send, taken.
@@ -345,7 +477,8 @@ impl Input {
return;
}
if let (Some(point), Some(mode)) = (at.point, guest_mode(at)) {
if self.capture.is_captured()
if !self.release_on_leave
&& self.capture.is_captured()
&& let Some(motion) = self.motion.clone()
&& let Some(hold) = self.game.begin(motion.as_ref(), point)
{
@@ -356,7 +489,8 @@ impl Input {
Some(ToHost::Pointer { at, .. }) => Some(at),
_ => None,
};
if self.capture.is_captured()
if !self.release_on_leave
&& self.capture.is_captured()
&& let Some(beyond) = self.beyond.clone()
&& let Some(hold) =
self.away
@@ -552,6 +686,18 @@ impl Input {
}
return Reaction::default();
}
if self.is_captured()
&& let Some(shortcut) = &self.release_shortcut
&& shortcut.keys.contains(&usage)
&& shortcut
.keys
.iter()
.all(|&key| key == usage || self.keys.is_held(key))
&& shortcut.modifiers == self.keys.held_modifiers()
&& !repeat
{
return self.release_capture();
}
if let Some(event) = self.keys.key_down(usage, repeat) {
self.out.push(ToHost::Key(event));
}
@@ -865,6 +1011,80 @@ mod tests {
assert_eq!(input.title_suffix(), UNCAPTURED_SUFFIX);
}
#[test]
fn custom_shortcut_releases_capture_without_forwarding_its_final_key() {
let mut input =
focused().with_release_shortcut(ReleaseShortcut::parse(" shift + ctrl + f12 "));
input.button_down(BUTTON_LEFT, 1_000_000_000, &at((10.0, 10.0)));
input.button_up(BUTTON_LEFT, &at((10.0, 10.0)));
assert!(input.title_suffix().contains("Ctrl+Shift+F12"));
input.take();
input.key(0xE0, true, false);
input.key(0xE1, true, false);
let reaction = input.key(0x45, true, false);
assert!(reaction.capture_changed && !input.is_captured());
assert_eq!(
input.take(),
vec![
ToHost::Key(KeyEvent::down(0xE0)),
ToHost::Key(KeyEvent::down(0xE1)),
ToHost::Key(KeyEvent::up(0xE1)),
ToHost::Key(KeyEvent::up(0xE0)),
]
);
}
#[test]
fn invalid_shortcut_keeps_the_default() {
for value in [
"",
"F12",
"Ctrl+Shift",
"Ctrl+Ctrl+F12",
"Ctrl+F13",
"Ctrl+F01",
] {
assert!(ReleaseShortcut::parse(value).is_none(), "{value:?}");
}
}
#[test]
fn custom_shortcut_can_hold_two_regular_keys() {
let mut input = focused().with_release_shortcut(ReleaseShortcut::parse("Ctrl+A+Z"));
let point = at((10.0, 10.0));
input.button_down(BUTTON_LEFT, 1_000_000_000, &point);
input.button_up(BUTTON_LEFT, &point);
assert!(input.title_suffix().contains("Ctrl+A+Z"));
assert!(!input.key(0xe0, true, false).capture_changed);
assert!(!input.key(0x04, true, false).capture_changed);
assert!(input.key(0x1d, true, false).capture_changed);
}
#[test]
fn leaving_the_window_releases_mouse_and_keyboard_when_enabled() {
for enabled in [false, true] {
let mut input = focused().with_release_on_leave(enabled);
let point = at((10.0, 10.0));
input.button_down(BUTTON_LEFT, 1_000_000_000, &point);
input.key(0x04, true, false);
assert!(input.is_captured());
assert_eq!(input.pointer_confinement(point.image).is_none(), enabled);
input.take();
assert_eq!(input.mouse_left().capture_changed, enabled);
assert_eq!(input.is_captured(), !enabled);
if enabled {
let events = input.take();
assert!(events.contains(&ToHost::Key(KeyEvent::up(0x04))));
assert!(
events
.iter()
.any(|event| matches!(event, ToHost::Pointer { buttons: 0, .. }))
);
assert!(!input.mouse_left().capture_changed);
}
}
}
/// With capture off, a click in the image is sent but captures nothing, so nothing holds the
/// pointer; the pointer outside the image is sent only in a drag; Ctrl, Alt and the GUI key
/// are the guest's keys and release nothing; the title says capture is off
@@ -113,6 +113,10 @@ impl Input {
self.0.focus_lost().capture_changed
}
pub(crate) fn mouse_left(&mut self) -> bool {
self.0.mouse_left().capture_changed
}
/// Whether input, the keyboard and the pointer, is captured.
pub(crate) fn is_captured(&self) -> bool {
self.0.is_captured()
@@ -124,7 +128,7 @@ impl Input {
}
/// What the title ends with in the current capture state.
pub(crate) fn title_suffix(&self) -> &'static str {
pub(crate) fn title_suffix(&self) -> std::borrow::Cow<'_, str> {
self.0.title_suffix()
}
@@ -211,6 +215,25 @@ pub(crate) fn open(window: &Arc<Window>, borderless: bool, _taken: &[Frame]) ->
display.0
);
let callbacks = window.callbacks();
let settings = crate::env::settings();
let release_shortcut = settings
.release_keys
.as_deref()
.and_then(input::ReleaseShortcut::parse);
if settings
.release_keys
.as_deref()
.is_some_and(|keys| !keys.trim().is_empty())
&& release_shortcut.is_none()
{
log::warn!(target: "reims_vgpu_window", "invalid input release shortcut; using the default");
}
log::info!(target: "reims_vgpu_window",
"input settings: capture={}, release shortcut={}, release on mouse leave={}",
settings.capture,
release_shortcut.as_ref().map_or("default", input::ReleaseShortcut::name),
settings.release_on_leave,
);
Some(Opened {
sdl,
asked: size,
@@ -221,7 +244,9 @@ pub(crate) fn open(window: &Arc<Window>, borderless: bool, _taken: &[Frame]) ->
.and_then(|callbacks| callbacks.beyond.clone()),
callbacks.and_then(|callbacks| callbacks.motion),
)
.with_capture(Capture::with_setting(crate::env::settings().capture)),
.with_capture(Capture::with_setting(settings.capture))
.with_release_shortcut(release_shortcut)
.with_release_on_leave(settings.release_on_leave),
),
state: State {
display,
+5 -1
View File
@@ -388,7 +388,11 @@ impl Shell {
// SDL's cursor is the process's: another window may have hidden it.
self.over_image = false;
self.refresh_cursor();
false
#[cfg(any(target_os = "linux", target_os = "windows"))]
let released = k == SDL_EVENT_WINDOW_MOUSE_LEAVE.0 && self.input.mouse_left();
#[cfg(target_os = "macos")]
let released = false;
released
}
_ => os::input_event(self, kind, event),
};
+1 -2
View File
@@ -212,8 +212,7 @@ std::string rgfxFamilyNameOf(const char *name);
std::string rgfxVendorNameOf(const char *name);
/// The `name` an x86-64 guest's Metal device answers where the host names its GPU `hostName`
/// (the device info's name, NUL-terminated): the kext's x86-64 name (rgfxX86Name,
/// guest/kext/src/RgfxDeviceName.hpp), which the kext states as the GPU's `model` too. That is
/// (the device info's name, NUL-terminated): rgfxX86Name (guest/kext/src/RgfxDeviceName.hpp). It is
/// "AMD - " and the host's name with the vendor words "Intel" and "NVIDIA" taken out, in any
/// case, each with a mark directly after it ("(R)", "(TM)", "®", "™") and then one space, on
/// every type of GPU (integrated, discrete, virtual, CPU, other): "AMD - Iris(R) Xe Graphics
+1 -1
View File
@@ -1519,7 +1519,7 @@ static NSString *rgfxHostNameOf(const RgfxCaps &caps)
return @"reims-graphics";
}
// On an x86-64 guest the x86-64 name, the kext's `model` there (rgfxMetalNameOf): "AMD - " and the
// On an x86-64 guest the Metal compatibility name (rgfxMetalNameOf): "AMD - " and the
// host's name without "Intel" and "NVIDIA", on every type of GPU: "AMD - GeForce RTX 3090",
// "AMD - Iris(R) Xe Graphics (RPL-P)". On an arm64 guest the host's name.
- (NSString *)name
+1 -3
View File
@@ -551,9 +551,7 @@ bool RgfxAccelerator::start(IOService *provider)
setProperty("VRAM,totalMB", memory.vramMB, 32);
}
}
// The GPU's name, as a Mac's GPU states it (RgfxDeviceName.hpp): `model` on the PCI device,
// which System Information shows as its Chipset Model. On an arm64 guest a host that gave no
// name has none stated.
// The host GPU's name as the PCI `model` that System Information shows as its Chipset Model.
{
uint8_t model[kRgfxDeviceModelMax];
const size_t length = readDeviceModel(model);
+1 -1
View File
@@ -432,7 +432,7 @@ public:
// false where the region is not mapped.
bool readMemorySize(RgfxMemorySize *out) const;
// The GPU's `model` bytes, from the host's device name (RgfxDeviceName.hpp): how many, 0
// where the region is not mapped or, on an arm64 guest, the host gave no name.
// where the region is not mapped or the host gave no name.
size_t readDeviceModel(uint8_t (&out)[kRgfxDeviceModelMax]) const;
// Shared events' ports (RgfxSharedEventUserClient.hpp): the client of ours that holds context
+13 -30
View File
@@ -1,9 +1,7 @@
// RgfxDeviceName: the GPU name the kext states to the guest, from the host's device name in the
// device info (RgfxDeviceInfo's name_len and name, written at RGFX_DEVICE_INFO_OFFSET when the
// device is made). On an arm64 guest it is the host's name whole. On an x86-64 guest it is the
// x86-64 name (rgfxX86Name): "AMD - " and the host's name without the vendor words "Intel" and
// "NVIDIA", on every host GPU. The bundle's Metal device answers the same name as its `name`
// on either guest (rgfxMetalNameOf, guest/bundle/src/RgfxCaps.hpp).
// RgfxDeviceName: the PCI model the kext states to the guest and the compatibility name the
// x86-64 Metal bundle answers. Both use the host's name from RgfxDeviceInfo. The PCI model
// keeps the host's name on both architectures. The x86-64 Metal name adds "AMD - " and drops
// the vendor words "Intel" and "NVIDIA" (rgfxX86Name, used by the bundle's rgfxMetalNameOf).
//
// A Mac's GPU states its name as its IOPCIDevice's `model`, an OSData of the name's bytes, which
// System Information shows as the GPU's "Chipset Model"; without one it shows "Graphics" and the
@@ -11,9 +9,8 @@
// 630's `model` is its 22 bytes and a NUL, the AMD Radeon Pro 5300M's its 20 bytes with none,
// and System Information names both. So the kext sets `model` as the Intel's is: the name's
// bytes, then a NUL. The host's name is its first name_len bytes (at most RGFX_DEVICE_NAME_LEN),
// cut at a NUL among them. On an arm64 guest, a host that gave no name (name_len 0, or a NUL
// first) has none stated; on an x86-64 guest it has "AMD - reims-graphics", as the bundle
// answers.
// cut at a NUL among them. The kext publishes no model when the host supplies no name
// (name_len 0 or a NUL first).
//
// Why the x86-64 name holds no vendor word: WindowServer's compositor (SkyLight, read from its
// code) takes a Metal device whose name holds "Intel" for an Intel GPU, and then scales a
@@ -25,9 +22,8 @@
// macOS 26.7.2 and 15.8.2. The compositor's other test, a name holding "NVIDIA", is the other
// vendor word: without either, every host takes the path of an AMD GPU's Mac.
//
// Header-only and free of the kernel's headers, so its native tests (tests/device_name_test.cpp,
// built for the x86-64 kext's rules and, as device_name_arm64_test, the arm64e kext's) build it
// as the kext does, and the bundle builds rgfxX86Name as the kext does.
// Header-only and free of the kernel's headers, so the native tests and Metal bundle can
// build it too.
//
// Our own code; it depends only on the committed wire header.
#ifndef RGFX_DEVICE_NAME_HPP_
@@ -38,10 +34,6 @@
#include <stddef.h>
#include <stdint.h>
#ifndef RGFX_GUEST_ARM64
#define RGFX_GUEST_ARM64 0
#endif
// The bytes of RgfxDeviceInfo the kext reads for the name: from name_len to the name's end.
static constexpr uint64_t kRgfxDeviceNameFirst = offsetof(RgfxDeviceInfo, name_len);
static constexpr uint64_t kRgfxDeviceNameEnd = offsetof(RgfxDeviceInfo, name) + RGFX_DEVICE_NAME_LEN;
@@ -54,8 +46,8 @@ static constexpr size_t kRgfxX86NamePrefixLen = sizeof(kRgfxX86NamePrefix) - 1;
// The most bytes of an x86-64 name: the prefix, a whole name field and a NUL.
static constexpr size_t kRgfxX86NameMax = kRgfxX86NamePrefixLen + RGFX_DEVICE_NAME_LEN + 1;
// The most bytes of `model`: the x86-64 name's, the longer of the two guests'.
static constexpr size_t kRgfxDeviceModelMax = kRgfxX86NameMax;
// The most bytes of `model`: the full name field and a NUL.
static constexpr size_t kRgfxDeviceModelMax = RGFX_DEVICE_NAME_LEN + 1;
// The vendor words the x86-64 name holds none of, and the marks it takes out with one directly
// before them: "(R)" and "(TM)", and the UTF-8 of "®" and "™". In lower case: each matches in
@@ -138,7 +130,7 @@ inline size_t rgfxX86Name(const uint8_t *name, size_t length, char (&out)[kRgfxX
return kRgfxX86NamePrefixLen + n;
}
// `model`'s bytes on an arm64 guest into `out`, from a name_len and the name field's
// `model`'s bytes into `out`, from a name_len and the name field's
// RGFX_DEVICE_NAME_LEN bytes: the host's name and a NUL. How many, its NUL counted, or 0 when
// the host gave no name.
inline size_t rgfxDeviceModel(uint32_t nameLen, const uint8_t *name, uint8_t (&out)[kRgfxDeviceModelMax])
@@ -155,23 +147,14 @@ inline size_t rgfxDeviceModel(uint32_t nameLen, const uint8_t *name, uint8_t (&o
return n + 1;
}
// `model`'s bytes on an x86-64 guest into `out`, from a name_len and the name field's
// RGFX_DEVICE_NAME_LEN bytes: the x86-64 name (rgfxX86Name) and a NUL. How many, its NUL
// counted; never 0.
inline size_t rgfxDeviceModelX86(uint32_t nameLen, const uint8_t *name, uint8_t (&out)[kRgfxDeviceModelMax])
{
return rgfxX86Name(name, nameLen, reinterpret_cast<char (&)[kRgfxX86NameMax]>(out)) + 1;
}
// `model`'s bytes out of the device info's bytes from kRgfxDeviceNameFirst to kRgfxDeviceNameEnd,
// as the kext's guest takes them (RGFX_GUEST_ARM64).
// `model`'s bytes out of the device info span.
inline size_t rgfxDeviceModelFrom(const uint8_t *span, uint8_t (&out)[kRgfxDeviceModelMax])
{
uint32_t nameLen = 0;
for (unsigned i = 0; i < sizeof(nameLen); i++)
nameLen |= static_cast<uint32_t>(span[i]) << (8 * i);
const uint8_t *name = span + (offsetof(RgfxDeviceInfo, name) - kRgfxDeviceNameFirst);
return RGFX_GUEST_ARM64 ? rgfxDeviceModel(nameLen, name, out) : rgfxDeviceModelX86(nameLen, name, out);
return rgfxDeviceModel(nameLen, name, out);
}
#endif // RGFX_DEVICE_NAME_HPP_
+4 -74
View File
@@ -1,10 +1,5 @@
// The native test of RgfxDeviceName.hpp: the `model` bytes the kext states on the PCI device, from
// the host's device name, as each guest's kext takes it (built twice: device_name_test for the
// x86-64 kext, device_name_arm64_test with RGFX_GUEST_ARM64 for the arm64e kext). Both cut the
// host's name at its length, at the field and at a NUL, and end it with a NUL, as an Intel Mac's
// Intel UHD Graphics 630 states its own (measured, macOS 26.7.1). The arm64e kext states the
// host's name whole, and none for no name. The x86-64 kext states the x86-64 name, "AMD - " and
// the host's name without "Intel" and "NVIDIA", and "AMD - reims-graphics" for no name.
// The native test of the PCI model bytes the kext publishes on either architecture.
// The bytes come from the host name, bounded by its length, field size, and any NUL.
#include "RgfxDeviceName.hpp"
#include <cstdio>
@@ -43,40 +38,18 @@ bool is(const uint8_t *model, size_t n, const char *want)
return n == len + 1 && !std::memcmp(model, want, len) && model[len] == 0;
}
#if !RGFX_GUEST_ARM64
// Whether `s` holds "intel" or "nvidia" in any ASCII case.
bool holdsVendorWord(const uint8_t *s, size_t n)
{
for (size_t i = 0; i < n; i++) {
for (const char *vendor : kRgfxVendorWords) {
if (rgfxMatchAnyCase(s + i, n - i, vendor))
return true;
}
}
return false;
}
// The x86-64 name of `host` through the device info.
bool x86NameIs(const char *host, const char *want)
{
uint8_t model[kRgfxDeviceModelMax];
const size_t n = fromDeviceInfo(static_cast<uint32_t>(std::strlen(host)), host, std::strlen(host), model);
return is(model, n, want) && !holdsVendorWord(model, n);
}
#endif
} // namespace
int main()
{
uint8_t model[kRgfxDeviceModelMax];
const char intel[] = "Intel UHD Graphics 630";
const char nvidia[] = "NVIDIA GeForce RTX 5080 Laptop GPU";
const char nvidia[] = "NVIDIA GeForce RTX 5090";
uint8_t full[RGFX_DEVICE_NAME_LEN];
for (size_t i = 0; i < sizeof(full); i++)
full[i] = static_cast<uint8_t>('A' + i % 26);
size_t n = 0;
#if RGFX_GUEST_ARM64
// A host GPU's name: its bytes and a NUL, as the Intel GPU's 23 bytes of `model`.
n = fromDeviceInfo(22, intel, 22, model);
check(n == 23, "a 22-byte name is 23 bytes of model");
@@ -108,49 +81,6 @@ int main()
// A NUL inside the length: the name up to it.
n = fromDeviceInfo(10, "AMD\0Radeon", 10, model);
check(is(model, n, "AMD"), "a NUL inside the length ends the name");
#else
// A host GPU's name: "AMD - " and the name without its vendor words, then a NUL.
check(x86NameIs(intel, "AMD - UHD Graphics 630"), "Intel's word and its space go");
check(x86NameIs(nvidia, "AMD - GeForce RTX 5080 Laptop GPU"), "NVIDIA's word and its space go");
check(x86NameIs("Intel(R) Iris(R) Xe Graphics (RPL-P)", "AMD - Iris(R) Xe Graphics (RPL-P)"),
"a mark after the word goes with it; a later one stays");
check(x86NameIs("Intel(R) UHD Graphics 630 (CFL GT2)", "AMD - UHD Graphics 630 (CFL GT2)"),
"the UHD 630 on Linux");
check(x86NameIs("Intel(R) Arc(tm) A770 Graphics (DG2)", "AMD - Arc(tm) A770 Graphics (DG2)"),
"the A770");
check(x86NameIs("NVIDIA GeForce RTX 3090", "AMD - GeForce RTX 3090"), "the 3090");
check(x86NameIs("AMD Radeon 780M Graphics (RADV PHOENIX)",
"AMD - AMD Radeon 780M Graphics (RADV PHOENIX)"),
"an AMD GPU's name whole");
check(x86NameIs("intel(tm) nViDiA\xc2\xae X\xe2\x84\xa2", "AMD - X\xe2\x84\xa2"),
"any case and either UTF-8 mark; a mark after no word stays");
check(x86NameIs("InNVIDIAtel(R) X", "AMD - X"), "a word that taking one out leaves goes too");
check(x86NameIs("Mesa Intel", "AMD - Mesa "), "a word at the end; the space before it stays");
// No name, or nothing left: "reims-graphics" after the prefix; a NUL first is no name.
check(fromDeviceInfo(0, intel, 22, model) == 21 && is(model, 21, "AMD - reims-graphics"),
"name_len 0 is AMD - reims-graphics");
n = fromDeviceInfo(5, "\0abcd", 5, model);
check(is(model, n, "AMD - reims-graphics"), "a NUL first is no name");
check(x86NameIs("NVIDIA", "AMD - reims-graphics"), "a name of a vendor word alone leaves none");
check(x86NameIs("Intel(R) ", "AMD - reims-graphics"), "a word, its mark and its space leave none");
// A whole field, 256 bytes and no NUL in it: the prefix, all of them, then a NUL.
n = fromDeviceInfo(RGFX_DEVICE_NAME_LEN, full, sizeof(full), model);
check(n == kRgfxDeviceModelMax, "a full field is the prefix, 256 bytes and a NUL");
check(!std::memcmp(model, "AMD - ", 6) && !std::memcmp(model + 6, full, sizeof(full)) &&
model[kRgfxDeviceModelMax - 1] == 0,
"every byte of a full field after the prefix, NUL-ended");
// A length past the field reads the field alone, never the bytes after it (architecture_name).
n = fromDeviceInfo(UINT32_MAX, full, sizeof(full), model);
check(n == kRgfxDeviceModelMax && model[kRgfxDeviceModelMax - 1] == 0, "a length past the field is cut to it");
// A length short of the name: its first bytes; a NUL inside the length ends it.
n = fromDeviceInfo(11, nvidia, sizeof(nvidia) - 1, model);
check(is(model, n, "AMD - GeFo"), "name_len bounds the name before its words go");
n = fromDeviceInfo(10, "AMD\0Radeon", 10, model);
check(is(model, n, "AMD - AMD"), "a NUL inside the length ends the name");
#endif
// The span the kext reads holds name_len and the whole field, and lies inside the device info.
check(kRgfxDeviceNameFirst == offsetof(RgfxDeviceInfo, name_len), "the span starts at name_len");
@@ -158,6 +88,6 @@ int main()
"the span ends at the name field's end");
check(kRgfxDeviceNameEnd <= sizeof(RgfxDeviceInfo), "the span ends inside the device info");
std::printf("device_name_test: OK (%d checks, %s kext)\n", checks, RGFX_GUEST_ARM64 ? "arm64e" : "x86-64");
std::printf("device_name_test: OK (%d checks)\n", checks);
return 0;
}
+1 -1
View File
@@ -24,7 +24,7 @@ Arch = "arm64e"
MinKernel = "23.0.0"
MaxKernel = ""
Comment = "The reims-graphics display and accelerator"
sha256 = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
sha256 = "efacd163e0b230f95ce7a43c05c87771e504137ffd6d675a14468cddc7865605"
[[kext]]
BundlePath = "RgfxGate.kext"
+9 -9
View File
@@ -3,8 +3,8 @@
# when a source or an output differs from its SHA-256 here (guest/tools/prebuilt.py).
# [built] records the local toolchain; every input is in the tree.
[built]
xcode = "Xcode 27.2 Build version 27B52"
sdk = "MacOSX27.2.sdk"
xcode = "unknown"
sdk = "MacOSX.sdk"
clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
[sources]
@@ -27,7 +27,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxBuffer.h" = "4b54841a30b0559c424b8aed06fcd5edd7c172cda1bf9fd5c892e30dc066ec7d"
"guest/bundle/src/RgfxBuffer.mm" = "360a494bb58668c4c66ce468b8ac39a10ccdad16e97a538ef48a6c8fa7cadbec"
"guest/bundle/src/RgfxCaps.cpp" = "d6020aeff1adcef0b74e9bbc51dea8d849f88355e019927ee9e8fb96a3007d12"
"guest/bundle/src/RgfxCaps.hpp" = "7063a6821533fdf44d66b4363aa14ba3a4d5321b2f3df62e2e3ff16ea9764a48"
"guest/bundle/src/RgfxCaps.hpp" = "4c8e0dba604b37d4509f54518f24337090fab595c5ed12c15d13298ad195f5dd"
"guest/bundle/src/RgfxClMode.cpp" = "c5d5127ef251d119cb104015676d16a475f615680b83d48eba32c48b76e39a5c"
"guest/bundle/src/RgfxClMode.hpp" = "138c803295021645c2854f3e9cb34dac96d485719d5447151ff9168c698e7a1a"
"guest/bundle/src/RgfxCommandObjects.h" = "cd504d3df8e3560758a926d31742e052bdda77e76c2c2c23e2dc6ae07346b9bc"
@@ -111,7 +111,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxMetalDevice+Unsupported.mm" = "a424349b2a969a53609b34ae3f4b72cc2e2c9378605ba780520eeb22643c535c"
"guest/bundle/src/RgfxMetalDevice+Video.mm" = "aa53c5a15243b11155c9342ab1c7867ff5e19ced9272471f9ea76e95db01d9af"
"guest/bundle/src/RgfxMetalDevice.h" = "92708ff70a7693edebc6402a8c68fa16ed1982c27d885a74ac56f6a92b4a10a9"
"guest/bundle/src/RgfxMetalDevice.mm" = "420bd3f1c54f87eb33d27e62427b4b1c967af8976193dd8f01b02794839e3fe8"
"guest/bundle/src/RgfxMetalDevice.mm" = "f1fa5b4c56b61766dd0f89f63be3eeeef51d927b51eef0065c7c79f3de50bcdc"
"guest/bundle/src/RgfxMetalError.h" = "e4440b3c0d0617ad118f16aa56fc9cfb0e7ebbf0ef2d3f8e16b27df9fd1f9803"
"guest/bundle/src/RgfxMetalPrivate.h" = "18196f21ce0808a37c8d8913fab72e16e032c7c73064b6a81618bb9f06a478f2"
"guest/bundle/src/RgfxMetallibWriter.cpp" = "a9f0e9a4a2ef80729470051130d201806f59d0c4d1803129a3662e4afc389f13"
@@ -333,8 +333,8 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
"guest/kext/src/RgfxAccelerator.cpp" = "e05bf13fb97b0e2fbc133dc83c451dd6b063323c8f2b26d67e82b8de9912ecd4"
"guest/kext/src/RgfxAccelerator.hpp" = "148d63554b5a5eaaaf280651d0f493b3741dbaf444808554f88af0e6bc670ce8"
"guest/kext/src/RgfxAcceleratorContexts.cpp" = "77f39e6d4750dfb0f1ff5a614b9d419362f159a8eac48b18673181a01d3f0451"
"guest/kext/src/RgfxAcceleratorLocks.cpp" = "171e708b5fb87abbf39423aa08fb0343ca8dd1777f47e125288a296940667124"
"guest/kext/src/RgfxAcceleratorSurfaces.cpp" = "54c72029acb78f19cc41e80ab1e646b1bb402af45ec0f073dc07eb2236f5baa0"
@@ -358,7 +358,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxDeferredAnswers.hpp" = "b7b62b567e38da8ce27d89aa47b1001f56f8f7afeda0def2b550b1f7ad9b18c6"
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
"guest/kext/src/RgfxDeviceName.hpp" = "7085045ea0c9ca3215e58ea43f0a23309a9ba8145e9c2d5ede541093a293f9c1"
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"Graft-arm64e.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
"Graft-arm64e.kext/Contents/MacOS/Graft" = "2f405e84ddd1414b6ac32e813a4369a6d4681d9c6e7331b933bb719761b1a31a"
"ReimsGraphics.kext/Contents/Info.plist" = "9683153587659c4bd4d5c52167eff1f3d2ae51dae575f60c15a27d89240f46c5"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "efacd163e0b230f95ce7a43c05c87771e504137ffd6d675a14468cddc7865605"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
"set.toml" = "a4da2409f25dd7bf12260de752c38c474b60d4b2d993810a44de0f4b07cb6dfd"
"set.toml" = "a0be05b8801df322a6d2276bb41821682c473157227fa29c7aef46e5ff171868"
+1 -1
View File
@@ -24,7 +24,7 @@ Arch = "x86_64"
MinKernel = "20.0.0"
MaxKernel = ""
Comment = "The reims-graphics display, accelerator and device control"
sha256 = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
sha256 = "c8b23bcde87d6d0415d09cbdf47ad444afe0c0ea2f51dca1a4583be8bea75f6e"
[[kext]]
BundlePath = "RgfxGate.kext"
+9 -9
View File
@@ -3,8 +3,8 @@
# when a source or an output differs from its SHA-256 here (guest/tools/prebuilt.py).
# [built] records the local toolchain; every input is in the tree.
[built]
xcode = "Xcode 27.2 Build version 27B52"
sdk = "MacOSX27.2.sdk"
xcode = "unknown"
sdk = "MacOSX.sdk"
clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
[sources]
@@ -27,7 +27,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxBuffer.h" = "4b54841a30b0559c424b8aed06fcd5edd7c172cda1bf9fd5c892e30dc066ec7d"
"guest/bundle/src/RgfxBuffer.mm" = "360a494bb58668c4c66ce468b8ac39a10ccdad16e97a538ef48a6c8fa7cadbec"
"guest/bundle/src/RgfxCaps.cpp" = "d6020aeff1adcef0b74e9bbc51dea8d849f88355e019927ee9e8fb96a3007d12"
"guest/bundle/src/RgfxCaps.hpp" = "7063a6821533fdf44d66b4363aa14ba3a4d5321b2f3df62e2e3ff16ea9764a48"
"guest/bundle/src/RgfxCaps.hpp" = "4c8e0dba604b37d4509f54518f24337090fab595c5ed12c15d13298ad195f5dd"
"guest/bundle/src/RgfxClMode.cpp" = "c5d5127ef251d119cb104015676d16a475f615680b83d48eba32c48b76e39a5c"
"guest/bundle/src/RgfxClMode.hpp" = "138c803295021645c2854f3e9cb34dac96d485719d5447151ff9168c698e7a1a"
"guest/bundle/src/RgfxCommandObjects.h" = "cd504d3df8e3560758a926d31742e052bdda77e76c2c2c23e2dc6ae07346b9bc"
@@ -111,7 +111,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/bundle/src/RgfxMetalDevice+Unsupported.mm" = "a424349b2a969a53609b34ae3f4b72cc2e2c9378605ba780520eeb22643c535c"
"guest/bundle/src/RgfxMetalDevice+Video.mm" = "aa53c5a15243b11155c9342ab1c7867ff5e19ced9272471f9ea76e95db01d9af"
"guest/bundle/src/RgfxMetalDevice.h" = "92708ff70a7693edebc6402a8c68fa16ed1982c27d885a74ac56f6a92b4a10a9"
"guest/bundle/src/RgfxMetalDevice.mm" = "420bd3f1c54f87eb33d27e62427b4b1c967af8976193dd8f01b02794839e3fe8"
"guest/bundle/src/RgfxMetalDevice.mm" = "f1fa5b4c56b61766dd0f89f63be3eeeef51d927b51eef0065c7c79f3de50bcdc"
"guest/bundle/src/RgfxMetalError.h" = "e4440b3c0d0617ad118f16aa56fc9cfb0e7ebbf0ef2d3f8e16b27df9fd1f9803"
"guest/bundle/src/RgfxMetalPrivate.h" = "18196f21ce0808a37c8d8913fab72e16e032c7c73064b6a81618bb9f06a478f2"
"guest/bundle/src/RgfxMetallibWriter.cpp" = "a9f0e9a4a2ef80729470051130d201806f59d0c4d1803129a3662e4afc389f13"
@@ -333,8 +333,8 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/ReimsGraphicsMobile.cpp" = "b73a2e5f5b061453817c5d0b18211a2d0782f5971f02d90b0fb7f930365086de"
"guest/kext/src/ReimsGraphicsPointer.cpp" = "255f049c3a5244a148d80fd25ef3388001ba180c58901e3620451c3158908f0e"
"guest/kext/src/RgfxAccelTypes.hpp" = "c65e032a617cda503b2534c68bec87947d7856accda676f35a1affa145998259"
"guest/kext/src/RgfxAccelerator.cpp" = "319e1148d2644e922ed2c30859019392764c9e64328594c1f593c5c4fe890030"
"guest/kext/src/RgfxAccelerator.hpp" = "2711b9225040feae3e45bb8057a60b30f5d17d83d953eadc82c2db91e83e28c5"
"guest/kext/src/RgfxAccelerator.cpp" = "e05bf13fb97b0e2fbc133dc83c451dd6b063323c8f2b26d67e82b8de9912ecd4"
"guest/kext/src/RgfxAccelerator.hpp" = "148d63554b5a5eaaaf280651d0f493b3741dbaf444808554f88af0e6bc670ce8"
"guest/kext/src/RgfxAcceleratorContexts.cpp" = "77f39e6d4750dfb0f1ff5a614b9d419362f159a8eac48b18673181a01d3f0451"
"guest/kext/src/RgfxAcceleratorLocks.cpp" = "171e708b5fb87abbf39423aa08fb0343ca8dd1777f47e125288a296940667124"
"guest/kext/src/RgfxAcceleratorSurfaces.cpp" = "54c72029acb78f19cc41e80ab1e646b1bb402af45ec0f073dc07eb2236f5baa0"
@@ -358,7 +358,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/kext/src/RgfxDeferredAnswers.hpp" = "b7b62b567e38da8ce27d89aa47b1001f56f8f7afeda0def2b550b1f7ad9b18c6"
"guest/kext/src/RgfxDeviceControl.cpp" = "53c7c6a722ef4d7edeb5756eb04091d4a56f397dc5aef83c3637b1c0f129b934"
"guest/kext/src/RgfxDeviceControl.hpp" = "c1357b80ee2141e1e2fd57213f3c9361cb497b8c6490a0b6aff8c64649be48c6"
"guest/kext/src/RgfxDeviceName.hpp" = "b242e0ccdce31c3c454bc3a4d64b13c30e574b25379a0833973dcecbbb1146d3"
"guest/kext/src/RgfxDeviceName.hpp" = "7085045ea0c9ca3215e58ea43f0a23309a9ba8145e9c2d5ede541093a293f9c1"
"guest/kext/src/RgfxDisplayBounds.hpp" = "c1e8fe52f89bcb25ee178f4e0ea4ac53396109fd934348408692d21d1931ecf7"
"guest/kext/src/RgfxDisplayIdentity.hpp" = "ce4328b8e255f942aea0f0dc097e2e80eb4a8d7e126ea0f342fd116252357731"
"guest/kext/src/RgfxDisplayModes.hpp" = "62026ac6fa3febe5ce403fbfe026760f0434b70cc47e5d74c191fa5509ae12cd"
@@ -464,7 +464,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"Graft.kext/Contents/Info.plist" = "fa8533d5ec06430f3ede502e6f9e739e9c8c3f6b6909c46d854effe6028cbc7f"
"Graft.kext/Contents/MacOS/Graft" = "04a1d44c0c80c20a71f3a662c46b56a1732b8134f095fb2ac57ec790f72baf72"
"ReimsGraphics.kext/Contents/Info.plist" = "ae0dafd3b6c36c24d1c92467d8203d76360eb6e4f6ad5c496167a21033b2c209"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "c8b23bcde87d6d0415d09cbdf47ad444afe0c0ea2f51dca1a4583be8bea75f6e"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
"set.toml" = "49182c19c3d961b251901e19a09016df684f1f102527a0d3274697eaaf3dbab5"
"set.toml" = "dcdad1148a389c4be577c0641f3f3942031df313983e09f5a445cb783a7e6a42"
-1
View File
@@ -1,2 +1 @@
patches/*.patch -text
patches/stambha-qemu/*.patch -text whitespace=-blank-at-eol,-blank-at-eof
@@ -1,261 +0,0 @@
From 7f323d0c8ed194ba81fcd3d33bfa2d3624d47e34 Mon Sep 17 00:00:00 2001
From: Reims-Go Builder <builder@reims-go.local>
Date: Thu, 3 Dec 2026 17:30:03 +0800
Subject: [PATCH 1/3] patches/series.txt: apply 4 pinned vendor/qemu patches
---
target/i386/whpx/whpx-all.c | 117 +++++++++++++++++++++++++++++++++---
util/coroutine-windows.c | 32 +++++++++-
2 files changed, 137 insertions(+), 12 deletions(-)
diff --git a/target/i386/whpx/whpx-all.c b/target/i386/whpx/whpx-all.c
index 5aa46bc3..f093b59c 100644
--- a/target/i386/whpx/whpx-all.c
+++ b/target/i386/whpx/whpx-all.c
@@ -58,6 +58,7 @@
static bool is_modern_os = true;
static bool whpx_msr_exits_available = true;
+static bool whpx_forward_startup_ipis;
static const WHV_REGISTER_NAME whpx_register_names[] = {
@@ -530,7 +531,8 @@ void whpx_set_registers(CPUState *cpu, WHPXStateLevel level)
assert(cpu_is_stopped(cpu) || qemu_cpu_is_self(cpu));
/* Assumes that cpu_synchronize_all_post_reset() runs cpu 0 first. */
- if (level == WHPX_LEVEL_RESET_STATE && cpu->cpu_index == 0) {
+ if (level == WHPX_LEVEL_RESET_STATE && cpu->cpu_index == 0 &&
+ whp_dispatch.WHvResetPartition) {
hr = whp_dispatch.WHvResetPartition(whpx->partition);
if (FAILED(hr)) {
error_report("WHPX: Failed to reset partition, hr=%08lx", hr);
@@ -1680,6 +1682,7 @@ HRESULT whpx_set_exception_exit_bitmap(UINT64 exceptions)
memset(&prop, 0, sizeof(WHV_PARTITION_PROPERTY));
prop.ExtendedVmExits.X64MsrExit = 1;
prop.ExtendedVmExits.X64CpuidExit = 1;
+ prop.ExtendedVmExits.X64ApicInitSipiExitTrap = whpx_forward_startup_ipis;
if (exceptions != 0 || whpx_get_default_exceptions() != 0) {
prop.ExtendedVmExits.ExceptionExit = 1;
@@ -2388,6 +2391,53 @@ static void whpx_inject_exceptions(CPUState* cpu)
}
}
+/* On Win10, a guest INIT/SIPI may leave a previously halted AP parked.
+ * Route just these boot-time interrupts through the WHP injection API. */
+static HRESULT whpx_forward_startup_ipi(CPUState *cpu, uint64_t icr)
+{
+ unsigned int shorthand = (icr >> APIC_ICR_DEST_SHORT_SHIFT) & 3;
+ WHV_INTERRUPT_CONTROL ipi = {
+ .Type = (icr & APIC_ICR_DELIV_MOD) >> APIC_ICR_DELIV_MOD_SHIFT,
+ .DestinationMode = !!(icr & APIC_ICR_DEST_MOD),
+ .TriggerMode = !!(icr & APIC_ICR_TRIGGER_MOD),
+ .Vector = icr & 0xff,
+ };
+ HRESULT hr;
+
+ /* INIT level deassert synchronizes arbitration IDs, without a reset. */
+ if (ipi.Type == WHvX64InterruptTypeInit && ipi.TriggerMode &&
+ !(icr & APIC_ICR_LEVEL)) {
+ return S_OK;
+ }
+ if (!shorthand) {
+ WHV_REGISTER_VALUE base = {};
+ WHV_REGISTER_NAME name = WHvX64RegisterApicBase;
+ hr = whp_dispatch.WHvGetVirtualProcessorRegisters(
+ whpx_global.partition, cpu->cpu_index, &name, 1, &base);
+ if (FAILED(hr)) {
+ return hr;
+ }
+ ipi.Destination = (base.Reg64 & MSR_IA32_APICBASE_EXTD)
+ ? (icr >> 32) : (icr >> 56);
+ return whp_dispatch.WHvRequestInterrupt(whpx_global.partition,
+ &ipi, sizeof(ipi));
+ }
+ ipi.DestinationMode = WHvX64InterruptDestinationModePhysical;
+ for (uint32_t i = 0; i <= max_vcpu_index; i++) {
+ if ((shorthand == 1 && i != cpu->cpu_index) ||
+ (shorthand == 3 && i == cpu->cpu_index)) {
+ continue;
+ }
+ ipi.Destination = i;
+ hr = whp_dispatch.WHvRequestInterrupt(whpx_global.partition,
+ &ipi, sizeof(ipi));
+ if (FAILED(hr)) {
+ return hr;
+ }
+ }
+ return S_OK;
+}
+
int whpx_vcpu_run(CPUState *cpu)
{
HRESULT hr;
@@ -2519,6 +2569,14 @@ int whpx_vcpu_run(CPUState *cpu)
ret = 0;
break;
+ case WHvRunVpExitReasonX64ApicInitSipiTrap:
+ hr = whpx_forward_startup_ipi(cpu, vcpu->exit_ctx.ApicInitSipi.ApicIcr);
+ ret = 0;
+ if (FAILED(hr)) {
+ error_report("WHPX: failed to forward startup IPI, hr=%08lx", hr);
+ ret = -1;
+ }
+ break;
case WHvRunVpExitReasonX64ApicEoi:
assert(whpx_irqchip_in_kernel());
ioapic_eoi_broadcast(vcpu->exit_ctx.ApicEoi.InterruptVector);
@@ -3211,22 +3269,56 @@ static bool whpx_tsc_deadline_refused(void)
{
WHV_REGISTER_NAME name = WHvX64RegisterTscDeadline;
WHV_REGISTER_VALUE value = {};
+ WHV_PARTITION_HANDLE probe = NULL;
+ WHV_PARTITION_PROPERTY prop = {};
HRESULT hr;
+ bool refused = false;
- hr = whp_dispatch.WHvCreateVirtualProcessor(whpx_global.partition, 0, 0);
+ /*
+ * Probe on a throwaway partition: on Windows 10 (e.g. 19045), deleting
+ * vCPU 0 on the real partition causes a subsequent WHvCreateVirtualProcessor
+ * for vCPU 0 in whpx_init_vcpu() to fail with E_INVALIDARG (0x80070057).
+ */
+ hr = whp_dispatch.WHvCreatePartition(&probe);
if (FAILED(hr)) {
return false;
}
- hr = whp_dispatch.WHvSetVirtualProcessorRegisters(whpx_global.partition,
- 0, &name, 1, &value);
- whp_dispatch.WHvDeleteVirtualProcessor(whpx_global.partition, 0);
+ prop.ProcessorCount = 1;
+ hr = whp_dispatch.WHvSetPartitionProperty(
+ probe, WHvPartitionPropertyCodeProcessorCount, &prop, sizeof(prop));
+ if (FAILED(hr)) {
+ goto out;
+ }
+ if (whpx_irqchip_in_kernel()) {
+ WHV_X64_LOCAL_APIC_EMULATION_MODE mode =
+ WHvX64LocalApicEmulationModeX2Apic;
+ hr = whp_dispatch.WHvSetPartitionProperty(
+ probe, WHvPartitionPropertyCodeLocalApicEmulationMode,
+ &mode, sizeof(mode));
+ if (FAILED(hr)) {
+ goto out;
+ }
+ }
+ hr = whp_dispatch.WHvSetupPartition(probe);
+ if (FAILED(hr)) {
+ goto out;
+ }
+ hr = whp_dispatch.WHvCreateVirtualProcessor(probe, 0, 0);
+ if (FAILED(hr)) {
+ goto out;
+ }
+ hr = whp_dispatch.WHvSetVirtualProcessorRegisters(probe, 0, &name, 1, &value);
+ whp_dispatch.WHvDeleteVirtualProcessor(probe, 0);
if (FAILED(hr)) {
warn_report("WHPX: Hyper-V refuses the TSC deadline timer's register,"
" hr=%08lx: the guest is offered no TSC deadline timer",
hr);
- return true;
+ refused = true;
}
- return false;
+
+out:
+ whp_dispatch.WHvDeletePartition(probe);
+ return refused;
}
int whpx_accel_init(AccelState *as, MachineState *ms)
@@ -3442,9 +3534,8 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
&prop,
sizeof(WHV_PARTITION_PROPERTY));
if (FAILED(hr)) {
- error_report("WHPX: Failed to enable nested virtualization, hr=%08lx", hr);
- ret = -EINVAL;
- goto error;
+ warn_report("WHPX: Failed to enable nested virtualization, hr=%08lx; continuing without nested virt", hr);
+ processor_features.Bank1.NestedVirtSupport = 0;
}
}
@@ -3584,6 +3675,12 @@ int whpx_accel_init(AccelState *as, MachineState *ms)
* We do not want to intercept any exceptions from the guest,
* until we actually start debugging with gdb.
*/
+ if (whpx_is_legacy_os() && whpx_irqchip_in_kernel() && ms->smp.max_cpus > 1) {
+ WHV_EXTENDED_VM_EXITS exits = {};
+ hr = whp_dispatch.WHvGetCapability(WHvCapabilityCodeExtendedVmExits,
+ &exits, sizeof(exits), &whpx_cap_size);
+ whpx_forward_startup_ipis = SUCCEEDED(hr) && exits.X64ApicInitSipiExitTrap;
+ }
whpx->exception_exit_bitmap = -1;
hr = whpx_set_exception_exit_bitmap(0);
diff --git a/util/coroutine-windows.c b/util/coroutine-windows.c
index 7db2e8f8..57f59ae3 100644
--- a/util/coroutine-windows.c
+++ b/util/coroutine-windows.c
@@ -26,6 +26,8 @@
#include "qemu/coroutine_int.h"
#include "qemu/coroutine-tls.h"
+#define COROUTINE_INITIAL_COMMIT_SIZE (64 * 1024)
+
typedef struct
{
Coroutine base;
@@ -72,10 +74,25 @@ static void CALLBACK coroutine_trampoline(void *co_)
Coroutine *qemu_coroutine_new(void)
{
const size_t stack_size = COROUTINE_STACK_SIZE;
+ const size_t commit_size = MIN(COROUTINE_INITIAL_COMMIT_SIZE, stack_size);
CoroutineWin32 *co;
co = g_malloc0(sizeof(*co));
- co->fiber = CreateFiber(stack_size, coroutine_trampoline, &co->base);
+ /*
+ * CreateFiber(stack_size, ...) commits the full 1 MiB stack up front,
+ * which can exhaust Windows commit charge during burst disk I/O + GPU
+ * workloads and return NULL (later crashing inside SwitchToFiber(NULL)
+ * reading 0x10). Reserve stack_size while committing only 64 KiB upfront.
+ */
+ co->fiber = CreateFiberEx(commit_size, stack_size, 0,
+ coroutine_trampoline, &co->base);
+ if (!co->fiber) {
+ fprintf(stderr,
+ "qemu_coroutine_new: CreateFiberEx(commit=%zu, reserve=%zu) failed: "
+ "GetLastError()=%lu\n",
+ commit_size, stack_size, (unsigned long)GetLastError());
+ abort();
+ }
return &co->base;
}
@@ -96,7 +113,18 @@ Coroutine *qemu_coroutine_self(void)
current = &leader->base;
set_current(current);
- leader->fiber = ConvertThreadToFiber(NULL);
+ if (IsThreadAFiber()) {
+ leader->fiber = GetCurrentFiber();
+ } else {
+ leader->fiber = ConvertThreadToFiber(NULL);
+ }
+ if (!leader->fiber) {
+ fprintf(stderr,
+ "qemu_coroutine_self: ConvertThreadToFiber failed: "
+ "GetLastError()=%lu\n",
+ (unsigned long)GetLastError());
+ abort();
+ }
}
return current;
}
--
2.55.0.windows.5
@@ -1,389 +0,0 @@
From a9b206aa666c59a62160dfa5c5c4a4a20e2805ae Mon Sep 17 00:00:00 2001
From: Reims-Go Builder <builder@reims-go.local>
Date: Thu, 3 Dec 2026 17:34:07 +0800
Subject: [PATCH 2/3] reims-go: hosted ARM64 display transport and 128-slot TCG
jump cache (control baseline)
---
accel/tcg/tb-hash.h | 10 +-
accel/tcg/tb-jmp-cache.h | 5 +
hw/display/reims-graphics-pci.c | 240 ++++++++++++++++++++++++++++++--
3 files changed, 240 insertions(+), 15 deletions(-)
diff --git a/accel/tcg/tb-hash.h b/accel/tcg/tb-hash.h
index f7b159f0..29ee4936 100644
--- a/accel/tcg/tb-hash.h
+++ b/accel/tcg/tb-hash.h
@@ -31,7 +31,7 @@
/* Only the bottom TB_JMP_PAGE_BITS of the jump cache hash bits vary for
addresses on the same page. The top bits are the same. This allows
TLB invalidation to quickly clear a subset of the hash table. */
-#define TB_JMP_PAGE_BITS (TB_JMP_CACHE_BITS / 2)
+#define TB_JMP_PAGE_BITS ((TB_JMP_CACHE_BITS + 1) / 2)
#define TB_JMP_PAGE_SIZE (1 << TB_JMP_PAGE_BITS)
#define TB_JMP_ADDR_MASK (TB_JMP_PAGE_SIZE - 1)
#define TB_JMP_PAGE_MASK (TB_JMP_CACHE_SIZE - TB_JMP_PAGE_SIZE)
@@ -45,10 +45,10 @@ static inline unsigned int tb_jmp_cache_hash_page(vaddr pc)
static inline unsigned int tb_jmp_cache_hash_func(vaddr pc)
{
- vaddr tmp;
- tmp = pc ^ (pc >> (TARGET_PAGE_BITS - TB_JMP_PAGE_BITS));
- return (((tmp >> (TARGET_PAGE_BITS - TB_JMP_PAGE_BITS)) & TB_JMP_PAGE_MASK)
- | (tmp & TB_JMP_ADDR_MASK));
+ /* Fold address bits above the slot index to spread aligned targets. */
+ vaddr slot = pc ^ (pc >> TB_JMP_PAGE_BITS);
+
+ return tb_jmp_cache_hash_page(pc) | (slot & TB_JMP_ADDR_MASK);
}
#else
diff --git a/accel/tcg/tb-jmp-cache.h b/accel/tcg/tb-jmp-cache.h
index c3a505e3..a7d434c2 100644
--- a/accel/tcg/tb-jmp-cache.h
+++ b/accel/tcg/tb-jmp-cache.h
@@ -12,7 +12,12 @@
#include "qemu/rcu.h"
#include "exec/cpu-common.h"
+#ifdef CONFIG_SOFTMMU
+/* Keep 64 page groups, with twice as many slots per group. */
+#define TB_JMP_CACHE_BITS 13
+#else
#define TB_JMP_CACHE_BITS 12
+#endif
#define TB_JMP_CACHE_SIZE (1 << TB_JMP_CACHE_BITS)
/*
diff --git a/hw/display/reims-graphics-pci.c b/hw/display/reims-graphics-pci.c
index db10858b..3f7e50df 100644
--- a/hw/display/reims-graphics-pci.c
+++ b/hw/display/reims-graphics-pci.c
@@ -245,6 +245,18 @@ struct ReimsGraphicsPCIState {
char *resolution; /* the property: each window's first size, or NULL */
uint32_t displays; /* the property: 1 to RVG_GRAPHICS_DISPLAYS_MAX */
+ bool hosted_arm64; /* ARM64 protocol over an x86 host transport */
+ uint32_t hosted_irq_generation; /* atomic; written by Reims callbacks */
+ uint64_t hosted_ram_guest_pa;
+ uint64_t hosted_ram_host_gpa;
+ uint64_t hosted_ram_bytes;
+ struct {
+ uint64_t guest_pa;
+ uint64_t host_gpa;
+ uint64_t bytes;
+ } hosted_ram_staged[64];
+ uint32_t hosted_ram_staged_count;
+ uint32_t hosted_ram_committed_count;
/* Mutable state (BQL protected) */
uint32_t input_buttons; /* RVG_WINDOW_BUTTON_* bits the guest was sent */
@@ -321,6 +333,11 @@ static void reims_graphics_pci_raise_interrupt_cb(void *ctx, uint32_t vector)
ReimsGraphicsInterruptJob *job;
bool sent = false;
+ if (s->hosted_arm64) {
+ /* The callback follows publication of the completion bytes. */
+ qatomic_inc(&s->hosted_irq_generation);
+ return;
+ }
if (qatomic_load_acquire(&s->irqfd_on)) {
event_notifier_set(&s->irqfd);
return;
@@ -1037,9 +1054,29 @@ static const MemoryRegionOps reims_graphics_pci_ops = {
* The doorbell pages: no register to read, and a write to the library on the
* vCPU, as a DOORBELL write is.
*/
+static void reims_graphics_commit_hosted_ram(ReimsGraphicsPCIState *s);
+
static uint64_t reims_graphics_doorbells_read(void *opaque, hwaddr offset,
unsigned size)
{
+ ReimsGraphicsPCIState *s = opaque;
+ uint64_t end = memory_region_size(&s->doorbells);
+
+ /* Hosted-translator-only control/IRQ readouts at top of BAR 4. */
+ if (s->hosted_arm64) {
+ if (offset == end - 0x08) {
+ return 0x52495251; /* RIRQ */
+ }
+ if (offset == end - 0x04) {
+ return qatomic_load_acquire(&s->hosted_irq_generation);
+ }
+ if (offset == end - 0x10) {
+ return 0x524d4150; /* RMAP */
+ }
+ if (offset == end - 0x14) {
+ return s->hosted_ram_committed_count;
+ }
+ }
return 0;
}
@@ -1047,6 +1084,51 @@ static void reims_graphics_doorbells_write(void *opaque, hwaddr offset,
uint64_t value, unsigned size)
{
ReimsGraphicsPCIState *s = opaque;
+ uint64_t end = memory_region_size(&s->doorbells);
+
+ if (s->hosted_arm64 && offset >= end - 0x2c && offset <= end - 0x14) {
+ uint64_t v = value & 0xffffffffULL;
+ if (offset == end - 0x2c) {
+ s->hosted_ram_guest_pa = (s->hosted_ram_guest_pa & 0xffffffff00000000ULL) | v;
+ return;
+ }
+ if (offset == end - 0x28) {
+ s->hosted_ram_guest_pa = (s->hosted_ram_guest_pa & 0x00000000ffffffffULL) | (v << 32);
+ return;
+ }
+ if (offset == end - 0x24) {
+ s->hosted_ram_host_gpa = (s->hosted_ram_host_gpa & 0xffffffff00000000ULL) | v;
+ return;
+ }
+ if (offset == end - 0x20) {
+ s->hosted_ram_host_gpa = (s->hosted_ram_host_gpa & 0x00000000ffffffffULL) | (v << 32);
+ return;
+ }
+ if (offset == end - 0x1c) {
+ s->hosted_ram_bytes = (s->hosted_ram_bytes & 0xffffffff00000000ULL) | v;
+ return;
+ }
+ if (offset == end - 0x18) {
+ s->hosted_ram_bytes = (s->hosted_ram_bytes & 0x00000000ffffffffULL) | (v << 32);
+ return;
+ }
+ if (offset == end - 0x14) {
+ if (v == 1) {
+ s->hosted_ram_staged_count = 0;
+ s->hosted_ram_committed_count = 0;
+ } else if (v == 2) {
+ if (s->hosted_ram_staged_count < 64 && s->hosted_ram_bytes != 0) {
+ uint32_t idx = s->hosted_ram_staged_count++;
+ s->hosted_ram_staged[idx].guest_pa = s->hosted_ram_guest_pa;
+ s->hosted_ram_staged[idx].host_gpa = s->hosted_ram_host_gpa;
+ s->hosted_ram_staged[idx].bytes = s->hosted_ram_bytes;
+ }
+ } else if (v == 3) {
+ reims_graphics_commit_hosted_ram(s);
+ }
+ return;
+ }
+ }
rvg_graphics_device_doorbell_write(s->device, offset, value);
}
@@ -2278,6 +2360,130 @@ static bool reims_graphics_add_memory_range(Int128 start, Int128 len,
return false;
}
+typedef struct {
+ ReimsGraphicsMemoryWalk *walk;
+ uint64_t guest_pa;
+ uint64_t host_gpa;
+ uint64_t bytes;
+} ReimsHostedClipWalk;
+
+static bool reims_graphics_clip_hosted_range(Int128 start, Int128 len,
+ const MemoryRegion *mr,
+ hwaddr offset_in_region,
+ void *opaque)
+{
+ ReimsHostedClipWalk *cw = opaque;
+ RAMBlock *rb = mr->ram_block;
+ uint64_t mr_start, mr_end, req_end, clip_start, clip_end, clip_len;
+ uint8_t *host;
+ RvgMemoryRange range;
+#ifdef _WIN32
+ RvgMemoryRangeFile file = { .handle = NULL };
+ HANDLE section;
+#else
+ RvgMemoryRangeFile file = { .fd = -1 };
+ int fd;
+#endif
+
+ if (!memory_access_is_direct(mr, true, MEMTXATTRS_UNSPECIFIED)) {
+ return false;
+ }
+ if (qemu_ram_pagesize(rb) != qemu_real_host_page_size()) {
+ return false;
+ }
+#ifdef _WIN32
+ section = qemu_ram_get_section(rb);
+ if (!section) {
+ return false;
+ }
+#else
+ fd = memory_region_get_fd(mr);
+#ifndef CONFIG_DARWIN
+ if (fd < 0 || !qemu_ram_is_shared(rb)) {
+ return false;
+ }
+#endif
+#endif
+ mr_start = int128_get64(start);
+ mr_end = mr_start + int128_get64(len);
+ req_end = cw->host_gpa + cw->bytes;
+ if (mr_end <= cw->host_gpa || mr_start >= req_end) {
+ return false;
+ }
+ clip_start = mr_start > cw->host_gpa ? mr_start : cw->host_gpa;
+ clip_end = mr_end < req_end ? mr_end : req_end;
+ clip_len = clip_end - clip_start;
+ host = (uint8_t *)memory_region_get_ram_ptr(mr) + offset_in_region +
+ (clip_start - mr_start);
+ range = (RvgMemoryRange) {
+ .physical_address = cw->guest_pa + (clip_start - cw->host_gpa),
+ .physical_length = clip_len,
+ .host_address = host,
+ };
+#if defined(_WIN32)
+ file.handle = section;
+ file.offset = qemu_ram_block_host_offset(rb, host);
+#elif !defined(CONFIG_DARWIN)
+ file.fd = fd;
+ file.offset = qemu_ram_block_host_offset(rb, host) +
+ qemu_ram_get_fd_offset(rb);
+#else
+ (void)fd;
+#endif
+ g_array_append_val(cw->walk->ranges, range);
+ g_array_append_val(cw->walk->files, file);
+ return false;
+}
+
+static void reims_graphics_commit_hosted_ram(ReimsGraphicsPCIState *s)
+{
+ ReimsGraphicsMemoryWalk walk = {
+ .ranges = g_array_new(false, false, sizeof(RvgMemoryRange)),
+ .files = g_array_new(false, false, sizeof(RvgMemoryRangeFile)),
+ };
+ FlatView *fv = address_space_to_flatview(&address_space_memory);
+ uint64_t total_bytes = 0;
+ RvgMemoryMap memory_map;
+ RvgStatus status;
+
+ s->hosted_ram_committed_count = 0;
+ for (uint32_t i = 0; i < s->hosted_ram_staged_count; i++) {
+ ReimsHostedClipWalk cw = {
+ .walk = &walk,
+ .guest_pa = s->hosted_ram_staged[i].guest_pa,
+ .host_gpa = s->hosted_ram_staged[i].host_gpa,
+ .bytes = s->hosted_ram_staged[i].bytes,
+ };
+ flatview_for_each_range(fv, reims_graphics_clip_hosted_range, &cw);
+ }
+ if (walk.ranges->len == 0) {
+ warn_report("%s: hosted ARM64 RAM map commit matched 0 shared RAM ranges "
+ "(ensure -object memory-backend-ram,id=ram,...,share=on)",
+ TYPE_REIMS_GRAPHICS_PCI);
+ goto out;
+ }
+ for (guint i = 0; i < walk.ranges->len; i++) {
+ total_bytes += g_array_index(walk.ranges, RvgMemoryRange, i).physical_length;
+ }
+ memory_map = (RvgMemoryMap) {
+ .ranges = (const RvgMemoryRange *)walk.ranges->data,
+ .range_count = walk.ranges->len,
+ };
+ status = rvg_graphics_device_set_memory_map(
+ s->device, &memory_map, (const RvgMemoryRangeFile *)walk.files->data);
+ if (status != RVG_OK) {
+ warn_report("%s: rvg_graphics_device_set_memory_map failed: %s",
+ TYPE_REIMS_GRAPHICS_PCI, rvg_status_message(status));
+ goto out;
+ }
+ s->hosted_ram_committed_count = walk.ranges->len;
+ info_report("%s: hosted ARM64 zero-copy RAM map installed (%u ranges, %" PRIu64 " MiB)",
+ TYPE_REIMS_GRAPHICS_PCI, walk.ranges->len, total_bytes >> 20);
+out:
+ g_array_free(walk.ranges, true);
+ g_array_free(walk.files, true);
+}
+
/*
* Warns where the machine leaves BAR 2 no address in a macOS guest. macOS
* lays every 64-bit prefetchable BAR out below 4 GiB, where the region's
@@ -2503,15 +2709,15 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
const RvgWindowConfig *display_windows[RVG_GRAPHICS_DISPLAYS_MAX - 1];
bool window = reims_graphics_window_wanted();
/*
- * The guest's architecture is this QEMU's target: the device answers an
- * arm64 guest's Metal as an Apple silicon Mac's GPU answers where the two
- * kinds of Mac differ (isFramebufferReadSupported).
+ * The device answers Metal for the architecture that speaks the
+ * graphics protocol. A hosted ARM64 translator can use the x86
+ * PCI transport for an ARM64 guest.
*/
RvgGraphicsDeviceConfig config = {
.struct_size = sizeof(config),
.callbacks = &callbacks,
- .guest_arch = target_aarch64() ? RVG_GUEST_ARCH_ARM64
- : RVG_GUEST_ARCH_X86_64,
+ .guest_arch = (target_aarch64() || s->hosted_arm64)
+ ? RVG_GUEST_ARCH_ARM64 : RVG_GUEST_ARCH_X86_64,
/* BAR 4 is registered below, its writes sent to the library. */
.doorbell_pages = 1,
};
@@ -2533,6 +2739,11 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
uint64_t pool_room = 0;
uint32_t i;
+ if (s->hosted_arm64 && !g_str_equal(target_name(), "x86_64")) {
+ error_setg(errp, "%s: x-hosted-arm64 requires the x86_64 target",
+ TYPE_REIMS_GRAPHICS_PCI);
+ return;
+ }
if (!reims_graphics_linux_floor(errp)) {
return;
}
@@ -2603,8 +2814,15 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
* views of the map's pages while the device lives, so they must stay the
* guest's RAM: no balloon or hot-unplug may discard them.
*/
- flatview_for_each_range(address_space_to_flatview(&address_space_memory),
- reims_graphics_add_memory_range, &walk);
+ /*
+ * A hosted guest's addresses belong to the inner address space.
+ * Until the translator supplies a mapping, share only the device's
+ * own region, never the outer VM's RAM.
+ */
+ if (!s->hosted_arm64) {
+ flatview_for_each_range(address_space_to_flatview(&address_space_memory),
+ reims_graphics_add_memory_range, &walk);
+ }
if (walk.ranges->len > 0) {
memory_map = (RvgMemoryMap) {
.ranges = (const RvgMemoryRange *)walk.ranges->data,
@@ -2612,7 +2830,7 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
};
config.memory_map = &memory_map;
config.memory_files = (const RvgMemoryRangeFile *)walk.files->data;
- } else {
+ } else if (!s->hosted_arm64) {
warn_report("%s: no guest RAM is "
#if defined(_WIN32)
"a shared section "
@@ -2630,8 +2848,9 @@ static void reims_graphics_pci_realize(PCIDevice *dev, Error **errp)
* room as the host GPU's memory heaps hold, summed, and the range is
* reserved once it answers (reims_graphics_pool_reserve).
*/
- if (reims_graphics_pool_room(dev, &pool_base, &pool_room) ||
- reims_graphics_pool_room_machine(&pool_base, &pool_room)) {
+ if (!s->hosted_arm64 &&
+ (reims_graphics_pool_room(dev, &pool_base, &pool_room) ||
+ reims_graphics_pool_room_machine(&pool_base, &pool_room))) {
config.pool_physical_address = pool_base;
config.pool_physical_length = pool_room;
}
@@ -2785,6 +3004,7 @@ static void reims_graphics_pci_finalize(Object *obj)
static const Property reims_graphics_pci_properties[] = {
DEFINE_PROP_STRING("resolution", ReimsGraphicsPCIState, resolution),
DEFINE_PROP_UINT32("displays", ReimsGraphicsPCIState, displays, 1),
+ DEFINE_PROP_BOOL("x-hosted-arm64", ReimsGraphicsPCIState, hosted_arm64, false),
};
static void reims_graphics_pci_class_init(ObjectClass *klass, const void *data)
--
2.55.0.windows.5
@@ -1,497 +0,0 @@
From fa0519c7b77668dd17b7ba710a3d3ecd802aa669 Mon Sep 17 00:00:00 2001
From: Reims-Go Builder <builder@reims-go.local>
Date: Thu, 3 Dec 2026 17:34:13 +0800
Subject: [PATCH 3/3] block/win32, nvme: complete cached Win32 file I/O inline
on I/O SQ doorbell
---
block/block-backend.c | 63 ++++++++++++++
block/file-win32.c | 90 ++++++++++++++++++++
hw/nvme/ctrl.c | 58 ++++++++++++-
hw/nvme/nvme.h | 1 +
include/system/block-backend-io.h | 6 ++
include/system/dma.h | 6 ++
system/dma-helpers.c | 135 ++++++++++++++++++++++++++++++
7 files changed, 358 insertions(+), 1 deletion(-)
diff --git a/block/block-backend.c b/block/block-backend.c
index 656c0aed..b8b616f9 100644
--- a/block/block-backend.c
+++ b/block/block-backend.c
@@ -1654,6 +1654,69 @@ static void coroutine_fn blk_aio_write_entry(void *opaque)
blk_aio_complete(acb);
}
+/*
+ * Like blk_aio_prwv(), but when called outside a coroutine and the underlying
+ * request completes synchronously without yielding, deliver the completion
+ * immediately and return NULL instead of scheduling a deferred BH.
+ */
+static BlockAIOCB *blk_aio_prwv_syncok(BlockBackend *blk, int64_t offset,
+ int64_t bytes, void *iobuf,
+ CoroutineEntry co_entry,
+ BdrvRequestFlags flags,
+ BlockCompletionFunc *cb,
+ void *opaque)
+{
+ BlkAioEmAIOCB *acb;
+ Coroutine *co;
+
+ blk_inc_in_flight(blk);
+ acb = blk_aio_get(&blk_aio_em_aiocb_info, blk, cb, opaque);
+ acb->rwco = (BlkRwCo) {
+ .blk = blk,
+ .offset = offset,
+ .iobuf = iobuf,
+ .flags = flags,
+ .ret = NOT_DONE,
+ };
+ acb->bytes = bytes;
+ acb->has_returned = false;
+
+ co = qemu_coroutine_create(co_entry, acb);
+ aio_co_enter(qemu_get_current_aio_context(), co);
+
+ acb->has_returned = true;
+ if (acb->rwco.ret != NOT_DONE) {
+ if (!qemu_in_coroutine()) {
+ blk_aio_complete(acb);
+ return NULL;
+ }
+ replay_bh_schedule_oneshot_event(qemu_get_current_aio_context(),
+ blk_aio_complete_bh, acb);
+ }
+
+ return &acb->common;
+}
+
+BlockAIOCB *blk_aio_preadv_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov,
+ BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque)
+{
+ assert((uint64_t)qiov->size <= INT64_MAX);
+ return blk_aio_prwv_syncok(blk, offset, qiov->size, qiov,
+ blk_aio_read_entry, flags, cb, opaque);
+}
+
+BlockAIOCB *blk_aio_pwritev_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov,
+ BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque)
+{
+ assert((uint64_t)qiov->size <= INT64_MAX);
+ return blk_aio_prwv_syncok(blk, offset, qiov->size, qiov,
+ blk_aio_write_entry, flags, cb, opaque);
+}
+
BlockAIOCB *blk_aio_pwrite_zeroes(BlockBackend *blk, int64_t offset,
int64_t bytes, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque)
diff --git a/block/file-win32.c b/block/file-win32.c
index b63ce1c1..308dfc6f 100644
--- a/block/file-win32.c
+++ b/block/file-win32.c
@@ -33,6 +33,7 @@
#include "trace.h"
#include "block/thread-pool.h"
#include "qemu/iov.h"
+#include "qemu/coroutine.h"
#include "qobject/qdict.h"
#include "qobject/qstring.h"
#include <windows.h>
@@ -436,6 +437,93 @@ static BlockAIOCB *raw_aio_pwritev(BlockDriverState *bs,
}
}
+/*
+ * Synchronous cached Windows file I/O fast path.
+ * Non-overlapped ReadFile/WriteFile on cached FTYPE_FILE handles hits
+ * NTFS FastIoRead/FastIoWrite directly on the caller thread; raw devices,
+ * aio=native, BDRV_O_NOCACHE, and all flush/discard requests still take
+ * the thread pool.
+ */
+static int coroutine_fn GRAPH_RDLOCK
+raw_co_prw(BlockDriverState *bs, int64_t offset, int64_t bytes,
+ QEMUIOVector *qiov, bool is_write)
+{
+ BDRVRawState *s = bs->opaque;
+ int64_t cur_offset = offset;
+ size_t total_done = 0;
+ int i;
+
+ if (s->aio != NULL || s->type != FTYPE_FILE ||
+ (bs->open_flags & BDRV_O_NOCACHE)) {
+ RawWin32AIOData *acb = g_new(RawWin32AIOData, 1);
+ acb->bs = bs;
+ acb->hfile = s->hfile;
+ acb->aio_type = is_write ? QEMU_AIO_WRITE : QEMU_AIO_READ;
+ acb->aio_iov = qiov->iov;
+ acb->aio_niov = qiov->niov;
+ acb->aio_nbytes = bytes;
+ acb->aio_offset = offset;
+ return thread_pool_submit_co(aio_worker, acb);
+ }
+
+ for (i = 0; i < qiov->niov; i++) {
+ size_t rem = qiov->iov[i].iov_len;
+ uint8_t *base = qiov->iov[i].iov_base;
+
+ while (rem > 0) {
+ DWORD chunk = (DWORD)MIN(rem, (size_t)0x7ffff000U);
+ OVERLAPPED ov;
+ DWORD done = 0;
+ BOOL ok;
+
+ memset(&ov, 0, sizeof(ov));
+ ov.Offset = (DWORD)cur_offset;
+ ov.OffsetHigh = (DWORD)((uint64_t)cur_offset >> 32);
+ if (is_write) {
+ ok = WriteFile(s->hfile, base, chunk, &done, &ov);
+ } else {
+ ok = ReadFile(s->hfile, base, chunk, &done, &ov);
+ }
+ if (!ok) {
+ DWORD err = GetLastError();
+ if (!is_write && err == ERROR_HANDLE_EOF) {
+ qemu_iovec_memset(qiov, total_done, 0, bytes - total_done);
+ return 0;
+ }
+ return -EIO;
+ }
+ if (done < chunk) {
+ if (!is_write) {
+ qemu_iovec_memset(qiov, total_done + done, 0,
+ bytes - (total_done + done));
+ return 0;
+ }
+ return -EINVAL;
+ }
+ cur_offset += done;
+ total_done += done;
+ base += done;
+ rem -= done;
+ }
+ }
+
+ return 0;
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+raw_co_preadv(BlockDriverState *bs, int64_t offset, int64_t bytes,
+ QEMUIOVector *qiov, BdrvRequestFlags flags)
+{
+ return raw_co_prw(bs, offset, bytes, qiov, false);
+}
+
+static int coroutine_fn GRAPH_RDLOCK
+raw_co_pwritev(BlockDriverState *bs, int64_t offset, int64_t bytes,
+ QEMUIOVector *qiov, BdrvRequestFlags flags)
+{
+ return raw_co_prw(bs, offset, bytes, qiov, true);
+}
+
static BlockAIOCB *raw_aio_flush(BlockDriverState *bs,
BlockCompletionFunc *cb, void *opaque)
{
@@ -727,6 +815,8 @@ BlockDriver bdrv_file = {
.bdrv_aio_preadv = raw_aio_preadv,
.bdrv_aio_pwritev = raw_aio_pwritev,
.bdrv_aio_flush = raw_aio_flush,
+ .bdrv_co_preadv = raw_co_preadv,
+ .bdrv_co_pwritev = raw_co_pwritev,
.bdrv_co_truncate = raw_co_truncate,
.bdrv_co_getlength = raw_co_getlength,
diff --git a/hw/nvme/ctrl.c b/hw/nvme/ctrl.c
index 10e5d976..48d23118 100644
--- a/hw/nvme/ctrl.c
+++ b/hw/nvme/ctrl.c
@@ -216,6 +216,7 @@
#include "migration/vmstate.h"
#include "nvme.h"
+#include "qemu/coroutine.h"
#include "dif.h"
#include "trace.h"
@@ -1479,6 +1480,21 @@ static inline void nvme_blk_read(BlockBackend *blk, int64_t offset,
{
assert(req->sg.flags & NVME_SG_ALLOC);
+ if (!qemu_in_coroutine() && !req->ns->lbaf.ms) {
+ BlockAIOCB *aiocb;
+ if (req->sg.flags & NVME_SG_DMA) {
+ aiocb = dma_blk_read_syncok(blk, &req->sg.qsg, offset, align,
+ cb, req);
+ } else {
+ aiocb = blk_aio_preadv_syncok(blk, offset, &req->sg.iov, 0,
+ cb, req);
+ }
+ if (aiocb) {
+ req->aiocb = aiocb;
+ }
+ return;
+ }
+
if (req->sg.flags & NVME_SG_DMA) {
req->aiocb = dma_blk_read(blk, &req->sg.qsg, offset, align, cb, req);
} else {
@@ -1492,6 +1508,21 @@ static inline void nvme_blk_write(BlockBackend *blk, int64_t offset,
{
assert(req->sg.flags & NVME_SG_ALLOC);
+ if (!qemu_in_coroutine() && !req->ns->lbaf.ms) {
+ BlockAIOCB *aiocb;
+ if (req->sg.flags & NVME_SG_DMA) {
+ aiocb = dma_blk_write_syncok(blk, &req->sg.qsg, offset, align,
+ cb, req);
+ } else {
+ aiocb = blk_aio_pwritev_syncok(blk, offset, &req->sg.iov, 0,
+ cb, req);
+ }
+ if (aiocb) {
+ req->aiocb = aiocb;
+ }
+ return;
+ }
+
if (req->sg.flags & NVME_SG_DMA) {
req->aiocb = dma_blk_write(blk, &req->sg.qsg, offset, align, cb, req);
} else {
@@ -1598,6 +1629,19 @@ static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
+ if (req->sq->inline_processing) {
+ /* Batch CQEs into the single post_cqes() flush at end of nvme_process_db(). */
+ return;
+ }
+ if (!DEVICE(cq->ctrl)->mem_reentrancy_guard.engaged_in_io &&
+ !qemu_in_coroutine()) {
+ /* Mirror aio_bh_call() guarded reentrancy state for async main-loop completions. */
+ DEVICE(cq->ctrl)->mem_reentrancy_guard.engaged_in_io = true;
+ nvme_post_cqes(cq);
+ DEVICE(cq->ctrl)->mem_reentrancy_guard.engaged_in_io = false;
+ return;
+ }
+
qemu_bh_schedule(cq->bh);
}
@@ -8690,7 +8734,19 @@ static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
stl_le_pci_dma(pci, sq->db_addr, sq->tail, MEMTXATTRS_UNSPECIFIED);
}
- qemu_bh_schedule(sq->bh);
+ if (qid != 0 && !n->dbbuf_enabled && !sq->inline_processing &&
+ !qemu_in_coroutine()) {
+ NvmeCQueue *cq = n->cq[sq->cqid];
+ assert(DEVICE(n)->mem_reentrancy_guard.engaged_in_io);
+ sq->inline_processing = true;
+ nvme_process_sq(sq);
+ sq->inline_processing = false;
+ if (cq && !QTAILQ_EMPTY(&cq->req_list)) {
+ nvme_post_cqes(cq);
+ }
+ } else {
+ qemu_bh_schedule(sq->bh);
+ }
}
}
diff --git a/hw/nvme/nvme.h b/hw/nvme/nvme.h
index a4b2c01a..78eca196 100644
--- a/hw/nvme/nvme.h
+++ b/hw/nvme/nvme.h
@@ -523,6 +523,7 @@ typedef struct NvmeSQueue {
QEMUBH *bh;
EventNotifier notifier;
bool ioeventfd_enabled;
+ bool inline_processing;
NvmeRequest *io_req;
QTAILQ_HEAD(, NvmeRequest) req_list;
QTAILQ_HEAD(, NvmeRequest) out_req_list;
diff --git a/include/system/block-backend-io.h b/include/system/block-backend-io.h
index 78d410b8..b6b577a3 100644
--- a/include/system/block-backend-io.h
+++ b/include/system/block-backend-io.h
@@ -51,6 +51,12 @@ BlockAIOCB *blk_aio_preadv(BlockBackend *blk, int64_t offset,
BlockAIOCB *blk_aio_pwritev(BlockBackend *blk, int64_t offset,
QEMUIOVector *qiov, BdrvRequestFlags flags,
BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *blk_aio_preadv_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov, BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *blk_aio_pwritev_syncok(BlockBackend *blk, int64_t offset,
+ QEMUIOVector *qiov, BdrvRequestFlags flags,
+ BlockCompletionFunc *cb, void *opaque);
BlockAIOCB *blk_aio_flush(BlockBackend *blk,
BlockCompletionFunc *cb, void *opaque);
BlockAIOCB *blk_aio_zone_report(BlockBackend *blk, int64_t offset,
diff --git a/include/system/dma.h b/include/system/dma.h
index 82e7ad54..cc3790ee 100644
--- a/include/system/dma.h
+++ b/include/system/dma.h
@@ -299,6 +299,12 @@ BlockAIOCB *dma_blk_read(BlockBackend *blk,
BlockAIOCB *dma_blk_write(BlockBackend *blk,
QEMUSGList *sg, uint64_t offset, uint32_t align,
BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *dma_blk_read_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ BlockCompletionFunc *cb, void *opaque);
+BlockAIOCB *dma_blk_write_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ BlockCompletionFunc *cb, void *opaque);
MemTxResult dma_buf_read(void *ptr, dma_addr_t len, dma_addr_t *residual,
QEMUSGList *sg, MemTxAttrs attrs);
MemTxResult dma_buf_write(void *ptr, dma_addr_t len, dma_addr_t *residual,
diff --git a/system/dma-helpers.c b/system/dma-helpers.c
index 0d592f64..830d7407 100644
--- a/system/dma-helpers.c
+++ b/system/dma-helpers.c
@@ -274,6 +274,141 @@ BlockAIOCB *dma_blk_write(BlockBackend *blk,
DMA_DIRECTION_TO_DEVICE);
}
+static void dma_blk_cb_syncok(void *opaque, int ret)
+{
+ DMAAIOCB *dbs = (DMAAIOCB *)opaque;
+ AioContext *ctx = dbs->ctx;
+ dma_addr_t cur_addr, cur_len;
+ void *mem;
+ BlockAIOCB *child_acb;
+
+ trace_dma_blk_cb(dbs, ret);
+
+ assert(ctx == qemu_get_current_aio_context());
+
+ dbs->acb = NULL;
+ dbs->offset += dbs->iov.size;
+
+ if (dbs->sg_cur_index == dbs->sg->nsg || ret < 0) {
+ dma_complete(dbs, ret);
+ return;
+ }
+ dma_blk_unmap(dbs);
+
+ while (dbs->sg_cur_index < dbs->sg->nsg) {
+ cur_addr = dbs->sg->sg[dbs->sg_cur_index].base + dbs->sg_cur_byte;
+ cur_len = dbs->sg->sg[dbs->sg_cur_index].len - dbs->sg_cur_byte;
+ mem = dma_memory_map(dbs->sg->as, cur_addr, &cur_len, dbs->dir,
+ MEMTXATTRS_UNSPECIFIED);
+ if (mem && icount_enabled() && dbs->dir == DMA_DIRECTION_FROM_DEVICE) {
+ int i;
+ for (i = 0; i < dbs->iov.niov; ++i) {
+ if (ranges_overlap((intptr_t)dbs->iov.iov[i].iov_base,
+ dbs->iov.iov[i].iov_len, (intptr_t)mem,
+ cur_len)) {
+ dma_memory_unmap(dbs->sg->as, mem, cur_len,
+ dbs->dir, cur_len);
+ mem = NULL;
+ break;
+ }
+ }
+ }
+ if (!mem) {
+ break;
+ }
+ qemu_iovec_add(&dbs->iov, mem, cur_len);
+ dbs->sg_cur_byte += cur_len;
+ if (dbs->sg_cur_byte == dbs->sg->sg[dbs->sg_cur_index].len) {
+ dbs->sg_cur_byte = 0;
+ ++dbs->sg_cur_index;
+ }
+ }
+
+ if (dbs->iov.size == 0) {
+ trace_dma_map_wait(dbs);
+ dbs->bh = aio_bh_new(ctx, reschedule_dma, dbs);
+ address_space_register_map_client(dbs->sg->as, dbs->bh);
+ return;
+ }
+
+ if (!QEMU_IS_ALIGNED(dbs->iov.size, dbs->align)) {
+ qemu_iovec_discard_back(&dbs->iov,
+ QEMU_ALIGN_DOWN(dbs->iov.size, dbs->align));
+ }
+
+ child_acb = dbs->io_func(dbs->offset, &dbs->iov,
+ dma_blk_cb_syncok, dbs, dbs->io_func_opaque);
+ if (child_acb) {
+ dbs->acb = child_acb;
+ }
+}
+
+static BlockAIOCB *dma_blk_io_syncok(
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ DMAIOFunc *io_func, void *io_func_opaque,
+ BlockCompletionFunc *cb,
+ void *opaque, DMADirection dir)
+{
+ DMAAIOCB *dbs = qemu_aio_get(&dma_aiocb_info, NULL, cb, opaque);
+
+ trace_dma_blk_io(dbs, io_func_opaque, offset, (dir == DMA_DIRECTION_TO_DEVICE));
+
+ dbs->acb = NULL;
+ dbs->sg = sg;
+ dbs->ctx = qemu_get_current_aio_context();
+ dbs->offset = offset;
+ dbs->align = align;
+ dbs->sg_cur_index = 0;
+ dbs->sg_cur_byte = 0;
+ dbs->dir = dir;
+ dbs->io_func = io_func;
+ dbs->io_func_opaque = io_func_opaque;
+ dbs->bh = NULL;
+ qemu_iovec_init(&dbs->iov, sg->nsg);
+ qemu_aio_ref(dbs);
+ dma_blk_cb_syncok(dbs, 0);
+ if (!dbs->acb && !dbs->bh) {
+ qemu_aio_unref(dbs);
+ return NULL;
+ }
+ qemu_aio_unref(dbs);
+ return &dbs->common;
+}
+
+static BlockAIOCB *dma_blk_read_syncok_io_func(int64_t offset, QEMUIOVector *iov,
+ BlockCompletionFunc *cb,
+ void *cb_opaque, void *opaque)
+{
+ BlockBackend *blk = opaque;
+ return blk_aio_preadv_syncok(blk, offset, iov, 0, cb, cb_opaque);
+}
+
+BlockAIOCB *dma_blk_read_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ void (*cb)(void *opaque, int ret), void *opaque)
+{
+ return dma_blk_io_syncok(sg, offset, align,
+ dma_blk_read_syncok_io_func, blk, cb, opaque,
+ DMA_DIRECTION_FROM_DEVICE);
+}
+
+static BlockAIOCB *dma_blk_write_syncok_io_func(int64_t offset, QEMUIOVector *iov,
+ BlockCompletionFunc *cb,
+ void *cb_opaque, void *opaque)
+{
+ BlockBackend *blk = opaque;
+ return blk_aio_pwritev_syncok(blk, offset, iov, 0, cb, cb_opaque);
+}
+
+BlockAIOCB *dma_blk_write_syncok(BlockBackend *blk,
+ QEMUSGList *sg, uint64_t offset, uint32_t align,
+ void (*cb)(void *opaque, int ret), void *opaque)
+{
+ return dma_blk_io_syncok(sg, offset, align,
+ dma_blk_write_syncok_io_func, blk, cb, opaque,
+ DMA_DIRECTION_TO_DEVICE);
+}
+
static MemTxResult dma_buf_rw(void *buf, dma_addr_t len, dma_addr_t *residual,
QEMUSGList *sg, DMADirection dir,
--
2.55.0.windows.5
@@ -1,3 +0,0 @@
0001-qemu-win32-compatibility.patch
0002-qemu-stambha-hosted-graphics.patch
0003-qemu-win32-nvme-inline-io.patch
@@ -30,6 +30,8 @@ param(
[string]$RequiredSuspendCompatID = '',
[string]$RequiredPackagingCommit = '',
[switch]$RequireSlim,
[switch]$SkipMsys2Sources,
[switch]$SkipSymbols,
# Only for checking packages built before the 2026-11-28 rename ("candidate").
[string]$ExpectChannel = 'alpha',
[string]$TempRoot = $env:RUNNER_TEMP
@@ -41,12 +43,14 @@ $AppliedPatches = @($AppliedPatches | ForEach-Object { $_ -split ',' } | ForEach
$names = @{
runtime = "reims-runtime-win-x64-$Commit.tar.zst"
source = "reims-runtime-src-$Commit.tar.zst"
msys2 = "reims-runtime-msys2-src-$Commit.tar.zst"
sums = 'SHA256SUMS.txt'
}
if (-not $SkipMsys2Sources) {
$names.msys2 = "reims-runtime-msys2-src-$Commit.tar.zst"
}
$symbolsName = "reims-runtime-symbols-$Commit"
if ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst"))) {
if ((-not $SkipSymbols) -and ($RequireSlim -or (Test-Path -LiteralPath (Join-Path $OutDir "$symbolsName.tar.zst")))) {
$names.symbols = "$symbolsName.tar.zst"
}
# 1. All assets for this layout.
@@ -121,6 +125,15 @@ try {
if (!(Test-Path -LiteralPath (Join-Path $root $rel) -PathType Leaf)) { throw "Missing runtime dependency: $rel" }
}
Write-Host 'PASS stripped executable hashes, detached debug members and video driver files'
} elseif ($RequireSlim) {
foreach ($rel in 'bin/reims-ctl.exe','bin/reims-util.exe','qemu/bin/qemu-system-x86_64.exe','qemu/bin/qemu-img.exe','qemu/bin/reims-vgpu-compile.exe') {
$hash = (Get-FileHash -LiteralPath (Join-Path $root $rel) -Algorithm SHA256).Hash
if ($hash -ne $m.sha256.$rel) { throw "Manifest hash mismatch for $rel" }
}
foreach ($rel in 'qemu/bin/libva.dll','qemu/bin/libva_win32.dll','qemu/bin/vaon12_drv_video.dll','NOTICE.md','MSYS2-PACKAGES.txt') {
if (!(Test-Path -LiteralPath (Join-Path $root $rel) -PathType Leaf)) { throw "Missing runtime dependency: $rel" }
}
Write-Host 'PASS stripped executable hashes and video driver files (light alpha)'
}
# 4. QEMU runs from the bundle alone and has the reims device.
@@ -139,7 +152,7 @@ try {
if ($proc.ExitCode -ne 0) { throw "qemu -device help exited $($proc.ExitCode): $err" }
if ($out -notmatch 'reims-graphics-pci') { throw "qemu -device help does not list reims-graphics-pci`n$out`n$err" }
Write-Host 'PASS qemu-system-x86_64 -device help lists reims-graphics-pci (no MSYS2 on PATH)'
if ($names.symbols) {
if ($names.symbols -or $RequireSlim) {
$oldPath = $env:PATH
$img = Join-Path $qemuBin 'qemu-img.exe'
try {
@@ -1,127 +0,0 @@
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)] [string]$AssetDir,
[Parameter(Mandatory)] [ValidatePattern('^[a-z0-9][a-z0-9.-]{0,63}$')] [string]$ReleaseId,
[Parameter(Mandatory)] [string]$Zstd
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'stambha-runtime-files.ps1')
$tar = Join-Path $env:SystemRoot 'System32/tar.exe'
$assets = (Resolve-Path -LiteralPath $AssetDir).Path
$runtime = "reims-stambha-runtime-win-x64-$ReleaseId"
$sources = "reims-stambha-runtime-src-$ReleaseId"
$sums = Get-Content -LiteralPath (Join-Path $assets 'SHA256SUMS.txt')
foreach ($base in @($runtime, $sources)) {
$name = "$base.tar.zst"
$line = Get-Content -Raw -LiteralPath (Join-Path $assets "$name.sha256")
$fields = $line.TrimEnd() -split ' ', 2
if ($fields.Count -ne 2 -or $fields[1] -cne $name -or $line.TrimEnd() -cnotin $sums) {
throw "Invalid or mismatched release checksum for $name"
}
Assert-StambhaHash (Join-Path $assets $name) $fields[0]
}
function Expand-StambhaAsset([string]$Stage, [string]$Name) {
$tarball = Join-Path $Stage "$Name.tar"
[void](Invoke-StambhaCommand $Zstd @('-d', '-q', (Join-Path $assets "$Name.tar.zst"), '-o', $tarball))
$entries = @(Invoke-StambhaCommand $tar @('-tf', $tarball))
$seen = [Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($entry in $entries) {
$normalized = $entry.TrimEnd('/')
$segments = $normalized -split '/'
if ($segments[0] -cne $Name -or $normalized -match '[\x00-\x1f:\\]' -or
($segments | Where-Object { $_ -in @('', '.', '..') }) -or !$seen.Add($normalized)) {
throw "Unexpected path in ${Name}: $entry"
}
}
$types = @(Invoke-StambhaCommand $tar @('-tvf', $tarball))
if (($types.Count -ne $entries.Count) -or ($types | Where-Object { $_ -notmatch '^[-d]' })) {
throw "Unexpected member type in $Name"
}
[void](Invoke-StambhaCommand $tar @('-xf', $tarball, '-C', $Stage))
Remove-Item -LiteralPath $tarball
Join-Path $Stage $Name
}
$parent = Split-Path -Parent $assets
$stage = Join-Path $parent ('.stambha-check-' + [guid]::NewGuid().ToString('N'))
[void][IO.Directory]::CreateDirectory($stage)
try {
$payload = Expand-StambhaAsset $stage $runtime
$source = Expand-StambhaAsset $stage $sources
$manifest = Get-Content -Raw -LiteralPath (Join-Path $payload 'manifest.json') | ConvertFrom-Json -AsHashtable
if ($manifest.schema_version -ne 2 -or $manifest.commit -cne $ReleaseId -or
$manifest.kind -cne 'stambha-hosted' -or $manifest.runtime_api -cne '0.1.0' -or
$manifest.platform -cne 'windows-x86_64' -or $manifest.channel -cne 'alpha' -or
$manifest.source_package -cne "$sources.tar.zst" -or !$manifest.license) {
throw 'Unexpected Stambha runtime manifest'
}
$files = @(Get-ChildItem -LiteralPath $payload -Force -Recurse -File)
$bytes = [long](($files | Measure-Object Length -Sum).Sum)
if ($files.Count -ne $manifest.file_count -or $bytes -ne $manifest.raw_bytes -or
$manifest.sha256.Count -ne ($files.Count - 1) -or
@($files | Where-Object { $_.Extension -ceq '.dll' }).Count -ne $manifest.dll_count) {
throw 'Manifest file counts, byte count, or hash coverage do not match the archive'
}
foreach ($file in $files) {
$relative = [IO.Path]::GetRelativePath($payload, $file.FullName).Replace('\', '/')
if ($relative -ceq 'manifest.json') { continue }
if (!(Test-StambhaPayloadPath $relative)) { throw "Unexpected runtime file: $relative" }
Assert-StambhaHash $file.FullName $manifest.sha256[$relative]
}
foreach ($name in $StambhaRequiredFiles) {
if (!$manifest.sha256[$name]) { throw "Missing runtime file: $name" }
}
$receipt = Get-Content -Raw -LiteralPath (Join-Path $source 'provenance.json') | ConvertFrom-Json -AsHashtable
foreach ($field in @('components', 'patches')) {
if (($receipt[$field] | ConvertTo-Json -Depth 8 -Compress) -cne
($manifest[$field] | ConvertTo-Json -Depth 8 -Compress)) { throw "Runtime and source $field differ" }
}
if ($receipt.sha256.Count -ne $manifest.sha256.Count -or
($manifest.sha256.Keys | Where-Object { $manifest.sha256[$_] -cne $receipt.sha256[$_] })) {
throw 'Runtime and source payload digests differ'
}
foreach ($item in $receipt.sources) {
if ($item.file -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.tar\.(gz|xz|zst)$') {
throw "Invalid source archive name: $($item.file)"
}
Assert-StambhaHash (Join-Path $source "sources/$($item.file)") $item.sha256
}
foreach ($patch in $receipt.patches) {
if ($patch.name -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.patch$') { throw "Invalid patch name: $($patch.name)" }
Assert-StambhaHash (Join-Path $source "patches/$($patch.name)") $patch.sha256
}
if (!(Test-Path -LiteralPath (Join-Path $source 'BUILD.md') -PathType Leaf) -or
$receipt.msys2_source -cnotin @($receipt.sources | ForEach-Object { $_.file })) {
throw 'Missing build instructions or MSYS2 corresponding source'
}
$version = Test-StambhaExecutables $payload
if ($version -cne $manifest.qemu_version) { throw 'QEMU version differs from the manifest' }
$media = Join-Path $stage 'probe-media'
$vm = Join-Path $stage 'probe-vm'
[void][IO.Directory]::CreateDirectory((Join-Path $media 'EFI/BOOT'))
[void][IO.Directory]::CreateDirectory((Join-Path $media 'EFI/stela'))
Copy-Item -LiteralPath (Join-Path $payload 'firmware/stambha.efi') -Destination (Join-Path $media 'EFI/BOOT/BOOTX64.EFI')
Write-StambhaText (Join-Path $media 'EFI/stela/stela.cfg') "# Packaging boot-plan probe`n"
$qemu = Join-Path $payload 'qemu/bin/qemu-system-x86_64.exe'
$engine = Join-Path $payload 'bin/stambha-engine.exe'
$plan = (Invoke-StambhaCommand $engine @(
'boot-plan', '--qemu', $qemu,
'--firmware-code', (Join-Path $payload 'firmware/edk2-code.fd'),
'--firmware-vars', (Join-Path $payload 'firmware/edk2-vars.fd'),
'--vm-dir', $vm, '--memory-mib', '8192', '--cpus', '4', '--boot-volume', $media
)) | ConvertFrom-Json
if ($plan.runtime_api -cne '0.1.0' -or $plan.exe_path -ne $qemu -or $plan.work_dir -ne $vm -or
!$plan.args.Count -or !(Test-Path -LiteralPath (Join-Path $vm 'uefi-vars.fd') -PathType Leaf)) {
throw 'The bundled engine did not produce the expected EDK2 boot plan'
}
Write-Host "PASS $ReleaseId runtime, source, payload hashes, engine, boot plan and $version"
} finally {
if ((Split-Path -Parent ([IO.Path]::GetFullPath($stage))) -eq $parent) {
Remove-Item -LiteralPath $stage -Recurse -Force
}
}
@@ -55,7 +55,12 @@ param(
[string]$PackagingCommit = '',
# Names from patches/series.txt actually applied. Not given: all of them.
# Given but empty: none (every patch already upstream).
[string[]]$Patches = @()
[string[]]$Patches = @(),
# Omit the 110 MB MSYS2 copyleft source bundle (e.g. for frequent alpha previews;
# include for stable releases or dedicated toolchain source releases).
[switch]$SkipMsys2Sources,
# Omit the ~95 MB detached debug symbols archive (binaries are still stripped).
[switch]$SkipSymbols
)
$ErrorActionPreference = 'Stop'
@@ -101,7 +106,9 @@ function Write-Utf8([string]$path, [string]$text) {
function New-TarZst([string]$parent, [string]$name, [string]$archive) {
$tar = Join-Path $TempRoot "$name.tar"
Invoke-Native 'tar.exe' @('-cf', $tar, '-C', $parent, $name)
Invoke-Native $zstd @('-T0', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
# --long=27 (128 MiB window) deduplicates shared QEMU code across x86_64 and aarch64
# binaries while staying within default zstd CLI and Go decoder window limits.
Invoke-Native $zstd @('-T0', '--long=27', "-$ZstdLevel", '-q', '-f', $tar, '-o', $archive)
Remove-Item -LiteralPath $tar -Force
}
@@ -192,9 +199,11 @@ foreach ($e in $series) {
if ($usePatchList -and $e.Name -notin $Patches) { continue }
$file = Join-Path $patchesDir $e.Name
if (-not (Test-Path -LiteralPath $file)) { throw "Patch missing: $file" }
# Files the patch touches ("--- a/x" / "+++ b/x"), to scope the diff checks.
# Files the patch touches ("--- a/x" / "+++ b/x", and each "diff --git a/x b/y" header, which a
# binary patch has alone), to scope the diff checks.
$paths = @(Get-Content -LiteralPath $file | ForEach-Object {
if ($_ -match '^(?:---|\+\+\+) [ab]/(.+?)\s*$') { $Matches[1] }
elseif ($_ -match '^diff --git a/(.+?) b/(.+?)\s*$') { $Matches[1]; $Matches[2] }
} | Select-Object -Unique)
$patchSpecs += @{
Name = $e.Name
@@ -226,7 +235,12 @@ foreach ($targetName in $byTarget.Keys) {
# object count between the upstream clone and the single-commit verify repo.
$diffArgs = @('-C', $repo, '-c', 'core.autocrlf=false', 'diff', '--full-index')
if ($paths.Count) { $diffArgs += '--'; $diffArgs += $paths }
$treeDiff = (& git @diffArgs | Out-String).Replace("`r`n", "`n").TrimEnd()
# The mode on an "index" line is the file's, not the change's: the verify tree is extracted by
# tar on Windows, which keeps no executable bit, so a changed executable (a prebuilt kext) reads
# 100644 there and 100755 here. A change of mode has its own "old mode"/"new mode" lines, which
# stay compared.
$indexMode = '(?m)^(index [0-9a-f]+\.\.[0-9a-f]+) [0-7]{6}$'
$treeDiff = ((& git @diffArgs | Out-String).Replace("`r`n", "`n") -replace $indexMode, '$1').TrimEnd()
# Apply the declared patch stack to a clean temporary clone of HEAD and compare diffs byte-for-byte.
$verifyDir = Join-Path $TempRoot ("patch-verify-" + [guid]::NewGuid())
@@ -270,7 +284,7 @@ foreach ($targetName in $byTarget.Keys) {
Invoke-GitApply $verifyDir $patchText
Remove-Item -LiteralPath $patchLf -Force
}
$expectedDiff = (& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n").TrimEnd()
$expectedDiff = ((& git -C $verifyDir -c core.autocrlf=false diff --full-index | Out-String).Replace("`r`n", "`n") -replace $indexMode, '$1').TrimEnd()
if ($treeDiff -ne $expectedDiff) {
$treeStat = (& git -C $repo diff --stat -- @paths | Out-String).Trim()
$expStat = (& git -C $verifyDir diff --stat | Out-String).Trim()
@@ -360,16 +374,51 @@ if (Test-Path -LiteralPath (Join-Path $ReimsRepo 'LICENSES')) {
Write-Host '==> Listing MSYS2 packages of bundled DLLs'
$bash = Join-Path $Msys2 'usr\bin\bash.exe'
$dlls = @(Get-ChildItem -LiteralPath "$bundleDir\qemu\bin" -Filter '*.dll' -File | Sort-Object Name)
$metadataScript = (Join-Path $PSScriptRoot 'read-msys2-package-metadata.sh').Replace('\', '/')
$dllPaths = @($dlls | ForEach-Object { "/clang64/bin/$($_.Name)" })
$expectedPaths = [Collections.Generic.HashSet[string]]::new([StringComparer]::Ordinal)
foreach ($path in $dllPaths) { [void]$expectedPaths.Add($path) }
$rows = @(& $bash -lc 'script=$1; shift; source "$script"' -- $metadataScript @dllPaths)
if ($LASTEXITCODE -ne 0) { throw "MSYS2 package metadata lookup failed ($LASTEXITCODE)" }
$owners = @{}
$licensesByPackage = @{}
foreach ($row in $rows) {
$type, $key, $value, $version = $row -split "`t", 4
switch ($type) {
'owned' {
if (!$expectedPaths.Remove($key) -or !$value -or !$version) {
throw "Unexpected MSYS2 ownership row: $row"
}
$owners[$key] = [pscustomobject]@{ Package = $value; Version = $version }
}
'unowned' {
if (!$expectedPaths.Remove($key) -or $value) {
throw "Unexpected MSYS2 ownership row: $row"
}
}
'license' {
if (!$key -or !$value -or !$value.StartsWith('/clang64/share/licenses/', [StringComparison]::Ordinal) -or $version) {
throw "Unexpected MSYS2 license row: $row"
}
if (!$licensesByPackage.ContainsKey($key)) {
$licensesByPackage[$key] = [Collections.Generic.List[string]]::new()
}
$licensesByPackage[$key].Add($value)
}
default { throw "Unexpected MSYS2 package metadata row: $row" }
}
}
if ($expectedPaths.Count -ne 0) { throw "MSYS2 ownership lookup did not answer for $($expectedPaths -join ', ')" }
$pkgLines = [Collections.Generic.List[string]]::new()
$pkgSet = [ordered]@{}
$pkgNames = [ordered]@{}
foreach ($d in $dlls) {
$owner = (& $bash -lc "LC_ALL=C pacman -Qqo /clang64/bin/$($d.Name) 2>/dev/null" | Select-Object -First 1)
$owner = $owners["/clang64/bin/$($d.Name)"]
if ($owner) {
$ver = (& $bash -lc "LC_ALL=C pacman -Q $owner" | Select-Object -First 1).Split(' ')[1]
$pkgLines.Add("$($d.Name)`t$owner`t$ver")
$pkgSet["$owner $ver"] = $true
$pkgNames[$owner] = $true
$pkgLines.Add("$($d.Name)`t$($owner.Package)`t$($owner.Version)")
$pkgSet["$($owner.Package) $($owner.Version)"] = $true
$pkgNames[$owner.Package] = $true
} else {
$pkgLines.Add("$($d.Name)`t(not from an MSYS2 package: built with qemu, source in the source package)`t-")
}
@@ -377,9 +426,7 @@ foreach ($d in $dlls) {
# Bundle each MSYS2 package's installed license texts under licenses/msys2/.
$msysLicRoot = Join-Path $bundleDir 'licenses\msys2'
foreach ($owner in $pkgNames.Keys) {
$licFiles = @(& $bash -lc "LC_ALL=C pacman -Ql $owner 2>/dev/null" | ForEach-Object {
if ($_ -match '^\S+\s+(/clang64/share/licenses/.+)$' -and -not $Matches[1].EndsWith('/')) { $Matches[1] }
})
$licFiles = $licensesByPackage[$owner]
foreach ($lf in $licFiles) {
$rel = $lf.Substring('/clang64/share/licenses/'.Length)
$srcFile = Join-Path $Msys2 ($lf.TrimStart('/') -replace '/', '\')
@@ -537,7 +584,6 @@ $manifest = [ordered]@{
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')
@@ -546,6 +592,7 @@ $manifest = [ordered]@{
raw_bytes = [int64]((Get-ChildItem -LiteralPath $bundleDir -Recurse -File | Measure-Object Length -Sum).Sum) # Add the manifest's own size after writing it below.
sha256 = $hashes
}
if (-not $SkipSymbols) { $manifest['symbols_package'] = "$symbolsName.tar.zst" }
if ($SuspendCompatID) { $manifest['suspend_compat_id'] = $SuspendCompatID }
if ($PackagingCommit) { $manifest['packaging_commit'] = $PackagingCommit }
Write-Utf8 "$bundleDir\manifest.json" ($manifest | ConvertTo-Json -Depth 5)
@@ -560,16 +607,25 @@ New-TarZst $stageRoot $bundleName $runtimeArchive
Write-Host '==> Compressing sources'
$srcArchive = Join-Path $OutDir "$srcName.tar.zst"
New-TarZst $stageRoot $srcName $srcArchive
$symbolsArchive = Join-Path $OutDir "$symbolsName.tar.zst"
New-TarZst $stageRoot $symbolsName $symbolsArchive
$rtHash = Get-Sha256 $runtimeArchive
$srcHash = Get-Sha256 $srcArchive
Write-Utf8 "$runtimeArchive.sha256" "$rtHash $bundleName.tar.zst`n"
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') "$rtHash $bundleName.tar.zst`n$srcHash $srcName.tar.zst`n$(Get-Sha256 $symbolsArchive) $symbolsName.tar.zst`n"
$sumsLines = @(
"$rtHash $bundleName.tar.zst"
"$srcHash $srcName.tar.zst"
)
if (-not $SkipSymbols) {
$symbolsArchive = Join-Path $OutDir "$symbolsName.tar.zst"
New-TarZst $stageRoot $symbolsName $symbolsArchive
$sumsLines += "$(Get-Sha256 $symbolsArchive) $symbolsName.tar.zst"
}
Write-Utf8 (Join-Path $OutDir 'SHA256SUMS.txt') (($sumsLines -join "`n") + "`n")
# Sources of the copyleft MSYS2 packages, as their own asset (adds a line to SHA256SUMS.txt).
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
if (-not $SkipMsys2Sources) {
& (Join-Path $PSScriptRoot 'pack-msys2-sources.ps1') -PackagesFile (Join-Path $bundleDir 'MSYS2-PACKAGES.txt') -Commit $id -OutDir $OutDir -Msys2 $Msys2 -TempRoot $TempRoot
}
Remove-Item -Recurse -Force -LiteralPath $stageRoot
@@ -1,177 +0,0 @@
[CmdletBinding(PositionalBinding = $false)]
param(
[Parameter(Mandatory)] [string]$InputRoot,
[Parameter(Mandatory)] [string]$OutDir,
[Parameter(Mandatory)] [ValidatePattern('^[a-z0-9][a-z0-9.-]{0,63}$')] [string]$ReleaseId,
[string]$Msys2 = "$env:SystemDrive/msys64",
[ValidateRange(1, 12)] [int]$ZstdLevel = 6
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'runtime-zstd.ps1')
. (Join-Path $PSScriptRoot 'stambha-runtime-files.ps1')
$zstd = Resolve-Zstd $Msys2
$tar = Join-Path $env:SystemRoot 'System32/tar.exe'
$input = (Resolve-Path -LiteralPath $InputRoot).Path
$out = $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath($OutDir)
if (Test-Path -LiteralPath $out) { throw "Output directory already exists: $out" }
$receiptPath = Join-Path $input 'provenance.json'
$receipt = Get-Content -LiteralPath $receiptPath -Raw | ConvertFrom-Json -AsHashtable
if ($receipt.schema_version -ne 1) { throw 'Unsupported provenance.json schema' }
$srcFiles = @{}
foreach ($source in $receipt.sources) {
$name = $source.file
if ($name -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.tar\.(gz|xz|zst)$' -or $srcFiles.ContainsKey($name)) {
throw "Invalid or duplicate corresponding source archive: $name"
}
$path = Join-Path $input "sources/$name"
Assert-StambhaHash $path $source.sha256
$srcFiles.Add($name, $path)
}
if (!$receipt.msys2_source -or !$srcFiles.ContainsKey($receipt.msys2_source)) {
throw 'The MSYS2 corresponding source archive is required'
}
$componentNames = @('reims-vgpu', 'qemu', 'qemu-img', 'metal2vulkan', 'stela', 'stambha-engine', 'edk2-code', 'edk2-vars')
$components = @{}
foreach ($component in $receipt.components) {
$name = $component.name
if ($name -cnotin $componentNames -or $components.ContainsKey($name) -or
$component.repo -cnotmatch '^https://[^\s]+$' -or $component.commit -cnotmatch '^[0-9a-f]{40}$' -or
($component.base_commit -and $component.base_commit -cnotmatch '^[0-9a-f]{40}$') -or
!$component.source -or !$srcFiles.ContainsKey($component.source)) {
throw "Invalid, duplicate or incomplete provenance for $name"
}
$components.Add($name, $component)
}
foreach ($name in $componentNames) {
if (!$components.ContainsKey($name)) { throw "Missing provenance for $name" }
}
$patchNames = @{}
foreach ($patch in $receipt.patches) {
$name = $patch.name
if ($name -cnotmatch '^[A-Za-z0-9_-][A-Za-z0-9_.-]*\.patch$' -or $patchNames.ContainsKey($name) -or
$patch.target -cnotin $componentNames) { throw "Invalid or duplicate patch: $name" }
$path = Join-Path $input "patches/$name"
Assert-StambhaHash $path $patch.sha256
$patchNames.Add($name, $path)
}
if (!$patchNames.Count) { throw 'The hosted runtime must declare its applied patches' }
$payload = Join-Path $input 'payload'
$files = @{}
foreach ($item in Get-ChildItem -LiteralPath $payload -Force -Recurse) {
if (($item.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0) {
throw "Reparse points are not supported in the runtime payload: $($item.FullName)"
}
if ($item.PSIsContainer) { continue }
$relative = [IO.Path]::GetRelativePath($payload, $item.FullName).Replace('\', '/')
if (!(Test-StambhaPayloadPath $relative)) { throw "Unexpected runtime file: $relative" }
$files.Add($relative, $item)
}
foreach ($name in $StambhaRequiredFiles) {
if (!$files.ContainsKey($name)) { throw "Missing runtime file: $name" }
}
if ($files.Count -ne $receipt.sha256.Count) { throw 'Provenance SHA256 keys differ from runtime files' }
foreach ($name in $files.Keys) { Assert-StambhaHash $files[$name].FullName $receipt.sha256[$name] }
function New-StambhaArchive([string]$Stage, [string]$Name, [string]$Assets) {
$tarball = Join-Path $Stage "$Name.tar"
[void](Invoke-StambhaCommand $tar @('-cf', $tarball, '-C', $Stage, $Name))
$archive = Join-Path $Assets "$Name.tar.zst"
[void](Invoke-StambhaCommand $zstd @('-q', '-T2', "-$ZstdLevel", $tarball, '-o', $archive))
Remove-Item -LiteralPath $tarball
"$Name.tar.zst"
}
$parent = Split-Path -Parent $out
[void][IO.Directory]::CreateDirectory($parent)
$stage = Join-Path $parent ('.stambha-pack-' + [guid]::NewGuid().ToString('N'))
try {
$assets = Join-Path $stage 'assets'
$runtimeName = "reims-stambha-runtime-win-x64-$ReleaseId"
$sourceName = "reims-stambha-runtime-src-$ReleaseId"
$runtimeDir = Join-Path $stage $runtimeName
$sourceDir = Join-Path $stage $sourceName
foreach ($dir in @($assets, $runtimeDir, "$sourceDir/sources", "$sourceDir/patches", "$sourceDir/packaging/scripts")) {
[void][IO.Directory]::CreateDirectory($dir)
}
$hashes = [ordered]@{}
$payloadBytes = [long]0
foreach ($name in $files.Keys | Sort-Object) {
$dest = Join-Path $runtimeDir $name
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
Copy-Item -LiteralPath $files[$name].FullName -Destination $dest
Assert-StambhaHash $dest $receipt.sha256[$name]
$hashes[$name] = $receipt.sha256[$name]
$payloadBytes += $files[$name].Length
}
$qemuVersion = Test-StambhaExecutables $runtimeDir
$manifest = [ordered]@{
schema_version = 2
name = $runtimeName
platform = 'windows-x86_64'
kind = 'stambha-hosted'
runtime_api = '0.1.0'
commit = $ReleaseId
channel = 'alpha'
origin = 'third-party'
publisher = 'Reims-Go'
license = 'GPL-2.0-only and GPL-3.0-or-later with other component licenses; see NOTICE.md and licenses/'
upstream_repo = $components['reims-vgpu'].repo
full_commit = $components['reims-vgpu'].commit
vendor_qemu_commit = $components.qemu.commit
qemu_version = $qemuVersion
metal2vulkan_commit = $components.metal2vulkan.commit
source_package = "$sourceName.tar.zst"
patches = @($receipt.patches)
components = @($receipt.components)
capabilities = @('stambha.uefi', 'stambha.qemu.boot-plan', 'stambha.hosted-reims')
built_at = [DateTimeOffset]::UtcNow.ToString('O')
file_count = $files.Count + 1
dll_count = @($files.Keys | Where-Object { $_.EndsWith('.dll') }).Count
raw_bytes = $payloadBytes
sha256 = $hashes
}
$manifestPath = Join-Path $runtimeDir 'manifest.json'
do {
$previous = $manifest.raw_bytes
Write-StambhaText $manifestPath (($manifest | ConvertTo-Json -Depth 8) + "`n")
$manifest.raw_bytes = $payloadBytes + (Get-Item -LiteralPath $manifestPath).Length
} until ($manifest.raw_bytes -eq $previous)
function Write-AssetSum([string]$Name) {
$line = "$(Get-StambhaHash (Join-Path $assets $name)) $name`n"
Write-StambhaText (Join-Path $assets "$name.sha256") $line
$line
}
$runtimeAsset = New-StambhaArchive $stage $runtimeName $assets
$runtimeSum = Write-AssetSum $runtimeAsset
Write-Host "Runtime staged for host smoke testing: $(Join-Path $assets $runtimeAsset)"
foreach ($name in $srcFiles.Keys) {
Copy-Item -LiteralPath $srcFiles[$name] -Destination (Join-Path $sourceDir "sources/$name")
}
foreach ($name in $patchNames.Keys) {
Copy-Item -LiteralPath $patchNames[$name] -Destination (Join-Path $sourceDir "patches/$name")
}
Copy-Item -LiteralPath $receiptPath, (Join-Path $input 'BUILD.md') -Destination $sourceDir
Copy-Item -LiteralPath (Join-Path (Split-Path -Parent $PSScriptRoot) 'LICENSE') -Destination "$sourceDir/packaging"
foreach ($name in @('runtime-zstd.ps1', 'stambha-runtime-files.ps1', 'pack-stambha-runtime.ps1', 'check-stambha-runtime.ps1')) {
Copy-Item -LiteralPath (Join-Path $PSScriptRoot $name) -Destination "$sourceDir/packaging/scripts"
}
$sourceAsset = New-StambhaArchive $stage $sourceName $assets
$sums = @($runtimeSum, (Write-AssetSum $sourceAsset))
Write-StambhaText (Join-Path $assets 'SHA256SUMS.txt') ($sums -join '')
& (Join-Path $PSScriptRoot 'check-stambha-runtime.ps1') -AssetDir $assets -ReleaseId $ReleaseId -Zstd $zstd
[IO.Directory]::Move($assets, $out)
Write-Host "Packaged Stambha preview: $out"
} finally {
if ((Split-Path -Parent ([IO.Path]::GetFullPath($stage))) -eq $parent -and
(Test-Path -LiteralPath $stage -PathType Container)) { Remove-Item -LiteralPath $stage -Recurse -Force }
}
@@ -0,0 +1,48 @@
#!/usr/bin/env bash
# Pacman's ownership query returns the owner and installed version together.
set -euo pipefail
export LC_ALL=C
if (($# == 0)); then
exit 0
fi
status=0
ownership=$(pacman -Qo -- "$@" 2>&1) || status=$?
owned='^(/clang64/bin/.+) is owned by ([^[:space:]]+) ([^[:space:]]+)$'
unowned='^error: No package owns (/clang64/bin/.+)$'
declare -A seen=()
packages=()
missing=0
while IFS= read -r line; do
if [[ $line =~ $owned ]]; then
path=${BASH_REMATCH[1]}
package=${BASH_REMATCH[2]}
version=${BASH_REMATCH[3]}
printf 'owned\t%s\t%s\t%s\n' "$path" "$package" "$version"
if [[ -z ${seen[$package]+yes} ]]; then
seen[$package]=1
packages+=("$package")
fi
elif [[ $line =~ $unowned ]]; then
printf 'unowned\t%s\n' "${BASH_REMATCH[1]}"
((missing += 1))
else
printf 'Unexpected pacman ownership response: %s\n' "$line" >&2
exit 1
fi
done <<< "$ownership"
if ((status != missing % 256)); then
printf 'pacman ownership query exited with %d for %d unowned files\n' "$status" "$missing" >&2
exit 1
fi
if ((${#packages[@]})); then
pacman -Ql -- "${packages[@]}" | awk '
{
package = $1
sub(/^[^[:space:]]+[[:space:]]+/, "")
if ($0 ~ /^\/clang64\/share\/licenses\/.+/ && $0 !~ /\/$/)
printf "license\t%s\t%s\n", package, $0
}
'
fi
@@ -10,23 +10,27 @@ param(
$ErrorActionPreference = 'Stop'
$programs = @('bin/reims-ctl.exe', 'bin/reims-util.exe', 'qemu/bin/qemu-system-x86_64.exe',
'qemu/bin/qemu-img.exe', 'qemu/bin/reims-vgpu-compile.exe')
# Additional executables that may be built alongside x64 (e.g. ARM64 guest support).
# Strip their debug info into the detached symbols archive whenever present.
$optionalPrograms = @('qemu/bin/qemu-system-aarch64.exe', 'qemu/bin/reims-restore.exe')
$allStripped = $programs + $optionalPrograms
# Omit only the paths tested with the x64 launcher. Keep new upstream files,
# in particular dynamically loaded video drivers, ROMs, and license notices.
$tools = @('bin/qemu-system-x86_64w.exe', 'bin/elf2dmp.exe', 'bin/qemu-edid.exe',
'bin/qemu-io.exe', 'bin/qemu-nbd.exe', 'bin/qemu-storage-daemon.exe')
$tools = @('bin/qemu-system-x86_64w.exe', 'bin/qemu-system-aarch64w.exe', 'bin/elf2dmp.exe',
'bin/qemu-edid.exe', 'bin/qemu-io.exe', 'bin/qemu-nbd.exe', 'bin/qemu-storage-daemon.exe')
foreach ($file in Get-ChildItem -LiteralPath $QemuDir -Recurse -Force -File) {
$rel = [IO.Path]::GetRelativePath($QemuDir, $file.FullName).Replace('\', '/')
if ($rel -in $tools) { continue }
if ($rel -match '^share/edk2-(aarch64|riscv64|loongarch64)-(code|vars)\.fd$' -or
$rel -match '^share/firmware/\d+-edk2-(aarch64|riscv64|loongarch64)\.json$') { continue }
if ("qemu/$rel" -in $programs) { continue }
if ("qemu/$rel" -in $allStripped) { continue }
$dest = Join-Path $BundleDir "qemu/$rel"
[void][IO.Directory]::CreateDirectory((Split-Path -Parent $dest))
Copy-Item -LiteralPath $file.FullName -Destination $dest
}
foreach ($rel in $programs) {
function Copy-StrippedBinary([string]$rel) {
$src = if ($rel.StartsWith('qemu/')) { Join-Path $QemuDir $rel.Substring(5) }
else { Join-Path $CargoBin (Split-Path -Leaf $rel) }
$dest = Join-Path $BundleDir $rel
@@ -38,5 +42,15 @@ foreach ($rel in $programs) {
& $Objcopy --strip-debug "--add-gnu-debuglink=$debug" $src $dest | Out-Null
if ($LASTEXITCODE) { throw "Stripping $src failed ($LASTEXITCODE)" }
}
foreach ($rel in $programs) {
Copy-StrippedBinary $rel
}
foreach ($rel in $optionalPrograms) {
$src = Join-Path $QemuDir $rel.Substring(5)
if (Test-Path -LiteralPath $src -PathType Leaf) {
Copy-StrippedBinary $rel
}
}
# The packer hashes these final, stripped bytes for manifest.json.
$programs
@@ -1,71 +0,0 @@
# The installable Stambha runtime is separate from the ordinary Reims runtime.
$StambhaRequiredFiles = @(
'bin/stambha-engine.exe'
'firmware/edk2-code.fd'
'firmware/edk2-vars.fd'
'firmware/stambha.efi'
'qemu/bin/qemu-img.exe'
'qemu/bin/qemu-system-x86_64.exe'
'qemu/bin/reims-vgpu-compile.exe'
'qemu/share/vgabios-stdvga.bin'
'NOTICE.md'
'MSYS2-PACKAGES.txt'
'licenses/stambha/NOTICE'
'licenses/stambha/LICENSE'
'licenses/stambha/LICENSES/GPL-3.0-or-later.txt'
'licenses/edk2-licenses.txt'
)
function Get-StambhaHash([string]$Path) {
(Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant()
}
function Assert-StambhaHash([string]$Path, [string]$Expected) {
if ($Expected -cnotmatch '^[0-9a-f]{64}$') { throw "Missing or invalid SHA256 for $Path" }
if ((Get-StambhaHash $Path) -cne $Expected) { throw "SHA256 mismatch for $Path" }
}
function Test-StambhaPayloadPath([string]$Path) {
$Path -cin $StambhaRequiredFiles -or
$Path -cmatch '^qemu/bin/[a-zA-Z0-9_.+-]+\.dll$' -or
$Path -cmatch '^qemu/share/(bios(-256k)?\.bin|kvmvapic\.bin|vgabios\.bin|(efi|pxe)-virtio\.rom)$' -or
$Path -ceq 'licenses/cargo/index.json' -or
$Path -ceq 'licenses/msys2/libjpeg-turbo/simd/jsimdext.inc' -or
$Path -match '^licenses/([A-Z0-9_+.-]+/)*([A-Z0-9_+.-]+\.(txt|md)|(LICEN[CS]E|COPYING|NOTICE|COPYRIGHT|README|AUTHORS)[A-Z0-9_.+-]*|[A-Z0-9-]+-[0-9]+\.[A-Z0-9_.+-]+|GPL|MIT|Linux-Syscall-Note)$'
}
function Write-StambhaText([string]$Path, [string]$Value) {
[IO.File]::WriteAllText($Path, $Value.Replace("`r`n", "`n"), [Text.UTF8Encoding]::new($false))
}
function Invoke-StambhaCommand([string]$Executable, [string[]]$Arguments) {
$output = & $Executable @Arguments
if ($LASTEXITCODE -ne 0) { throw "$Executable $($Arguments -join ' ') failed ($LASTEXITCODE)" }
$output
}
function Test-StambhaExecutables([string]$Payload) {
$originalPath = $env:PATH
try {
$qemuBin = Join-Path $Payload 'qemu/bin'
$env:PATH = "$qemuBin;$env:SystemRoot\System32;$env:SystemRoot"
$engine = Join-Path $Payload 'bin/stambha-engine.exe'
$info = (Invoke-StambhaCommand $engine @('info')) | ConvertFrom-Json
if ($info.runtime_kind -cne 'stambha-hosted' -or $info.runtime_api -cne '0.1.0' -or
$info.host_os -cne 'windows' -or $info.host_arch -cne 'x86_64' -or
!$info.capabilities.qemu_uefi_boot_plan) { throw 'Unexpected Stambha boot-plan engine or API' }
$selfTest = (Invoke-StambhaCommand $engine @('self-test')) | ConvertFrom-Json
if ($selfTest.result -ne 42 -or $selfTest.guest_arch -cne 'arm64') {
throw 'Stambha translated ARM64 self-test failed'
}
$qemu = Join-Path $qemuBin 'qemu-system-x86_64.exe'
$features = (Invoke-StambhaCommand $qemu @('-device', 'reims-graphics-pci,help')) -join "`n"
if ($features -notmatch '(?m)^\s*x-hosted-arm64=') { throw 'QEMU lacks hosted ARM64 Reims graphics' }
$accelerators = (Invoke-StambhaCommand $qemu @('-accel', 'help')) -join "`n"
if ($accelerators -notmatch '(?m)^\s*whpx\s*$') { throw 'QEMU lacks WHPX' }
[void](Invoke-StambhaCommand (Join-Path $qemuBin 'qemu-img.exe') @('--version'))
(Invoke-StambhaCommand $qemu @('--version')) | Select-Object -First 1
} finally {
$env:PATH = $originalPath
}
}
@@ -0,0 +1,53 @@
#!/usr/bin/env bash
# Exercise the batched queries and their failure handling without a package database.
set -euo pipefail
helper="$(dirname "$0")/read-msys2-package-metadata.sh"
mode=ok
pacman() {
case "$*" in
'-Qo -- /clang64/bin/a.dll /clang64/bin/local.dll /clang64/bin/b.dll')
echo '/clang64/bin/a.dll is owned by same-package 2:1.0-3'
echo 'error: No package owns /clang64/bin/local.dll' >&2
echo '/clang64/bin/b.dll is owned by same-package 2:1.0-3'
case $mode in
query-failure) echo 'error: invalid local database' >&2; return 2 ;;
wrong-status) return 0 ;;
esac
return 1
;;
'-Ql -- same-package')
echo 'same-package /clang64/bin/a.dll'
echo 'same-package /clang64/share/licenses/example/'
echo 'same-package /clang64/share/licenses/example/<LICENSE> text'
if [[ $mode == list-failure ]]; then
echo 'error: failed to read package file list' >&2
return 1
fi
;;
*)
printf 'Unexpected pacman invocation: %s\n' "$*" >&2
return 255
;;
esac
}
read_metadata() (
source "$helper" "$@"
)
paths=(/clang64/bin/a.dll /clang64/bin/local.dll /clang64/bin/b.dll)
expected=$'owned\t/clang64/bin/a.dll\tsame-package\t2:1.0-3\nunowned\t/clang64/bin/local.dll\nowned\t/clang64/bin/b.dll\tsame-package\t2:1.0-3\nlicense\tsame-package\t/clang64/share/licenses/example/<LICENSE> text'
actual=$(read_metadata "${paths[@]}")
if [[ $actual != "$expected" ]]; then
printf 'Metadata did not match:\n%s\n' "$actual" >&2
exit 1
fi
[[ -z $(read_metadata) ]]
for mode in query-failure wrong-status list-failure; do
if read_metadata "${paths[@]}" >/dev/null 2>&1; then
printf 'Accepted an unexpected pacman failure: %s\n' "$mode" >&2
exit 1
fi
done
printf 'MSYS2 package metadata checks passed\n'
@@ -1,78 +0,0 @@
# Stambha ARM64 macOS runtime preview
The `stambha-hosted` runtime runs on Windows x86-64 with WHPX. Stambha translates the ARM64 guest, and QEMU connects Stambha to Reims vGPU. The preview pack has its own QEMU and EDK2 firmware and can be imported in a Reims-Go client with the Stambha driver. Its runtime API is `0.1.0`.
Each release includes the runtime archive, the corresponding-source archive, and checksums. Users supply their own macOS boot media or virtual disk. Keep Apple system images, macOS installation material, signing tickets, and VM state outside the runtime package.
## Validated preview baseline
The first preview uses the A5000 `B-disk` configuration. This variant passed the Reims-Go client startup test, a Finder cold restart, and disk persistence checks. QEMU uses the display transport and NVMe changes in [the ARM-only patch series](patches/stambha-qemu/series.txt). The regular runtime workflow uses its own patch series.
| Component | Source revision |
| --- | --- |
| Reims vGPU | [`3731afd9b13416a24f74ec27a90b3913aef2dcc0`](https://github.com/steelbrain/reims-vgpu/commit/3731afd9b13416a24f74ec27a90b3913aef2dcc0) plus the hosted graphics sources archived with the preview |
| QEMU | [`4571bc5fecb039e8cfd6837e077810fbe074e11b`](https://github.com/steelbrain/qemu-reims-vgpu/commit/4571bc5fecb039e8cfd6837e077810fbe074e11b) plus the three patches below, archived as `fa0519c7b77668dd17b7ba710a3d3ecd802aa669` |
| `qemu-img` | The same QEMU base with the Win32 compatibility patch, reused from the tested base build |
| Metal2Vulkan | [`0b0ac58eb0f69ed3b37007fbdf3b135a46f90699`](https://github.com/steelbrain/metal2vulkan/commit/0b0ac58eb0f69ed3b37007fbdf3b135a46f90699) |
| Stela EFI | `d6d1ad81cf0c0940c8ee6713871fbc8ecca6d177`, based on Stambha v0.6.2 [`65340914732f3afd08de01a5c82560d27449df92`](https://github.com/garvitsurana271/stambha/commit/65340914732f3afd08de01a5c82560d27449df92) with the hosted Reims graphics and default GPU interrupt polling |
| `stambha-engine` | [`5e3d6f76266de89df321e6f16f7305e523c242c2`](https://github.com/yxc0915/stambha/commit/5e3d6f76266de89df321e6f16f7305e523c242c2) |
Apply the QEMU patches to a separate checkout of the baseline above, in the order listed. The Windows build targets `x86_64-softmmu` under MSYS2 CLANG64 and links Reims vGPU through its dist tree. The archived recipe and component sources record the complete inputs for each binary.
```powershell
$series = 'packaging/windows-runtime/patches/stambha-qemu'
foreach ($patch in Get-Content -LiteralPath "$series/series.txt") {
$file = (Resolve-Path -LiteralPath "$series/$patch").Path
git -C $qemuRepo apply --check $file
if ($LASTEXITCODE) { throw "Could not apply $patch" }
git -C $qemuRepo apply $file
if ($LASTEXITCODE) { throw "Could not apply $patch" }
}
```
## Assemble a preview from verified build outputs
Prepare an input directory using build outputs from the same validated configuration. Separate the hosted display and NVMe QEMU patches from the regular Intel runtime. Preserve the boot engine, outer-QEMU executable, `qemu-img`, both EDK2 images, and the Stela EFI at the tested revisions. Record the components and build commands in `BUILD.md` with the archive.
```text
input/
BUILD.md
provenance.json
patches/<applied-patch>.patch
sources/<component-source>.tar.gz
sources/<copyleft-msys2-source>.tar.zst
payload/
bin/stambha-engine.exe
firmware/edk2-code.fd
firmware/edk2-vars.fd
firmware/stambha.efi
qemu/bin/qemu-system-x86_64.exe
qemu/bin/qemu-img.exe
qemu/bin/reims-vgpu-compile.exe
qemu/bin/<required DLLs>
qemu/share/vgabios-stdvga.bin
MSYS2-PACKAGES.txt
NOTICE.md
licenses/
edk2-licenses.txt
stambha/NOTICE
stambha/LICENSE
stambha/LICENSES/GPL-3.0-or-later.txt
<other component and dependency license texts>
```
The provenance receipt uses `schema_version: 1`. Include the following fields.
- `components` lists `reims-vgpu`, `qemu`, `qemu-img`, `metal2vulkan`, `stela`, `stambha-engine`, `edk2-code`, and `edk2-vars`. Each object has `name`, `repo`, `commit`, and `source`. `commit` is the full Git object ID. Include `base_commit` for a patched revision when applicable. `source` is the filename of its archive in `sources/`.
- `sources` lists each archive with `file` and `sha256`. Set `msys2_source` to the archive of corresponding sources for the copyleft DLLs. Keep `MSYS2-PACKAGES.txt` in the payload so users can identify the package versions behind the DLLs.
- `patches` lists each applied patch in order with `name`, `target`, and `sha256`. Supply the matching patch files even when their changes appear in an exported source tree.
- `sha256` maps every payload-relative path to its lowercase SHA-256, including licenses and notices. The package verifier requires the entire payload to match.
The Stambha source package must include the source and license materials for both the hosted engine and EFI and the required `third_party/` submodules at their pins. Include Reims vGPU and Metal2Vulkan sources used to link QEMU, QEMU's required source dependencies, and the corresponding EDK2 source material.
```powershell
pwsh -File packaging/windows-runtime/scripts/pack-stambha-runtime.ps1 `
-InputRoot $input -OutDir $releaseFolder -ReleaseId $revision
```
The output folder must be new. The packer reopens the emitted archives, verifies provenance and payload checksums, and runs the engine ARM64 self-test and QEMU graphics-device and WHPX feature checks with a restricted Windows `PATH`. A Windows host smoke test with user-supplied boot media verifies the import and boot path.
+5
View File
@@ -0,0 +1,5 @@
{
"capabilities": [
"window-release-shortcut"
]
}