diff --git a/src/cli.rs b/src/cli.rs index 1b50002..024c412 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -43,7 +43,7 @@ pub struct Cli { pub enum Command { /// Make an OpenCore boot image, and write OVMF beside it #[command(after_help = OPENCORE_HELP)] - Opencore(OpencoreArgs), + Opencore(Box), /// Make an online installer: Apple's recovery image, which installs the newest release of /// its macOS (10.13 to 26) over the network #[command(after_help = ONLINE_HELP)] @@ -112,6 +112,9 @@ pub struct OpencoreArgs { /// Repeat it for more: they load in the order given #[arg(long = "add-kext", value_name = "PATH[,MIN[,MAX]]", value_parser = added::parse)] pub add_kext: Vec, + /// Carry the saved OpenCore preboot input settings and EFI drivers from DIR + #[arg(long, value_name = "DIR")] + pub preboot_input: Option, /// Accepted and ignored: --no-apv-arm64-port and --no-video, whose kexts images no longer /// carry #[arg( @@ -359,6 +362,7 @@ pub fn opencore_options(a: &OpencoreArgs) -> Result { show_picker: a.show_picker, }, add_kexts: a.add_kext.clone(), + preboot_input: a.preboot_input.clone(), ovmf_dir, }) } diff --git a/src/opencore/added.rs b/src/opencore/added.rs index 2fe3ad7..095f80d 100644 --- a/src/opencore/added.rs +++ b/src/opencore/added.rs @@ -3,9 +3,66 @@ //! whole into `EFI/OC/Kexts` (dotfiles left out), and loaded by a Kernel > Add entry made from its //! Info.plist and the Darwin versions it was given (config.rs). -use anyhow::{Context, Result, bail}; +use anyhow::{Context, Result, bail, ensure}; +use plist::{Dictionary, Value}; use std::path::{Path, PathBuf}; +#[derive(serde::Deserialize)] +#[serde(rename_all = "PascalCase")] +struct PrebootManifest { + input: Dictionary, + drivers: Vec, +} + +/// Saved UEFI input settings and the original preboot drivers, in load order. +pub struct PrebootInput { + pub input: Dictionary, + pub drivers: Vec, + pub files: Vec<(String, Vec)>, +} + +impl PrebootInput { + pub fn read(dir: &Path) -> Result { + let manifest = dir.join("input.plist"); + let PrebootManifest { input, drivers } = plist::from_bytes(&read_regular_file(&manifest)?) + .with_context(|| format!("read {}", manifest.display()))?; + let mut files = Vec::with_capacity(drivers.len()); + let mut seen = Vec::<&str>::new(); + for entry in &drivers { + let path = entry + .get("Path") + .and_then(Value::as_string) + .context("a preboot driver has no Path string")?; + let name = ["ReimsTablet.efi", "OpenUsbKbDxe.efi"] + .into_iter() + .find(|name| path.eq_ignore_ascii_case(name)) + .with_context(|| format!("unsupported preboot driver {path:?}"))?; + ensure!(!seen.contains(&name), "duplicate preboot driver {path:?}"); + seen.push(name); + // Path is one of the supported basenames above. Keep the spelling in the plist. + let bytes = read_regular_file(&dir.join(path))?; + files.push((format!("EFI/OC/Drivers/{path}"), bytes)); + } + Ok(Self { + input, + drivers, + files, + }) + } +} + +fn read_regular_file(path: &Path) -> Result> { + let context = || format!("read {}", path.display()); + ensure!( + std::fs::symlink_metadata(path) + .with_context(context)? + .is_file(), + "{} is not a regular file", + path.display() + ); + std::fs::read(path).with_context(context) +} + /// A `--add-kext` value, `PATH[,MIN[,MAX]]`: a bundle, and the Darwin versions it loads on, each /// bound empty for none. #[derive(Clone, Debug, PartialEq)] @@ -300,6 +357,82 @@ pub(crate) mod tests { } } + fn preboot_manifest(paths: &[&str]) -> Vec { + let mut input = Dictionary::new(); + input.insert("KeySupport".into(), false.into()); + input.insert("PointerSupport".into(), true.into()); + let drivers = paths + .iter() + .map(|&path| { + let mut row = Dictionary::new(); + row.insert("Path".into(), path.into()); + row.insert("LoadEarly".into(), true.into()); + row.insert("Enabled".into(), true.into()); + Value::Dictionary(row) + }) + .collect(); + let mut manifest = Dictionary::new(); + manifest.insert("Input".into(), input.into()); + manifest.insert("Drivers".into(), Value::Array(drivers)); + let mut bytes = Vec::new(); + Value::Dictionary(manifest) + .to_writer_xml(&mut bytes) + .unwrap(); + bytes + } + + #[test] + fn preboot_input_preserves_driver_order_casing_and_bytes() { + let paths = ["OpenUsbKbDxe.efi", "reimstablet.EFI"]; + let manifest = preboot_manifest(&paths); + let dir = Bundle::new( + "preboot", + &[ + ("input.plist", &manifest), + (paths[0], b"keyboard"), + (paths[1], b"tablet"), + ], + ); + let preboot = PrebootInput::read(&dir.path).unwrap(); + assert_eq!(preboot.input["KeySupport"], Value::Boolean(false)); + assert_eq!(preboot.input["PointerSupport"], Value::Boolean(true)); + for (entry, path) in preboot.drivers.iter().zip(paths) { + assert_eq!(entry["Path"], Value::String(path.into())); + assert_eq!(entry["LoadEarly"], Value::Boolean(true)); + } + assert_eq!( + preboot.files, + [ + ( + "EFI/OC/Drivers/OpenUsbKbDxe.efi".into(), + b"keyboard".to_vec() + ), + ("EFI/OC/Drivers/reimstablet.EFI".into(), b"tablet".to_vec()), + ] + ); + } + + #[test] + fn preboot_input_refuses_duplicates_and_missing_or_unrecognized_files() { + for (paths, expected) in [ + (&["../ReimsTablet.efi"][..], "unsupported preboot driver"), + (&["Anything.efi"][..], "unsupported preboot driver"), + ( + &["ReimsTablet.efi", "reimstablet.EFI"][..], + "duplicate preboot driver", + ), + (&["OpenUsbKbDxe.efi"][..], "OpenUsbKbDxe.efi"), + ] { + let manifest = preboot_manifest(paths); + let dir = Bundle::new( + "preboot", + &[("input.plist", &manifest), ("ReimsTablet.efi", b"tablet")], + ); + let error = PrebootInput::read(&dir.path).err().unwrap(); + assert!(format!("{error:#}").contains(expected), "{error:#}"); + } + } + /// An Info.plist: its identifier, executable and libraries. pub(crate) fn info(id: &str, executable: Option<&str>, libraries: &[&str]) -> Vec { let mut d = plist::Dictionary::new(); diff --git a/src/opencore/config.rs b/src/opencore/config.rs index 4ec45ad..a6d4816 100644 --- a/src/opencore/config.rs +++ b/src/opencore/config.rs @@ -70,7 +70,12 @@ pub struct Options { } /// The config.plist for `o`, from the release's `sample`, loading the kexts `added` (added.rs). -pub fn make(sample: &[u8], o: &Options, added: &[added::Kext]) -> Result> { +pub fn make( + sample: &[u8], + o: &Options, + added: &[added::Kext], + preboot: Option<&added::PrebootInput>, +) -> Result> { let mut root: Value = plist::from_bytes(sample).context("read Sample.plist")?; let c = root .as_dictionary_mut() @@ -268,6 +273,10 @@ pub fn make(sample: &[u8], o: &Options, added: &[added::Kext]) -> Result e.insert("LoadEarly".into(), false.into()); entries.push(Value::Dictionary(e)); } + if let Some(preboot) = preboot { + set(c, &["UEFI"], "Input", preboot.input.clone().into())?; + entries.extend(preboot.drivers.iter().cloned().map(Value::Dictionary)); + } set(c, &["UEFI"], "Drivers", Value::Array(entries))?; set(c, &["UEFI"], "ReservedMemory", Value::Array(vec![]))?; diff --git a/src/opencore/mod.rs b/src/opencore/mod.rs index 4131ad9..0453c85 100644 --- a/src/opencore/mod.rs +++ b/src/opencore/mod.rs @@ -52,6 +52,8 @@ pub struct Options { pub config: config::Options, /// Kexts to load, in this order. pub add_kexts: Vec, + /// Directory containing the original VM's preboot input settings and drivers. + pub preboot_input: Option, /// Where OVMF's files go, or None to write none. pub ovmf_dir: Option, } @@ -75,12 +77,20 @@ pub fn build(o: &Options, r: &dyn Reporter) -> Result { .map(added::read) .collect::>>()?; added::check(&added)?; + let preboot = o + .preboot_input + .as_deref() + .map(added::PrebootInput::read) + .transpose()?; let zip_path = cache::fetch(&RELEASE, r)?; progress::check(r)?; let resources_path = cache::fetch(&RESOURCES, r)?; progress::check(r)?; r.step(&format!("Building the OpenCore {VERSION} image")); - let mut files = files(&zip_path, &o.config, &added)?; + let mut files = files(&zip_path, &o.config, &added, preboot.as_ref())?; + if let Some(preboot) = preboot { + files.extend(preboot.files); + } files.extend(resources(&resources_path, o.config.graphical_picker)?); let mut kext_names = Vec::new(); for k in added { @@ -125,6 +135,7 @@ fn files( zip_path: &Path, c: &config::Options, added: &[added::Kext], + preboot: Option<&added::PrebootInput>, ) -> Result)>> { let f = std::fs::File::open(zip_path).with_context(|| format!("open {}", zip_path.display()))?; @@ -157,7 +168,7 @@ fn files( let sample = read("Docs/Sample.plist")?; files.push(( "EFI/OC/config.plist".into(), - config::make(&sample, c, added)?, + config::make(&sample, c, added, preboot)?, )); files.push(( format!("EFI/OC/ACPI/{}", acpi::FILE_NAME), diff --git a/src/tui.rs b/src/tui.rs index 38a4aca..845c56a 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -270,6 +270,7 @@ impl App { text_picker: !form.toggle(7), show_picker: form.toggle(8), add_kext: Vec::new(), + preboot_input: None, _retired: 0, no_ovmf: !form.toggle(3), ovmf_dir: None,