Fix UB lint in virtio-core

error: casting references to a bigger memory layout than the backing allocation is undefined behavior, even if the reference is unused
   --> virtio-core/src/probe.rs:126:21
    |
86  |         let capability = unsafe { &*(capability.data.as_ptr() as *const PciCapability) };
    |                                    --------------------------------------------------- backing allocation comes from here
...
126 |                     (&*(capability as *const PciCapability as *const PciCapabilityNotify))
    |                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    |
    = note: casting from `transport_pci::PciCapability` (13 bytes) to `transport_pci::PciCapabilityNotify` (17 bytes)
    = note: `#[deny(invalid_reference_casting)]` on by default
This commit is contained in:
bjorn3
2024-03-06 21:06:26 +01:00
parent 25dcb8adc1
commit 9bb1222933
+3 -3
View File
@@ -71,7 +71,7 @@ pub fn probe_device(pcid_handle: &mut PcidServerHandle) -> Result<Device, Error>
let mut notify_addr = None;
let mut device_addr = None;
for capability in pcid_handle
for raw_capability in pcid_handle
.get_capabilities()?
.iter()
.filter_map(|capability| {
@@ -83,7 +83,7 @@ pub fn probe_device(pcid_handle: &mut PcidServerHandle) -> Result<Device, Error>
})
{
// SAFETY: We have verified that the length of the data is correct.
let capability = unsafe { &*(capability.data.as_ptr() as *const PciCapability) };
let capability = unsafe { &*(raw_capability.data.as_ptr() as *const PciCapability) };
match capability.cfg_type {
CfgType::Common | CfgType::Notify | CfgType::Device => {}
@@ -123,7 +123,7 @@ pub fn probe_device(pcid_handle: &mut PcidServerHandle) -> Result<Device, Error>
// SAFETY: The capability type is `Notify`, so its safe to access
// the `notify_multiplier` field.
let multiplier = unsafe {
(&*(capability as *const PciCapability as *const PciCapabilityNotify))
(&*(raw_capability.data.as_ptr() as *const PciCapability as *const PciCapabilityNotify))
.notify_off_multiplier()
};
notify_addr = Some((address, multiplier));