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,
#[value(name = "host-no-rdrand")]
#[serde(rename = "host-no-rdrand")]
HostNoRdrand,
#[value(name = "auto")]
#[serde(rename = "auto")]
Auto,
}
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",
CpuProfile::HostNoRdrand => "host-no-rdrand",
CpuProfile::Auto => "auto",
}
}
pub fn lowest_presenting(level: u8) -> Option<CpuProfile> {
match level {
0..=2 => Some(CpuProfile::X86_64V2),
3 => Some(CpuProfile::X86_64V3),
_ => None,
}
}
pub fn x86_64_level(&self) -> Option<u8> {
match self {
CpuProfile::X86_64V2 => Some(2),
CpuProfile::X86_64V3 => Some(3),
CpuProfile::HostNoRdrand | CpuProfile::Auto => None,
}
}
}
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. \
x86-64-v2 runs, including an auto run that resolves to x86-64-v2 where nothing \
declares more, are not affected."
};
}
pub const V3_RESIDUAL: &str = v3_residual!();
#[macro_export]
macro_rules! host_no_rdrand_residual {
() => {
"With --cpu-profile host-no-rdrand, CPUID remains intercepted, but its answers \
come from the host CPU with hardware-randomness and unvirtualized timing \
features hidden. Results are host-CPU-model specific: cross-host builds need \
the same CPU model and compatible kernel/XSTATE settings and CPU topology. \
The tracer and guest are pinned to the lowest originally allowed CPU, even \
with the timeslice disabled; repeat runs require the same allowed CPU set. Host XSAVE behavior \
is retained without the x86-64-v3 XSTATE qualification, so programs inspecting \
XSAVE or signal-register metadata have no determinism guarantee. Programs must honor \
the advertised feature bits; unconditional RDRAND or RDSEED is not trapped \
by this profile."
};
}
pub const HOST_NO_RDRAND_RESIDUAL: &str = host_no_rdrand_residual!();
pub const CPU_PROFILE_LONG_HELP: &str = concat!(
"The CPU the guest sees: auto (the default), x86-64-v2, x86-64-v3, or host-no-rdrand. \
auto picks the lowest of x86-64-v2 and x86-64-v3 that satisfies what the guest's \
executable and its program interpreter declare they need (GNU_PROPERTY_X86_ISA_1_NEEDED), \
x86-64-v2 where nothing is declared, and refuses a program it cannot read rather than \
guess; the chosen profile is what runs, is qualified like an explicit one, is logged at \
debug level, and is what a recording holds. A later exec of an image needing more is \
refused where each exec is checked (the ptrace backend), never upgraded; KVM checks \
only the first image, so a later KVM exec gets no such refusal. auto reads no shared library: where only a library such as \
libc declares its need (as on distributions whose loader is unmarked), name the profile. \
A named profile always means exactly itself. host-no-rdrand is available for `hermit run` on the ptrace backend with CPUID \
faulting and virtual time; it refuses hosts without CPUID faulting instead of \
allowing native CPUID. RDRAND and RDSEED are hidden. Check availability with \
`hermit host-capabilities --cpu-profile host-no-rdrand`. Recording and replay \
with host-no-rdrand are not supported.\n\n",
host_no_rdrand_residual!(),
"\n\n",
"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 the_lowest_profile_presenting_a_level() {
for (level, profile) in [
(0, Some(CpuProfile::X86_64V2)),
(1, Some(CpuProfile::X86_64V2)),
(2, Some(CpuProfile::X86_64V2)),
(3, Some(CpuProfile::X86_64V3)),
(4, None),
(5, None),
] {
assert_eq!(CpuProfile::lowest_presenting(level), profile, "{level}");
if let Some(profile) = profile {
assert!(profile.x86_64_level().unwrap() >= level.max(2));
}
}
assert_eq!(CpuProfile::Auto.x86_64_level(), None);
assert!(!CpuProfile::Auto.is_default());
}
#[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());
assert!(!CpuProfile::HostNoRdrand.is_default());
}
}