Compare commits

...
Author SHA1 Message Date
YXC0915 d9c9bbb7e8 Use the OpenGL array-size fix in the wire-2 compatibility profile 2026-12-07 06:49:03 +08:00
YXC0915 2eb50111d1 Preserve FileVault preboot input when rebuilding the wire-2 OpenCore image
Backport 79fdedd8f0 with its reims-util pin. Verify the normal cold-start path updates guest drivers, preserves the existing keyboard and tablet, and reuses that image on the next start.
2026-12-07 05:38:11 +08:00
YXC0915 89ea5866ac 🐛 Restore the wire-2 bundle over a placed bundle link
Exchange the staged driver with the directory entry in GPUBundles so rolling back from a newer runtime replaces the symlink itself. Keep the linked cache intact and use the normal staged-tree cleanup for the displaced link.
2026-12-06 19:15:39 +08:00
YXC0915 2df30ffea9 🆕 Pin the organization runtime dependencies [skip ci]
Resolve metal2vulkan and reims-util from the maintained Reims-Go repositories. The new Vulkan pin establishes a suspend baseline for these build inputs.
2026-12-03 02:53:58 +08:00
Xiaochi You 6b7e7d7cad Merge pull request #1 from YinLiaoCo/feat/window-file-drop
feat(window): forward SDL3 file and text drops with normalized coords to host bridge
2026-12-03 02:08:14 +08:00
YXC0915 1a6d1626ca 📝 Record the Places texture-pool suspend baseline
The Places allocation patch changes the graphics memory layout. Give this Alpha build its own suspend compatibility family until recovery of older snapshots has been verified.
2026-12-03 01:02:03 +08:00
Shroap bfea2dc988 feat(window): forward SDL3 text and URL drops to host bridge 2026-12-02 04:00:53 +08:00
Shroap 3fdde46abd feat(window): forward SDL3 file drops with normalized coords to host bridge 2026-12-02 03:56:21 +08:00
17 changed files with 844 additions and 32 deletions

No files matched your search

Generated
+3
View File
@@ -213,6 +213,7 @@ checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
[[package]]
name = "metal2vulkan"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=ea2656f72ac572f98c8fdb76490fd96e9e81b833#ea2656f72ac572f98c8fdb76490fd96e9e81b833"
dependencies = [
"ash",
"metal2vulkan-air",
@@ -223,6 +224,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-air"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=ea2656f72ac572f98c8fdb76490fd96e9e81b833#ea2656f72ac572f98c8fdb76490fd96e9e81b833"
dependencies = [
"sha2 0.11.1",
]
@@ -230,6 +232,7 @@ dependencies = [
[[package]]
name = "metal2vulkan-runtime"
version = "0.2.0"
source = "git+https://github.com/reims-go/metal2vulkan?rev=ea2656f72ac572f98c8fdb76490fd96e9e81b833#ea2656f72ac572f98c8fdb76490fd96e9e81b833"
dependencies = [
"ash",
"libc",
+2 -2
View File
@@ -33,11 +33,11 @@ reims-vgpu-graphics = { path = "crates/reims-vgpu-graphics" }
reims-vgpu-video = { path = "crates/reims-vgpu-video" }
# metal2vulkan's Metal types, for the Metal enums and descriptor values the runtime's calls take,
# from metal2vulkan's public repository at the commit both name.
metal2vulkan = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
metal2vulkan = { git = "https://github.com/reims-go/metal2vulkan", rev = "ea2656f72ac572f98c8fdb76490fd96e9e81b833" }
# The Vulkan platform's runtime (architecture D1), metal2vulkan-runtime: a Metal-shaped API on
# Vulkan, one path for every device, under reims-vgpu-vulkan's `rt_platform` and `seam` and
# reims-vgpu's `pool::rt_blocks`.
metal2vulkan-runtime = { git = "https://github.com/steelbrain/metal2vulkan", rev = "0b0ac58eb0f69ed3b37007fbdf3b135a46f90699" }
metal2vulkan-runtime = { git = "https://github.com/reims-go/metal2vulkan", rev = "ea2656f72ac572f98c8fdb76490fd96e9e81b833" }
# The hashes of the Vulkan platform's metallib sources (reims-vgpu-vulkan/build.rs).
sha2 = "0.10.9"
# A display window's swapchain on Linux (reims-vgpu-vulkan/src/swapchain.rs), at the runtime's
+206 -4
View File
@@ -18,8 +18,9 @@ use crate::vm::{Graphics, ImageFormat, Vm};
use crate::{paths, prebuilt, reims_util, runtime};
use anyhow::{Context, Result, bail, ensure};
use std::collections::BTreeMap;
use std::fs::File;
use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Mutex, PoisonError};
use std::time::{Duration, SystemTime};
@@ -382,11 +383,108 @@ pub fn made_for_other_graphics(vm: &Vm) -> bool {
}
}
/// The existing OpenCore drivers that provide keyboard and pointer input before macOS starts.
const PREBOOT_INPUT_DRIVERS: [&str; 2] = ["ReimsTablet.efi", "OpenUsbKbDxe.efi"];
#[derive(PartialEq)]
struct PrebootInput {
config: plist::Value,
files: BTreeMap<String, Vec<u8>>,
}
impl PrebootInput {
/// Reads the selected driver entries, their binaries, and the existing UEFI input settings.
fn read(config: &Config, image: &Path, format: ImageFormat) -> Result<Option<Self>> {
let Some(uefi) = config.0.get("UEFI").and_then(plist::Value::as_dictionary) else {
return Ok(None);
};
let mut drivers = Vec::new();
let mut files = BTreeMap::<String, Vec<u8>>::new();
for driver in uefi
.get("Drivers")
.and_then(plist::Value::as_array)
.into_iter()
.flatten()
{
let Some(path) = driver
.as_dictionary()
.and_then(|entry| entry.get("Path"))
.and_then(plist::Value::as_string)
else {
continue;
};
if !PREBOOT_INPUT_DRIVERS
.iter()
.any(|name| path.eq_ignore_ascii_case(name))
{
continue;
}
ensure!(
!files.keys().any(|seen| seen.eq_ignore_ascii_case(path)),
"OpenCore lists the preboot input driver {path} more than once"
);
let efi_path = format!("EFI/OC/Drivers/{path}");
let bytes = read_file(image, format, &efi_path)?
.filter(|bytes| !bytes.is_empty())
.with_context(|| {
format!("OpenCore's preboot input driver {efi_path} is missing or empty")
})?;
files.insert(path.to_owned(), bytes);
drivers.push(driver.clone());
}
if drivers.is_empty() {
return Ok(None);
}
let input = uefi
.get("Input")
.filter(|input| input.as_dictionary().is_some())
.context("OpenCore's preboot drivers require the existing UEFI > Input dictionary")?;
let mut bundle = plist::Dictionary::new();
bundle.insert("Input".into(), input.clone());
bundle.insert("Drivers".into(), plist::Value::Array(drivers));
Ok(Some(Self {
config: plist::Value::Dictionary(bundle),
files,
}))
}
fn stage(&self) -> Result<PrebootInputDir> {
static NEXT: AtomicU64 = AtomicU64::new(0);
let dir = std::env::temp_dir().join(format!(
"reims-ctl-opencore-input-{}-{}-{}",
std::process::id(),
SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)?
.as_nanos(),
NEXT.fetch_add(1, Ordering::Relaxed),
));
crate::os::create_private_dir(&dir).context("create temporary preboot input directory")?;
let dir = PrebootInputDir(dir);
self.config
.to_writer_xml(File::create(dir.0.join("input.plist"))?)
.context("write preboot input configuration")?;
for (name, bytes) in &self.files {
fs::write(dir.0.join(name), bytes)
.with_context(|| format!("stage OpenCore's preboot input driver {name}"))?;
}
Ok(dir)
}
}
struct PrebootInputDir(PathBuf);
impl Drop for PrebootInputDir {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Replaces a stopped VM's OpenCore image with one the installed reims-util makes, presenting
/// the same Mac, with its boot picker shown where `show_picker` says, or as the old image shows
/// it when `None`. The new image is made beside the old one, which stays as it was if that fails.
/// It holds the kexts for the VM's graphics ([`reims_util::kext_args`]): on reims-vgpu's own
/// device, the guest's that this reims-ctl carries. The VM keeps its OVMF: its variables hold
/// device, the guest's that this reims-ctl carries. Existing preboot keyboard and tablet drivers
/// and their input options are carried over. The VM keeps its OVMF: its variables hold
/// its boot entries. The image is set in the VM's settings as they are once it is made, which
/// `vm` becomes: others may be saved meanwhile. Returns what happened, and, where the old image
/// loaded reims-vgpu's kexts on other graphics, what they left in the guest
@@ -409,14 +507,33 @@ pub fn renew(
let read = || format!("read the Mac {} presents", paths::tilde(&old));
let config = Config::read(&old, q.opencore_format).with_context(read)?;
let id = config.identity().with_context(read)?;
let preboot = PrebootInput::read(&config, &old, q.opencore_format)
.context("read the old OpenCore image's preboot input")?;
let staged = preboot.as_ref().map(PrebootInput::stage).transpose()?;
let picker = show_picker.unwrap_or_else(|| config.shows_picker());
let image = vm.dir.join("opencore.qcow2");
let new = vm.dir.join("opencore.new.qcow2");
let dropped = holds_unused_guest_kexts(vm);
let kexts = reims_util::kext_args(vm.config.graphics())?;
let made = reims_util::opencore_as(&new, &id, picker, &kexts, progress).and_then(|()| {
let made = reims_util::opencore_as(
&new,
&id,
picker,
&kexts,
staged.as_ref().map(|dir| dir.0.as_path()),
progress,
)
.and_then(|()| {
let config = Config::read(&new, ImageFormat::Qcow2)
.context("read the new OpenCore image before replacing the old one")?;
if let Some(expected) = &preboot {
let actual = PrebootInput::read(&config, &new, ImageFormat::Qcow2)
.context("verify the new OpenCore image's preboot input")?;
ensure!(
actual.as_ref() == Some(expected),
"reims-util did not preserve the old OpenCore image's preboot input"
);
}
ensure!(
!config
.configured_kexts()
@@ -1178,6 +1295,88 @@ pub(crate) mod tests {
assert!(!dir.join("opencore.img").exists());
}
#[test]
fn renew_keeps_preboot_input_and_refuses_a_lost_driver() {
let env = crate::testenv::Env::new("renew-preboot-input");
let dir = env.root.join("vm");
fs::create_dir(&dir).unwrap();
let plist = plist(&(enabled("A.kext") + &enabled("B.kext"))).replace(
"</dict></plist>",
r#"<key>UEFI</key><dict>
<key>Drivers</key><array>
<dict><key>Path</key><string>reimstablet.efi</string>
<key>Enabled</key><true/><key>Arguments</key><string>tablet</string></dict>
<dict><key>Path</key><string>OpenUsbKbDxe.efi</string>
<key>Enabled</key><true/><key>LoadEarly</key><true/></dict>
<dict><key>Path</key><string>Extra.efi</string><key>Enabled</key><true/></dict>
</array>
<key>Input</key><dict><key>KeySupport</key><false/></dict>
</dict></dict></plist>"#,
);
let tablet = ("EFI/OC/Drivers/ReimsTablet.efi", &b"fake tablet"[..]);
let keyboard = ("EFI/OC/Drivers/OpenUsbKbDxe.efi", &b"fake keyboard"[..]);
let old = image_of_config(&plist, b"", &[tablet, keyboard]);
let mut vm = on_reims_vgpu(&dir, &old, ImageFormat::Raw);
let made = env.root.join("made.img");
let args = env.root.join("args");
let input = env.root.join("staged.plist");
let script = format!(
"#!/bin/sh\nprintf '%s\\n' \"$@\" > '{args}'\n\
while [ \"$1\" != -o ]; do shift; done\n\
out=$2\nshift 2\n\
while [ \"$1\" != --preboot-input ]; do shift; done\n\
cp \"$2/input.plist\" '{input}'\n\
test \"$(cat \"$2/reimstablet.efi\")\" = 'fake tablet' || exit 1\n\
test \"$(cat \"$2/OpenUsbKbDxe.efi\")\" = 'fake keyboard' || exit 1\n\
test ! -e \"$2/Extra.efi\" || exit 1\n\
cp '{made}' \"$out\"\n\
echo '{{\"event\":\"done\",\"result\":{{}}}}'\n",
args = args.display(),
input = input.display(),
made = made.display(),
);
let util = crate::testenv::program(&env.root.join("reims-util"), &script);
env.set("REIMS_CTL_UTIL", &util);
let old_path = dir.join("opencore.img");
fs::write(&old_path, image_of_config(&plist, b"", &[keyboard])).unwrap();
let err = renew(&mut vm, None, &mut |_| {}).unwrap_err();
assert!(format!("{err:#}").contains("reimstablet.efi is missing"));
assert!(!args.exists());
fs::write(&old_path, &old).unwrap();
fs::write(&made, qcow2(&image_of_config(&plist, b"", &[tablet]))).unwrap();
let err = renew(&mut vm, None, &mut |_| {}).unwrap_err();
assert!(format!("{err:#}").contains("OpenUsbKbDxe.efi is missing"));
assert_eq!(fs::read(&old_path).unwrap(), old);
assert!(!dir.join("opencore.new.qcow2").exists());
let carried = crate::prebuilt::set().unwrap()[0].files[1].1;
fs::write(
&made,
qcow2(&image_of_config(&plist, carried, &[tablet, keyboard])),
)
.unwrap();
assert!(holds_other_guest_kexts(&vm));
let warnings = crate::runtime::prepare(&mut vm, &mut |_| {});
assert!(warnings.is_empty(), "{warnings:?}");
assert!(holds_guest_kexts(&vm));
let captured = fs::read_to_string(&args).unwrap();
assert!(captured.lines().any(|arg| arg == "--add-kext"));
let staging = captured.lines().last().unwrap();
assert!(!Path::new(staging).exists());
let bundle = plist::Value::from_file(input).unwrap();
let bundle = bundle.as_dictionary().unwrap();
assert_eq!(
bundle["Input"].as_dictionary().unwrap()["KeySupport"].as_boolean(),
Some(false)
);
assert_eq!(bundle["Drivers"].as_array().unwrap().len(), 2);
assert!(!old_path.exists());
fs::remove_file(&args).unwrap();
let warnings = crate::runtime::prepare(&mut vm, &mut |_| {});
assert!(warnings.is_empty() && !args.exists(), "{warnings:?}");
}
/// The old image goes only where its path, resolved, names a file in the VM's directory
/// other than the new image: an OpenCore path edited to `../other/oc.img` leaves that file
/// be, and one spelling the new image's place another way, `sub/../opencore.qcow2`, leaves
@@ -1522,7 +1721,10 @@ pub(crate) mod tests {
/// [`image_with_set`]'s files, its config.plist's Kernel > Add holding `kexts`.
pub(crate) fn image_loading(kexts: &str, a: &[u8], more: &[(&str, &[u8])]) -> Vec<u8> {
let config = plist(kexts);
image_of_config(&plist(kexts), a, more)
}
fn image_of_config(config: &str, a: &[u8], more: &[(&str, &[u8])]) -> Vec<u8> {
let mut files: Vec<(&str, &[u8])> = vec![
("EFI/OC/config.plist", config.as_bytes()),
(
+16 -7
View File
@@ -1,4 +1,4 @@
//! reims-util (<https://github.com/steelbrain/reims-util>) makes what a new x86-64 VM boots from:
//! reims-util (<https://github.com/reims-go/reims-util>) makes what a new x86-64 VM boots from:
//! an OpenCore image, with OVMF's code and variables beside it, and a macOS installer, downloaded
//! from Apple and checked against Apple's chunklists. It also makes an existing VM a new OpenCore
//! image presenting the same Mac (opencore.rs). For a VM on reims-vgpu's own device, an image
@@ -43,9 +43,9 @@ use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};
pub const REPO: &str = "https://github.com/steelbrain/reims-util";
pub const REPO: &str = "https://github.com/reims-go/reims-util";
/// The commit [`install`] installs.
pub const REV: &str = "7867384c0ab703b4c6aae36cbbb1a35fcffc8321";
pub const REV: &str = "c363a029b1a9bce696184b3247e6465aa11321bc";
/// The reims-util binary: `REIMS_CTL_UTIL`, else the one beside reims-ctl, where both are
/// installed, else the first on PATH.
@@ -342,7 +342,7 @@ pub fn opencore(
args.extend(["--model", m]);
}
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, None, progress)
}
/// Makes an OpenCore image at `image` presenting the Mac `id`, for a VM that has its OVMF: no
@@ -353,6 +353,7 @@ pub fn opencore_as(
id: &Identity,
show_picker: bool,
kexts: &[String],
preboot_input: Option<&Path>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let mut args = identity_args(id);
@@ -361,7 +362,7 @@ pub fn opencore_as(
args.push("--show-picker");
}
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, preboot_input, progress)
}
/// Makes an OpenCore image at `image` presenting the Mac `id`, with `OVMF_CODE.fd` and
@@ -375,7 +376,7 @@ pub fn opencore_presenting(
) -> Result<()> {
let mut args = identity_args(id);
args.extend(kexts.iter().map(String::as_str));
make_opencore(image, &args, progress)
make_opencore(image, &args, None, progress)
}
/// The arguments that make reims-util's image present the Mac `id`.
@@ -386,9 +387,17 @@ fn identity_args(id: &Identity) -> Vec<&str> {
]
}
fn make_opencore(image: &Path, args: &[&str], progress: &mut dyn FnMut(&str)) -> Result<()> {
fn make_opencore(
image: &Path,
args: &[&str],
preboot_input: Option<&Path>,
progress: &mut dyn FnMut(&str),
) -> Result<()> {
let mut all: Vec<&OsStr> = vec!["opencore".as_ref(), "-o".as_ref(), image.as_os_str()];
all.extend(args.iter().map(OsStr::new));
if let Some(dir) = preboot_input {
all.extend([OsStr::new("--preboot-input"), dir.as_os_str()]);
}
let r = run(&all, progress)?;
if let Ok(o) = serde_json::from_value::<OpencoreResult>(r) {
progress(&format!(
+500
View File
@@ -0,0 +1,500 @@
//! Collects a window's SDL file or text drop and forwards it to the local host bridge.
use std::fmt::Write as _;
use std::io::{self, Write as _};
use std::net::{SocketAddr, TcpStream};
use std::sync::OnceLock;
use std::sync::mpsc::{self, SyncSender, TrySendError};
use std::time::Duration;
use crate::geometry::{self, Rect};
/// Maximum number of files forwarded in a single drop.
const MAX_DROP_PATHS: usize = 256;
/// Maximum joined UTF-8 text size forwarded in a single drop.
const MAX_DROP_TEXT_BYTES: usize = 128 << 10;
/// Drop contents and guest-image coordinates for one completed host drop.
#[derive(Debug)]
pub(crate) struct DropPayload {
/// Guest display port that received the drop.
pub display_index: u64,
/// Horizontal position, clamped to the guest image.
pub norm_x: f64,
/// Vertical position, clamped to the guest image.
pub norm_y: f64,
/// Whether the original position was inside the guest image.
pub in_image: bool,
/// Host paths in the order SDL delivered them.
pub paths: Vec<String>,
/// Joined text for a drop without files.
pub text: Option<String>,
}
/// Maps a window point to the guest image, using its center when geometry is unavailable.
pub(crate) fn normalize_point(point: Option<(f64, f64)>, image: Rect) -> (f64, f64, bool) {
let Some((x, y)) = point else {
return (0.5, 0.5, false);
};
if ![x, y, image.x, image.y, image.width, image.height]
.into_iter()
.all(f64::is_finite)
|| image.width <= 0.0
|| image.height <= 0.0
{
return (0.5, 0.5, false);
}
(
((x - image.x) / image.width).clamp(0.0, 1.0),
((y - image.y) / image.height).clamp(0.0, 1.0),
geometry::contains(image, (x, y)),
)
}
/// Drop state for one SDL window, active from begin or the first file, text or position.
#[derive(Debug, Default)]
pub(crate) struct DropBatch {
/// Host paths collected for this batch.
paths: Option<Vec<String>>,
/// Nonempty input chunks in delivery order, bounded before joining.
texts: Option<Vec<String>>,
/// Joined bytes consumed, saturated at the limit once a chunk is truncated.
text_bytes: usize,
/// Most recent finite position, in SDL window coordinates.
last_pos: Option<(f64, f64)>,
}
impl DropBatch {
/// Starts a new batch, discarding an unfinished drop.
pub(crate) fn begin(&mut self) {
self.paths = Some(Vec::new());
self.texts = None;
self.text_bytes = 0;
self.last_pos = None;
}
/// Records the most recent usable position.
pub(crate) fn position(&mut self, x: f64, y: f64) {
if x.is_finite() && y.is_finite() {
self.last_pos = Some((x, y));
}
}
/// Accepts a file even if SDL omitted begin, taking its position as a fallback.
pub(crate) fn file(&mut self, path: String, pos: Option<(f64, f64)>) {
if path.is_empty() {
return;
}
let paths = self.paths.get_or_insert_with(Vec::new);
if paths.len() < MAX_DROP_PATHS {
paths.push(path);
}
if self.last_pos.is_none() && let Some((x, y)) = pos {
self.position(x, y);
}
}
/// Collects UTF-8 text up to the byte limit, including separators between chunks.
pub(crate) fn text(&mut self, chunk: String, pos: Option<(f64, f64)>) {
if chunk.is_empty() {
return;
}
if self.last_pos.is_none() && let Some((x, y)) = pos {
self.position(x, y);
}
if self.text_bytes == MAX_DROP_TEXT_BYTES {
return;
}
let separator = usize::from(self.texts.is_some());
let remaining = MAX_DROP_TEXT_BYTES - self.text_bytes - separator;
let texts = self.texts.get_or_insert_with(Vec::new);
if chunk.len() > remaining {
let kept = &chunk[..chunk.floor_char_boundary(remaining)];
if !kept.is_empty() {
texts.push(kept.to_owned());
}
self.text_bytes = MAX_DROP_TEXT_BYTES;
} else {
self.text_bytes += separator + chunk.len();
texts.push(chunk);
}
}
/// Finishes this batch and yields its files or text and normalized drop position.
pub(crate) fn complete(
&mut self,
display_index: u64,
image: Rect,
pos: Option<(f64, f64)>,
) -> Option<DropPayload> {
let point = self.last_pos.take().or(pos);
let paths = self.paths.take().unwrap_or_default();
let texts = self.texts.take();
self.text_bytes = 0;
let text = if paths.is_empty() {
Some(texts.filter(|chunks| !chunks.is_empty())?.join("\n"))
} else {
None
};
let (norm_x, norm_y, in_image) = normalize_point(point, image);
Some(DropPayload {
display_index,
norm_x,
norm_y,
in_image,
paths,
text,
})
}
/// Discards drop contents and position when the window closes.
pub(crate) fn reset(&mut self) {
*self = Self::default();
}
}
/// Appends one quoted string with RFC 8259 escapes.
fn push_json_string(json: &mut String, value: &str) {
json.push('"');
for ch in value.chars() {
match ch {
'"' => json.push_str("\\\""),
'\\' => json.push_str("\\\\"),
'\u{8}' => json.push_str("\\b"),
'\u{c}' => json.push_str("\\f"),
'\n' => json.push_str("\\n"),
'\r' => json.push_str("\\r"),
'\t' => json.push_str("\\t"),
'\0'..='\u{1f}' => {
// Writing to a String is infallible.
let _ = write!(json, "\\u{:04x}", u32::from(ch));
}
_ => json.push(ch),
}
}
json.push('"');
}
/// Encodes a file or text drop as UTF-8 JSON.
pub(crate) fn encode_drop_json(payload: &DropPayload) -> String {
let mut json = format!(
r#"{{"display_index":{},"norm_x":{},"norm_y":{},"in_image":{}"#,
payload.display_index, payload.norm_x, payload.norm_y, payload.in_image,
);
if !payload.paths.is_empty() {
json.push_str(r#","paths":["#);
for (i, path) in payload.paths.iter().enumerate() {
if i != 0 {
json.push(',');
}
push_json_string(&mut json, path);
}
json.push(']');
} else if let Some(text) = &payload.text {
json.push_str(r#","text":"#);
push_json_string(&mut json, text);
}
json.push('}');
json
}
/// Parses the explicit IPv4 loopback endpoint used by the host drop bridge.
fn parse_loopback_drop_url(raw: &str) -> Option<(SocketAddr, String)> {
let rest = raw.strip_prefix("http://127.0.0.1:")?;
let (port, path) = match rest.find('/') {
Some(i) => (&rest[..i], &rest[i..]),
None => (rest, "/v1/host-drop"),
};
if !port.bytes().all(|b| b.is_ascii_digit())
|| path.bytes().any(|b| b.is_ascii_control() || b == b' ')
{
return None;
}
let port: u16 = port.parse().ok()?;
(port != 0).then(|| (SocketAddr::from(([127, 0, 0, 1], port)), path.to_owned()))
}
/// SDL's bounded queue to the HTTP worker.
static DROP_TX: OnceLock<SyncSender<DropPayload>> = OnceLock::new();
/// Starts the HTTP worker when the runtime provides a valid local URL and bearer token.
#[cfg_attr(
not(any(target_os = "linux", target_os = "windows")),
expect(dead_code, reason = "only the SDL thread starts the host drop forwarder")
)]
pub(crate) fn install_host_drop_forwarder() {
let Ok(url) = std::env::var("REIMS_GO_DROP_URL") else {
return;
};
let Ok(token) = std::env::var("REIMS_GO_DROP_TOKEN") else {
return;
};
if token.is_empty() || token.contains(['\r', '\n']) || DROP_TX.get().is_some() {
return;
}
let Some((addr, path)) = parse_loopback_drop_url(&url) else {
log::warn!(target: "reims_vgpu_window", "ignoring invalid REIMS_GO_DROP_URL");
return;
};
let (tx, rx) = mpsc::sync_channel(16);
match std::thread::Builder::new()
.name("reims-vgpu.drop".into())
.spawn(move || {
for payload in rx {
if let Err(err) = post_loopback_drop(addr, &path, &token, &payload) {
log::warn!(target: "reims_vgpu_window", "could not forward file drop: {err}");
}
}
}) {
Ok(_) => {
let _ = DROP_TX.set(tx);
}
Err(err) => log::warn!(target: "reims_vgpu_window", "could not start drop worker: {err}"),
}
}
/// Enqueues a drop without waiting for network I/O or queue space on the UI thread.
pub(crate) fn submit(payload: DropPayload) {
if let Some(tx) = DROP_TX.get()
&& let Err(TrySendError::Full(_)) = tx.try_send(payload)
{
log::warn!(target: "reims_vgpu_window", "file drop queue is full");
}
}
/// Posts one complete JSON payload to the authenticated IPv4 loopback bridge.
fn post_loopback_drop(
addr: SocketAddr,
path: &str,
token: &str,
payload: &DropPayload,
) -> io::Result<()> {
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_millis(500))?;
stream.set_write_timeout(Some(Duration::from_millis(2000)))?;
let body = encode_drop_json(payload);
write!(
stream,
"POST {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nAuthorization: Bearer {token}\r\n\
Content-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
)?;
stream.write_all(body.as_bytes())
}
/// Offline tests for window drops and the host bridge protocol.
#[cfg(test)]
mod tests {
use super::*;
use std::io::Read;
use std::net::TcpListener;
/// Guest image offset from the window edges.
const IMAGE: Rect = Rect { x: 10.0, y: 20.0, width: 40.0, height: 80.0 };
/// Coordinates use half-open image bounds and clamp outside those bounds.
#[test]
fn normalizes_window_points() {
for (point, expected) in [
((20.0, 80.0), (0.25, 0.75, true)),
((10.0, 20.0), (0.0, 0.0, true)),
((50.0, 100.0), (1.0, 1.0, false)),
((0.0, 120.0), (0.0, 1.0, false)),
] {
assert_eq!(normalize_point(Some(point), IMAGE), expected);
}
let center = (0.5, 0.5, false);
for point in [None, Some((f64::NAN, 40.0)), Some((20.0, f64::INFINITY))] {
assert_eq!(normalize_point(point, IMAGE), center);
}
for bad in [0.0, -1.0, f64::NAN, f64::INFINITY] {
for image in [Rect { width: bad, ..IMAGE }, Rect { height: bad, ..IMAGE }] {
assert_eq!(normalize_point(Some((20.0, 80.0)), image), center);
}
}
}
/// Position events override file and completion coordinates, retaining file order.
#[test]
#[allow(clippy::expect_used)]
fn batch_completes_with_latest_position() {
let mut batch = DropBatch::default();
batch.begin();
batch.file("first".into(), Some((50.0, 100.0)));
batch.position(20.0, 80.0);
batch.position(f64::NAN, 90.0);
batch.file("second".into(), Some((40.0, 30.0)));
let p = batch.complete(42, IMAGE, Some((30.0, 60.0))).expect("two files");
assert_eq!(p.display_index, 42);
assert_eq!(p.paths, ["first", "second"]);
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
assert!(batch.complete(42, IMAGE, None).is_none());
}
/// Missing begin, invalid file coordinates, completion fallback and reset are independent.
#[test]
#[allow(clippy::expect_used)]
fn handles_partial_batches() {
let mut batch = DropBatch::default();
batch.file("".into(), Some((10.0, 20.0)));
batch.file("first".into(), Some((1.0, f64::NAN)));
batch.file("second".into(), Some((20.0, 80.0)));
batch.file("third".into(), Some((40.0, 30.0)));
let p = batch.complete(1, IMAGE, None).expect("file-only drop");
assert_eq!(p.paths, ["first", "second", "third"]);
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
batch.file("abandoned".into(), Some((20.0, 80.0)));
batch.begin();
assert!(batch.complete(1, IMAGE, None).is_none());
batch.file("closed".into(), Some((20.0, 80.0)));
batch.reset();
assert!(batch.complete(1, IMAGE, None).is_none());
batch.position(20.0, 80.0);
assert!(batch.complete(1, IMAGE, None).is_none());
batch.file("next".into(), None);
let p = batch.complete(2, IMAGE, Some((60.0, 60.0))).expect("fresh drop");
assert_eq!((p.norm_x, p.norm_y, p.in_image), (1.0, 0.5, false));
}
/// Oversized drops retain the first 256 paths in order.
#[test]
#[allow(clippy::expect_used)]
fn caps_paths() {
let mut batch = DropBatch::default();
for i in 0..260 {
batch.file(i.to_string(), None);
}
let p = batch.complete(0, IMAGE, None).expect("bounded drop");
assert_eq!(p.paths, (0..256).map(|i| i.to_string()).collect::<Vec<_>>());
}
/// URL drops keep their position and subsequent batches join chunks in order.
#[test]
#[allow(clippy::expect_used)]
fn collects_url_and_multiline_text() {
let mut batch = DropBatch::default();
let url = "https://example.org/路径";
batch.text(url.into(), Some((20.0, 80.0)));
let p = batch.complete(1, IMAGE, None).expect("URL drop");
assert_eq!(p.text.as_deref(), Some(url));
assert!(p.paths.is_empty());
assert_eq!((p.norm_x, p.norm_y, p.in_image), (0.25, 0.75, true));
batch.text("abandoned".into(), None);
batch.begin();
batch.text("one\ntwo".into(), None);
batch.text(String::new(), None);
batch.text("three".into(), None);
let p = batch.complete(1, IMAGE, None).expect("multiline drop");
assert_eq!(p.text.as_deref(), Some("one\ntwo\nthree"));
}
/// A split UTF-8 character ends collection even when a smaller chunk would fit.
#[test]
#[allow(clippy::expect_used)]
fn truncates_text_at_utf8_boundary() {
let mut batch = DropBatch::default();
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 6);
batch.text(prefix.clone(), None);
batch.text("界界".into(), None);
batch.text("x".into(), None);
let p = batch.complete(0, IMAGE, None).expect("bounded text drop");
assert_eq!(p.text, Some(format!("{prefix}\n界")));
let prefix = "a".repeat(MAX_DROP_TEXT_BYTES - 3);
batch.text(prefix.clone(), None);
batch.text("界".into(), None);
let p = batch.complete(0, IMAGE, None).expect("two bytes remaining");
assert_eq!(p.text, Some(prefix));
}
/// Files take precedence over text regardless of arrival order.
#[test]
#[allow(clippy::expect_used)]
fn files_take_precedence() {
let mut batch = DropBatch::default();
batch.text("before".into(), None);
batch.file("path".into(), None);
batch.text("after".into(), None);
let p = batch.complete(0, IMAGE, None).expect("mixed drop");
assert_eq!(p.paths, ["path"]);
assert_eq!(p.text, None);
assert!(batch.complete(0, IMAGE, None).is_none());
}
/// Text JSON preserves Unicode and escapes quotes, backslashes and newlines.
#[test]
fn encodes_json_text() {
let p = DropPayload {
text: Some("你好 \"\\\n".into()),
paths: Vec::new(),
..sample()
};
assert_eq!(encode_drop_json(&p), concat!(
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"#,
r#""text":"你好 \"\\\n"}"#,
));
}
/// An example drop containing Unicode, delimiters and control characters.
fn sample() -> DropPayload {
DropPayload {
display_index: 17,
norm_x: 0.25,
norm_y: 0.75,
in_image: true,
text: None,
paths: vec![r"D:\Downloads\测试.pdf".into(), "\"\u{8}\u{c}\n\r\t\0\u{10}".into()],
}
}
/// Checks UTF-8 preservation and each class of RFC 8259 escape.
#[test]
fn encodes_json_paths() {
assert_eq!(encode_drop_json(&sample()), concat!(
r#"{"display_index":17,"norm_x":0.25,"norm_y":0.75,"in_image":true,"paths":["#,
r#""D:\\Downloads\\测试.pdf","\"\b\f\n\r\t\u0000\u0010"]}"#,
));
}
/// Only the literal loopback host, a numeric nonzero port and a safe path are accepted.
#[test]
fn validates_loopback_urls() {
let addr = SocketAddr::from(([127, 0, 0, 1], 42));
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42"), Some((addr, "/v1/host-drop".into())));
assert_eq!(parse_loopback_drop_url("http://127.0.0.1:42/drop?q=1"), Some((addr, "/drop?q=1".into())));
for raw in [
"https://127.0.0.1:42/drop", "http://localhost:42/drop", "http://127.0.0.2:42/drop",
"http://[::1]:42/drop", "http://127.0.0.1:/drop", "http://127.0.0.1:0/drop",
"http://127.0.0.1:65536/drop", "http://127.0.0.1:+42/drop", "http://127.0.0.1:42@evil/drop",
"http://127.0.0.1:42/a b", "http://127.0.0.1:42/a\rheader", "http://127.0.0.1:42/a\nheader",
" http://127.0.0.1:42", "http://127.0.0.1:42/drop\r\n",
] {
assert!(parse_loopback_drop_url(raw).is_none(), "{raw:?}");
}
}
/// A real loopback peer receives the authenticated request and exact UTF-8 byte count.
#[test]
#[allow(clippy::expect_used)]
fn posts_the_complete_drop_to_loopback() -> io::Result<()> {
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
listener.set_nonblocking(true)?;
let payload = sample();
post_loopback_drop(listener.local_addr()?, "/custom/drop", "test-token", &payload)?;
let (mut stream, _) = listener.accept()?;
stream.set_nonblocking(false)?;
stream.set_read_timeout(Some(Duration::from_secs(2)))?;
let mut request = String::new();
stream.read_to_string(&mut request)?;
let (headers, body) = request.split_once("\r\n\r\n").expect("HTTP headers");
assert_eq!(headers.lines().next(), Some("POST /custom/drop HTTP/1.1"));
for field in ["Host: 127.0.0.1", "Authorization: Bearer test-token",
"Content-Type: application/json", "Connection: close"] {
assert!(headers.lines().any(|line| line == field), "{field}");
}
assert!(headers.lines().any(|line| line == format!("Content-Length: {}", body.len())));
assert_eq!(body, encode_drop_json(&payload));
Ok(())
}
}
+2
View File
@@ -64,6 +64,8 @@ pub mod scroll;
// The SDL3 window: Linux's and Windows's (`native/sdl_thread.rs`), and macOS's with the
// `macos-sdl` feature, behind `REIMS_VGPU_WINDOW_IMPL`.
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
mod drop;
#[cfg(any(target_os = "linux", target_os = "windows", feature = "macos-sdl"))]
mod sdl;
pub use config::{
@@ -185,6 +185,7 @@ fn start_video() -> bool {
}
#[cfg(target_os = "windows")]
super::super::windows::install_unicode_input_hook();
crate::drop::install_host_drop_forwarder();
// SAFETY: SDL's video runs.
let kind = unsafe { SDL_RegisterEvents(1) };
WAKE.store(kind, Ordering::Release);
+72 -1
View File
@@ -83,6 +83,8 @@ pub(crate) struct Shell {
density: f64,
/// Its input.
pub(crate) input: Input,
/// Files and coordinates supplied by SDL for the current drop.
drop_batch: crate::drop::DropBatch,
/// What its OS keeps of it.
pub(crate) os: os::State,
/// The guest's cursor, built for SDL.
@@ -177,6 +179,7 @@ pub(crate) fn open(window: &Arc<Window>) {
layout: Layout::default(),
density: 1.0,
input: opened.input,
drop_batch: crate::drop::DropBatch::default(),
os: opened.state,
cursor: CursorCache::default(),
over_image: false,
@@ -204,6 +207,7 @@ pub(crate) fn open(window: &Arc<Window>) {
pub(crate) fn close(id: u64) {
let gone = with_shell(id, |shell| {
ended(shell);
shell.drop_batch.reset();
shell.closed = true;
os::close(shell) || shell.released
});
@@ -312,6 +316,14 @@ fn settled(before: Option<bool>, kind: u32) -> Option<bool> {
pub(crate) fn event(event: &SDL_Event) {
// SAFETY: every event starts with its type, and each arm reads the variant its type names.
let kind = unsafe { event.r#type };
let is_drop = [
SDL_EVENT_DROP_BEGIN.0,
SDL_EVENT_DROP_POSITION.0,
SDL_EVENT_DROP_FILE.0,
SDL_EVENT_DROP_TEXT.0,
SDL_EVENT_DROP_COMPLETE.0,
]
.contains(&kind);
let sdl_id = match kind {
k if (SDL_EVENT_WINDOW_FIRST.0..=SDL_EVENT_WINDOW_LAST.0).contains(&k) => unsafe {
event.window.windowID.0
@@ -324,9 +336,20 @@ pub(crate) fn event(event: &SDL_Event) {
event.button.windowID.0
},
k if k == SDL_EVENT_MOUSE_WHEEL.0 => unsafe { event.wheel.windowID.0 },
_ if is_drop => unsafe { event.drop.windowID.0 },
_ => return,
};
let Some(id) = window_of(sdl_id) else {
let target = if is_drop && sdl_id == 0 {
OPEN.with(|open| {
let open = open.borrow();
let mut live = open.iter().filter(|shell| !shell.closed);
let first = live.next()?;
live.next().is_none().then(|| first.window.id())
})
} else {
window_of(sdl_id)
};
let Some(id) = target else {
return;
};
with_shell(id, |shell| {
@@ -390,6 +413,54 @@ impl Shell {
self.refresh_cursor();
false
}
k if k == SDL_EVENT_DROP_BEGIN.0 => {
self.drop_batch.begin();
false
}
k if k == SDL_EVENT_DROP_POSITION.0 => {
// SAFETY: the event type selects the drop member.
let (x, y) = unsafe { (event.drop.x, event.drop.y) };
self.drop_batch.position(f64::from(x), f64::from(y));
false
}
k if k == SDL_EVENT_DROP_FILE.0 => {
// SAFETY: the event type selects the drop member.
let drop = unsafe { event.drop };
if !drop.data.is_null() {
// SAFETY: SDL3 owns this NUL-terminated path for the event's lifetime.
let path = unsafe { std::ffi::CStr::from_ptr(drop.data) }
.to_string_lossy()
.into_owned();
self.drop_batch
.file(path, Some((f64::from(drop.x), f64::from(drop.y))));
}
false
}
k if k == SDL_EVENT_DROP_TEXT.0 => {
// SAFETY: the event type selects the drop member.
let drop = unsafe { event.drop };
if !drop.data.is_null() {
// SAFETY: SDL3 owns this NUL-terminated text for the event's lifetime.
let text = unsafe { std::ffi::CStr::from_ptr(drop.data) }
.to_string_lossy()
.into_owned();
self.drop_batch
.text(text, Some((f64::from(drop.x), f64::from(drop.y))));
}
false
}
k if k == SDL_EVENT_DROP_COMPLETE.0 => {
// SAFETY: the event type selects the drop member.
let drop = unsafe { event.drop };
if let Some(payload) = self.drop_batch.complete(
self.window.port(),
self.layout.image,
Some((f64::from(drop.x), f64::from(drop.y))),
) {
crate::drop::submit(payload);
}
false
}
_ => os::input_event(self, kind, event),
};
self.flush();
+1 -1
View File
@@ -34,4 +34,4 @@ Arch = "arm64e"
MinKernel = "23.0.0"
MaxKernel = ""
Comment = "Installs the reims-graphics Metal bundle and admits it"
sha256 = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
sha256 = "09853275a5e976bb9c435f76e8f84702f1692b7b98029957404951f626bbebfc"
+5 -5
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]
@@ -445,7 +445,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/rgfxgate/src/RgfxGate.hpp" = "90cf92a9b031fc857dfda215db37a4056ea1919d418289b1d8a2dd056fe9d51c"
"guest/rgfxgate/src/RgfxGateFile.hpp" = "4683d072fe3d0aecc0308eb6e9896bb694a9d2899e44070a17a7859448b10566"
"guest/rgfxgate/src/RgfxGateHooks.cpp" = "3c77cf33042c062ccc41f864801db1759afe145dbaaaa4336e935ddc305d3843"
"guest/rgfxgate/src/RgfxGateInstall.cpp" = "0dd5e94467eb37ad447e638c561148d42bbc5cd2bf0129e290f87e9490d3c9fc"
"guest/rgfxgate/src/RgfxGateInstall.cpp" = "533d7d489d240ef34a065256ad16025dec6f7a1c929db5eae92ed27073a578ef"
"guest/rgfxgate/src/RgfxGatePrefs.cpp" = "19851da9d270161f3c58ae97b35cfc15b2c7484514c287d41cb23f95c83ea3b8"
"guest/rgfxgate/src/RgfxGatePrefs.hpp" = "7a9cbf500b1578ee780470e9b789030dd12c88469fda9d557e65e52cd81b1a07"
"guest/rgfxgate/src/RgfxGateVnop.hpp" = "ca2743778b2c13cfaf48807469f926134bb3813a0963f0dcc3f5346a3e7dd84c"
@@ -466,5 +466,5 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"ReimsGraphics.kext/Contents/Info.plist" = "9683153587659c4bd4d5c52167eff1f3d2ae51dae575f60c15a27d89240f46c5"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "33a086b90fa116b3cf0c6bb826c27f8a55cd83f15522ee794e20186d469bdbc7"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "deb1696453b7d754547abc24e3fa30e5affea059bd19d2d732bee243054a300e"
"set.toml" = "a4da2409f25dd7bf12260de752c38c474b60d4b2d993810a44de0f4b07cb6dfd"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "09853275a5e976bb9c435f76e8f84702f1692b7b98029957404951f626bbebfc"
"set.toml" = "7b7041b0b0644f18b18ca17f17d7a65eb8d8525f37c8603baf7e81c4519ec066"
Binary file not shown.
+1 -1
View File
@@ -34,4 +34,4 @@ Arch = "x86_64"
MinKernel = "20.0.0"
MaxKernel = ""
Comment = "Installs the reims-graphics Metal bundle and admits it"
sha256 = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
sha256 = "9801337a4a9b1cd60dc83eaac59f2a64637c123d178dbc63d8247476161810a4"
+5 -5
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]
@@ -445,7 +445,7 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"guest/rgfxgate/src/RgfxGate.hpp" = "90cf92a9b031fc857dfda215db37a4056ea1919d418289b1d8a2dd056fe9d51c"
"guest/rgfxgate/src/RgfxGateFile.hpp" = "4683d072fe3d0aecc0308eb6e9896bb694a9d2899e44070a17a7859448b10566"
"guest/rgfxgate/src/RgfxGateHooks.cpp" = "3c77cf33042c062ccc41f864801db1759afe145dbaaaa4336e935ddc305d3843"
"guest/rgfxgate/src/RgfxGateInstall.cpp" = "0dd5e94467eb37ad447e638c561148d42bbc5cd2bf0129e290f87e9490d3c9fc"
"guest/rgfxgate/src/RgfxGateInstall.cpp" = "533d7d489d240ef34a065256ad16025dec6f7a1c929db5eae92ed27073a578ef"
"guest/rgfxgate/src/RgfxGatePrefs.cpp" = "19851da9d270161f3c58ae97b35cfc15b2c7484514c287d41cb23f95c83ea3b8"
"guest/rgfxgate/src/RgfxGatePrefs.hpp" = "7a9cbf500b1578ee780470e9b789030dd12c88469fda9d557e65e52cd81b1a07"
"guest/rgfxgate/src/RgfxGateVnop.hpp" = "ca2743778b2c13cfaf48807469f926134bb3813a0963f0dcc3f5346a3e7dd84c"
@@ -466,5 +466,5 @@ clang = "Apple clang version 21.0.0 (clang-2100.4.1.1)"
"ReimsGraphics.kext/Contents/Info.plist" = "ae0dafd3b6c36c24d1c92467d8203d76360eb6e4f6ad5c496167a21033b2c209"
"ReimsGraphics.kext/Contents/MacOS/ReimsGraphics" = "d0277f202173dcecc35bce8aa2ec84cd9d53759a0fd34c26e913bcd65a191d50"
"RgfxGate.kext/Contents/Info.plist" = "7b78d915fab4d36e6cdb3f40aa2a6c1e7224f30158ee879af23451d2e6969992"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "90d8327eb2243b820dd90ce29e4be79a80516f3e6341137b76e9b575ea3d10eb"
"set.toml" = "49182c19c3d961b251901e19a09016df684f1f102527a0d3274697eaaf3dbab5"
"RgfxGate.kext/Contents/MacOS/RgfxGate" = "9801337a4a9b1cd60dc83eaac59f2a64637c123d178dbc63d8247476161810a4"
"set.toml" = "8947f58f02818cd1ac50e9fad53a77d983f2a424ace8320b5b085a965c1adb6b"
+8 -5
View File
@@ -371,6 +371,8 @@ static void renameIdentity(vnode_t vp, vnode_t olddvp, const char *oldleaf, vnod
// swap (both ends must exist), the two are exchanged atomically
// (VFS_RENAME_SWAP): a reader of `to` always sees one whole tree, never a
// half-swapped one. Without swap, `from` replaces `to`, which need not exist.
// Look up the directory entries themselves: a symlink is exchanged as a link,
// even if dangling, and its target stays where it is.
// Each renamed vnode then takes its new name and parent (renameIdentity), as
// after vn_rename: the installed bundle's vnodes would otherwise keep the
// staging name, reims-graphics.bundle.new.
@@ -378,10 +380,10 @@ static void renameIdentity(vnode_t vp, vnode_t olddvp, const char *oldleaf, vnod
bool rgfxRenameNode(const char *from, const char *to, bool swap,
vfs_context_t ctx) {
vnode_t fvp = nullptr;
if (vnode_lookup(from, 0, &fvp, ctx) != 0)
if (vnode_lookup(from, VNODE_LOOKUP_NOFOLLOW, &fvp, ctx) != 0)
return false; // nothing to rename
vnode_t tvp = nullptr;
if (vnode_lookup(to, 0, &tvp, ctx) != 0)
if (vnode_lookup(to, VNODE_LOOKUP_NOFOLLOW, &tvp, ctx) != 0)
tvp = nullptr; // target absent: a plain rename into a free name
bool ok = false;
if (!(swap && tvp == nullptr)) {
@@ -559,13 +561,14 @@ static bool installBundle(vfs_context_t ctx) {
tagTree(stageRoot, ctx);
if (ok) {
vnode_t live = nullptr;
bool haveLive = vnode_lookup(kBundlePath, 0, &live, ctx) == 0;
// A newer runtime may have placed its bundle behind a symlink.
bool haveLive = vnode_lookup(kBundlePath, VNODE_LOOKUP_NOFOLLOW, &live, ctx) == 0;
if (haveLive)
vnode_put(live);
ok = rgfxRenameNode(stageRoot, kBundlePath, haveLive, ctx);
}
// On a swap the old tree is now at stageRoot; on a move it is gone; on a
// failure the staged tree is still there. One sweep clears whichever remains.
// On a swap the old tree or link is now at stageRoot; on a move it is gone;
// on a failure the staged tree is still there. The sweep never follows links.
removeTree(stageRoot, ctx);
// The container carries the class on every install (it may be freshly made).
tagRootless(kContainerPath, ctx);
+19
View File
@@ -235,6 +235,24 @@ void testLinksAreNotFollowed() {
assert(exists("outside/kept/file"));
}
void testSwappedBundleLinkLeavesItsTarget() {
PosixFs fs;
const char *bundle = "t7/reims-graphics.bundle";
const std::string stage = std::string(bundle) + ".new";
const char *placed = "t7-cache/reims-graphics.bundle";
const char *oldMarker = "t7-cache/reims-graphics.bundle/Contents/Resources/wire-version-3";
mkdirs(std::string(placed) + "/Contents/Resources");
touch(oldMarker);
mkdirs(stage + "/Contents/Resources");
touch(stage + "/Contents/Resources/wire-version-2");
assert(symlink(at(placed).c_str(), at(bundle).c_str()) == 0);
assert(renamex_np(at(stage).c_str(), at(bundle).c_str(), RENAME_SWAP) == 0);
assert(removeTree(stage, fs));
assert(!exists(stage));
assert(exists(std::string(bundle) + "/Contents/Resources/wire-version-2"));
assert(exists(oldMarker));
}
// A tree deeper than the walk descends stops it, and the walk says so; what
// lies outside the tree is untouched.
void testTooDeep() {
@@ -296,6 +314,7 @@ int main() {
testLeftoverOfAnOlderBuild();
testShapes();
testLinksAreNotFollowed();
testSwappedBundleLinkLeavesItsTarget();
testTooDeep();
testStuck();
testPathTooLong();
+3 -1
View File
@@ -7,6 +7,8 @@
"win10-compat",
"win10-startup-ipis",
"win32-coroutine-fiber",
"win32-unicode-input"
"win32-unicode-input",
"window-file-drop",
"window-text-drop"
]
}