use serde::Deserialize;
use serde::Serialize;
#[derive(
Debug,
Clone,
Copy,
Default,
PartialEq,
Eq,
Hash,
Serialize,
Deserialize,
clap::ValueEnum
)]
pub enum CpuProfile {
#[default]
#[value(name = "x86-64-v2")]
#[serde(rename = "x86-64-v2")]
X86_64V2,
#[value(name = "x86-64-v3")]
#[serde(rename = "x86-64-v3")]
X86_64V3,
}
impl CpuProfile {
pub fn is_default(&self) -> bool {
*self == CpuProfile::X86_64V2
}
pub fn name(&self) -> &'static str {
match self {
CpuProfile::X86_64V2 => "x86-64-v2",
CpuProfile::X86_64V3 => "x86-64-v3",
}
}
}
impl std::fmt::Display for CpuProfile {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.name())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct HostXstate {
pub vendor: [u32; 3],
pub signature: u32,
pub xcr0: u64,
pub xsave_leaves: Vec<[u32; 5]>,
pub xcomp_supp: u64,
pub xcomp_perm: u64,
pub xcomp_guest_perm: u64,
pub xfeature_max: u32,
pub probe_cases: u32,
pub probe_forced_exit: bool,
}
impl HostXstate {
pub fn xsave_leaf(&self, subleaf: u32) -> Option<[u32; 4]> {
self.xsave_leaves
.iter()
.find(|row| row[0] == subleaf)
.map(|row| [row[1], row[2], row[3], row[4]])
}
}
#[macro_export]
macro_rules! v3_residual {
() => {
"With --cpu-profile x86-64-v3, Hermit checks at startup that this host does not \
change the XSTATE_BV bits a guest reads (with XSAVE, XSAVEC or XSAVEOPT, or in a \
signal frame) when the host saves and restores the guest's registers. The check \
samples a fixed set of cases and forces only CPUID exits, so a CPU or hypervisor \
that behaves differently only on other instruction paths, or on VM exits the guest \
cannot see, is not excluded. Firmware (SMM) entries cannot be checked at all. \
Default runs use x86-64-v2, which this does not affect."
};
}
pub const V3_RESIDUAL: &str = v3_residual!();
pub const CPU_PROFILE_LONG_HELP: &str = concat!(
"The CPU the guest sees: x86-64-v2 (the default) or x86-64-v3. v3 is offered only on \
the ptrace backend, on hosts that pass a startup qualification \
(`hermit host-capabilities --cpu-profile x86-64-v3` runs it alone). A recording binds \
the host facts its guest's answers come from, and replay refuses a host where any of \
them differs (<https://github.com/rrnewton/hermit/issues/4243>).\n\n",
v3_residual!()
);
#[cfg(test)]
mod tests {
use clap::ValueEnum;
use super::*;
#[test]
fn names_round_trip_on_the_command_line_and_in_serde() {
for profile in CpuProfile::value_variants() {
assert_eq!(CpuProfile::from_str(profile.name(), false), Ok(*profile));
let json = serde_json::to_string(profile).unwrap();
assert_eq!(json, format!("\"{}\"", profile.name()));
assert_eq!(serde_json::from_str::<CpuProfile>(&json).unwrap(), *profile);
}
assert_eq!(CpuProfile::default(), CpuProfile::X86_64V2);
assert!(CpuProfile::X86_64V2.is_default());
assert!(!CpuProfile::X86_64V3.is_default());
}
}