Skip to content

openvmm: a restored CPU profile's XSAVE layout overflows XSAVE length math #1382

Closed

Description

@tangruize

On KVM, restoring a snapshot whose time-ABI host CPU profile describes huge XSAVE components (CPUID leaf 0xD) overflows u32 in XsaveCapabilities::standard_len_for and compact_len_for while the partition is built, so a debug build's VM worker panics ("attempt to add with overflow") and aborts. A release build wraps, and the restore then fails the CPU profile support check with E_PROFILE_UNSUPPORTED, before any VP runs, since no host's KVM has that layout. Only a crafted snapshot reaches this: a host profile is the snapshot's own document, and host CPUIDs never describe such components.

Reproduction

In a debug build, call X86PartitionCapabilities::from_cpuid with a CPUID whose XSAVE component 2 has offset 0xffff_ff00 and size 0x100 (this overflows offset + len), or with two components of size 0x8000_0000 (this overflows the compact sum). Expected: saturated lengths. Actual: a panic, "attempt to add with overflow". The new test from_cpuid_xsave_lengths_saturate covers both, plus an alignment that overflows.

Cause

In vmm_core/virt/src/x86/mod.rs, standard_len_for and compact_len_for add and align in unchecked u32 arithmetic. from_cpuid calls both, and KvmProtoPartition::build builds a time-ABI partition's caps from the profile's CPUID:

// vmm_core/virt/src/x86/mod.rs
pub fn standard_len_for(&self, xfem: u64) -> u32 {
    // ...
        len = len.max(feature.offset + feature.len);
// ...
pub fn compact_len_for(&self, xfem: u64) -> u32 {
    // ...
        if feature.align {
            len = (len + 63) & !63;
        }
        len += feature.len;

Fix

fix.patch saturates both sums, and makes an alignment that overflows yield u32::MAX: rounding a saturated length up and masking it would otherwise bring it back below u32::MAX. The KVM build then calls the new check_xsave_layout, so that it refuses, before any VP exists, caps whose XSAVE layout its own buffers cannot hold, which today only the later profile support check catches. It refuses a compact length below 576 or not a multiple of 8 (which Xsave::at_reset cannot build its buffer from) with XSaveLengthTooSmall, a component whose standard end is past the 4096 bytes of KVM_GET_XSAVE's buffer with the new XSaveLengthTooLarge, and a component past the compact length. A host's own CPUID passes all of these, and such a restore now fails while the partition is built, with KvmError::Capabilities. Tests: from_cpuid_xsave_lengths_saturate (virt) and check_xsave_layout_refuses_what_kvm_cannot_hold (virt_kvm).

Related: #1381.

Activity

  1. tangruize commented on Nov 8, 2026

    @tangruize
    ContributorAuthor

    Proposed patch

    Patch against OpenVMM 3cf58a5234ed824435825c9f87187f5129219724. Save the contents below as fix.patch and run git apply fix.patch.

    fix.patch
    diff --git a/vmm_core/virt/src/x86/mod.rs b/vmm_core/virt/src/x86/mod.rs
    index a95e885..02bfe3c 100644
    --- a/vmm_core/virt/src/x86/mod.rs
    +++ b/vmm_core/virt/src/x86/mod.rs
    @@ -111,6 +111,10 @@ pub enum X86PartitionCapabilitiesError {
             "advertised xsave length ({advertised}) too small for features, requires ({required}) bytes"
         )]
         XSaveLengthTooSmall { advertised: u32, required: u32 },
    +    #[error(
    +        "xsave length ({required}) larger than the hypervisor's xsave buffer ({supported} bytes)"
    +    )]
    +    XSaveLengthTooLarge { required: u32, supported: u32 },
         #[error("x2apic topology and cpuid mismatch, expected x2apic={expected}, found {found}")]
         X2ApicMismatch { expected: bool, found: bool },
     }
    @@ -324,7 +328,7 @@ fn variable_features(&self, mask: u64) -> impl Iterator<Item = (u32, &XsaveFeatu
         pub fn standard_len_for(&self, xfem: u64) -> u32 {
             let mut len = XSAVE_VARIABLE_OFFSET as u32;
             for (_, feature) in self.variable_features(xfem) {
    -            len = len.max(feature.offset + feature.len);
    +            len = len.max(feature.offset.saturating_add(feature.len));
             }
             len
         }
    @@ -333,9 +337,14 @@ pub fn compact_len_for(&self, xfem: u64) -> u32 {
             let mut len = XSAVE_VARIABLE_OFFSET as u32;
             for (_, feature) in self.variable_features(xfem) {
                 if feature.align {
    -                len = (len + 63) & !63;
    +                // Alignment must not bring a saturated length back below
    +                // u32::MAX.
    +                len = match len.checked_add(63) {
    +                    Some(len) => len & !63,
    +                    None => u32::MAX,
    +                };
                 }
    -            len += feature.len;
    +            len = len.saturating_add(feature.len);
             }
             len
         }
    @@ -555,6 +564,74 @@ fn try_from(value: usize) -> Result<Self, Self::Error> {
     #[cfg(test)]
     mod tests {
         use super::*;
    +
    +    fn xsave_cpuid(components: &[(u32, u32, u32, bool)]) -> impl FnMut(u32, u32) -> [u32; 4] + '_ {
    +        move |leaf, subleaf| match (leaf, subleaf) {
    +            (0, _) => [
    +                0xd,
    +                u32::from_le_bytes(*b"Genu"),
    +                u32::from_le_bytes(*b"ntel"),
    +                u32::from_le_bytes(*b"ineI"),
    +            ],
    +            (1, _) => [0, 0, (1 << 26) | (1 << 21), 0],
    +            (0xd, 0) => [
    +                components
    +                    .iter()
    +                    .fold(3, |mask, &(bit, _, _, _)| mask | (1 << bit)),
    +                0,
    +                u32::MAX,
    +                0,
    +            ],
    +            (0xd, i) => components
    +                .iter()
    +                .find(|&&(bit, _, _, _)| bit == i)
    +                .map_or([0; 4], |&(_, size, offset, align)| {
    +                    [size, offset, u32::from(align) << 1, 0]
    +                }),
    +            _ => [0; 4],
    +        }
    +    }
    +
    +    #[test]
    +    fn from_cpuid_xsave_lengths_saturate() {
    +        let topology = vm_topology::processor::TopologyBuilder::new_x86()
    +            .build(1)
    +            .unwrap();
    +        for (components, expected_standard, expected_compact) in [
    +            (vec![(2, 0x100, 0xffff_ff00, false)], u32::MAX, 0x340),
    +            (
    +                vec![
    +                    (2, 0x8000_0000, 0x240, false),
    +                    (3, 0x8000_0000, 0x240, false),
    +                ],
    +                0x8000_0240,
    +                u32::MAX,
    +            ),
    +            (
    +                vec![
    +                    (2, 0x8000_0000, 0x240, false),
    +                    (3, 0x8000_0000, 0x240, false),
    +                    (4, 0x10, 0x240, true),
    +                ],
    +                0x8000_0240,
    +                u32::MAX,
    +            ),
    +            (
    +                vec![
    +                    (2, u32::MAX - 0x240 - 31, 0x240, false),
    +                    (3, 0, 0x240, true),
    +                ],
    +                u32::MAX - 31,
    +                u32::MAX,
    +            ),
    +        ] {
    +            let caps =
    +                X86PartitionCapabilities::from_cpuid(&topology, &mut xsave_cpuid(&components))
    +                    .unwrap();
    +            assert_eq!(caps.xsave.standard_len, expected_standard);
    +            assert_eq!(caps.xsave.compact_len, expected_compact);
    +        }
    +    }
         use test_with_tracing::test;
     
         #[test]
    diff --git a/vmm_core/virt_kvm/src/arch/x86_64/mod.rs b/vmm_core/virt_kvm/src/arch/x86_64/mod.rs
    index 90fd24d..d53bc1d 100644
    --- a/vmm_core/virt_kvm/src/arch/x86_64/mod.rs
    +++ b/vmm_core/virt_kvm/src/arch/x86_64/mod.rs
    @@ -605,6 +605,11 @@ fn build(
                 )
             }
             .map_err(KvmError::Capabilities)?;
    +        // Refuse caps whose XSAVE layout this backend cannot hold: a compact
    +        // length that `Xsave::at_reset` cannot build its buffer from, or a
    +        // component past the 4096 bytes of KVM_GET_XSAVE's buffer. A host's
    +        // own CPUID never fails this; a restored CPU profile can.
    +        check_xsave_layout(&caps).map_err(KvmError::Capabilities)?;
             let time_abi = match &self.config.time_abi {
                 Some(config) => {
                     time_abi::check_capabilities(&caps)?;
    @@ -2203,6 +2208,51 @@ fn signal_msi(&self, _devid: Option<u32>, address: u64, data: u32) {
         }
     }
     
    +/// Checks that the caps' XSAVE layout fits this backend: the compact length
    +/// holds the legacy area and the header (576 bytes) in whole words, which
    +/// `Xsave::at_reset` builds its buffer from; each component the caps select
    +/// ends, at its standard offset, within the 4096 bytes of KVM_GET_XSAVE's
    +/// buffer; and, at its compact place, within the compact length.
    +fn check_xsave_layout(
    +    caps: &virt::x86::X86PartitionCapabilities,
    +) -> Result<(), virt::x86::X86PartitionCapabilitiesError> {
    +    let advertised = caps.xsave.compact_len;
    +    if advertised < 576 || !advertised.is_multiple_of(8) {
    +        let required = if advertised < 576 {
    +            576
    +        } else {
    +            advertised.checked_next_multiple_of(8).unwrap_or(u32::MAX)
    +        };
    +        return Err(
    +            virt::x86::X86PartitionCapabilitiesError::XSaveLengthTooSmall {
    +                advertised,
    +                required,
    +            },
    +        );
    +    }
    +    let xcomp =
    +        caps.xsave.features | caps.xsave.supervisor_features | x86defs::xsave::XCOMP_COMPRESSED;
    +    let standard = caps.xsave.standard_len_for(xcomp);
    +    let compact = caps.xsave.compact_len_for(xcomp);
    +    if standard > 4096 {
    +        Err(
    +            virt::x86::X86PartitionCapabilitiesError::XSaveLengthTooLarge {
    +                required: standard,
    +                supported: 4096,
    +            },
    +        )
    +    } else if compact > advertised {
    +        Err(
    +            virt::x86::X86PartitionCapabilitiesError::XSaveLengthTooSmall {
    +                advertised,
    +                required: compact,
    +            },
    +        )
    +    } else {
    +        Ok(())
    +    }
    +}
    +
     #[cfg(test)]
     mod tests {
         use super::kvm_recommends_hyperv_apic_msrs;
    @@ -2211,6 +2261,60 @@ mod tests {
         use hvdef::HvEnlightenmentInformation;
         use test_with_tracing::test;
     
    +    #[test]
    +    fn check_xsave_layout_refuses_what_kvm_cannot_hold() {
    +        use virt::x86::X86PartitionCapabilitiesError as E;
    +        let topology = vm_topology::processor::TopologyBuilder::new_x86()
    +            .build(1)
    +            .unwrap();
    +        let x2apic = topology.apic_mode() != vm_topology::processor::x86::ApicMode::XApic;
    +        let base = || {
    +            virt::x86::X86PartitionCapabilities::from_cpuid(&topology, &mut |leaf, _| match leaf {
    +                0 => [1, 0, 0, 0],
    +                1 => [0, 0, if x2apic { 1 << 21 } else { 0 }, 0],
    +                _ => [0; 4],
    +            })
    +            .unwrap()
    +        };
    +        super::check_xsave_layout(&base()).unwrap();
    +        // A compact length short of the legacy area and header, or not in
    +        // whole words.
    +        for (len, required) in [(0, 576), (575, 576), (577, 584), (u32::MAX, u32::MAX)] {
    +            let mut caps = base();
    +            caps.xsave.compact_len = len;
    +            assert!(matches!(
    +                super::check_xsave_layout(&caps),
    +                Err(E::XSaveLengthTooSmall { advertised, required: r })
    +                    if advertised == len && r == required
    +            ));
    +        }
    +        // A component ending past KVM's 4096-byte buffer, and one at its end.
    +        for (offset, ok) in [(4096 - 64, true), (4096 - 63, false)] {
    +            let mut caps = base();
    +            caps.xsave.features |= 1 << 2;
    +            caps.xsave.feature_info[2] = virt::x86::XsaveFeature {
    +                offset,
    +                len: 64,
    +                align: false,
    +            };
    +            caps.xsave.compact_len = 576 + 64;
    +            assert_eq!(super::check_xsave_layout(&caps).is_ok(), ok, "{offset}");
    +        }
    +        // A component past the compact length.
    +        let mut caps = base();
    +        caps.xsave.features |= 1 << 2;
    +        caps.xsave.feature_info[2] = virt::x86::XsaveFeature {
    +            offset: 576,
    +            len: 64,
    +            align: false,
    +        };
    +        caps.xsave.compact_len = 576 + 56;
    +        assert!(matches!(
    +            super::check_xsave_layout(&caps),
    +            Err(E::XSaveLengthTooSmall { required: 640, .. })
    +        ));
    +    }
    +
         #[test]
         fn only_recommends_apic_msrs_when_kvm_does() {
             let recommendation =
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

No labels
No labels

Type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions