Compare commits

..
Author SHA1 Message Date
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
2 changed files with 220 additions and 9 deletions

No files matched your search

+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()),
(
+14 -5
View File
@@ -45,7 +45,7 @@ use std::time::{Duration, Instant};
pub const REPO: &str = "https://github.com/reims-go/reims-util";
/// The commit [`install`] installs.
pub const REV: &str = "573d4a5ffacfc31430ff7372727fce287fef89e1";
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!(