Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8a21294e6 | ||
|
|
2373afdd01 |
No files matched your search
@@ -21,6 +21,7 @@ mod opencore;
|
||||
mod os;
|
||||
mod paths;
|
||||
mod prebuilt;
|
||||
mod processor;
|
||||
mod qemu;
|
||||
mod qmp;
|
||||
mod reims_util;
|
||||
|
||||
@@ -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, OpenOptions};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Mutex, PoisonError};
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
@@ -49,7 +50,7 @@ pub struct Config(plist::Dictionary);
|
||||
|
||||
impl Config {
|
||||
pub fn read(path: &Path, format: ImageFormat) -> Result<Config> {
|
||||
let bytes = read_file(path, format, "EFI/OC/config.plist")?
|
||||
let bytes = read_file(path, format, CONFIG_PLIST)?
|
||||
.context("its EFI system partition has no EFI/OC/config.plist")?;
|
||||
Config::parse(&bytes)
|
||||
}
|
||||
@@ -132,6 +133,171 @@ impl Config {
|
||||
}
|
||||
}
|
||||
|
||||
const CONFIG_PLIST: &str = "EFI/OC/config.plist";
|
||||
|
||||
/// Update the type used by macOS's About This Mac when OpenCore is set to automatic.
|
||||
pub fn match_processor_type(vm: &Vm, value: u16) -> Result<bool> {
|
||||
let Some(q) = vm.config.q35.as_ref() else {
|
||||
return Ok(false);
|
||||
};
|
||||
let image = vm.path(&q.opencore);
|
||||
if !fs::symlink_metadata(&image)?.is_file() {
|
||||
return Ok(false);
|
||||
}
|
||||
let format = q.opencore_format;
|
||||
let stamp = Stamp::of(&image).context("read OpenCore image metadata")?;
|
||||
let Some(bytes) = read_file(&image, format, CONFIG_PLIST)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
let Some(edited) = with_processor_type(&bytes, value)? else {
|
||||
return Ok(false);
|
||||
};
|
||||
ensure_opencore_unused(vm, &image)?;
|
||||
|
||||
// Keep the original until the candidate is synced and read back. Each caller owns its copy.
|
||||
static NEXT: AtomicU64 = AtomicU64::new(0);
|
||||
let part = image.with_extension(format!(
|
||||
"cpu-{}-{}-{}.part",
|
||||
std::process::id(),
|
||||
SystemTime::now()
|
||||
.duration_since(SystemTime::UNIX_EPOCH)?
|
||||
.as_nanos(),
|
||||
NEXT.fetch_add(1, Ordering::Relaxed),
|
||||
));
|
||||
let file = OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&part)?;
|
||||
let result = (|| -> Result<()> {
|
||||
let mut source = File::open(&image)?;
|
||||
file.set_permissions(source.metadata()?.permissions())?;
|
||||
std::io::copy(&mut source, &mut &file)?;
|
||||
drop(source);
|
||||
let disk = Disk::from_file(file, format)?;
|
||||
let fat = Fat32::open(&disk, esp_start(&disk)?)?;
|
||||
ensure!(
|
||||
fat.holds(CONFIG_PLIST, &bytes)? == Some(true),
|
||||
"OpenCore config changed while copying"
|
||||
);
|
||||
fat.overwrite(CONFIG_PLIST, &edited)?;
|
||||
disk.file().sync_all()?;
|
||||
drop(disk);
|
||||
ensure!(
|
||||
read_file(&part, format, CONFIG_PLIST)?.as_deref() == Some(&edited),
|
||||
"the new OpenCore config did not read back"
|
||||
);
|
||||
|
||||
ensure_opencore_unused(vm, &image)?;
|
||||
ensure!(
|
||||
Stamp::of(&image) == Some(stamp),
|
||||
"OpenCore image changed while copying"
|
||||
);
|
||||
fs::rename(&part, &image).with_context(|| format!("replace {}", image.display()))
|
||||
})();
|
||||
if let Err(error) = result {
|
||||
let _ = fs::remove_file(&part);
|
||||
return Err(error);
|
||||
}
|
||||
|
||||
KEPT.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.remove(&image);
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn ensure_opencore_unused(vm: &Vm, image: &Path) -> Result<()> {
|
||||
ensure!(!runtime::running(vm), "{} is running", vm.name());
|
||||
let image = fs::canonicalize(image)?;
|
||||
for entry in crate::vm::Registry::load()?.vms {
|
||||
if runtime::pid_at(&crate::vm::pidfile_in(&entry.dir)).is_none() {
|
||||
continue;
|
||||
}
|
||||
let other = Vm::load(&entry.dir)
|
||||
.with_context(|| format!("read settings of running VM {}", entry.name))?;
|
||||
if let Some(q) = &other.config.q35 {
|
||||
let other_image = fs::canonicalize(other.path(&q.opencore))?;
|
||||
ensure!(
|
||||
other_image != image,
|
||||
"{} is running on this OpenCore image",
|
||||
entry.name
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Replace the integer in the plist without resizing the FAT file. The parsed comparison
|
||||
/// guards against editing a similarly named key elsewhere in the XML.
|
||||
fn with_processor_type(bytes: &[u8], value: u16) -> Result<Option<Vec<u8>>> {
|
||||
let mut expected = Config::parse(bytes)?.0;
|
||||
let vault = expected
|
||||
.get("Misc")
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.and_then(|misc| misc.get("Security"))
|
||||
.and_then(plist::Value::as_dictionary)
|
||||
.and_then(|security| security.get("Vault"))
|
||||
.and_then(plist::Value::as_string);
|
||||
if vault != Some("Optional") {
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(platform) = expected
|
||||
.get_mut("PlatformInfo")
|
||||
.and_then(plist::Value::as_dictionary_mut)
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if platform.get("Automatic").and_then(plist::Value::as_boolean) != Some(true)
|
||||
|| platform
|
||||
.get("UpdateSMBIOS")
|
||||
.and_then(plist::Value::as_boolean)
|
||||
!= Some(true)
|
||||
|| platform
|
||||
.get("UpdateSMBIOSMode")
|
||||
.and_then(plist::Value::as_string)
|
||||
!= Some("Create")
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let Some(processor) = platform
|
||||
.get_mut("Generic")
|
||||
.and_then(plist::Value::as_dictionary_mut)
|
||||
.and_then(|generic| generic.get_mut("ProcessorType"))
|
||||
else {
|
||||
return Ok(None);
|
||||
};
|
||||
if value == 0 || processor.as_unsigned_integer() != Some(0) {
|
||||
return Ok(None);
|
||||
}
|
||||
*processor = plist::Value::Integer(value.into());
|
||||
|
||||
const KEY: &[u8] = b"<key>ProcessorType</key>";
|
||||
let start = bytes
|
||||
.windows(KEY.len())
|
||||
.position(|w| w == KEY)
|
||||
.context("OpenCore config has no XML ProcessorType key")?
|
||||
+ KEY.len();
|
||||
let whitespace = bytes[start..]
|
||||
.iter()
|
||||
.take_while(|b| b.is_ascii_whitespace())
|
||||
.count();
|
||||
const ZERO: &[u8] = b"<integer>0</integer>";
|
||||
let integer = start + whitespace;
|
||||
let replacement = format!("<integer>{value}</integer>");
|
||||
let growth = replacement.len() - ZERO.len();
|
||||
ensure!(
|
||||
bytes[integer..].starts_with(ZERO) && whitespace >= growth,
|
||||
"OpenCore ProcessorType cannot be replaced at its original length"
|
||||
);
|
||||
let mut edited = bytes.to_vec();
|
||||
edited[integer - growth..integer + ZERO.len()].copy_from_slice(replacement.as_bytes());
|
||||
ensure!(
|
||||
Config::parse(&edited)?.0 == expected,
|
||||
"OpenCore config would change beyond ProcessorType"
|
||||
);
|
||||
Ok(Some(edited))
|
||||
}
|
||||
|
||||
/// Whether a VM's OpenCore image shows its boot picker; `None` for an image reims-ctl cannot
|
||||
/// read, or a VM with no OpenCore.
|
||||
pub fn shows_picker(vm: &Vm) -> Option<bool> {
|
||||
@@ -545,6 +711,10 @@ pub(crate) enum Disk {
|
||||
impl Disk {
|
||||
pub(crate) fn open(path: &Path, format: ImageFormat) -> Result<Disk> {
|
||||
let file = File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
Self::from_file(file, format)
|
||||
}
|
||||
|
||||
fn from_file(file: File, format: ImageFormat) -> Result<Disk> {
|
||||
Ok(match format {
|
||||
ImageFormat::Raw => Disk::Raw {
|
||||
size: file.metadata()?.len(),
|
||||
@@ -554,6 +724,29 @@ impl Disk {
|
||||
})
|
||||
}
|
||||
|
||||
fn file(&self) -> &File {
|
||||
match self {
|
||||
Disk::Raw { file, .. } => file,
|
||||
Disk::Qcow2(q) => &q.file,
|
||||
}
|
||||
}
|
||||
|
||||
fn write(&self, offset: u64, buf: &[u8]) -> Result<()> {
|
||||
let size = match self {
|
||||
Disk::Raw { size, .. } => *size,
|
||||
Disk::Qcow2(q) => q.size,
|
||||
};
|
||||
ensure!(
|
||||
offset.saturating_add(buf.len() as u64) <= size,
|
||||
"write past image end"
|
||||
);
|
||||
match self {
|
||||
Disk::Raw { file, .. } => file.write_all_at(buf, offset)?,
|
||||
Disk::Qcow2(q) => q.write(offset, buf)?,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn read(&self, offset: u64, buf: &mut [u8]) -> Result<()> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
@@ -619,8 +812,8 @@ impl Qcow2 {
|
||||
})
|
||||
}
|
||||
|
||||
/// Where guest cluster `index` is in the file; None where it reads as zeros.
|
||||
fn cluster(&self, index: u64) -> Result<Option<u64>> {
|
||||
/// Host offset and whether the cluster is exclusively owned.
|
||||
fn cluster(&self, index: u64) -> Result<Option<(u64, bool)>> {
|
||||
let per_table = 1u64 << (self.cluster_bits - 3);
|
||||
let l1 = self
|
||||
.l1
|
||||
@@ -636,7 +829,32 @@ impl Qcow2 {
|
||||
let e = u64::from_be_bytes(e);
|
||||
ensure!(e & 1 << 62 == 0, "a qcow2 image with compressed clusters");
|
||||
// Bit 0: a zero cluster.
|
||||
Ok((e & 1 == 0 && e & QCOW2_OFFSET != 0).then_some(e & QCOW2_OFFSET))
|
||||
let exclusive = l1 & e & (1 << 63) != 0;
|
||||
Ok((e & 1 == 0 && e & QCOW2_OFFSET != 0).then_some((e & QCOW2_OFFSET, exclusive)))
|
||||
}
|
||||
|
||||
fn write(&self, offset: u64, buf: &[u8]) -> Result<()> {
|
||||
let mut snapshots = [0; 4];
|
||||
self.file.read_exact_at(&mut snapshots, 60)?;
|
||||
ensure!(snapshots == [0; 4], "OpenCore image has internal snapshots");
|
||||
|
||||
let cluster = 1u64 << self.cluster_bits;
|
||||
let mut done = 0;
|
||||
while done < buf.len() {
|
||||
let at = offset + done as u64;
|
||||
let within = at & (cluster - 1);
|
||||
let n = ((cluster - within) as usize).min(buf.len() - done);
|
||||
let (host, true) = self
|
||||
.cluster(at >> self.cluster_bits)?
|
||||
.context("OpenCore QCOW2 cluster is unallocated")?
|
||||
else {
|
||||
bail!("OpenCore QCOW2 cluster is shared");
|
||||
};
|
||||
self.file
|
||||
.write_all_at(&buf[done..done + n], host + within)?;
|
||||
done += n;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn read(&self, offset: u64, buf: &mut [u8]) -> Result<()> {
|
||||
@@ -648,7 +866,7 @@ impl Qcow2 {
|
||||
let n = ((cluster - within) as usize).min(buf.len() - done);
|
||||
let part = &mut buf[done..done + n];
|
||||
match self.cluster(at >> self.cluster_bits)? {
|
||||
Some(c) => self.file.read_exact_at(part, c + within)?,
|
||||
Some((c, _)) => self.file.read_exact_at(part, c + within)?,
|
||||
None => part.fill(0),
|
||||
}
|
||||
done += n;
|
||||
@@ -732,6 +950,29 @@ impl<'a> Fat32<'a> {
|
||||
Ok(Some(bytes))
|
||||
}
|
||||
|
||||
/// Overwrite only changed clusters of a file whose size stays the same.
|
||||
fn overwrite(&self, path: &str, bytes: &[u8]) -> Result<()> {
|
||||
let entry = self
|
||||
.find(path)?
|
||||
.with_context(|| format!("missing {path}"))?;
|
||||
ensure!(entry.size as usize == bytes.len(), "{path} changed size");
|
||||
let mut rest = bytes;
|
||||
self.chain(
|
||||
entry.cluster,
|
||||
bytes.len() as u64,
|
||||
&mut |offset, original| {
|
||||
let (new, remaining) = rest.split_at(original.len());
|
||||
if new != original {
|
||||
self.disk.write(offset, new)?;
|
||||
}
|
||||
rest = remaining;
|
||||
Ok(true)
|
||||
},
|
||||
)?;
|
||||
ensure!(rest.is_empty(), "{path} is cut short");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether the file at `path` (as [`Fat32::find`] takes it) holds `bytes`, however many: its
|
||||
/// entry's size first, then its clusters, a cluster at a time, to the first that differs, so
|
||||
/// none of it is read where its size differs, and no more than `bytes` holds where it does;
|
||||
@@ -744,12 +985,12 @@ impl<'a> Fat32<'a> {
|
||||
return Ok(Some(false));
|
||||
}
|
||||
let mut rest = bytes;
|
||||
self.chain(e.cluster, bytes.len() as u64, &mut |part| {
|
||||
self.chain(e.cluster, bytes.len() as u64, &mut |_, part| {
|
||||
let same = rest.starts_with(part);
|
||||
if same {
|
||||
rest = &rest[part.len()..];
|
||||
}
|
||||
same
|
||||
Ok(same)
|
||||
})?;
|
||||
// A chain that ends before the file's size does not hold the rest.
|
||||
Ok(Some(rest.is_empty()))
|
||||
@@ -758,16 +999,21 @@ impl<'a> Fat32<'a> {
|
||||
/// The bytes of the clusters from `first`, at most `most`.
|
||||
fn read_chain(&self, first: u32, most: u64) -> Result<Vec<u8>> {
|
||||
let mut out = Vec::new();
|
||||
self.chain(first, most, &mut |part| {
|
||||
self.chain(first, most, &mut |_, part| {
|
||||
out.extend_from_slice(part);
|
||||
true
|
||||
Ok(true)
|
||||
})?;
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Gives `part` the bytes of the clusters from `first`, a cluster at a time, until the chain
|
||||
/// ends, `most` bytes are given (the last cluster's cut to them), or `part` returns false.
|
||||
fn chain(&self, first: u32, most: u64, part: &mut dyn FnMut(&[u8]) -> bool) -> Result<()> {
|
||||
fn chain(
|
||||
&self,
|
||||
first: u32,
|
||||
most: u64,
|
||||
part: &mut impl FnMut(u64, &[u8]) -> Result<bool>,
|
||||
) -> Result<()> {
|
||||
let mut buf = vec![0u8; self.cluster_size as usize];
|
||||
let mut c = first;
|
||||
let mut given = 0;
|
||||
@@ -775,7 +1021,7 @@ impl<'a> Fat32<'a> {
|
||||
let n = (most - given).min(self.cluster_size) as usize;
|
||||
let offset = self.data + u64::from(c - 2) * self.cluster_size;
|
||||
self.disk.read(offset, &mut buf[..n])?;
|
||||
if !part(&buf[..n]) {
|
||||
if !part(offset, &buf[..n])? {
|
||||
break;
|
||||
}
|
||||
given += n as u64;
|
||||
@@ -1760,4 +2006,152 @@ pub(crate) mod tests {
|
||||
assert!(!with("<key>ShowPicker</key><false/>").shows_picker());
|
||||
assert!(with("<key>ShowPicker</key><true/>").shows_picker());
|
||||
}
|
||||
|
||||
fn plist_with_processor_type(processor_type: u16) -> String {
|
||||
plist(&enabled("Example.kext"))
|
||||
.replacen(
|
||||
" <key>PlatformInfo</key>",
|
||||
concat!(
|
||||
" <key>Misc</key><dict><key>Security</key><dict>",
|
||||
"<key>Vault</key><string>Optional</string></dict></dict>\n",
|
||||
" <key>PlatformInfo</key>",
|
||||
),
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
" <key>Automatic</key><true/>",
|
||||
concat!(
|
||||
" <key>Automatic</key><true/>\n",
|
||||
" <key>UpdateSMBIOS</key><true/>\n",
|
||||
" <key>UpdateSMBIOSMode</key><string>Create</string>",
|
||||
),
|
||||
1,
|
||||
)
|
||||
.replacen(
|
||||
" <key>ROM</key>",
|
||||
&format!(
|
||||
" <key>ProcessorType</key>\n <integer>{processor_type}</integer>\n <key>ROM</key>"
|
||||
),
|
||||
1,
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_updates_only_the_generated_config() {
|
||||
let env = crate::testenv::Env::new("processor-type");
|
||||
let original = plist_with_processor_type(0);
|
||||
let expected = plist_with_processor_type(0x0609);
|
||||
let unrelated = b"unrelated EFI payload";
|
||||
let raw = image_of(&[
|
||||
("EFI/OC/config.plist", original.as_bytes()),
|
||||
("EFI/OC/Other.txt", unrelated),
|
||||
]);
|
||||
|
||||
for format in [ImageFormat::Raw, ImageFormat::Qcow2] {
|
||||
let dir = env.root.join(format!("{format:?}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = match format {
|
||||
ImageFormat::Raw => raw.clone(),
|
||||
ImageFormat::Qcow2 => qcow2(&raw),
|
||||
};
|
||||
let vm = on_reims_vgpu(&dir, &source, format);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
assert!(match_processor_type(&vm, 0x0609).unwrap(), "{format:?}");
|
||||
let written = std::fs::read(&path).unwrap();
|
||||
assert_eq!(written.len(), source.len(), "{format:?}");
|
||||
assert_eq!(
|
||||
Config::read(&path, format).unwrap().0,
|
||||
Config::parse(expected.as_bytes()).unwrap().0,
|
||||
"{format:?}"
|
||||
);
|
||||
assert_eq!(
|
||||
read_file(&path, format, "EFI/OC/Other.txt")
|
||||
.unwrap()
|
||||
.as_deref(),
|
||||
Some(unrelated.as_slice()),
|
||||
"{format:?}"
|
||||
);
|
||||
|
||||
assert!(!match_processor_type(&vm, 0x0609).unwrap(), "{format:?}");
|
||||
assert!(!match_processor_type(&vm, 0x0709).unwrap(), "{format:?}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), written, "{format:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_preserves_explicit_or_unsupported_configs() {
|
||||
let env = crate::testenv::Env::new("processor-type-custom");
|
||||
let baseline = plist_with_processor_type(0);
|
||||
for (label, config) in [
|
||||
("explicit", plist_with_processor_type(0x0709)),
|
||||
(
|
||||
"manual",
|
||||
baseline.replace(
|
||||
"<key>Automatic</key><true/>",
|
||||
"<key>Automatic</key><false/>",
|
||||
),
|
||||
),
|
||||
(
|
||||
"no-smbios-update",
|
||||
baseline.replace(
|
||||
"<key>UpdateSMBIOS</key><true/>",
|
||||
"<key>UpdateSMBIOS</key><false/>",
|
||||
),
|
||||
),
|
||||
(
|
||||
"other-mode",
|
||||
baseline.replace("<string>Create</string>", "<string>Custom</string>"),
|
||||
),
|
||||
(
|
||||
"secure",
|
||||
baseline.replace("<string>Optional</string>", "<string>Secure</string>"),
|
||||
),
|
||||
(
|
||||
"basic",
|
||||
baseline.replace("<string>Optional</string>", "<string>Basic</string>"),
|
||||
),
|
||||
] {
|
||||
let dir = env.root.join(label);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let source = image(config.as_bytes());
|
||||
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Raw);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
assert!(!match_processor_type(&vm, 0x0609).unwrap(), "{label}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn processor_type_preserves_qcow2_with_shared_or_snapshotted_clusters() {
|
||||
let env = crate::testenv::Env::new("processor-type-shared-clusters");
|
||||
let config = plist_with_processor_type(0);
|
||||
let generated = qcow2(&image(config.as_bytes()));
|
||||
let mut shared = generated.clone();
|
||||
let l1 = be64(&shared, 40) as usize;
|
||||
let l1_size = be32(&shared, 36) as usize * 8;
|
||||
for entry in shared[l1..l1 + l1_size].chunks_exact_mut(8) {
|
||||
entry[0] &= 0x7f;
|
||||
}
|
||||
let mut snapshot = generated;
|
||||
snapshot[60..64].copy_from_slice(&1u32.to_be_bytes());
|
||||
|
||||
for (label, source) in [("shared", shared), ("snapshots", snapshot)] {
|
||||
let dir = env.root.join(label);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let vm = on_reims_vgpu(&dir, &source, ImageFormat::Qcow2);
|
||||
let path = vm.path(&vm.config.q35.as_ref().unwrap().opencore);
|
||||
|
||||
let error = match_processor_type(&vm, 0x0609).unwrap_err().to_string();
|
||||
assert!(error.contains(label), "{error}");
|
||||
assert_eq!(std::fs::read(&path).unwrap(), source, "{label}");
|
||||
assert!(std::fs::read_dir(&dir).unwrap().all(|file| {
|
||||
file.unwrap()
|
||||
.path()
|
||||
.extension()
|
||||
.is_none_or(|ext| ext != "part")
|
||||
}));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
//! Apple SMBIOS processor types for the host CPU family shown in an x86-64 macOS guest.
|
||||
|
||||
/// Returns the OpenCore ProcessorType for this host's CPU family and the guest's vCPU count.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn for_host(cpus: u32) -> Option<u16> {
|
||||
use std::arch::x86_64::__cpuid;
|
||||
|
||||
if __cpuid(0x8000_0000).eax < 0x8000_0004 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let bytes: Vec<u8> = (0x8000_0002..=0x8000_0004)
|
||||
.flat_map(|leaf| {
|
||||
let registers = __cpuid(leaf);
|
||||
[registers.eax, registers.ebx, registers.ecx, registers.edx]
|
||||
.into_iter()
|
||||
.flat_map(u32::to_le_bytes)
|
||||
})
|
||||
.collect();
|
||||
let brand = String::from_utf8_lossy(&bytes);
|
||||
for_brand(
|
||||
brand.trim_matches(|c: char| c == '\0' || c.is_whitespace()),
|
||||
cpus,
|
||||
)
|
||||
}
|
||||
|
||||
/// Other host architectures do not expose an x86 CPU brand.
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
pub fn for_host(_cpus: u32) -> Option<u16> {
|
||||
None
|
||||
}
|
||||
|
||||
#[cfg(any(target_arch = "x86_64", test))]
|
||||
fn for_brand(brand: &str, cpus: u32) -> Option<u16> {
|
||||
let normalized = brand
|
||||
.to_ascii_lowercase()
|
||||
.replace("(r)", " ")
|
||||
.replace("(tm)", " ");
|
||||
let words: Vec<_> = normalized
|
||||
.split(|c: char| c.is_whitespace() || c == '-')
|
||||
.filter(|word| !word.is_empty())
|
||||
.collect();
|
||||
if words
|
||||
.iter()
|
||||
.any(|word| matches!(*word, "xeon" | "threadripper" | "epyc"))
|
||||
{
|
||||
// macOS counts 5–8 vCPUs as eight cores, which has a name in the Xeon W family.
|
||||
return match cpus {
|
||||
1..=4 => Some(0x0501),
|
||||
5..=16 => Some(0x0F01),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
|
||||
// Apple's name table is keyed by family and the core count reported by the guest.
|
||||
// Keep automatic detection where this family has no label for the VM's topology.
|
||||
let processor_type = |rank: &str| match (rank, cpus) {
|
||||
("3", 2..=4) => Some(0x0909),
|
||||
("5", 2..=8) => Some(0x0609),
|
||||
("7", 2..=8) => Some(0x0709),
|
||||
("9", 5..=8) => Some(0x1009),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(value) = words
|
||||
.iter()
|
||||
.find_map(|word| word.strip_prefix('i').and_then(processor_type))
|
||||
{
|
||||
return Some(value);
|
||||
}
|
||||
|
||||
// Intel Core and AMD Ryzen ranks share Apple's corresponding display families.
|
||||
words.iter().enumerate().find_map(|(index, word)| {
|
||||
let qualifiers: &[&str] = match *word {
|
||||
"core" => &["ultra"],
|
||||
"ryzen" => &["ai", "pro"],
|
||||
_ => return None,
|
||||
};
|
||||
let rank = words[index + 1..]
|
||||
.iter()
|
||||
.find(|word| !qualifiers.contains(word))?;
|
||||
processor_type(rank)
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn host_brand_maps_to_an_apple_processor_type() {
|
||||
for (brand, cpus, expected) in [
|
||||
("Intel(R) Core(TM) i7 CPU 920 @ 2.67GHz", 4, 0x0709),
|
||||
("Intel(R) Core(TM) i3-8100B CPU @ 3.60GHz", 4, 0x0909),
|
||||
("Intel(R) Core(TM) i5-1035G1 CPU @ 1.00GHz", 4, 0x0609),
|
||||
("12th Gen Intel(R) Core(TM) i5-12400", 8, 0x0609),
|
||||
("12th Gen Intel(R) Core(TM) i7-12700H", 8, 0x0709),
|
||||
("13th Gen Intel(R) Core(TM) i9-13900H", 8, 0x1009),
|
||||
("Intel(R) Core(TM) Ultra 5 125H", 6, 0x0609),
|
||||
("Intel(R) Core(TM) Ultra 7 155H", 8, 0x0709),
|
||||
("Intel(R) Core(TM) Ultra 9 275HX", 8, 0x1009),
|
||||
("Intel(R) Core(TM) 3 100U", 4, 0x0909),
|
||||
("Intel(R) Core(TM) 7 150U", 8, 0x0709),
|
||||
("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz", 4, 0x0501),
|
||||
("Intel(R) Xeon(R) W-2145 CPU @ 3.70GHz", 5, 0x0F01),
|
||||
("Intel(R) Xeon(R) CPU E5-2680 v4 @ 2.40GHz", 6, 0x0F01),
|
||||
("Intel(R) Xeon(R) Gold 6338 CPU @ 2.00GHz", 8, 0x0F01),
|
||||
("AMD Ryzen 3 3200G with Radeon Vega Graphics", 4, 0x0909),
|
||||
("AMD Ryzen 5 5600X 6-Core Processor", 6, 0x0609),
|
||||
("AMD Ryzen 5 PRO 4650G with Radeon Graphics", 8, 0x0609),
|
||||
("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics", 4, 0x0709),
|
||||
("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics", 8, 0x0709),
|
||||
("AMD Ryzen 7 8745H w/ Radeon 780M Graphics", 8, 0x0709),
|
||||
("AMD Ryzen 9 7950X 16-Core Processor", 8, 0x1009),
|
||||
("AMD Ryzen AI 9 HX 370 w/ Radeon 890M Graphics", 8, 0x1009),
|
||||
("AMD Ryzen AI 7 PRO 360 w/ Radeon 880M Graphics", 8, 0x0709),
|
||||
("AMD Ryzen Threadripper PRO 5995WX 64-Cores", 1, 0x0501),
|
||||
("AMD EPYC 7763 64-Core Processor", 8, 0x0F01),
|
||||
] {
|
||||
assert_eq!(for_brand(brand, cpus), Some(expected), "{brand}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_family_without_a_label_for_the_core_count_keeps_automatic_detection() {
|
||||
for (brand, cpus) in [
|
||||
("Intel Core i3-8100B", 8),
|
||||
("Intel Core i5-12400", 1),
|
||||
("Intel Core i7-12700", 10),
|
||||
("Intel Core i9-13900H", 4),
|
||||
("Intel Xeon E5-2680", 17),
|
||||
] {
|
||||
assert_eq!(for_brand(brand, cpus), None, "{brand}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unrecognized_host_leaves_processor_type_to_opencore() {
|
||||
for brand in [
|
||||
"Intel(R) Core(TM)2 Duo CPU E8400 @ 3.00GHz",
|
||||
"Intel(R) Core(TM) m3-7Y30 CPU @ 1.00GHz",
|
||||
"Intel(R) Pentium(R) Gold 7505 @ 2.00GHz",
|
||||
"Intel(R) Celeron(R) N4020 CPU @ 1.10GHz",
|
||||
"Intel(R) N100",
|
||||
"AMD Athlon Silver 3050U with Radeon Graphics",
|
||||
"AMD Ryzen AI Max+ 395 w/ Radeon 8060S",
|
||||
"AMD Ryzen Z1 Extreme",
|
||||
"Intel Core Processor (Skylake, IBRS, no TSX)",
|
||||
"",
|
||||
] {
|
||||
assert_eq!(for_brand(brand, 8), None, "{brand}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -725,6 +725,22 @@ pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec<String> {
|
||||
)),
|
||||
}
|
||||
}
|
||||
if vm.config.profile == Profile::Q35X86_64
|
||||
&& !vm
|
||||
.config
|
||||
.extra_args
|
||||
.iter()
|
||||
.any(|arg| arg == "-incoming" || arg.starts_with("-incoming="))
|
||||
&& let Some(value) = crate::processor::for_host(vm.config.cpus)
|
||||
{
|
||||
match crate::opencore::match_processor_type(vm, value) {
|
||||
Ok(true) => progress("updated the OpenCore processor type for About This Mac"),
|
||||
Ok(false) => {}
|
||||
Err(error) => w.push(format!(
|
||||
"{name}: could not update the OpenCore processor type ({error:#})"
|
||||
)),
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user