1use petri_artifacts_common::capabilities;
7use std::collections::BTreeSet;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum ExecutionEnvironment {
12 Baremetal,
14 Nested,
16}
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum Vendor {
21 Amd,
23 Intel,
25 Arm,
27}
28
29impl Vendor {
30 pub fn host() -> Self {
32 cfg_select! {
33 target_arch = "x86_64" => {
35 let result = safe_intrinsics::cpuid(
36 x86defs::cpuid::CpuidFunction::VendorAndMaxFunction.0,
37 0,
38 );
39 let vendor =
40 x86defs::cpuid::Vendor::from_ebx_ecx_edx(result.ebx, result.ecx, result.edx);
41 if vendor.is_amd_compatible() {
42 Vendor::Amd
43 } else {
44 assert!(vendor.is_intel_compatible());
45 Vendor::Intel
46 }
47 }
48 _ => Vendor::Arm,
49 }
50 }
51}
52
53#[derive(Clone, Copy, Debug, PartialEq)]
55pub enum IsolationType {
56 Vbs,
58 Snp,
60 Tdx,
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66pub enum VmmType {
67 OpenVmm,
69 HyperV,
71 Qemu,
73}
74
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum OpenVmmHypervisor {
78 Mshv,
80 Kvm,
82 Whp,
84 Hvf,
86}
87
88#[derive(Debug, Clone)]
91pub struct VmHostInfo {
92 pub vbs_supported: bool,
94 pub snp_status: bool,
96 pub tdx_status: bool,
98}
99
100#[derive(Debug, Clone)]
102pub struct HostContext {
103 pub vm_host_info: Option<VmHostInfo>,
105 pub vendor: Vendor,
107 pub execution_environment: ExecutionEnvironment,
109 pub openvmm_hypervisor: Option<OpenVmmHypervisor>,
111 pub nested_reset_supported: bool,
113}
114
115impl HostContext {
116 pub async fn new() -> Self {
118 let is_nested = cfg_select! {
119 target_arch = "x86_64" => {{
121 let result = safe_intrinsics::cpuid(
122 hvdef::HV_CPUID_FUNCTION_MS_HV_ENLIGHTENMENT_INFORMATION,
123 0,
124 );
125 hvdef::HvEnlightenmentInformation::from(
126 result.eax as u128
127 | (result.ebx as u128) << 32
128 | (result.ecx as u128) << 64
129 | (result.edx as u128) << 96,
130 )
131 .nested()
132 }}
133 _ => false,
134 };
135
136 let vendor = Vendor::host();
137
138 let openvmm_hypervisor = cfg_select! {
139 target_os = "linux" => {
140 if fs_err::File::open("/dev/mshv").is_ok() {
141 Some(OpenVmmHypervisor::Mshv)
142 } else if fs_err::File::options()
143 .read(true)
144 .write(true)
145 .open("/dev/kvm")
146 .is_ok()
147 {
148 Some(OpenVmmHypervisor::Kvm)
149 } else {
150 None
151 }
152 }
153 windows => Some(OpenVmmHypervisor::Whp),
154 target_os = "macos" => Some(OpenVmmHypervisor::Hvf),
155 _ => None,
156 };
157
158 let nested_reset_supported = match openvmm_hypervisor {
159 Some(OpenVmmHypervisor::Kvm) => openvmm_hypervisors::kvm_nested_state_available(),
160 Some(OpenVmmHypervisor::Mshv) => openvmm_hypervisors::mshv_partition_scrub_available(),
161 Some(OpenVmmHypervisor::Whp) => openvmm_hypervisors::whp_nested_reset_available(),
162 _ => false,
163 };
164
165 let vm_host_info = cfg_select! {
166 windows => crate::vm::hyperv::powershell::run_get_vm_host()
167 .await
168 .ok()
169 .map(|info| VmHostInfo {
170 vbs_supported: info.guest_isolation_types.contains(
171 &crate::vm::hyperv::powershell::HyperVGuestStateIsolationType::Vbs,
172 ),
173 snp_status: info.snp_status,
174 tdx_status: info.tdx_status,
175 }),
176 _ => {
177 (vendor == Vendor::Amd && openvmm_hypervisor == Some(OpenVmmHypervisor::Mshv)).then(
180 || VmHostInfo {
181 vbs_supported: false,
182 snp_status: openvmm_hypervisors::mshv_snp_available(),
183 tdx_status: false,
184 },
185 )
186 }
187 };
188
189 Self {
190 vm_host_info,
191 vendor,
192 execution_environment: if is_nested {
193 ExecutionEnvironment::Nested
194 } else {
195 ExecutionEnvironment::Baremetal
196 },
197 openvmm_hypervisor,
198 nested_reset_supported,
199 }
200 }
201}
202
203pub enum TestRequirement {
205 ExecutionEnvironment(ExecutionEnvironment),
207 Vendor(Vendor),
209 OpenVmmHypervisor(OpenVmmHypervisor),
211 HostCapability(fn() -> bool),
221 Isolation(IsolationType),
223 RequiresCapability {
234 name: &'static str,
236 vmm: VmmType,
238 },
239 And(Box<TestRequirement>, Box<TestRequirement>),
241 Or(Box<TestRequirement>, Box<TestRequirement>),
243 Not(Box<TestRequirement>),
245 Any,
247}
248
249impl TestRequirement {
250 pub fn and(self, other: TestRequirement) -> TestRequirement {
252 TestRequirement::And(Box::new(self), Box::new(other))
253 }
254
255 pub fn or(self, other: TestRequirement) -> TestRequirement {
257 TestRequirement::Or(Box::new(self), Box::new(other))
258 }
259
260 #[expect(clippy::should_implement_trait)]
262 pub fn not(self) -> TestRequirement {
263 TestRequirement::Not(Box::new(self))
264 }
265
266 pub fn is_satisfied(&self, context: &HostContext) -> bool {
268 match self {
269 TestRequirement::ExecutionEnvironment(env) => context.execution_environment == *env,
270 TestRequirement::Vendor(vendor) => context.vendor == *vendor,
271 TestRequirement::OpenVmmHypervisor(hypervisor) => {
272 context.openvmm_hypervisor == Some(*hypervisor)
273 }
274 TestRequirement::HostCapability(probe) => probe(),
275 TestRequirement::Isolation(isolation_type) => {
276 if let Some(vm_host_info) = &context.vm_host_info {
277 match isolation_type {
278 IsolationType::Vbs => vm_host_info.vbs_supported,
279 IsolationType::Snp => vm_host_info.snp_status,
280 IsolationType::Tdx => vm_host_info.tdx_status,
281 }
282 } else {
283 false
284 }
285 }
286 TestRequirement::RequiresCapability { name, vmm } => {
287 available_capabilities(context, *vmm).contains(name)
288 }
289 TestRequirement::And(req1, req2) => {
290 req1.is_satisfied(context) && req2.is_satisfied(context)
291 }
292 TestRequirement::Or(req1, req2) => {
293 req1.is_satisfied(context) || req2.is_satisfied(context)
294 }
295 TestRequirement::Not(req) => !req.is_satisfied(context),
296 TestRequirement::Any => true,
297 }
298 }
299}
300
301pub fn known_capability(name: &str) -> Option<&'static str> {
303 capabilities::known(name)
304}
305
306pub fn is_known_capability(name: &str) -> bool {
308 known_capability(name).is_some()
309}
310
311fn available_capabilities(context: &HostContext, vmm: VmmType) -> BTreeSet<&'static str> {
312 let mut capabilities = BTreeSet::new();
313
314 if matches!(
317 (vmm, context.openvmm_hypervisor),
318 (VmmType::HyperV, _)
319 | (
320 VmmType::OpenVmm,
321 Some(OpenVmmHypervisor::Whp | OpenVmmHypervisor::Mshv)
322 )
323 ) {
324 capabilities.insert(capabilities::VPCI);
325 }
326
327 if !matches!(
333 (vmm, context.openvmm_hypervisor),
334 (VmmType::OpenVmm, Some(OpenVmmHypervisor::Mshv))
335 ) {
336 capabilities.insert(capabilities::WINDOWS_PARTITION_RESET);
337 }
338
339 if matches!(
341 (vmm, context.openvmm_hypervisor),
342 (
343 VmmType::OpenVmm,
344 Some(OpenVmmHypervisor::Kvm | OpenVmmHypervisor::Whp | OpenVmmHypervisor::Mshv)
345 ) | (VmmType::Qemu, _)
346 ) {
347 capabilities.insert(capabilities::NESTED_VIRT);
348 }
349
350 if matches!(
353 (vmm, context.openvmm_hypervisor),
354 (
355 VmmType::OpenVmm,
356 Some(OpenVmmHypervisor::Kvm | OpenVmmHypervisor::Whp)
357 )
358 ) {
359 capabilities.insert(capabilities::NESTED_MSHV);
360 }
361
362 if vmm == VmmType::OpenVmm && context.nested_reset_supported {
363 capabilities.insert(capabilities::NESTED_RESET);
364 }
365
366 match std::env::var("PETRI_CAPABILITIES") {
367 Ok(env_capabilities) => {
368 for capability in env_capabilities.split(',').map(str::trim) {
369 if capability.is_empty() {
370 continue;
371 }
372 let capability = known_capability(capability)
373 .unwrap_or_else(|| panic!("unknown PETRI_CAPABILITIES entry: {capability}"));
374 capabilities.insert(capability);
375 }
376 }
377 Err(std::env::VarError::NotPresent) => {}
378 Err(std::env::VarError::NotUnicode(_)) => {
379 panic!("PETRI_CAPABILITIES is not valid UTF-8")
380 }
381 }
382
383 capabilities
384}
385
386pub struct TestCaseRequirements {
388 requirements: TestRequirement,
389}
390
391impl TestCaseRequirements {
392 pub fn new(requirements: TestRequirement) -> Self {
394 Self { requirements }
395 }
396}
397
398pub fn can_run_test_with_context(
400 config: Option<&TestCaseRequirements>,
401 context: &HostContext,
402) -> bool {
403 if let Some(config) = config {
404 config.requirements.is_satisfied(context)
405 } else {
406 true
407 }
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 fn host_context(openvmm_hypervisor: OpenVmmHypervisor) -> HostContext {
415 HostContext {
416 vm_host_info: None,
417 vendor: Vendor::Intel,
418 execution_environment: ExecutionEnvironment::Baremetal,
419 openvmm_hypervisor: Some(openvmm_hypervisor),
420 nested_reset_supported: false,
421 }
422 }
423
424 #[test]
425 fn capabilities_are_evaluated_for_the_selected_vmm() {
426 let requirement = |vmm| TestRequirement::RequiresCapability {
427 name: capabilities::WINDOWS_PARTITION_RESET,
428 vmm,
429 };
430 let mshv = host_context(OpenVmmHypervisor::Mshv);
431
432 assert!(!requirement(VmmType::OpenVmm).is_satisfied(&mshv));
433 assert!(requirement(VmmType::HyperV).is_satisfied(&mshv));
434 assert!(requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
435 }
436
437 #[test]
438 fn nested_virt_capability_matches_the_selected_backend() {
439 let requirement = TestRequirement::RequiresCapability {
440 name: capabilities::NESTED_VIRT,
441 vmm: VmmType::OpenVmm,
442 };
443
444 assert!(requirement.is_satisfied(&host_context(OpenVmmHypervisor::Mshv)));
445 assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Hvf)));
446 }
447
448 #[test]
449 fn nested_mshv_capability_excludes_the_mshv_backend() {
450 let requirement = |vmm| TestRequirement::RequiresCapability {
451 name: capabilities::NESTED_MSHV,
452 vmm,
453 };
454
455 assert!(requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
456 assert!(requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Whp)));
457 assert!(
458 !requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Mshv))
459 );
460 assert!(!requirement(VmmType::OpenVmm).is_satisfied(&host_context(OpenVmmHypervisor::Hvf)));
461 assert!(!requirement(VmmType::Qemu).is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
462 }
463
464 #[test]
465 fn openvmm_hypervisor_requirement_matches_the_selected_backend() {
466 let requirement = TestRequirement::OpenVmmHypervisor(OpenVmmHypervisor::Mshv);
467 assert!(requirement.is_satisfied(&host_context(OpenVmmHypervisor::Mshv)));
468 assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Kvm)));
469 assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Whp)));
470 let mut without_hypervisor = host_context(OpenVmmHypervisor::Mshv);
471 without_hypervisor.openvmm_hypervisor = None;
472 assert!(!requirement.is_satisfied(&without_hypervisor));
473 }
474
475 #[test]
476 fn capability_probes_are_short_circuited_by_backend_requirements() {
477 let requirement = TestRequirement::OpenVmmHypervisor(OpenVmmHypervisor::Kvm).and(
478 TestRequirement::HostCapability(|| panic!("unavailable backend must not be probed")),
479 );
480 assert!(!requirement.is_satisfied(&host_context(OpenVmmHypervisor::Mshv)));
481 assert!(
482 !TestRequirement::HostCapability(|| false)
483 .is_satisfied(&host_context(OpenVmmHypervisor::Kvm))
484 );
485 assert!(
486 TestRequirement::HostCapability(|| true)
487 .is_satisfied(&host_context(OpenVmmHypervisor::Kvm))
488 );
489 }
490}