From f20af151e2aaa9c384ad7ceada720702e25ffcc2 Mon Sep 17 00:00:00 2001 From: Daniel Verkamp Date: Tue, 8 Oct 2024 10:41:48 -0700 Subject: [PATCH] crosvm: upgrade zerocopy to 0.8 BUG=b:372549215 TEST=tools/dev_container tools/presubmit Change-Id: I3fcc524d1c6c41ae92c51cecb6e4d856c3d60670 Reviewed-on: https://chromium-review.googlesource.com/c/crosvm/crosvm/+/6255229 Reviewed-by: Frederick Mayle Reviewed-by: Dennis Kempin Commit-Queue: Daniel Verkamp --- Cargo.lock | 47 +++--- Cargo.toml | 2 +- acpi_tables/Cargo.toml | 2 +- acpi_tables/src/facs.rs | 7 +- acpi_tables/src/rsdp.rs | 9 +- acpi_tables/src/sdt.rs | 23 +-- base/Cargo.toml | 2 +- base/src/mmap.rs | 11 +- base/src/sys/linux/acpi_event.rs | 33 ++--- base/src/sys/linux/netlink.rs | 93 +++--------- base/src/sys/windows/tube.rs | 9 +- base/src/volatile_memory.rs | 12 +- common/data_model/Cargo.toml | 2 +- common/data_model/src/endian.rs | 7 +- devices/Cargo.toml | 2 +- devices/src/pci/coiommu.rs | 5 +- devices/src/pci/msi.rs | 9 +- devices/src/pci/msix.rs | 9 +- devices/src/pci/pci_configuration.rs | 7 +- devices/src/pci/pcie/pcie_device.rs | 7 +- devices/src/pci/pcie/pcie_host.rs | 6 +- devices/src/pci/pm.rs | 7 +- devices/src/register_space/register.rs | 6 +- devices/src/usb/backend/device.rs | 2 +- .../usb/backend/fido_backend/fido_device.rs | 5 +- .../backend/fido_backend/fido_passthrough.rs | 6 +- .../usb/backend/host_backend/host_device.rs | 2 +- devices/src/usb/xhci/event_ring.rs | 2 +- devices/src/usb/xhci/xhci_abi.rs | 71 +++++----- devices/src/vfio.rs | 15 +- devices/src/virtio/balloon.rs | 15 +- devices/src/virtio/block/asynchronous.rs | 2 +- devices/src/virtio/console/control.rs | 2 +- devices/src/virtio/console/device.rs | 2 +- devices/src/virtio/descriptor_utils.rs | 19 ++- devices/src/virtio/device_constants.rs | 40 +++--- devices/src/virtio/fs/arc_ioctl.rs | 9 +- devices/src/virtio/fs/mod.rs | 2 +- devices/src/virtio/fs/passthrough.rs | 34 ++--- devices/src/virtio/fs/read_dir.rs | 20 +-- devices/src/virtio/gpu/mod.rs | 4 +- devices/src/virtio/gpu/protocol.rs | 73 +++++----- devices/src/virtio/input/event_source.rs | 4 +- devices/src/virtio/input/mod.rs | 34 ++++- devices/src/virtio/iommu.rs | 12 +- devices/src/virtio/iommu/ipc_memory_mapper.rs | 10 +- devices/src/virtio/iommu/protocol.rs | 31 ++-- devices/src/virtio/net.rs | 9 +- devices/src/virtio/pmem.rs | 13 +- devices/src/virtio/pvclock.rs | 9 +- .../virtio/queue/packed_descriptor_chain.rs | 9 +- .../virtio/queue/split_descriptor_chain.rs | 7 +- devices/src/virtio/queue/split_queue.rs | 17 ++- devices/src/virtio/scsi/commands.rs | 80 ++++++++--- devices/src/virtio/scsi/device.rs | 11 +- .../virtio/snd/common_backend/async_funcs.rs | 2 +- devices/src/virtio/snd/common_backend/mod.rs | 2 +- devices/src/virtio/snd/layout.rs | 49 ++++--- devices/src/virtio/snd/vios_backend/mod.rs | 2 +- .../src/virtio/snd/vios_backend/shm_vios.rs | 40 +++--- devices/src/virtio/snd/vios_backend/worker.rs | 13 +- devices/src/virtio/vhost/net.rs | 2 +- devices/src/virtio/vhost/user/device/fs.rs | 2 +- .../src/virtio/vhost/user/device/handler.rs | 13 +- devices/src/virtio/vhost/user/device/net.rs | 2 +- devices/src/virtio/vhost/user/device/snd.rs | 2 +- devices/src/virtio/vhost/user/device/vsock.rs | 2 +- devices/src/virtio/vhost/vsock.rs | 2 +- devices/src/virtio/vhost_user_frontend/fs.rs | 2 +- devices/src/virtio/video/decoder/mod.rs | 2 +- devices/src/virtio/video/encoder/mod.rs | 4 +- devices/src/virtio/video/mod.rs | 4 +- devices/src/virtio/video/protocol.rs | 93 ++++++------ devices/src/virtio/video/resource.rs | 31 ++-- devices/src/virtio/virtio_pci_device.rs | 11 +- .../src/virtio/vsock/sys/windows/protocol.rs | 13 +- devices/src/virtio/vsock/sys/windows/vsock.rs | 20 +-- devices/src/virtio/wl.rs | 27 ++-- disk/Cargo.toml | 2 +- disk/src/android_sparse.rs | 14 +- disk/src/qcow/qcow_raw_file.rs | 6 +- ext2/Cargo.toml | 2 +- ext2/src/arena.rs | 12 +- ext2/src/blockgroup.rs | 7 +- ext2/src/fs.rs | 7 +- ext2/src/inode.rs | 11 +- ext2/src/superblock.rs | 7 +- ext2/src/xattr.rs | 7 +- fuse/Cargo.toml | 2 +- fuse/src/server.rs | 20 ++- fuse/src/sys.rs | 134 +++++++++--------- gpu_display/Cargo.toml | 2 +- gpu_display/src/event_device.rs | 6 +- hypervisor/Cargo.toml | 2 +- hypervisor/tests/hypervisor_virtualization.rs | 13 +- jail/Cargo.toml | 2 +- jail/src/helpers.rs | 6 +- kernel_loader/Cargo.toml | 2 +- kernel_loader/bindgen.sh | 13 +- kernel_loader/src/arm64.rs | 12 +- kernel_loader/src/elf.rs | 13 +- kernel_loader/src/lib.rs | 10 +- kvm/Cargo.toml | 2 +- kvm/src/lib.rs | 10 +- kvm_sys/Cargo.toml | 2 +- kvm_sys/bindgen.sh | 61 ++++---- kvm_sys/src/aarch64/bindings.rs | 21 +-- kvm_sys/src/riscv64/bindings.rs | 5 +- kvm_sys/src/x86/bindings.rs | 45 +++--- linux_input_sys/Cargo.toml | 2 +- linux_input_sys/src/lib.rs | 17 ++- net_util/Cargo.toml | 2 +- net_util/src/slirp/sys/windows/handler.rs | 2 +- perfetto/Cargo.toml | 2 +- perfetto/src/lib.rs | 7 +- src/crosvm/plugin/process.rs | 17 ++- src/crosvm/plugin/vcpu.rs | 22 +-- third_party/vmm_vhost/Cargo.toml | 2 +- third_party/vmm_vhost/src/backend_client.rs | 21 +-- third_party/vmm_vhost/src/backend_server.rs | 28 ++-- third_party/vmm_vhost/src/connection.rs | 17 +-- third_party/vmm_vhost/src/frontend_client.rs | 5 +- third_party/vmm_vhost/src/message.rs | 42 +++--- usb_util/Cargo.toml | 2 +- usb_util/src/descriptor.rs | 8 +- usb_util/src/types.rs | 17 +-- vfio_sys/Cargo.toml | 2 +- vfio_sys/bindgen.sh | 13 +- vfio_sys/src/vfio.rs | 13 +- virtio_sys/Cargo.toml | 2 +- virtio_sys/bindgen.sh | 42 +++--- virtio_sys/src/virtio_fs.rs | 7 +- virtio_sys/src/virtio_net.rs | 9 +- virtio_sys/src/virtio_scsi.rs | 19 +-- virtio_sys/src/virtio_vsock.rs | 7 +- vm_memory/Cargo.toml | 2 +- vm_memory/src/guest_memory.rs | 11 +- x86_64/Cargo.toml | 2 +- x86_64/src/acpi.rs | 15 +- x86_64/src/bootparam.rs | 69 ++++----- x86_64/src/bzimage.rs | 4 +- x86_64/src/lib.rs | 7 +- x86_64/src/mpspec.rs | 19 +-- x86_64/src/mptable.rs | 32 ++--- x86_64/src/multiboot_spec.rs | 9 +- x86_64/src/smbios.rs | 21 +-- 146 files changed, 1169 insertions(+), 1035 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 3eee4b89e..54399b530 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -34,7 +34,7 @@ name = "acpi_tables" version = "0.1.0" dependencies = [ "tempfile", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -309,7 +309,7 @@ dependencies = [ "uuid", "win_util", "winapi", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -895,7 +895,7 @@ dependencies = [ "win_util", "winapi", "x86_64", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -989,7 +989,7 @@ name = "data_model" version = "0.1.1-alpha.1" dependencies = [ "serde", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1101,7 +1101,7 @@ dependencies = [ "win_audio", "win_util", "winapi", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1127,7 +1127,7 @@ dependencies = [ "uuid", "vm_memory", "winapi", - "zerocopy 0.7.32", + "zerocopy 0.8.14", "zstd", ] @@ -1238,7 +1238,7 @@ dependencies = [ "tempfile", "uuid", "walkdir", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1325,7 +1325,7 @@ dependencies = [ "libc", "remain", "thiserror", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1494,7 +1494,7 @@ dependencies = [ "which", "win_util", "winapi", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1567,7 +1567,7 @@ dependencies = [ "win_util", "winapi", "windows", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1694,7 +1694,7 @@ dependencies = [ "serde_keyvalue", "static_assertions", "which", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1728,7 +1728,7 @@ dependencies = [ "tempfile", "thiserror", "vm_memory", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1742,7 +1742,7 @@ dependencies = [ "static_assertions", "sync", "vm_memory", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1752,7 +1752,7 @@ dependencies = [ "base", "data_model", "libc", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -1853,7 +1853,7 @@ dependencies = [ "base", "data_model", "libc", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -2077,7 +2077,7 @@ dependencies = [ "thiserror", "virtio_sys", "winapi", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -2300,7 +2300,7 @@ dependencies = [ "protobuf", "serde", "sync", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3141,7 +3141,7 @@ dependencies = [ "sync", "thiserror", "usb_sys", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3211,7 +3211,7 @@ name = "vfio_sys" version = "0.1.0" dependencies = [ "base", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3250,7 +3250,7 @@ version = "0.1.0" dependencies = [ "base", "data_model", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3319,7 +3319,7 @@ dependencies = [ "snapshot", "tempfile", "thiserror", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3338,7 +3338,7 @@ dependencies = [ "tempfile", "thiserror", "tube_transporter", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3744,7 +3744,7 @@ dependencies = [ "uuid", "vm_control", "vm_memory", - "zerocopy 0.7.32", + "zerocopy 0.8.14", ] [[package]] @@ -3759,7 +3759,6 @@ version = "0.7.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "74d4d3961e53fa4c9a25a8637fc2bfaf2595b3d3ae34875568a5cf64787716be" dependencies = [ - "byteorder", "zerocopy-derive 0.7.32", ] diff --git a/Cargo.toml b/Cargo.toml index 2fd0b23bb..ab37f0435 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -545,7 +545,7 @@ acpi_tables = { path = "acpi_tables" } vm_memory = { path = "vm_memory" } vmm_vhost = { path = "third_party/vmm_vhost" } uuid = { version = "1", features = ["v4"] } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(target_arch = "riscv64")'.dependencies] riscv64 = { path = "riscv64" } diff --git a/acpi_tables/Cargo.toml b/acpi_tables/Cargo.toml index 1aac94f16..09e12e476 100644 --- a/acpi_tables/Cargo.toml +++ b/acpi_tables/Cargo.toml @@ -5,7 +5,7 @@ authors = ["The ChromiumOS Authors"] edition = "2021" [dependencies] -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [dev-dependencies] tempfile = "3" diff --git a/acpi_tables/src/facs.rs b/acpi_tables/src/facs.rs index 7e161a457..adcbb924f 100644 --- a/acpi_tables/src/facs.rs +++ b/acpi_tables/src/facs.rs @@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[repr(C, packed)] -#[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct FACS { pub signature: [u8; 4], pub length: u32, diff --git a/acpi_tables/src/rsdp.rs b/acpi_tables/src/rsdp.rs index e2f896103..2b0f43996 100644 --- a/acpi_tables/src/rsdp.rs +++ b/acpi_tables/src/rsdp.rs @@ -2,12 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[repr(C, packed)] -#[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct RSDP { pub signature: [u8; 8], pub checksum: u8, @@ -46,7 +47,7 @@ impl RSDP { #[cfg(test)] mod tests { - use zerocopy::AsBytes; + use zerocopy::IntoBytes; use super::RSDP; diff --git a/acpi_tables/src/sdt.rs b/acpi_tables/src/sdt.rs index 837837ed0..a23c8ac3c 100644 --- a/acpi_tables/src/sdt.rs +++ b/acpi_tables/src/sdt.rs @@ -8,8 +8,9 @@ use std::io::Read; use std::io::Result; use std::path::Path; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; /// SDT represents for System Description Table. The structure SDT is a /// generic format for creating various ACPI tables like DSDT/FADT/MADT. @@ -89,7 +90,7 @@ impl SDT { self.data.as_slice() } - pub fn append(&mut self, value: T) { + pub fn append(&mut self, value: T) { self.data.extend_from_slice(value.as_bytes()); self.write(LENGTH_OFFSET, self.data.len() as u32); } @@ -100,18 +101,18 @@ impl SDT { } /// Read a value at the given offset - pub fn read(&self, offset: usize) -> T { - let value_len = std::mem::size_of::(); - T::read_from( - self.as_slice() - .get(offset..offset + value_len) - .unwrap_or(T::default().as_bytes()), - ) - .unwrap() + pub fn read(&self, offset: usize) -> T { + self.as_slice() + .get(offset..) + .and_then(|bytes| { + let (val, _) = T::read_from_prefix(bytes).ok()?; + Some(val) + }) + .unwrap_or_default() } /// Write a value at the given offset - pub fn write(&mut self, offset: usize, value: T) { + pub fn write(&mut self, offset: usize, value: T) { let value_len = std::mem::size_of::(); if (offset + value_len) > self.data.len() { return; diff --git a/base/Cargo.toml b/base/Cargo.toml index f813e7d19..f73010e7a 100644 --- a/base/Cargo.toml +++ b/base/Cargo.toml @@ -26,7 +26,7 @@ serde_json = "1" smallvec = "1.6.1" thiserror = "1.0.20" uuid = { version = "1", features = ["v4"] } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [dev-dependencies] protos = { path = "../protos", features = ["composite-disk"] } diff --git a/base/src/mmap.rs b/base/src/mmap.rs index f5a6e7779..d8d7ba327 100644 --- a/base/src/mmap.rs +++ b/base/src/mmap.rs @@ -18,8 +18,9 @@ use std::sync::OnceLock; use remain::sorted; use serde::Deserialize; use serde::Serialize; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::descriptor::AsRawDescriptor; use crate::descriptor::SafeDescriptor; @@ -252,7 +253,7 @@ impl MemoryMapping { /// let res = mem_map.write_obj(55u64, 16); /// assert!(res.is_ok()); /// ``` - pub fn write_obj(&self, val: T, offset: usize) -> Result<()> { + pub fn write_obj(&self, val: T, offset: usize) -> Result<()> { self.mapping.range_end(offset, size_of::())?; // SAFETY: // This is safe because we checked the bounds above. @@ -311,7 +312,11 @@ impl MemoryMapping { /// let res = mem_map.write_obj_volatile(0xf00u32, 16); /// assert!(res.is_ok()); /// ``` - pub fn write_obj_volatile(&self, val: T, offset: usize) -> Result<()> { + pub fn write_obj_volatile( + &self, + val: T, + offset: usize, + ) -> Result<()> { self.mapping.range_end(offset, size_of::())?; // Make sure writes to memory have been committed before performing I/O that could // potentially depend on them. diff --git a/base/src/sys/linux/acpi_event.rs b/base/src/sys/linux/acpi_event.rs index 514619d2f..fe6a6cf40 100644 --- a/base/src/sys/linux/acpi_event.rs +++ b/base/src/sys/linux/acpi_event.rs @@ -6,7 +6,8 @@ use std::str; use thiserror::Error; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::KnownLayout; use super::netlink::*; @@ -40,10 +41,10 @@ enum GenmsghdrCmd { } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] struct AcpiGenlEvent { - device_class: [::std::os::raw::c_char; 20usize], - bus_id: [::std::os::raw::c_char; 15usize], + device_class: [u8; 20], + bus_id: [u8; 15], _type: u32, data: u32, } @@ -63,12 +64,11 @@ impl AcpiNotifyEvent { return Err(AcpiEventError::InvalidMsgLen(msg_len)); } - let genl_hdr = GenlMsgHdr::read_from(&netlink_message.data[..GENL_HDRLEN]) + let (genl_hdr, nl_attr) = GenlMsgHdr::read_from_prefix(netlink_message.data) .expect("unable to get GenlMsgHdr from slice"); - let nlattr_end = GENL_HDRLEN + NLA_HDRLEN; - let nl_attr = NlAttr::read_from(&netlink_message.data[GENL_HDRLEN..nlattr_end]) - .expect("unable to get NlAttr from slice"); + let (nl_attr, body) = + NlAttr::read_from_prefix(nl_attr).expect("unable to get NlAttr from slice"); // Sanity check that the headers have correct for acpi event `cmd` and `_type` if genl_hdr.cmd != GenmsghdrCmd::AcpiGenlCmdEvent as u8 @@ -77,21 +77,12 @@ impl AcpiNotifyEvent { return Err(AcpiEventError::TypeAttrMissmatch); } - let acpi_event = AcpiGenlEvent::read_from(&netlink_message.data[nlattr_end..msg_len]) - .expect("unable to get AcpiGenlEvent from slice"); - - // The raw::c_char is either i8 or u8 which is known portability issue: - // https://github.com/rust-lang/rust/issues/79089, - // before using device_class further cast it to u8. - let device_class: &[u8; 20usize] = - // SAFETY: trivially safe - unsafe { ::std::mem::transmute(&acpi_event.device_class) }; - // SAFETY: trivially safe - let bus_id: &[u8; 15usize] = unsafe { ::std::mem::transmute(&acpi_event.bus_id) }; + let acpi_event = + AcpiGenlEvent::read_from_bytes(body).expect("unable to get AcpiGenlEvent from slice"); Ok(AcpiNotifyEvent { - device_class: strip_padding(device_class).to_owned(), - bus_id: strip_padding(bus_id).to_owned(), + device_class: strip_padding(&acpi_event.device_class).to_owned(), + bus_id: strip_padding(&acpi_event.bus_id).to_owned(), _type: acpi_event._type, data: acpi_event.data, }) diff --git a/base/src/sys/linux/netlink.rs b/base/src/sys/linux/netlink.rs index 12ef583dd..8290ddfe6 100644 --- a/base/src/sys/linux/netlink.rs +++ b/base/src/sys/linux/netlink.rs @@ -9,10 +9,10 @@ use std::str; use libc::EINVAL; use log::error; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; -use zerocopy::Ref; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use super::errno_result; use super::getpid; @@ -36,7 +36,7 @@ const NLA_HDRLEN: usize = std::mem::size_of::(); const NLATTR_ALIGN_TO: usize = 4; #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] struct NlMsgHdr { pub nlmsg_len: u32, pub nlmsg_type: u16, @@ -47,7 +47,7 @@ struct NlMsgHdr { /// Netlink attribute struct, can be used by netlink consumer #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NlAttr { pub len: u16, pub _type: u16, @@ -55,7 +55,7 @@ pub struct NlAttr { /// Generic netlink header struct, can be used by netlink consumer #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct GenlMsgHdr { pub cmd: u8, pub version: u8, @@ -76,10 +76,6 @@ pub struct NlAttrWithData<'a> { pub data: &'a [u8], } -fn nlattr_align(offset: usize) -> usize { - (offset + NLATTR_ALIGN_TO - 1) & !(NLATTR_ALIGN_TO - 1) -} - /// Iterator over `struct NlAttr` as received from a netlink socket. pub struct NetlinkGenericDataIter<'a> { // `data` must be properly aligned for NlAttr. @@ -90,28 +86,13 @@ impl<'a> Iterator for NetlinkGenericDataIter<'a> { type Item = NlAttrWithData<'a>; fn next(&mut self) -> Option { - if self.data.len() < NLA_HDRLEN { - return None; - } - let nl_hdr = NlAttr::read_from(&self.data[..NLA_HDRLEN])?; - - // Make sure NlAtrr fits + let (nl_hdr, _) = NlAttr::read_from_prefix(self.data).ok()?; let nl_data_len = nl_hdr.len as usize; - if nl_data_len < NLA_HDRLEN || nl_data_len > self.data.len() { - return None; - } - - // Get data related to processed NlAttr - let data_start = NLA_HDRLEN; - let data = &self.data[data_start..nl_data_len]; + let data = self.data.get(NLA_HDRLEN..nl_data_len)?; // Get next NlAttr - let next_hdr = nlattr_align(nl_data_len); - if next_hdr >= self.data.len() { - self.data = &[]; - } else { - self.data = &self.data[next_hdr..]; - } + let next_hdr = nl_data_len.next_multiple_of(NLATTR_ALIGN_TO); + self.data = self.data.get(next_hdr..).unwrap_or(&[]); Some(NlAttrWithData { _type: nl_hdr._type, @@ -131,29 +112,13 @@ impl<'a> Iterator for NetlinkMessageIter<'a> { type Item = NetlinkMessage<'a>; fn next(&mut self) -> Option { - if self.data.len() < NLMSGHDR_SIZE { - return None; - } - let hdr = NlMsgHdr::read_from(&self.data[..NLMSGHDR_SIZE])?; - - // NLMSG_OK + let (hdr, _) = NlMsgHdr::read_from_prefix(self.data).ok()?; let msg_len = hdr.nlmsg_len as usize; - if msg_len < NLMSGHDR_SIZE || msg_len > self.data.len() { - return None; - } - - // NLMSG_DATA - let data_start = NLMSGHDR_SIZE; - let data = &self.data[data_start..msg_len]; + let data = self.data.get(NLMSGHDR_SIZE..msg_len)?; // NLMSG_NEXT - let align_to = std::mem::align_of::(); - let next_hdr = (msg_len + align_to - 1) & !(align_to - 1); - if next_hdr >= self.data.len() { - self.data = &[]; - } else { - self.data = &self.data[next_hdr..]; - } + let next_hdr = msg_len.next_multiple_of(std::mem::align_of::()); + self.data = self.data.get(next_hdr..).unwrap_or(&[]); Some(NetlinkMessage { _type: hdr.nlmsg_type, @@ -262,9 +227,7 @@ impl NetlinkGenericSocket { let data = unsafe { allocation.as_mut_slice(buf_size) }; // Prepare the netlink message header - let hdr = Ref::<_, NlMsgHdr>::new(&mut data[..NLMSGHDR_SIZE]) - .expect("failed to unwrap") - .into_mut(); + let (hdr, genl_hdr) = NlMsgHdr::mut_from_prefix(data).expect("failed to unwrap"); hdr.nlmsg_len = NLMSGHDR_SIZE as u32 + GENL_HDRLEN as u32; hdr.nlmsg_len += NLA_HDRLEN as u32 + family_name.len() as u32 + 1; hdr.nlmsg_flags = libc::NLM_F_REQUEST as u16; @@ -272,36 +235,26 @@ impl NetlinkGenericSocket { hdr.nlmsg_pid = getpid() as u32; // Prepare generic netlink message header - let genl_hdr_end = NLMSGHDR_SIZE + GENL_HDRLEN; - let genl_hdr = Ref::<_, GenlMsgHdr>::new(&mut data[NLMSGHDR_SIZE..genl_hdr_end]) - .expect("unable to get GenlMsgHdr from slice") - .into_mut(); + let (genl_hdr, nlattr) = + GenlMsgHdr::mut_from_prefix(genl_hdr).expect("unable to get GenlMsgHdr from slice"); genl_hdr.cmd = libc::CTRL_CMD_GETFAMILY as u8; genl_hdr.version = 0x1; // Netlink attributes - let nlattr_start = genl_hdr_end; - let nlattr_end = nlattr_start + NLA_HDRLEN; - let nl_attr = Ref::<_, NlAttr>::new(&mut data[nlattr_start..nlattr_end]) - .expect("unable to get NlAttr from slice") - .into_mut(); + let (nl_attr, payload) = + NlAttr::mut_from_prefix(nlattr).expect("unable to get NlAttr from slice"); nl_attr._type = libc::CTRL_ATTR_FAMILY_NAME as u16; nl_attr.len = family_name.len() as u16 + 1 + NLA_HDRLEN as u16; // Fill the message payload with the family name - let payload_start = nlattr_end; - let payload_end = payload_start + family_name.len(); - data[payload_start..payload_end].copy_from_slice(family_name.as_bytes()); + payload[..family_name.len()].copy_from_slice(family_name.as_bytes()); + + let len = NLMSGHDR_SIZE + GENL_HDRLEN + NLA_HDRLEN + family_name.len() + 1; // SAFETY: // Safe because we pass a valid, owned socket fd and a valid pointer/size for the buffer. unsafe { - let res = libc::send( - self.sock.as_raw_fd(), - allocation.as_ptr(), - payload_end + 1, - 0, - ); + let res = libc::send(self.sock.as_raw_fd(), allocation.as_ptr(), len, 0); if res < 0 { error!("failed to send get_family_cmd"); return errno_result(); diff --git a/base/src/sys/windows/tube.rs b/base/src/sys/windows/tube.rs index 613370203..7e4a80058 100644 --- a/base/src/sys/windows/tube.rs +++ b/base/src/sys/windows/tube.rs @@ -16,9 +16,10 @@ use serde::de::DeserializeOwned; use serde::Deserialize; use serde::Serialize; use serde::Serializer; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::descriptor::AsRawDescriptor; use crate::descriptor::FromRawDescriptor; @@ -81,7 +82,7 @@ where } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct MsgHeader { msg_json_size: usize, @@ -308,7 +309,7 @@ pub fn deserialize_and_recv io::Resu mut read_fn: F, ) -> Result { let mut header = MsgHeader::default(); - perform_read(&mut read_fn, header.as_bytes_mut()).map_err(Error::from_recv_io_error)?; + perform_read(&mut read_fn, header.as_mut_bytes()).map_err(Error::from_recv_io_error)?; let mut msg_json = vec![0u8; header.msg_json_size]; perform_read(&mut read_fn, msg_json.as_mut_slice()).map_err(Error::from_recv_io_error)?; diff --git a/base/src/volatile_memory.rs b/base/src/volatile_memory.rs index 6cadc42ac..05ace361d 100644 --- a/base/src/volatile_memory.rs +++ b/base/src/volatile_memory.rs @@ -31,9 +31,8 @@ use std::slice; use remain::sorted; use thiserror::Error; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::Ref; +use zerocopy::IntoBytes; use crate::IoBufMut; @@ -231,7 +230,7 @@ impl<'a> VolatileSlice<'a> { /// ``` pub fn copy_to(&self, buf: &mut [T]) where - T: FromBytes + AsBytes + Copy, + T: FromBytes + IntoBytes + Copy, { let mut addr = self.as_mut_ptr() as *const u8; for v in buf.iter_mut().take(self.size() / size_of::()) { @@ -296,16 +295,13 @@ impl<'a> VolatileSlice<'a> { /// ``` pub fn copy_from(&self, buf: &[T]) where - T: FromBytes + AsBytes, + T: IntoBytes + Copy, { let mut addr = self.as_mut_ptr(); for v in buf.iter().take(self.size() / size_of::()) { // SAFETY: Safe because buf is valid, aligned to type `T` and is mutable. unsafe { - write_volatile( - addr as *mut T, - Ref::<_, T>::new(v.as_bytes()).unwrap().read(), - ); + write_volatile(addr as *mut T, *v); addr = addr.add(size_of::()); } } diff --git a/common/data_model/Cargo.toml b/common/data_model/Cargo.toml index d0c30b8bc..664a94f31 100644 --- a/common/data_model/Cargo.toml +++ b/common/data_model/Cargo.toml @@ -9,4 +9,4 @@ license-file = "LICENSE" [dependencies] serde = { version = "1", features = ["derive"] } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/common/data_model/src/endian.rs b/common/data_model/src/endian.rs index f45b1daa4..c4e4689f0 100644 --- a/common/data_model/src/endian.rs +++ b/common/data_model/src/endian.rs @@ -36,9 +36,10 @@ use serde::Deserialize; use serde::Deserializer; use serde::Serialize; use serde::Serializer; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; macro_rules! endian_type { ($old_type:ident, $new_type:ident, $to_new:ident, $from_new:ident) => { @@ -46,7 +47,7 @@ macro_rules! endian_type { /// /// See module level documentation for examples. #[repr(transparent)] - #[derive(Copy, Clone, Eq, PartialEq, Debug, Default, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Eq, PartialEq, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct $new_type($old_type); impl $new_type { diff --git a/devices/Cargo.toml b/devices/Cargo.toml index 56426c0ac..748dbd912 100644 --- a/devices/Cargo.toml +++ b/devices/Cargo.toml @@ -102,7 +102,7 @@ virtio_sys = { path = "../virtio_sys" } virtio-media = { version = "0.0.7", optional = true } vm_control = { path = "../vm_control" } vm_memory = { path = "../vm_memory" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(any(target_os = "android", target_os = "linux"))'.dependencies] android_audio = { path = "../android_audio" } diff --git a/devices/src/pci/coiommu.rs b/devices/src/pci/coiommu.rs index a2ba2e55e..44e4c6d00 100644 --- a/devices/src/pci/coiommu.rs +++ b/devices/src/pci/coiommu.rs @@ -64,9 +64,8 @@ use vm_control::VmMemoryDestination; use vm_control::VmMemorySource; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::IntoBytes; use crate::pci::pci_configuration::PciBarConfiguration; use crate::pci::pci_configuration::PciBarPrefetchable; @@ -270,7 +269,7 @@ fn vfio_unmap(vfio_container: &Arc>, iova: u64, size: u64) } } -#[derive(Default, Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Debug, Copy, Clone, FromBytes, IntoBytes)] #[repr(C)] struct PinPageInfo { bdf: u16, diff --git a/devices/src/pci/msi.rs b/devices/src/pci/msi.rs index ab45a17fd..18536b0c1 100644 --- a/devices/src/pci/msi.rs +++ b/devices/src/pci/msi.rs @@ -12,9 +12,10 @@ use base::Tube; use bit_field::*; use vm_control::VmIrqRequest; use vm_control::VmIrqResponse; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::pci::pci_configuration::PciCapConfig; use crate::pci::pci_configuration::PciCapConfigWriteResult; @@ -265,7 +266,7 @@ impl MsiConfig { } #[bitfield] -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct MsiCtrl { enable: B1, multi_msg_capable: B3, @@ -279,7 +280,7 @@ pub struct MsiCtrl { #[allow(dead_code)] #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] /// MSI Capability Structure pub struct MsiCap { // To make add_capability() happy diff --git a/devices/src/pci/msix.rs b/devices/src/pci/msix.rs index 25be63122..afc1668ee 100644 --- a/devices/src/pci/msix.rs +++ b/devices/src/pci/msix.rs @@ -21,9 +21,10 @@ use snapshot::AnySnapshot; use thiserror::Error; use vm_control::VmIrqRequest; use vm_control::VmIrqResponse; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::pci::pci_configuration::PciCapConfig; use crate::pci::pci_configuration::PciCapConfigWriteResult; @@ -755,7 +756,7 @@ impl AsRawDescriptor for MsixConfig { // 15: Enable. Enable all MSI-X when set. // See for the details. #[bitfield] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct MsixCtrl { table_size: B10, reserved: B4, @@ -765,7 +766,7 @@ pub struct MsixCtrl { #[allow(dead_code)] #[repr(C)] -#[derive(Clone, Copy, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] /// MSI-X Capability Structure pub struct MsixCap { // To make add_capability() happy diff --git a/devices/src/pci/pci_configuration.rs b/devices/src/pci/pci_configuration.rs index d8402847a..be02ac7b9 100644 --- a/devices/src/pci/pci_configuration.rs +++ b/devices/src/pci/pci_configuration.rs @@ -1097,12 +1097,15 @@ impl PciCapMapping { #[cfg(test)] mod tests { - use zerocopy::AsBytes; + use zerocopy::FromBytes; + use zerocopy::Immutable; + use zerocopy::IntoBytes; + use zerocopy::KnownLayout; use super::*; #[repr(C, packed)] - #[derive(Clone, Copy, AsBytes)] + #[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] #[allow(dead_code)] struct TestCap { _vndr: u8, diff --git a/devices/src/pci/pcie/pcie_device.rs b/devices/src/pci/pcie/pcie_device.rs index a0b9efa93..97c866c5d 100644 --- a/devices/src/pci/pcie/pcie_device.rs +++ b/devices/src/pci/pcie/pcie_device.rs @@ -6,7 +6,10 @@ use std::sync::Arc; use resources::SystemAllocator; use sync::Mutex; -use zerocopy::AsBytes; +use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::pci::pci_configuration::PciCapConfig; use crate::pci::pci_configuration::PciCapConfigWriteResult; @@ -52,7 +55,7 @@ pub trait PcieDevice: Send { } #[repr(C)] -#[derive(Clone, Copy, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct PcieCap { _cap_vndr: u8, _cap_next: u8, diff --git a/devices/src/pci/pcie/pcie_host.rs b/devices/src/pci/pcie/pcie_host.rs index ce49c01de..1ec95a74a 100644 --- a/devices/src/pci/pcie/pcie_host.rs +++ b/devices/src/pci/pcie/pcie_host.rs @@ -23,8 +23,8 @@ use vm_control::HotPlugDeviceInfo; use vm_control::HotPlugDeviceType; use vm_control::VmRequest; use vm_control::VmResponse; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::IntoBytes; use crate::pci::pci_configuration::PciBridgeSubclass; use crate::pci::pci_configuration::CAPABILITY_LIST_HEAD_OFFSET; @@ -66,7 +66,7 @@ impl PciHostConfig { } // Read host pci device's config register - fn read_config(&self, offset: u64) -> T { + fn read_config(&self, offset: u64) -> T { let length = std::mem::size_of::(); let mut val = T::default(); if offset % length as u64 != 0 { @@ -74,7 +74,7 @@ impl PciHostConfig { "read_config, offset {} isn't aligned to length {}", offset, length ); - } else if let Err(e) = self.config_file.read_exact_at(val.as_bytes_mut(), offset) { + } else if let Err(e) = self.config_file.read_exact_at(val.as_mut_bytes(), offset) { error!("failed to read host sysfs config: {}", e); } diff --git a/devices/src/pci/pm.rs b/devices/src/pci/pm.rs index 3b5244408..d622ce0b2 100644 --- a/devices/src/pci/pm.rs +++ b/devices/src/pci/pm.rs @@ -4,9 +4,10 @@ #![cfg_attr(windows, allow(dead_code))] -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::pci::pci_configuration::PciCapConfig; use crate::pci::pci_configuration::PciCapConfigWriteResult; @@ -35,7 +36,7 @@ pub enum PciDevicePower { } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct PciPmCap { _cap_vndr: u8, _cap_next: u8, diff --git a/devices/src/register_space/register.rs b/devices/src/register_space/register.rs index c5cbe7eb4..f2c613de7 100644 --- a/devices/src/register_space/register.rs +++ b/devices/src/register_space/register.rs @@ -14,8 +14,8 @@ use std::sync::MutexGuard; use base::error; use sync::Mutex; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::IntoBytes; /// Type of offset in the register space. pub type RegisterOffset = u64; @@ -65,8 +65,8 @@ pub trait RegisterValue: 'static + Into + Clone - + AsBytes + FromBytes + + IntoBytes + Send + Sync + Copy @@ -269,7 +269,7 @@ impl RegisterInterface for Register { let total_size = (overlap.to - overlap.from) as usize + 1; let mut reg_value: T = self.lock().value; - let value: &mut [u8] = reg_value.as_bytes_mut(); + let value: &mut [u8] = reg_value.as_mut_bytes(); for i in 0..total_size { value[my_start_idx + i] = self.apply_write_masks_to_byte( value[my_start_idx + i], diff --git a/devices/src/usb/backend/device.rs b/devices/src/usb/backend/device.rs index c1231a414..9f7eebfd2 100644 --- a/devices/src/usb/backend/device.rs +++ b/devices/src/usb/backend/device.rs @@ -23,7 +23,7 @@ use usb_util::Transfer; use usb_util::TransferBuffer; use usb_util::TransferStatus; use usb_util::UsbRequestSetup; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::usb::backend::endpoint::ControlEndpointState; use crate::usb::backend::endpoint::UsbEndpoint; diff --git a/devices/src/usb/backend/fido_backend/fido_device.rs b/devices/src/usb/backend/fido_backend/fido_device.rs index d5ad4cc60..8f1a2c8c3 100644 --- a/devices/src/usb/backend/fido_backend/fido_device.rs +++ b/devices/src/usb/backend/fido_backend/fido_device.rs @@ -16,7 +16,6 @@ use base::EventType; use base::RawDescriptor; use sync::Mutex; use zerocopy::FromBytes; -use zerocopy::FromZeroes; use crate::usb::backend::fido_backend::constants; use crate::usb::backend::fido_backend::error::Error; @@ -27,7 +26,7 @@ use crate::usb::backend::fido_backend::hid_utils::verify_is_fido_device; use crate::usb::backend::fido_backend::poll_thread::PollTimer; use crate::utils::EventLoop; -#[derive(FromZeroes, FromBytes, Debug)] +#[derive(FromBytes, Debug)] #[repr(C)] pub struct InitPacket { cid: [u8; constants::CID_SIZE], @@ -52,7 +51,7 @@ impl InitPacket { return Err(Error::InvalidInitPacket); } - InitPacket::read_from(bytes).ok_or_else(|| Error::CannotConvertInitPacketFromBytes) + InitPacket::read_from_bytes(bytes).map_err(|_| Error::CannotConvertInitPacketFromBytes) } pub fn bcnt(&self) -> u16 { diff --git a/devices/src/usb/backend/fido_backend/fido_passthrough.rs b/devices/src/usb/backend/fido_backend/fido_passthrough.rs index 697423931..8cc0ba93e 100644 --- a/devices/src/usb/backend/fido_backend/fido_passthrough.rs +++ b/devices/src/usb/backend/fido_backend/fido_passthrough.rs @@ -30,8 +30,8 @@ use usb_util::Error as UsbUtilError; use usb_util::TransferBuffer; use usb_util::TransferStatus; use usb_util::UsbRequestSetup; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::IntoBytes; use crate::usb::backend::device::BackendDevice; use crate::usb::backend::device::DeviceState; @@ -149,7 +149,9 @@ impl FidoPassthroughDevice { transfer.actual_length = 0; let request_setup = match &transfer.buffer { TransferBuffer::Vector(v) => { - UsbRequestSetup::read_from_prefix(v).ok_or_else(|| Error::InvalidDataBufferSize)? + UsbRequestSetup::read_from_prefix(v) + .map_err(|_| Error::InvalidDataBufferSize)? + .0 } _ => { return Err(Error::UnsupportedTransferBufferType); diff --git a/devices/src/usb/backend/host_backend/host_device.rs b/devices/src/usb/backend/host_backend/host_device.rs index 73ba24d79..868805b48 100644 --- a/devices/src/usb/backend/host_backend/host_device.rs +++ b/devices/src/usb/backend/host_backend/host_device.rs @@ -23,7 +23,7 @@ use usb_util::TransferBuffer; use usb_util::TransferHandle; use usb_util::TransferStatus; use usb_util::UsbRequestSetup; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::usb::backend::device::BackendDevice; use crate::usb::backend::device::DeviceState; diff --git a/devices/src/usb/xhci/event_ring.rs b/devices/src/usb/xhci/event_ring.rs index f8679dadf..717e166e2 100644 --- a/devices/src/usb/xhci/event_ring.rs +++ b/devices/src/usb/xhci/event_ring.rs @@ -11,7 +11,7 @@ use thiserror::Error; use vm_memory::GuestAddress; use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use super::xhci_abi::EventRingSegmentTableEntry; use super::xhci_abi::Trb; diff --git a/devices/src/usb/xhci/xhci_abi.rs b/devices/src/usb/xhci/xhci_abi.rs index 1f9d1119e..854626a76 100644 --- a/devices/src/usb/xhci/xhci_abi.rs +++ b/devices/src/usb/xhci/xhci_abi.rs @@ -10,9 +10,10 @@ use bit_field::*; use remain::sorted; use thiserror::Error; use vm_memory::GuestAddress; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[sorted] #[derive(Error, Debug)] @@ -118,7 +119,7 @@ impl DequeuePtr { // Generic TRB struct containing only fields common to all types. #[bitfield] -#[derive(Clone, Copy, PartialEq, Eq, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, PartialEq, Eq, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Trb { parameter: B64, status: B32, @@ -295,7 +296,7 @@ impl Trb { } #[bitfield] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NormalTrb { data_buffer: B64, trb_transfer_length: B17, @@ -315,7 +316,7 @@ pub struct NormalTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SetupStageTrb { request_type: B8, request: B8, @@ -336,7 +337,7 @@ pub struct SetupStageTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct DataStageTrb { data_buffer_pointer: B64, trb_transfer_length: B17, @@ -356,7 +357,7 @@ pub struct DataStageTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct StatusStageTrb { reserved0: B64, reserved1: B22, @@ -373,7 +374,7 @@ pub struct StatusStageTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct IsochTrb { data_buffer_pointer: B64, trb_transfer_length: B17, @@ -395,7 +396,7 @@ pub struct IsochTrb { } #[bitfield] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct LinkTrb { ring_segment_pointer: B64, reserved0: B22, @@ -411,7 +412,7 @@ pub struct LinkTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct EventDataTrb { event_data: B64, reserved0: B22, @@ -428,7 +429,7 @@ pub struct EventDataTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NoopTrb { reserved0: B64, reserved1: B22, @@ -444,7 +445,7 @@ pub struct NoopTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct DisableSlotCommandTrb { reserved0: B32, reserved1: B32, @@ -457,7 +458,7 @@ pub struct DisableSlotCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct AddressDeviceCommandTrb { input_context_pointer: B64, reserved: B32, @@ -470,7 +471,7 @@ pub struct AddressDeviceCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ConfigureEndpointCommandTrb { input_context_pointer: B64, reserved0: B32, @@ -483,7 +484,7 @@ pub struct ConfigureEndpointCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct EvaluateContextCommandTrb { input_context_pointer: B64, reserved0: B32, @@ -495,7 +496,7 @@ pub struct EvaluateContextCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ResetEndpointCommandTrb { reserved0: B32, reserved1: B32, @@ -510,7 +511,7 @@ pub struct ResetEndpointCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct StopEndpointCommandTrb { reserved0: B32, reserved1: B32, @@ -525,7 +526,7 @@ pub struct StopEndpointCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SetTRDequeuePointerCommandTrb { dequeue_cycle_state: bool, stream_context_type: B3, @@ -542,7 +543,7 @@ pub struct SetTRDequeuePointerCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ResetDeviceCommandTrb { reserved0: B32, reserved1: B32, @@ -555,7 +556,7 @@ pub struct ResetDeviceCommandTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct TransferEventTrb { trb_pointer: B64, trb_transfer_length: B24, @@ -571,7 +572,7 @@ pub struct TransferEventTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct CommandCompletionEventTrb { trb_pointer: B64, command_completion_parameter: B24, @@ -584,7 +585,7 @@ pub struct CommandCompletionEventTrb { } #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct PortStatusChangeEventTrb { reserved0: B24, port_id: B8, @@ -686,16 +687,18 @@ impl TypedTrb for PortStatusChangeEventTrb { /// /// All trb structs have the same size. One trb could be safely casted to another, though the /// values might be invalid. -pub unsafe trait TrbCast: FromBytes + AsBytes + TypedTrb { +pub unsafe trait TrbCast: + FromBytes + Immutable + IntoBytes + KnownLayout + TypedTrb +{ fn cast(&self) -> Result<&T> { - zerocopy::Ref::<_, T>::new(self.as_bytes()) - .ok_or(Error::CannotCastTrb) + zerocopy::Ref::<_, T>::from_bytes(self.as_bytes()) + .map_err(|_| Error::CannotCastTrb) .map(zerocopy::Ref::into_ref) } fn cast_mut(&mut self) -> Result<&mut T> { - zerocopy::Ref::<_, T>::new(self.as_bytes_mut()) - .ok_or(Error::CannotCastTrb) + zerocopy::Ref::<_, T>::from_bytes(self.as_mut_bytes()) + .map_err(|_| Error::CannotCastTrb) .map(zerocopy::Ref::into_mut) } @@ -766,7 +769,7 @@ unsafe impl TrbCast for CommandCompletionEventTrb {} unsafe impl TrbCast for PortStatusChangeEventTrb {} #[bitfield] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct EventRingSegmentTableEntry { ring_segment_base_address: B64, ring_segment_size: B16, @@ -774,7 +777,7 @@ pub struct EventRingSegmentTableEntry { } #[bitfield] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InputControlContext { // Xhci spec 6.2.5.1. drop_context_flags: B32, @@ -806,7 +809,7 @@ impl InputControlContext { pub const DEVICE_CONTEXT_ENTRY_SIZE: usize = 32usize; #[bitfield] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SlotContext { route_string: B20, speed: B4, @@ -832,7 +835,7 @@ pub struct SlotContext { } #[bitfield] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct EndpointContext { endpoint_state: EndpointState, reserved1: B5, @@ -859,7 +862,7 @@ pub struct EndpointContext { } #[bitfield] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct StreamContext { dequeue_cycle_state: bool, stream_context_type: B3, @@ -870,14 +873,14 @@ pub struct StreamContext { } #[repr(C)] -#[derive(Clone, Copy, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct StreamContextArray { pub stream_contexts: [StreamContext; 16], } /// Device context. #[repr(C)] -#[derive(Clone, Copy, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct DeviceContext { pub slot_context: SlotContext, pub endpoint_context: [EndpointContext; 31], diff --git a/devices/src/vfio.rs b/devices/src/vfio.rs index 043847961..2115ce29f 100644 --- a/devices/src/vfio.rs +++ b/devices/src/vfio.rs @@ -48,8 +48,9 @@ use thiserror::Error; use vfio_sys::vfio::vfio_acpi_dsm; use vfio_sys::vfio::VFIO_IRQ_SET_DATA_BOOL; use vfio_sys::*; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::IommuDevType; @@ -318,7 +319,7 @@ fn extract_vfio_struct(bytes: &[u8], offset: usize) -> Option where T: FromBytes, { - bytes.get(offset..).and_then(T::read_from_prefix) + Some(T::read_from_prefix(bytes.get(offset..)?).ok()?.0) } const VFIO_API_VERSION: u8 = 0; @@ -1818,8 +1819,8 @@ impl VfioDevice { } /// Writes data into the specified `VfioRegionAddr.addr` + `offset`. - pub fn region_write_to_addr(&self, val: &T, addr: &VfioRegionAddr, offset: u64) { - self.region_write(addr.index, val.as_bytes(), addr.addr + offset); + pub fn region_write_to_addr(&self, data: &[u8], addr: &VfioRegionAddr, offset: u64) { + self.region_write(addr.index, data, addr.addr + offset); } /// get vfio device's descriptors which are passed into minijail process @@ -1898,17 +1899,17 @@ impl VfioPciConfig { VfioPciConfig { device } } - pub fn read_config(&self, offset: u32) -> T { + pub fn read_config(&self, offset: u32) -> T { let mut config = T::new_zeroed(); self.device.region_read( VFIO_PCI_CONFIG_REGION_INDEX as usize, - config.as_bytes_mut(), + config.as_mut_bytes(), offset.into(), ); config } - pub fn write_config(&self, config: T, offset: u32) { + pub fn write_config(&self, config: T, offset: u32) { self.device.region_write( VFIO_PCI_CONFIG_REGION_INDEX as usize, config.as_bytes(), diff --git a/devices/src/virtio/balloon.rs b/devices/src/virtio/balloon.rs index e856730da..6a98feff5 100644 --- a/devices/src/virtio/balloon.rs +++ b/devices/src/virtio/balloon.rs @@ -53,9 +53,10 @@ use vm_control::api::VmMemoryClient; use vm_control::RegisteredEventWithData; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use super::async_utils; use super::copy_config; @@ -135,7 +136,7 @@ pub enum BalloonFeatures { } // virtio_balloon_config is the balloon device configuration space defined by the virtio spec. -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtio_balloon_config { num_pages: Le32, @@ -175,7 +176,7 @@ const VIRTIO_BALLOON_S_NONSTANDARD_SHMEM: u16 = 65534; const VIRTIO_BALLOON_S_NONSTANDARD_UNEVICTABLE: u16 = 65535; // BalloonStat is used to deserialize stats from the stats_queue. -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] struct BalloonStat { tag: Le16, @@ -205,7 +206,7 @@ impl BalloonStat { // virtio_balloon_ws is used to deserialize from the ws data vq. #[repr(C)] -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct virtio_balloon_ws { tag: Le16, node_id: Le16, @@ -237,7 +238,7 @@ const _VIRTIO_BALLOON_WS_OP_DISCARD: u16 = 3; // virtio_balloon_op is used to serialize to the ws cmd vq. #[repr(C, packed)] -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct virtio_balloon_op { type_: Le16, } @@ -1409,7 +1410,7 @@ impl VirtioDevice for Balloon { fn write_config(&mut self, offset: u64, data: &[u8]) { let mut config = self.get_config(); - copy_config(config.as_bytes_mut(), offset, data, 0); + copy_config(config.as_mut_bytes(), offset, data, 0); let mut state = block_on(self.state.lock()); state.actual_pages = config.actual.to_native(); diff --git a/devices/src/virtio/block/asynchronous.rs b/devices/src/virtio/block/asynchronous.rs index d8e6aa468..fe26ea45d 100644 --- a/devices/src/virtio/block/asynchronous.rs +++ b/devices/src/virtio/block/asynchronous.rs @@ -56,7 +56,7 @@ use virtio_sys::virtio_config::VIRTIO_F_RING_PACKED; use vm_control::DiskControlCommand; use vm_control::DiskControlResult; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::async_utils; use crate::virtio::block::sys::*; diff --git a/devices/src/virtio/console/control.rs b/devices/src/virtio/console/control.rs index 09aa0d373..cbef5a230 100644 --- a/devices/src/virtio/console/control.rs +++ b/devices/src/virtio/console/control.rs @@ -11,7 +11,7 @@ use anyhow::anyhow; use anyhow::Context; use base::debug; use base::error; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::console::worker::WorkerPort; use crate::virtio::device_constants::console::virtio_console_control; diff --git a/devices/src/virtio/console/device.rs b/devices/src/virtio/console/device.rs index 028ad1173..3c396bbb3 100644 --- a/devices/src/virtio/console/device.rs +++ b/devices/src/virtio/console/device.rs @@ -9,7 +9,7 @@ use data_model::Le32; use hypervisor::ProtectionType; use serde::Deserialize; use serde::Serialize; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::base_features; use crate::virtio::console::port::ConsolePort; diff --git a/devices/src/virtio/descriptor_utils.rs b/devices/src/virtio/descriptor_utils.rs index 36e240e20..1191f2e16 100644 --- a/devices/src/virtio/descriptor_utils.rs +++ b/devices/src/virtio/descriptor_utils.rs @@ -25,9 +25,10 @@ use disk::AsyncDisk; use smallvec::SmallVec; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use super::DescriptorChain; use crate::virtio::SplitDescriptorChain; @@ -533,7 +534,7 @@ impl Writer { } /// Writes an object to the descriptor chain buffer. - pub fn write_obj(&mut self, val: T) -> io::Result<()> { + pub fn write_obj(&mut self, val: T) -> io::Result<()> { self.write_all(val.as_bytes()) } @@ -541,12 +542,18 @@ impl Writer { /// this doesn't require the values to be stored in an intermediate collection first. It also /// allows callers to choose which elements in a collection to write, for example by using the /// `filter` or `take` methods of the `Iterator` trait. - pub fn write_iter>(&mut self, mut iter: I) -> io::Result<()> { + pub fn write_iter>( + &mut self, + mut iter: I, + ) -> io::Result<()> { iter.try_for_each(|v| self.write_obj(v)) } /// Writes a collection of objects into the descriptor chain buffer. - pub fn consume>(&mut self, vals: C) -> io::Result<()> { + pub fn consume>( + &mut self, + vals: C, + ) -> io::Result<()> { self.write_iter(vals.into_iter()) } @@ -766,7 +773,7 @@ pub enum DescriptorType { Writable, } -#[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtq_desc { addr: Le64, diff --git a/devices/src/virtio/device_constants.rs b/devices/src/virtio/device_constants.rs index b40695cf4..e4ef9e4ca 100644 --- a/devices/src/virtio/device_constants.rs +++ b/devices/src/virtio/device_constants.rs @@ -11,9 +11,10 @@ use data_model::Le32; use data_model::Le64; use serde::Deserialize; use serde::Serialize; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; /// Virtio feature bits that are specific to a device type. /// @@ -44,7 +45,7 @@ pub mod block { pub const VIRTIO_BLK_F_DISCARD: u32 = 13; pub const VIRTIO_BLK_F_WRITE_ZEROES: u32 = 14; - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_blk_geometry { cylinders: Le16, @@ -52,7 +53,7 @@ pub mod block { sectors: u8, } - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_blk_topology { physical_block_exp: u8, @@ -61,7 +62,7 @@ pub mod block { opt_io_size: Le32, } - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct virtio_blk_config { pub capacity: Le64, @@ -82,7 +83,7 @@ pub mod block { pub unused1: [u8; 3], } - #[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub(crate) struct virtio_blk_req_header { pub req_type: Le32, @@ -90,7 +91,7 @@ pub mod block { pub sector: Le64, } - #[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub(crate) struct virtio_blk_discard_write_zeroes { pub sector: Le64, @@ -122,7 +123,7 @@ pub mod gpu { pub const VIRTIO_GPU_SHM_ID_HOST_VISIBLE: u8 = 0x0001; - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_config { pub events_read: Le32, @@ -139,9 +140,10 @@ pub mod snd { Copy, Clone, Default, - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Serialize, Deserialize, PartialEq, @@ -166,9 +168,10 @@ pub mod video { use serde::Deserialize; use serde::Serialize; use serde_keyvalue::FromKeyValues; - use zerocopy::AsBytes; use zerocopy::FromBytes; - use zerocopy::FromZeroes; + use zerocopy::Immutable; + use zerocopy::IntoBytes; + use zerocopy::KnownLayout; pub const CMD_QUEUE_INDEX: usize = 0; pub const EVENT_QUEUE_INDEX: usize = 1; @@ -235,7 +238,7 @@ pub mod video { } #[repr(C)] - #[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] + #[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_config { pub version: Le32, pub max_caps_length: Le32, @@ -259,15 +262,16 @@ pub mod wl { pub mod console { use data_model::Le16; use data_model::Le32; - use zerocopy::AsBytes; use zerocopy::FromBytes; - use zerocopy::FromZeroes; + use zerocopy::Immutable; + use zerocopy::IntoBytes; + use zerocopy::KnownLayout; pub const VIRTIO_CONSOLE_F_SIZE: u32 = 0; pub const VIRTIO_CONSOLE_F_MULTIPORT: u32 = 1; pub const VIRTIO_CONSOLE_F_EMERG_WRITE: u32 = 2; - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_console_config { pub cols: Le16, @@ -276,7 +280,7 @@ pub mod console { pub emerg_wr: Le32, } - #[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_console_control { pub id: Le32, @@ -284,7 +288,7 @@ pub mod console { pub value: Le16, } - #[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_console_resize { pub cols: Le16, diff --git a/devices/src/virtio/fs/arc_ioctl.rs b/devices/src/virtio/fs/arc_ioctl.rs index 74b41697c..6533e1501 100644 --- a/devices/src/virtio/fs/arc_ioctl.rs +++ b/devices/src/virtio/fs/arc_ioctl.rs @@ -4,16 +4,17 @@ //! Data structures and logic for virtio-fs IOCTLs specific to ARCVM. -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const FS_IOCTL_PATH_MAX_LEN: usize = 128; pub const FS_IOCTL_XATTR_NAME_MAX_LEN: usize = 128; pub const FS_IOCTL_XATTR_VALUE_MAX_LEN: usize = 128; #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct FsPermissionDataBuffer { pub guest_uid: u32, pub guest_gid: u32, @@ -37,7 +38,7 @@ impl XattrData { } } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct FsPathXattrDataBuffer { pub path: [u8; FS_IOCTL_PATH_MAX_LEN], pub xattr_name: [u8; FS_IOCTL_XATTR_NAME_MAX_LEN], diff --git a/devices/src/virtio/fs/mod.rs b/devices/src/virtio/fs/mod.rs index 8a32b4953..84a752c5d 100644 --- a/devices/src/virtio/fs/mod.rs +++ b/devices/src/virtio/fs/mod.rs @@ -24,7 +24,7 @@ use virtio_sys::virtio_fs::VIRTIO_FS_SHMCAP_ID_CACHE; use vm_control::FsMappingRequest; use vm_control::VmResponse; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::pci::PciAddress; use crate::pci::PciBarConfiguration; diff --git a/devices/src/virtio/fs/passthrough.rs b/devices/src/virtio/fs/passthrough.rs index a37e473a2..21276652a 100644 --- a/devices/src/virtio/fs/passthrough.rs +++ b/devices/src/virtio/fs/passthrough.rs @@ -76,9 +76,11 @@ use system_api::client::OrgChromiumSpaced; use system_api::spaced::SetProjectIdReply; #[cfg(feature = "arc_quota")] use system_api::spaced::SetProjectInheritanceFlagReply; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::FromZeros; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[cfg(feature = "arc_quota")] use crate::virtio::fs::arc_ioctl::FsPathXattrDataBuffer; @@ -124,7 +126,7 @@ macro_rules! fs_trace { } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] struct fscrypt_policy_v1 { _version: u8, _contents_encryption_mode: u8, @@ -134,7 +136,7 @@ struct fscrypt_policy_v1 { } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] struct fscrypt_policy_v2 { _version: u8, _contents_encryption_mode: u8, @@ -145,7 +147,7 @@ struct fscrypt_policy_v2 { } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] union fscrypt_policy { _version: u8, _v1: fscrypt_policy_v1, @@ -153,7 +155,7 @@ union fscrypt_policy { } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] struct fscrypt_get_policy_ex_arg { policy_size: u64, /* input/output */ policy: fscrypt_policy, /* output */ @@ -176,7 +178,7 @@ impl From<&fscrypt_get_policy_ex_arg> for &[u8] { ioctl_iowr_nr!(FS_IOC_GET_ENCRYPTION_POLICY_EX, 'f' as u32, 22, [u8; 9]); #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] struct fsxattr { fsx_xflags: u32, /* xflags field value (get/set) */ fsx_extsize: u32, /* extsize field value (get/set) */ @@ -204,7 +206,7 @@ ioctl_iow_nr!(FS_IOC_SETPERMISSION, 'f' as u32, 1, FsPermissionDataBuffer); ioctl_iow_nr!(FS_IOC_SETPATHXATTR, 'f' as u32, 1, FsPathXattrDataBuffer); #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] struct fsverity_enable_arg { _version: u32, _hash_algorithm: u32, @@ -218,7 +220,7 @@ struct fsverity_enable_arg { } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] struct fsverity_digest { _digest_algorithm: u16, digest_size: u16, @@ -1358,7 +1360,7 @@ impl PassthroughFs { // SAFETY: this struct only has integer fields and any value is valid. let mut arg = unsafe { MaybeUninit::::zeroed().assume_init() }; - r.read_exact(arg.policy_size.as_bytes_mut())?; + r.read_exact(arg.policy_size.as_mut_bytes())?; let policy_size = cmp::min(arg.policy_size, size_of::() as u64); arg.policy_size = policy_size; @@ -1408,7 +1410,7 @@ impl PassthroughFs { }; let mut in_attr = fsxattr::new_zeroed(); - r.read_exact(in_attr.as_bytes_mut())?; + r.read_exact(in_attr.as_mut_bytes())?; #[cfg(feature = "arc_quota")] let st = stat(&*data)?; @@ -1501,7 +1503,7 @@ impl PassthroughFs { // The ioctl encoding is a long but the parameter is actually an int. let mut in_flags: c_int = 0; - r.read_exact(in_flags.as_bytes_mut())?; + r.read_exact(in_flags.as_mut_bytes())?; #[cfg(feature = "arc_quota")] let st = stat(&*data)?; @@ -1619,7 +1621,7 @@ impl PassthroughFs { }; let mut arg = fsverity_enable_arg::new_zeroed(); - r.read_exact(arg.as_bytes_mut())?; + r.read_exact(arg.as_mut_bytes())?; let mut salt; if arg.salt_size > 0 { @@ -1672,7 +1674,7 @@ impl PassthroughFs { }; let mut digest = fsverity_digest::new_zeroed(); - r.read_exact(digest.as_bytes_mut())?; + r.read_exact(digest.as_mut_bytes())?; // Taken from fs/verity/fsverity_private.h. const FS_VERITY_MAX_DIGEST_SIZE: u16 = 64; @@ -1877,7 +1879,7 @@ impl PassthroughFs { fn read_permission_data(&self, mut r: R) -> io::Result { let mut fs_permission_data = FsPermissionDataBuffer::new_zeroed(); - r.read_exact(fs_permission_data.as_bytes_mut())?; + r.read_exact(fs_permission_data.as_mut_bytes())?; let perm_path = self.string_from_u8_slice(&fs_permission_data.perm_path)?; if !perm_path.starts_with('/') { @@ -1964,7 +1966,7 @@ impl PassthroughFs { fn read_xattr_data(&self, mut r: R) -> io::Result { let mut fs_path_xattr_data = FsPathXattrDataBuffer::new_zeroed(); - r.read_exact(fs_path_xattr_data.as_bytes_mut())?; + r.read_exact(fs_path_xattr_data.as_mut_bytes())?; let xattr_path = self.string_from_u8_slice(&fs_path_xattr_data.path)?; if !xattr_path.starts_with('/') { diff --git a/devices/src/virtio/fs/read_dir.rs b/devices/src/virtio/fs/read_dir.rs index d210932d3..1079b6830 100644 --- a/devices/src/virtio/fs/read_dir.rs +++ b/devices/src/virtio/fs/read_dir.rs @@ -11,12 +11,13 @@ use std::ops::DerefMut; use base::AsRawDescriptor; use fuse::filesystem::DirEntry; use fuse::filesystem::DirectoryIterator; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[repr(C, packed)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] struct LinuxDirent64 { d_ino: libc::ino64_t, d_off: libc::off64_t, @@ -76,17 +77,8 @@ impl> DirectoryIterator for ReadDir

{ return None; } - // We only use debug asserts here because these values are coming from the kernel and we - // trust them implicitly. - debug_assert!( - rem.len() >= size_of::(), - "not enough space left in `rem`" - ); - - let (front, back) = rem.split_at(size_of::()); - - let dirent64 = - LinuxDirent64::read_from(front).expect("unable to get LinuxDirent64 from slice"); + let (dirent64, back) = + LinuxDirent64::read_from_prefix(rem).expect("unable to get LinuxDirent64 from slice"); let namelen = dirent64.d_reclen as usize - size_of::(); debug_assert!(namelen <= back.len(), "back is smaller than `namelen`"); diff --git a/devices/src/virtio/gpu/mod.rs b/devices/src/virtio/gpu/mod.rs index fe953f65a..2a376eb75 100644 --- a/devices/src/virtio/gpu/mod.rs +++ b/devices/src/virtio/gpu/mod.rs @@ -65,7 +65,7 @@ pub use vm_control::gpu::DEFAULT_REFRESH_RATE; use vm_control::ModifyWaitContext; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; pub use self::protocol::virtio_gpu_config; pub use self::protocol::VIRTIO_GPU_F_CONTEXT_INIT; @@ -1842,7 +1842,7 @@ impl VirtioDevice for Gpu { fn write_config(&mut self, offset: u64, data: &[u8]) { let mut cfg = self.get_config(); - copy_config(cfg.as_bytes_mut(), offset, data, 0); + copy_config(cfg.as_mut_bytes(), offset, data, 0); if (cfg.events_clear.to_native() & VIRTIO_GPU_EVENT_DISPLAY) != 0 { self.display_event.store(false, Ordering::Relaxed); } diff --git a/devices/src/virtio/gpu/protocol.rs b/devices/src/virtio/gpu/protocol.rs index 379552a08..f8535923e 100644 --- a/devices/src/virtio/gpu/protocol.rs +++ b/devices/src/virtio/gpu/protocol.rs @@ -25,9 +25,10 @@ use remain::sorted; use rutabaga_gfx::RutabagaError; use thiserror::Error; use vm_memory::udmabuf::UdmabufError; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub use super::super::device_constants::gpu::virtio_gpu_config; pub use super::super::device_constants::gpu::VIRTIO_GPU_F_CONTEXT_INIT; @@ -157,7 +158,7 @@ pub const VIRTIO_GPU_FLAG_FENCE: u32 = 1 << 0; pub const VIRTIO_GPU_FLAG_INFO_RING_IDX: u32 = 1 << 1; pub const VIRTIO_GPU_FLAG_FENCE_HOST_SHAREABLE: u32 = 1 << 2; -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_ctrl_hdr { pub type_: Le32, @@ -170,7 +171,7 @@ pub struct virtio_gpu_ctrl_hdr { /* data passed in the cursor vq */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_cursor_pos { pub scanout_id: Le32, @@ -180,7 +181,7 @@ pub struct virtio_gpu_cursor_pos { } /* VIRTIO_GPU_CMD_UPDATE_CURSOR, VIRTIO_GPU_CMD_MOVE_CURSOR */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_update_cursor { pub hdr: virtio_gpu_ctrl_hdr, @@ -193,7 +194,7 @@ pub struct virtio_gpu_update_cursor { /* data passed in the control vq, 2d related */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_rect { pub x: Le32, @@ -203,7 +204,7 @@ pub struct virtio_gpu_rect { } /* VIRTIO_GPU_CMD_RESOURCE_UNREF */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_unref { pub hdr: virtio_gpu_ctrl_hdr, @@ -212,7 +213,7 @@ pub struct virtio_gpu_resource_unref { } /* VIRTIO_GPU_CMD_RESOURCE_CREATE_2D: create a 2d resource with a format */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_create_2d { pub hdr: virtio_gpu_ctrl_hdr, @@ -223,7 +224,7 @@ pub struct virtio_gpu_resource_create_2d { } /* VIRTIO_GPU_CMD_SET_SCANOUT */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_set_scanout { pub hdr: virtio_gpu_ctrl_hdr, @@ -233,7 +234,7 @@ pub struct virtio_gpu_set_scanout { } /* VIRTIO_GPU_CMD_RESOURCE_FLUSH */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_flush { pub hdr: virtio_gpu_ctrl_hdr, @@ -243,7 +244,7 @@ pub struct virtio_gpu_resource_flush { } /* VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D: simple transfer to_host */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_transfer_to_host_2d { pub hdr: virtio_gpu_ctrl_hdr, @@ -253,7 +254,7 @@ pub struct virtio_gpu_transfer_to_host_2d { pub padding: Le32, } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_mem_entry { pub addr: Le64, @@ -262,7 +263,7 @@ pub struct virtio_gpu_mem_entry { } /* VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_attach_backing { pub hdr: virtio_gpu_ctrl_hdr, @@ -271,7 +272,7 @@ pub struct virtio_gpu_resource_attach_backing { } /* VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_detach_backing { pub hdr: virtio_gpu_ctrl_hdr, @@ -279,7 +280,7 @@ pub struct virtio_gpu_resource_detach_backing { pub padding: Le32, } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_display_one { pub r: virtio_gpu_rect, @@ -289,7 +290,7 @@ pub struct virtio_gpu_display_one { /* VIRTIO_GPU_RESP_OK_DISPLAY_INFO */ pub const VIRTIO_GPU_MAX_SCANOUTS: usize = 16; -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resp_display_info { pub hdr: virtio_gpu_ctrl_hdr, @@ -298,7 +299,7 @@ pub struct virtio_gpu_resp_display_info { /* data passed in the control vq, 3d related */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_box { pub x: Le32, @@ -310,7 +311,7 @@ pub struct virtio_gpu_box { } /* VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D, VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_transfer_host_3d { pub hdr: virtio_gpu_ctrl_hdr, @@ -324,7 +325,7 @@ pub struct virtio_gpu_transfer_host_3d { /* VIRTIO_GPU_CMD_RESOURCE_CREATE_3D */ pub const VIRTIO_GPU_RESOURCE_FLAG_Y_0_TOP: u32 = 1 << 0; -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_create_3d { pub hdr: virtio_gpu_ctrl_hdr, @@ -344,7 +345,7 @@ pub struct virtio_gpu_resource_create_3d { /* VIRTIO_GPU_CMD_CTX_CREATE */ pub const VIRTIO_GPU_CONTEXT_INIT_CAPSET_ID_MASK: u32 = 1 << 0; -#[derive(Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_ctx_create { pub hdr: virtio_gpu_ctrl_hdr, @@ -378,14 +379,14 @@ impl fmt::Debug for virtio_gpu_ctx_create { } /* VIRTIO_GPU_CMD_CTX_DESTROY */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_ctx_destroy { pub hdr: virtio_gpu_ctrl_hdr, } /* VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE, VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_ctx_resource { pub hdr: virtio_gpu_ctrl_hdr, @@ -394,7 +395,7 @@ pub struct virtio_gpu_ctx_resource { } /* VIRTIO_GPU_CMD_SUBMIT_3D */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_cmd_submit { pub hdr: virtio_gpu_ctrl_hdr, @@ -422,7 +423,7 @@ pub const VIRTIO_GPU_CAPSET_VENUS: u32 = 4; pub const VIRTIO_GPU_CAPSET_CROSS_DOMAIN: u32 = 5; /* VIRTIO_GPU_CMD_GET_CAPSET_INFO */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_get_capset_info { pub hdr: virtio_gpu_ctrl_hdr, @@ -431,7 +432,7 @@ pub struct virtio_gpu_get_capset_info { } /* VIRTIO_GPU_RESP_OK_CAPSET_INFO */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resp_capset_info { pub hdr: virtio_gpu_ctrl_hdr, @@ -442,7 +443,7 @@ pub struct virtio_gpu_resp_capset_info { } /* VIRTIO_GPU_CMD_GET_CAPSET */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_get_capset { pub hdr: virtio_gpu_ctrl_hdr, @@ -459,7 +460,7 @@ pub struct virtio_gpu_resp_capset { } /* VIRTIO_GPU_CMD_GET_EDID */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_get_edid { pub hdr: virtio_gpu_ctrl_hdr, @@ -468,7 +469,7 @@ pub struct virtio_gpu_get_edid { } /* VIRTIO_GPU_RESP_OK_EDID */ -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resp_get_edid { pub hdr: virtio_gpu_ctrl_hdr, @@ -478,7 +479,7 @@ pub struct virtio_gpu_resp_get_edid { } /* VIRTIO_GPU_RESP_OK_RESOURCE_PLANE_INFO */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resp_resource_plane_info { pub hdr: virtio_gpu_ctrl_hdr, @@ -493,7 +494,7 @@ pub const PLANE_INFO_MAX_COUNT: usize = 4; pub const VIRTIO_GPU_EVENT_DISPLAY: u32 = 1 << 0; -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_create_blob { pub hdr: virtio_gpu_ctrl_hdr, @@ -505,7 +506,7 @@ pub struct virtio_gpu_resource_create_blob { pub size: Le64, } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_map_blob { pub hdr: virtio_gpu_ctrl_hdr, @@ -514,7 +515,7 @@ pub struct virtio_gpu_resource_map_blob { pub offset: Le64, } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_unmap_blob { pub hdr: virtio_gpu_ctrl_hdr, @@ -522,7 +523,7 @@ pub struct virtio_gpu_resource_unmap_blob { pub padding: Le32, } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resp_map_info { pub hdr: virtio_gpu_ctrl_hdr, @@ -530,7 +531,7 @@ pub struct virtio_gpu_resp_map_info { pub padding: u32, } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resource_assign_uuid { pub hdr: virtio_gpu_ctrl_hdr, @@ -538,7 +539,7 @@ pub struct virtio_gpu_resource_assign_uuid { pub padding: Le32, } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_resp_resource_uuid { pub hdr: virtio_gpu_ctrl_hdr, @@ -546,7 +547,7 @@ pub struct virtio_gpu_resp_resource_uuid { } /* VIRTIO_GPU_CMD_SET_SCANOUT_BLOB */ -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_gpu_set_scanout_blob { pub hdr: virtio_gpu_ctrl_hdr, diff --git a/devices/src/virtio/input/event_source.rs b/devices/src/virtio/input/event_source.rs index 583827c68..d0ceb66f4 100644 --- a/devices/src/virtio/input/event_source.rs +++ b/devices/src/virtio/input/event_source.rs @@ -13,7 +13,7 @@ use linux_input_sys::constants::*; use linux_input_sys::input_event; use linux_input_sys::virtio_input_event; use linux_input_sys::InputEventDecoder; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use super::evdev::grab_evdev; use super::evdev::ungrab_evdev; @@ -253,7 +253,7 @@ mod tests { use data_model::Le16; use data_model::SLe32; use linux_input_sys::InputEventDecoder; - use zerocopy::AsBytes; + use zerocopy::IntoBytes; use crate::virtio::input::event_source::input_event; use crate::virtio::input::event_source::virtio_input_event; diff --git a/devices/src/virtio/input/mod.rs b/devices/src/virtio/input/mod.rs index 8688b8525..faeb550b8 100644 --- a/devices/src/virtio/input/mod.rs +++ b/devices/src/virtio/input/mod.rs @@ -38,9 +38,10 @@ use serde::Serialize; use snapshot::AnySnapshot; use thiserror::Error; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use self::event_source::EvdevEventSource; use self::event_source::EventSource; @@ -105,7 +106,18 @@ pub enum InputError { pub type Result = std::result::Result; -#[derive(Copy, Clone, Default, Debug, AsBytes, FromZeroes, FromBytes, Serialize, Deserialize)] +#[derive( + Copy, + Clone, + Default, + Debug, + FromBytes, + Immutable, + IntoBytes, + KnownLayout, + Serialize, + Deserialize, +)] #[repr(C)] pub struct virtio_input_device_ids { bustype: Le16, @@ -126,7 +138,17 @@ impl virtio_input_device_ids { } #[derive( - Copy, Clone, Default, Debug, AsBytes, FromZeroes, FromBytes, PartialEq, Serialize, Deserialize, + Copy, + Clone, + Default, + Debug, + FromBytes, + Immutable, + IntoBytes, + KnownLayout, + PartialEq, + Serialize, + Deserialize, )] #[repr(C)] pub struct virtio_input_absinfo { @@ -147,7 +169,7 @@ impl virtio_input_absinfo { } } -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtio_input_config { select: u8, @@ -352,7 +374,7 @@ impl VirtioInputConfig { fn write(&mut self, offset: usize, data: &[u8]) { let mut config = self.build_config_memory(); - copy_config(config.as_bytes_mut(), offset as u64, data, 0); + copy_config(config.as_mut_bytes(), offset as u64, data, 0); self.select = config.select; self.subsel = config.subsel; } diff --git a/devices/src/virtio/iommu.rs b/devices/src/virtio/iommu.rs index bec053cf0..c9061cc29 100644 --- a/devices/src/virtio/iommu.rs +++ b/devices/src/virtio/iommu.rs @@ -52,11 +52,13 @@ use vm_control::VmMemoryRegionId; use vm_memory::GuestAddress; use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; -use zerocopy::AsBytes; #[cfg(target_arch = "x86_64")] use zerocopy::FromBytes; #[cfg(target_arch = "x86_64")] -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +#[cfg(target_arch = "x86_64")] +use zerocopy::KnownLayout; #[cfg(target_arch = "x86_64")] use crate::pci::PciAddress; @@ -86,7 +88,7 @@ const VIRTIO_IOMMU_VIOT_NODE_PCI_RANGE: u8 = 1; #[cfg(target_arch = "x86_64")] const VIRTIO_IOMMU_VIOT_NODE_VIRTIO_IOMMU_PCI: u8 = 3; -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] #[cfg(target_arch = "x86_64")] struct VirtioIommuViotHeader { @@ -95,7 +97,7 @@ struct VirtioIommuViotHeader { reserved: [u8; 8], } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] #[cfg(target_arch = "x86_64")] struct VirtioIommuViotVirtioPciNode { @@ -107,7 +109,7 @@ struct VirtioIommuViotVirtioPciNode { reserved2: [u8; 8], } -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] #[cfg(target_arch = "x86_64")] struct VirtioIommuViotPciRangeNode { diff --git a/devices/src/virtio/iommu/ipc_memory_mapper.rs b/devices/src/virtio/iommu/ipc_memory_mapper.rs index e1edfbbac..7c1e4a503 100644 --- a/devices/src/virtio/iommu/ipc_memory_mapper.rs +++ b/devices/src/virtio/iommu/ipc_memory_mapper.rs @@ -23,8 +23,10 @@ use smallvec::SmallVec; use sync::Mutex; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::FromZeros; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::virtio::memory_mapper::MemRegion; @@ -277,13 +279,13 @@ impl ExportedRegion { /// Reads an object from the given iova. Fails if the specified iova range does /// not lie within this region, or if part of the region isn't readable. - pub fn read_obj_from_addr( + pub fn read_obj_from_addr( &self, mem: &GuestMemory, iova: u64, ) -> anyhow::Result { let mut val = T::new_zeroed(); - let buf = val.as_bytes_mut(); + let buf = val.as_mut_bytes(); self.do_copy(iova, buf.len(), Protection::read(), |offset, gpa, len| { mem.read_at_addr(&mut buf[offset..(offset + len)], gpa) .context("failed to read from gpa") @@ -293,7 +295,7 @@ impl ExportedRegion { /// Writes an object at a given iova. Fails if the specified iova range does /// not lie within this region, or if part of the region isn't writable. - pub fn write_obj_at_addr( + pub fn write_obj_at_addr( &self, mem: &GuestMemory, val: T, diff --git a/devices/src/virtio/iommu/protocol.rs b/devices/src/virtio/iommu/protocol.rs index 3e99bee95..7e1161599 100644 --- a/devices/src/virtio/iommu/protocol.rs +++ b/devices/src/virtio/iommu/protocol.rs @@ -17,7 +17,7 @@ //! The main points of the manual modifications are as follows: //! * Removed `head` and `tail` from each command struct. Instead, we process //! them as separate payloads. -//! * Derive implementations of zerocopy::{AsBytes, FromZeroes, FromBytes} as needed. +//! * Derive implementations of zerocopy traits as needed. //! * Use of `packed` because removing `head` and `tail` introduces paddings //! * Remove `IncompleteArrayField` //! * Convert padding of [u8; 64usize] to [u64; 8usize]. According to the rust @@ -30,9 +30,10 @@ use data_model::Le16; use data_model::Le32; use data_model::Le64; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const VIRTIO_IOMMU_F_INPUT_RANGE: u32 = 0; pub const VIRTIO_IOMMU_F_DOMAIN_RANGE: u32 = 1; @@ -72,21 +73,21 @@ pub const VIRTIO_IOMMU_FAULT_F_EXEC: u32 = 4; pub const VIRTIO_IOMMU_FAULT_F_ADDRESS: u32 = 256; #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_range_64 { pub start: Le64, pub end: Le64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_range_32 { pub start: Le32, pub end: Le32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_config { pub page_size_mask: Le64, pub input_range: virtio_iommu_range_64, @@ -95,21 +96,21 @@ pub struct virtio_iommu_config { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_head { pub type_: u8, pub reserved: [u8; 3usize], } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_tail { pub status: u8, pub reserved: [u8; 3usize], } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_attach { pub domain: Le32, pub endpoint: Le32, @@ -117,7 +118,7 @@ pub struct virtio_iommu_req_attach { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_detach { pub domain: Le32, pub endpoint: Le32, @@ -125,7 +126,7 @@ pub struct virtio_iommu_req_detach { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_map { pub domain: Le32, pub virt_start: Le64, @@ -135,7 +136,7 @@ pub struct virtio_iommu_req_map { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_unmap { pub domain: Le32, pub virt_start: Le64, @@ -144,14 +145,14 @@ pub struct virtio_iommu_req_unmap { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_probe_property { pub type_: Le16, pub length: Le16, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_probe_resv_mem { pub head: virtio_iommu_probe_property, pub subtype: u8, @@ -161,7 +162,7 @@ pub struct virtio_iommu_probe_resv_mem { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_iommu_req_probe { pub endpoint: Le32, pub reserved: [u64; 8usize], diff --git a/devices/src/virtio/net.rs b/devices/src/virtio/net.rs index fa38bf3a8..9ee6df8b8 100644 --- a/devices/src/virtio/net.rs +++ b/devices/src/virtio/net.rs @@ -45,9 +45,10 @@ use virtio_sys::virtio_net::VIRTIO_NET_CTRL_MQ_VQ_PAIRS_SET; use virtio_sys::virtio_net::VIRTIO_NET_ERR; use virtio_sys::virtio_net::VIRTIO_NET_OK; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use super::copy_config; use super::DeviceType; @@ -218,13 +219,13 @@ impl FromStr for NetParameters { } #[repr(C, packed)] -#[derive(Debug, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_net_ctrl_hdr { pub class: u8, pub cmd: u8, } -#[derive(Debug, Clone, Copy, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct VirtioNetConfig { mac: [u8; 6], diff --git a/devices/src/virtio/pmem.rs b/devices/src/virtio/pmem.rs index eae69e415..0279d10eb 100644 --- a/devices/src/virtio/pmem.rs +++ b/devices/src/virtio/pmem.rs @@ -37,9 +37,10 @@ use vm_control::VmMemoryMappingRequest; use vm_control::VmMemoryMappingResponse; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use super::async_utils; use super::copy_config; @@ -60,26 +61,26 @@ const VIRTIO_PMEM_REQ_TYPE_DISCARD: u32 = u32::MAX; const VIRTIO_PMEM_RESP_TYPE_OK: u32 = 0; const VIRTIO_PMEM_RESP_TYPE_EIO: u32 = 1; -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtio_pmem_config { start_address: Le64, size: Le64, } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtio_pmem_resp { status_code: Le32, } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtio_pmem_req { type_: Le32, } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct virtio_pmem_range_req { type_: Le32, diff --git a/devices/src/virtio/pvclock.rs b/devices/src/virtio/pvclock.rs index d687d7383..49f6a461f 100644 --- a/devices/src/virtio/pvclock.rs +++ b/devices/src/virtio/pvclock.rs @@ -83,9 +83,10 @@ use vm_control::PvClockCommandResponse; use vm_memory::GuestAddress; use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use super::copy_config; use super::DeviceType; @@ -187,7 +188,7 @@ fn freq_scale_shift(scaled_hz: u64, base_hz: u64) -> (u32, i8) { // The config structure being exposed to the guest to tell them how much suspend time should be // injected to the guest's CLOCK_BOOTTIME. -#[derive(Debug, Clone, Copy, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[allow(non_camel_case_types)] #[repr(C)] struct virtio_pvclock_config { @@ -199,7 +200,7 @@ struct virtio_pvclock_config { padding: u32, } -#[derive(Debug, Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[allow(non_camel_case_types)] #[repr(C)] struct virtio_pvclock_set_pvclock_page_req { diff --git a/devices/src/virtio/queue/packed_descriptor_chain.rs b/devices/src/virtio/queue/packed_descriptor_chain.rs index f795bc0ec..3c4f5b7fe 100644 --- a/devices/src/virtio/queue/packed_descriptor_chain.rs +++ b/devices/src/virtio/queue/packed_descriptor_chain.rs @@ -16,9 +16,10 @@ use data_model::Le32; use data_model::Le64; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::descriptor_chain::Descriptor; use crate::virtio::descriptor_chain::DescriptorAccess; @@ -38,7 +39,7 @@ pub const RING_EVENT_FLAGS_DISABLE: u16 = 0x1; pub const RING_EVENT_FLAGS_DESC: u16 = 0x2; /// A packed virtio packed queue descriptor (`struct pvirtq_desc` in the spec). -#[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct PackedDesc { /// Guest address of memory buffer address @@ -83,7 +84,7 @@ impl PackedDesc { } } -#[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct PackedDescEvent { pub desc: Le16, diff --git a/devices/src/virtio/queue/split_descriptor_chain.rs b/devices/src/virtio/queue/split_descriptor_chain.rs index d7da10001..9d8f3d9f8 100644 --- a/devices/src/virtio/queue/split_descriptor_chain.rs +++ b/devices/src/virtio/queue/split_descriptor_chain.rs @@ -15,9 +15,10 @@ use data_model::Le32; use data_model::Le64; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::descriptor_chain::Descriptor; use crate::virtio::descriptor_chain::DescriptorAccess; @@ -26,7 +27,7 @@ use crate::virtio::descriptor_chain::VIRTQ_DESC_F_NEXT; use crate::virtio::descriptor_chain::VIRTQ_DESC_F_WRITE; /// A single virtio split queue descriptor (`struct virtq_desc` in the spec). -#[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct Desc { /// Guest address of memory described by this descriptor. diff --git a/devices/src/virtio/queue/split_queue.rs b/devices/src/virtio/queue/split_queue.rs index c63f8680d..3046f2268 100644 --- a/devices/src/virtio/queue/split_queue.rs +++ b/devices/src/virtio/queue/split_queue.rs @@ -18,9 +18,10 @@ use snapshot::AnySnapshot; use virtio_sys::virtio_ring::VIRTIO_RING_F_EVENT_IDX; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::DescriptorChain; use crate::virtio::Interrupt; @@ -78,7 +79,7 @@ pub struct SplitQueueSnapshot { } #[repr(C)] -#[derive(AsBytes, FromZeroes, FromBytes)] +#[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] struct virtq_used_elem { id: Le32, len: Le32, @@ -572,8 +573,10 @@ mod tests { use data_model::Le16; use data_model::Le32; use data_model::Le64; - use zerocopy::AsBytes; use zerocopy::FromBytes; + use zerocopy::Immutable; + use zerocopy::IntoBytes; + use zerocopy::KnownLayout; use super::*; use crate::virtio::create_descriptor_chain; @@ -589,7 +592,7 @@ mod tests { const BUFFER_OFFSET: u64 = 0x8000; const BUFFER_LEN: u32 = 0x400; - #[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct Avail { flags: Le16, @@ -609,7 +612,7 @@ mod tests { } } - #[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] struct UsedElem { id: Le32, @@ -625,7 +628,7 @@ mod tests { } } - #[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] + #[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] struct Used { flags: Le16, diff --git a/devices/src/virtio/scsi/commands.rs b/devices/src/virtio/scsi/commands.rs index e59a212e7..2aa790a34 100644 --- a/devices/src/virtio/scsi/commands.rs +++ b/devices/src/virtio/scsi/commands.rs @@ -10,9 +10,10 @@ use base::warn; use data_model::Be16; use data_model::Be32; use data_model::Be64; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::scsi::constants::INQUIRY; use crate::virtio::scsi::constants::MAINTENANCE_IN; @@ -83,7 +84,8 @@ impl Command { } fn parse_command(cdb: &[u8]) -> Result { - T::read_from_prefix(cdb).ok_or(ExecuteError::ReadCommand) + let (command, _) = T::read_from_prefix(cdb).map_err(|_| ExecuteError::ReadCommand)?; + Ok(command) } fn parse_maintenance_in(cdb: &[u8]) -> Result { @@ -148,7 +150,9 @@ impl Command { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct TestUnitReady { opcode: u8, @@ -189,7 +193,9 @@ async fn read_from_disk( }) } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct Read6 { opcode: u8, @@ -230,7 +236,9 @@ impl Read6 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct Inquiry { opcode: u8, @@ -433,7 +441,9 @@ fn fill_mode_page( // According to the spec, devices that implement MODE SENSE(6) shall also implement MODE SELECT(6) // as well. -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct ModeSelect6 { opcode: u8, @@ -450,7 +460,9 @@ impl ModeSelect6 { } fn emulate(&self, reader: &mut Reader, dev: &AsyncLogicalUnit) -> Result<(), ExecuteError> { - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] + #[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, + )] #[repr(C, packed)] struct BlockDescriptor { _density: u8, @@ -502,14 +514,18 @@ impl ModeSelect6 { } fn handle_mode_page(reader: &mut Reader) -> Result<(), ExecuteError> { - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] + #[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, + )] #[repr(C, packed)] struct Page0Header { page_code: u8, page_len: u8, } - #[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] + #[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, + )] #[repr(C, packed)] struct SubpageHeader { page_code: u8, @@ -546,7 +562,9 @@ impl ModeSelect6 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct ModeSense6 { opcode: u8, @@ -695,7 +713,9 @@ impl ModeSense6 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct ReadCapacity10 { opcode: u8, @@ -718,7 +738,9 @@ impl ReadCapacity10 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct ReadCapacity16 { opcode: u8, @@ -743,7 +765,9 @@ impl ReadCapacity16 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct Read10 { opcode: u8, @@ -775,7 +799,9 @@ impl Read10 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct Write10 { opcode: u8, @@ -830,7 +856,9 @@ async fn write_to_disk( }) } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct SynchronizeCache10 { opcode: u8, @@ -887,7 +915,9 @@ async fn write_same( } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct WriteSame10 { opcode: u8, @@ -942,7 +972,9 @@ impl WriteSame10 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct Unmap { opcode: u8, @@ -1008,7 +1040,9 @@ impl Unmap { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct WriteSame16 { opcode: u8, @@ -1060,7 +1094,9 @@ impl WriteSame16 { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct ReportLuns { opcode: u8, @@ -1097,7 +1133,9 @@ impl ReportLuns { } } -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes, PartialEq, Eq)] +#[derive( + Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout, PartialEq, Eq, +)] #[repr(C, packed)] pub struct ReportSupportedTMFs { opcode: u8, diff --git a/devices/src/virtio/scsi/device.rs b/devices/src/virtio/scsi/device.rs index f6203e2bb..90bf385ff 100644 --- a/devices/src/virtio/scsi/device.rs +++ b/devices/src/virtio/scsi/device.rs @@ -49,9 +49,10 @@ use virtio_sys::virtio_scsi::VIRTIO_SCSI_T_TMF; use virtio_sys::virtio_scsi::VIRTIO_SCSI_T_TMF_I_T_NEXUS_RESET; use virtio_sys::virtio_scsi::VIRTIO_SCSI_T_TMF_LOGICAL_UNIT_RESET; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::async_utils; use crate::virtio::block::sys::get_seg_max; @@ -98,7 +99,7 @@ const MAX_SECTORS: u32 = u32::MAX; const FIXED_FORMAT_SENSE_SIZE: u32 = 18; #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] struct VirtioScsiCmdReqHeader { lun: [u8; 8usize], tag: u64, @@ -108,7 +109,7 @@ struct VirtioScsiCmdReqHeader { } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] struct VirtioScsiCmdRespHeader { sense_len: u32, resid: u32, @@ -612,7 +613,7 @@ impl VirtioDevice for Controller { fn write_config(&mut self, offset: u64, data: &[u8]) { let mut config = self.build_config_space(); - copy_config(config.as_bytes_mut(), offset, data, 0); + copy_config(config.as_mut_bytes(), offset, data, 0); // Only `sense_size` and `cdb_size` are modifiable by the driver. self.sense_size = config.sense_size; self.cdb_size = config.cdb_size; diff --git a/devices/src/virtio/snd/common_backend/async_funcs.rs b/devices/src/virtio/snd/common_backend/async_funcs.rs index 0c0b7ae02..6647adb56 100644 --- a/devices/src/virtio/snd/common_backend/async_funcs.rs +++ b/devices/src/virtio/snd/common_backend/async_funcs.rs @@ -34,7 +34,7 @@ use futures::StreamExt; use thiserror::Error as ThisError; use vm_control::SndControlCommand; use vm_control::VmResponse; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use super::Error; use super::SndData; diff --git a/devices/src/virtio/snd/common_backend/mod.rs b/devices/src/virtio/snd/common_backend/mod.rs index 43c5aa936..0e8973949 100644 --- a/devices/src/virtio/snd/common_backend/mod.rs +++ b/devices/src/virtio/snd/common_backend/mod.rs @@ -42,7 +42,7 @@ use serde::Serialize; use snapshot::AnySnapshot; use thiserror::Error as ThisError; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::async_utils; use crate::virtio::copy_config; diff --git a/devices/src/virtio/snd/layout.rs b/devices/src/virtio/snd/layout.rs index 59baeac6e..4e8eb0995 100644 --- a/devices/src/virtio/snd/layout.rs +++ b/devices/src/virtio/snd/layout.rs @@ -6,34 +6,37 @@ use data_model::Le32; use data_model::Le64; use serde::Deserialize; use serde::Serialize; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::snd::constants::StatusCode; use crate::virtio::snd::constants::VIRTIO_SND_CHMAP_MAX_SIZE; -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes, Serialize, Deserialize)] +#[derive( + Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout, Serialize, Deserialize, +)] #[repr(C)] pub struct virtio_snd_hdr { pub code: Le32, } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_snd_jack_hdr { pub hdr: virtio_snd_hdr, pub jack_id: Le32, } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_snd_event { pub hdr: virtio_snd_hdr, pub data: Le32, } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_snd_query_info { pub hdr: virtio_snd_hdr, @@ -46,9 +49,10 @@ pub struct virtio_snd_query_info { Copy, Clone, Default, - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Serialize, Deserialize, PartialEq, @@ -64,9 +68,10 @@ pub struct virtio_snd_info { Copy, Clone, Default, - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Serialize, Deserialize, PartialEq, @@ -86,14 +91,18 @@ pub struct virtio_snd_pcm_info { pub padding: [u8; 5], } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes, Serialize, Deserialize)] +#[derive( + Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout, Serialize, Deserialize, +)] #[repr(C)] pub struct virtio_snd_pcm_hdr { pub hdr: virtio_snd_hdr, pub stream_id: Le32, } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes, Serialize, Deserialize)] +#[derive( + Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout, Serialize, Deserialize, +)] #[repr(C)] pub struct virtio_snd_pcm_set_params { pub hdr: virtio_snd_pcm_hdr, @@ -106,13 +115,13 @@ pub struct virtio_snd_pcm_set_params { pub padding: u8, } -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_snd_pcm_xfer { pub stream_id: Le32, } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_snd_pcm_status { pub status: Le32, @@ -132,9 +141,10 @@ impl virtio_snd_pcm_status { Copy, Clone, Default, - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Serialize, Deserialize, PartialEq, @@ -151,7 +161,7 @@ pub struct virtio_snd_jack_info { pub padding: [u8; 7], } -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_snd_jack_remap { pub hdr: virtio_snd_jack_hdr, /* .code = VIRTIO_SND_R_JACK_REMAP */ @@ -163,9 +173,10 @@ pub struct virtio_snd_jack_remap { Copy, Clone, Default, - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Serialize, Deserialize, PartialEq, diff --git a/devices/src/virtio/snd/vios_backend/mod.rs b/devices/src/virtio/snd/vios_backend/mod.rs index 84401163c..4f84b24c8 100644 --- a/devices/src/virtio/snd/vios_backend/mod.rs +++ b/devices/src/virtio/snd/vios_backend/mod.rs @@ -36,7 +36,7 @@ use sync::Mutex; use thiserror::Error as ThisError; use vm_memory::GuestMemory; use worker::*; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::copy_config; use crate::virtio::device_constants::snd::virtio_snd_config; diff --git a/devices/src/virtio/snd/vios_backend/shm_vios.rs b/devices/src/virtio/snd/vios_backend/shm_vios.rs index f69ce6d8f..c67039124 100644 --- a/devices/src/virtio/snd/vios_backend/shm_vios.rs +++ b/devices/src/virtio/snd/vios_backend/shm_vios.rs @@ -41,9 +41,10 @@ use serde::Deserialize; use serde::Serialize; use sync::Mutex; use thiserror::Error as ThisError; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::snd::constants::*; use crate::virtio::snd::layout::*; @@ -175,7 +176,7 @@ impl VioSClient { let mut config: VioSConfig = Default::default(); const NUM_FDS: usize = 5; let (recv_size, mut safe_fds) = client_socket - .recv_with_fds(config.as_bytes_mut(), NUM_FDS) + .recv_with_fds(config.as_mut_bytes(), NUM_FDS) .map_err(Error::ServerError)?; if recv_size != std::mem::size_of::() { @@ -499,7 +500,7 @@ impl VioSClient { Ok(()) } - fn request_info( + fn request_info( &self, req_code: u32, count: usize, @@ -515,13 +516,13 @@ impl VioSClient { size: (std::mem::size_of::() as u32).into(), }; let control_socket_lock = self.control_socket.lock(); - seq_socket_send(&control_socket_lock, req)?; + seq_socket_send(&control_socket_lock, req.as_bytes())?; let reply = control_socket_lock .recv_as_vec() .map_err(Error::ServerIOError)?; let mut status: virtio_snd_hdr = Default::default(); status - .as_bytes_mut() + .as_mut_bytes() .copy_from_slice(&reply[0..status_size]); if status.code.to_native() != VIRTIO_SND_S_OK { return Err(Error::CommandFailed(status.code.to_native())); @@ -533,7 +534,7 @@ impl VioSClient { } Ok(reply[status_size..] .chunks(info_size) - .map(|info_buffer| T::read_from(info_buffer).unwrap()) + .map(|info_buffer| T::read_from_bytes(info_buffer).unwrap()) .collect()) } @@ -630,7 +631,7 @@ fn recv_buffer_status_msg( ) -> Result<()> { let mut msg: IoStatusMsg = Default::default(); let size = socket - .recv(msg.as_bytes_mut()) + .recv(msg.as_mut_bytes()) .map_err(Error::ServerIOError)?; if size != std::mem::size_of::() { return Err(Error::ProtocolError( @@ -668,7 +669,7 @@ fn recv_buffer_status_msg( fn recv_event(socket: &UnixSeqpacket) -> Result { let mut msg: virtio_snd_event = Default::default(); let size = socket - .recv(msg.as_bytes_mut()) + .recv(msg.as_mut_bytes()) .map_err(Error::ServerIOError)?; if size != std::mem::size_of::() { return Err(Error::ProtocolError( @@ -794,7 +795,7 @@ impl IoBufferQueue { fn send_buffer(&self, stream_id: u32, offset: usize, size: usize) -> Result<()> { let msg = IoTransferMsg::new(stream_id, offset, size); - seq_socket_send(&self.socket, msg) + seq_socket_send(&self.socket, msg.as_bytes()) } fn keep_rds(&self) -> Vec { @@ -835,15 +836,15 @@ impl From<(u32, VioSStreamParams)> for virtio_snd_pcm_set_params { } } -fn send_cmd(control_socket: &UnixSeqpacket, data: T) -> Result<()> { - seq_socket_send(control_socket, data)?; +fn send_cmd(control_socket: &UnixSeqpacket, data: T) -> Result<()> { + seq_socket_send(control_socket, data.as_bytes())?; recv_cmd_status(control_socket) } fn recv_cmd_status(control_socket: &UnixSeqpacket) -> Result<()> { let mut status: virtio_snd_hdr = Default::default(); control_socket - .recv(status.as_bytes_mut()) + .recv(status.as_mut_bytes()) .map_err(Error::ServerIOError)?; if status.code.to_native() == VIRTIO_SND_S_OK { Ok(()) @@ -852,9 +853,9 @@ fn recv_cmd_status(control_socket: &UnixSeqpacket) -> Result<()> { } } -fn seq_socket_send(socket: &UnixSeqpacket, data: T) -> Result<()> { +fn seq_socket_send(socket: &UnixSeqpacket, data: &[u8]) -> Result<()> { loop { - let send_res = socket.send(data.as_bytes()); + let send_res = socket.send(data); if let Err(e) = send_res { match e.kind() { // Retry if interrupted @@ -875,9 +876,10 @@ const VIOS_VERSION: u32 = 2; Copy, Clone, Default, - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Serialize, Deserialize, PartialEq, @@ -898,7 +900,7 @@ struct BufferReleaseMsg { } #[repr(C)] -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] struct IoTransferMsg { io_xfer: virtio_snd_pcm_xfer, buffer_offset: u32, @@ -918,7 +920,7 @@ impl IoTransferMsg { } #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct IoStatusMsg { status: virtio_snd_pcm_status, buffer_offset: u32, diff --git a/devices/src/virtio/snd/vios_backend/worker.rs b/devices/src/virtio/snd/vios_backend/worker.rs index bfbbdcd70..24a1d12f7 100644 --- a/devices/src/virtio/snd/vios_backend/worker.rs +++ b/devices/src/virtio/snd/vios_backend/worker.rs @@ -14,7 +14,8 @@ use base::EventToken; use base::WaitContext; use data_model::Le32; use sync::Mutex; -use zerocopy::AsBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use super::super::constants::*; use super::super::layout::*; @@ -262,7 +263,7 @@ impl Worker { VIRTIO_SND_S_BAD_MSG } else { let mut request: virtio_snd_jack_remap = Default::default(); - request.as_bytes_mut().copy_from_slice(&read_buf); + request.as_mut_bytes().copy_from_slice(&read_buf); let jack_id = request.hdr.jack_id.to_native(); let association = request.association.to_native(); let sequence = request.sequence.to_native(); @@ -404,7 +405,7 @@ impl Worker { return None; } let mut query: virtio_snd_query_info = Default::default(); - query.as_bytes_mut().copy_from_slice(read_buf); + query.as_mut_bytes().copy_from_slice(read_buf); let start_id = query.start_id.to_native(); let count = query.count.to_native(); Some((start_id, count)) @@ -420,7 +421,7 @@ impl Worker { return reply_control_op_status(VIRTIO_SND_S_BAD_MSG, desc, &self.control_queue); } let mut params: virtio_snd_pcm_set_params = Default::default(); - params.as_bytes_mut().copy_from_slice(read_buf); + params.as_mut_bytes().copy_from_slice(read_buf); let stream_id = params.hdr.stream_id.to_native(); if stream_id < self.vios_client.lock().num_streams() { self.streams[stream_id as usize].send(StreamMsg::SetParams(desc, params)) @@ -453,7 +454,7 @@ impl Worker { ); } let mut pcm_hdr: virtio_snd_pcm_hdr = Default::default(); - pcm_hdr.as_bytes_mut().copy_from_slice(read_buf); + pcm_hdr.as_mut_bytes().copy_from_slice(read_buf); let stream_id = pcm_hdr.stream_id.to_native(); if stream_id < self.vios_client.lock().num_streams() { self.streams[stream_id as usize].send(msg) @@ -476,7 +477,7 @@ impl Worker { } } - fn send_info_reply( + fn send_info_reply( &mut self, mut desc: DescriptorChain, code: u32, diff --git a/devices/src/virtio/vhost/net.rs b/devices/src/virtio/vhost/net.rs index e9d97f5ce..bab260743 100644 --- a/devices/src/virtio/vhost/net.rs +++ b/devices/src/virtio/vhost/net.rs @@ -21,7 +21,7 @@ use vhost::NetT as VhostNetT; use virtio_sys::virtio_config::VIRTIO_F_RING_PACKED; use virtio_sys::virtio_net; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use super::control_socket::*; use super::worker::Worker; diff --git a/devices/src/virtio/vhost/user/device/fs.rs b/devices/src/virtio/vhost/user/device/fs.rs index ee093fd47..2a9398c44 100644 --- a/devices/src/virtio/vhost/user/device/fs.rs +++ b/devices/src/virtio/vhost/user/device/fs.rs @@ -24,7 +24,7 @@ use virtio_sys::virtio_fs::virtio_fs_config; use vm_memory::GuestMemory; use vmm_vhost::message::VhostUserProtocolFeatures; use vmm_vhost::VHOST_USER_F_PROTOCOL_FEATURES; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio; use crate::virtio::copy_config; diff --git a/devices/src/virtio/vhost/user/device/handler.rs b/devices/src/virtio/vhost/user/device/handler.rs index 12bc78b2e..0c2b87b3a 100644 --- a/devices/src/virtio/vhost/user/device/handler.rs +++ b/devices/src/virtio/vhost/user/device/handler.rs @@ -981,16 +981,18 @@ mod tests { use base::Event; use vmm_vhost::BackendServer; use vmm_vhost::FrontendReq; - use zerocopy::AsBytes; use zerocopy::FromBytes; - use zerocopy::FromZeroes; + use zerocopy::FromZeros; + use zerocopy::Immutable; + use zerocopy::IntoBytes; + use zerocopy::KnownLayout; use super::*; use crate::virtio::vhost_user_frontend::VhostUserFrontend; use crate::virtio::DeviceType; use crate::virtio::VirtioDevice; - #[derive(Clone, Copy, Debug, PartialEq, Eq, AsBytes, FromZeroes, FromBytes)] + #[derive(Clone, Copy, Debug, PartialEq, Eq, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed(4))] struct FakeConfig { x: u32, @@ -1135,10 +1137,9 @@ mod tests { .unwrap(); println!("read_config"); - let mut buf = vec![0; std::mem::size_of::()]; - vmm_device.read_config(0, &mut buf); + let mut config = FakeConfig::new_zeroed(); + vmm_device.read_config(0, config.as_mut_bytes()); // Check if the obtained config data is correct. - let config = FakeConfig::read_from(buf.as_bytes()).unwrap(); assert_eq!(config, FAKE_CONFIG_DATA); let activate = |vmm_device: &mut VhostUserFrontend| { diff --git a/devices/src/virtio/vhost/user/device/net.rs b/devices/src/virtio/vhost/user/device/net.rs index 758b4acd5..3e207d9c8 100644 --- a/devices/src/virtio/vhost/user/device/net.rs +++ b/devices/src/virtio/vhost/user/device/net.rs @@ -25,7 +25,7 @@ pub use sys::start_device as run_net_device; pub use sys::Options; use vm_memory::GuestMemory; use vmm_vhost::message::VhostUserProtocolFeatures; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio; use crate::virtio::net::build_config; diff --git a/devices/src/virtio/vhost/user/device/snd.rs b/devices/src/virtio/vhost/user/device/snd.rs index 4e27351f5..d49b2bb10 100644 --- a/devices/src/virtio/vhost/user/device/snd.rs +++ b/devices/src/virtio/vhost/user/device/snd.rs @@ -26,7 +26,7 @@ pub use sys::Options; use vm_memory::GuestMemory; use vmm_vhost::message::VhostUserProtocolFeatures; use vmm_vhost::VHOST_USER_F_PROTOCOL_FEATURES; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio; use crate::virtio::copy_config; diff --git a/devices/src/virtio/vhost/user/device/vsock.rs b/devices/src/virtio/vhost/user/device/vsock.rs index 0075b2f95..442300d2e 100644 --- a/devices/src/virtio/vhost/user/device/vsock.rs +++ b/devices/src/virtio/vhost/user/device/vsock.rs @@ -37,7 +37,7 @@ use vmm_vhost::message::VhostUserVringState; use vmm_vhost::Error; use vmm_vhost::Result; use vmm_vhost::VHOST_USER_F_PROTOCOL_FEATURES; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use super::BackendConnection; use crate::virtio::device_constants::vsock::NUM_QUEUES; diff --git a/devices/src/virtio/vhost/vsock.rs b/devices/src/virtio/vhost/vsock.rs index fb4072df2..ff46d4c3a 100644 --- a/devices/src/virtio/vhost/vsock.rs +++ b/devices/src/virtio/vhost/vsock.rs @@ -22,7 +22,7 @@ use snapshot::AnySnapshot; use vhost::Vhost; use vhost::Vsock as VhostVsockHandle; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use super::worker::VringBase; use super::worker::Worker; diff --git a/devices/src/virtio/vhost_user_frontend/fs.rs b/devices/src/virtio/vhost_user_frontend/fs.rs index 125e91f41..1e3e85494 100644 --- a/devices/src/virtio/vhost_user_frontend/fs.rs +++ b/devices/src/virtio/vhost_user_frontend/fs.rs @@ -4,7 +4,7 @@ use data_model::Le32; use virtio_sys::virtio_fs::virtio_fs_config; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::device_constants::fs::FS_MAX_TAG_LEN; use crate::virtio::vhost_user_frontend::Error; diff --git a/devices/src/virtio/video/decoder/mod.rs b/devices/src/virtio/video/decoder/mod.rs index d0bde2db7..39c387ceb 100644 --- a/devices/src/virtio/video/decoder/mod.rs +++ b/devices/src/virtio/video/decoder/mod.rs @@ -575,7 +575,7 @@ impl Decoder { // Safe because we confirmed the correct type for the resource. // unwrap() is also safe here because we just tested above that `entries` had // exactly one element. - unsafe { entries.first().unwrap().object }, + entries.first().unwrap().object(), &self.resource_bridge, params, ) diff --git a/devices/src/virtio/video/encoder/mod.rs b/devices/src/virtio/video/encoder/mod.rs index be5478dc7..4a837e82f 100644 --- a/devices/src/virtio/video/encoder/mod.rs +++ b/devices/src/virtio/video/encoder/mod.rs @@ -673,7 +673,7 @@ impl EncoderDevice { // Safe because we confirmed the correct type for the resource. // unwrap() is also safe here because we just tested above that // `entries` had exactly one element. - unsafe { entries.first().unwrap().object }, + entries.first().unwrap().object(), &self.resource_bridge, &stream.src_params, ) @@ -723,7 +723,7 @@ impl EncoderDevice { // Safe because we confirmed the correct type for the resource. // unwrap() is also safe here because we just tested above that // `entries` had exactly one element. - unsafe { entries.first().unwrap().object }, + entries.first().unwrap().object(), &self.resource_bridge, &stream.dst_params, ) diff --git a/devices/src/virtio/video/mod.rs b/devices/src/virtio/video/mod.rs index 67ae485a8..8c86d4b3d 100644 --- a/devices/src/virtio/video/mod.rs +++ b/devices/src/virtio/video/mod.rs @@ -24,7 +24,7 @@ use data_model::Le32; use remain::sorted; use thiserror::Error; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::virtio::copy_config; use crate::virtio::virtio_device::VirtioDevice; @@ -208,7 +208,7 @@ impl VirtioDevice for VideoDevice { fn read_config(&self, offset: u64, data: &mut [u8]) { let mut cfg = build_config(self.backend); - copy_config(data, 0, cfg.as_bytes_mut(), offset); + copy_config(data, 0, cfg.as_mut_bytes(), offset); } fn activate( diff --git a/devices/src/virtio/video/protocol.rs b/devices/src/virtio/video/protocol.rs index e6f57413e..ae0acef9e 100644 --- a/devices/src/virtio/video/protocol.rs +++ b/devices/src/virtio/video/protocol.rs @@ -18,7 +18,7 @@ //! The main points of the manual modifications are as follows: //! * Removed `hdr` from each command struct so that we can read the header and a command body //! separately. (cf. [related discussion](https://markmail.org/message/tr5g6axqq2zzq64y)) -//! * Derive implementations of AsBytes and FromBytes for each struct as needed. +//! * Derive implementations of zerocopy traits for each struct as needed. //! * Added GET_PARAMS_EXT and SET_PARAMS_EXT to allow querying and changing the resource type //! dynamically. //! * Moved some definitions such as virtio_video_config to device_constants to make them visible to @@ -28,9 +28,10 @@ use data_model::Le32; use data_model::Le64; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const VIRTIO_VIDEO_MAX_PLANES: u32 = 8; pub const VIRTIO_VIDEO_FORMAT_RAW_MIN: virtio_video_format = 1; @@ -131,7 +132,7 @@ pub const VIRTIO_VIDEO_RESP_ERR_INVALID_PARAMETER: virtio_video_cmd_type = 772; pub const VIRTIO_VIDEO_RESP_ERR_UNSUPPORTED_CONTROL: virtio_video_cmd_type = 773; pub type virtio_video_cmd_type = u32; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_cmd_hdr { pub type_: Le32, pub stream_id: Le32, @@ -141,7 +142,7 @@ pub const VIRTIO_VIDEO_QUEUE_TYPE_INPUT: virtio_video_queue_type = 256; pub const VIRTIO_VIDEO_QUEUE_TYPE_OUTPUT: virtio_video_queue_type = 257; pub type virtio_video_queue_type = u32; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_capability { pub queue_type: Le32, pub padding: [u8; 4usize], @@ -151,7 +152,7 @@ pub const VIRTIO_VIDEO_PLANES_LAYOUT_SINGLE_BUFFER: virtio_video_planes_layout_f pub const VIRTIO_VIDEO_PLANES_LAYOUT_PER_PLANE: virtio_video_planes_layout_flag = 2; pub type virtio_video_planes_layout_flag = u32; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_format_range { pub min: Le32, pub max: Le32, @@ -160,7 +161,7 @@ pub struct virtio_video_format_range { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_format_frame { pub width: virtio_video_format_range, pub height: virtio_video_format_range, @@ -169,7 +170,7 @@ pub struct virtio_video_format_frame { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_format_desc { pub mask: Le64, pub format: Le32, @@ -179,7 +180,7 @@ pub struct virtio_video_format_desc { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_capability_resp { pub hdr: virtio_video_cmd_hdr, pub num_descs: Le32, @@ -190,7 +191,7 @@ pub const VIRTIO_VIDEO_MEM_TYPE_GUEST_PAGES: virtio_video_mem_type = 0; pub const VIRTIO_VIDEO_MEM_TYPE_VIRTIO_OBJECT: virtio_video_mem_type = 1; pub type virtio_video_mem_type = u32; #[repr(C)] -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_stream_create { pub in_mem_type: Le32, pub out_mem_type: Le32, @@ -206,28 +207,28 @@ impl Default for virtio_video_stream_create { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_stream_destroy {} #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_stream_drain {} #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_mem_entry { pub addr: Le64, pub length: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_object_entry { pub uuid: [u8; 16usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_resource_create { pub queue_type: Le32, pub resource_id: Le32, @@ -238,7 +239,7 @@ pub struct virtio_video_resource_create { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_resource_queue { pub queue_type: Le32, pub resource_id: Le32, @@ -255,7 +256,7 @@ pub const VIRTIO_VIDEO_BUFFER_FLAG_PFRAME: virtio_video_buffer_flag = 8; pub const VIRTIO_VIDEO_BUFFER_FLAG_BFRAME: virtio_video_buffer_flag = 16; pub type virtio_video_buffer_flag = u32; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_resource_queue_resp { pub hdr: virtio_video_cmd_hdr, pub timestamp: Le64, @@ -264,27 +265,27 @@ pub struct virtio_video_resource_queue_resp { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_resource_destroy_all { pub queue_type: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_queue_clear { pub queue_type: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_plane_format { pub plane_size: Le32, pub stride: Le32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_crop { pub left: Le32, pub top: Le32, @@ -292,7 +293,7 @@ pub struct virtio_video_crop { pub height: Le32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_params { pub queue_type: Le32, pub format: Le32, @@ -306,21 +307,21 @@ pub struct virtio_video_params { pub plane_formats: [virtio_video_plane_format; 8usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_get_params { pub queue_type: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_get_params_resp { pub hdr: virtio_video_cmd_hdr, pub params: virtio_video_params, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_set_params { pub params: virtio_video_params, } @@ -329,28 +330,28 @@ pub struct virtio_video_set_params { /// was an oversight and the {GET,SET}_PARAMS_EXT commands use this structure to fix it, while /// the older {GET,SET}_PARAMS commands are kept for backward compatibility. #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_params_ext { pub base: virtio_video_params, pub resource_type: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_get_params_ext { pub queue_type: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_get_params_ext_resp { pub hdr: virtio_video_cmd_hdr, pub params: virtio_video_params_ext, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_set_params_ext { pub params: virtio_video_params_ext, } @@ -364,110 +365,110 @@ pub const VIRTIO_VIDEO_CONTROL_BITRATE_PEAK: virtio_video_control_type = 6; pub const VIRTIO_VIDEO_CONTROL_PREPEND_SPSPPS_TO_IDR: virtio_video_control_type = 7; pub type virtio_video_control_type = u32; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_control_profile { pub format: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_control_level { pub format: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_control { pub control: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_control_resp_profile { pub num: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_control_resp_level { pub num: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_query_control_resp { pub hdr: virtio_video_cmd_hdr, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_get_control { pub control: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_control_val_bitrate { pub bitrate: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_control_val_bitrate_peak { pub bitrate_peak: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_control_val_bitrate_mode { pub bitrate_mode: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_control_val_profile { pub profile: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_control_val_level { pub level: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_control_val_prepend_spspps_to_idr { pub prepend_spspps_to_idr: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_get_control_resp { pub hdr: virtio_video_cmd_hdr, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_set_control { pub control: Le32, pub padding: [u8; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_set_control_resp { pub hdr: virtio_video_cmd_hdr, } @@ -476,7 +477,7 @@ pub const VIRTIO_VIDEO_EVENT_ERROR: virtio_video_event_type = 256; pub const VIRTIO_VIDEO_EVENT_DECODER_RESOLUTION_CHANGED: virtio_video_event_type = 512; pub type virtio_video_event_type = u32; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_video_event { pub event_type: Le32, pub stream_id: Le32, diff --git a/devices/src/virtio/video/resource.rs b/devices/src/virtio/video/resource.rs index 08c3136a2..2b062e4d0 100644 --- a/devices/src/virtio/video/resource.rs +++ b/devices/src/virtio/video/resource.rs @@ -19,9 +19,10 @@ use thiserror::Error as ThisError; use vm_memory::GuestAddress; use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::virtio::resource_bridge; use crate::virtio::resource_bridge::ResourceBridgeError; @@ -44,27 +45,19 @@ pub enum ResourceType { } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] /// A guest resource entry which type is not decided yet. -pub union UnresolvedResourceEntry { - pub object: virtio_video_object_entry, - pub guest_mem: virtio_video_mem_entry, -} +pub struct UnresolvedResourceEntry([u8; 16]); impl fmt::Debug for UnresolvedResourceEntry { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!( - f, - "unresolved {:?} or {:?}", - // SAFETY: - // Safe because `self.object` and `self.guest_mem` are the same size and both made of - // integers, making it safe to display them no matter their value. - unsafe { self.object }, - // SAFETY: - // Safe because `self.object` and `self.guest_mem` are the same size and both made of - // integers, making it safe to display them no matter their value. - unsafe { self.guest_mem } - ) + write!(f, "unresolved {:?}", self.0) + } +} + +impl UnresolvedResourceEntry { + pub fn object(&self) -> virtio_video_object_entry { + virtio_video_object_entry::read_from_bytes(&self.0).unwrap() } } diff --git a/devices/src/virtio/virtio_pci_device.rs b/devices/src/virtio/virtio_pci_device.rs index 5d6cec5a8..f771fea41 100644 --- a/devices/src/virtio/virtio_pci_device.rs +++ b/devices/src/virtio/virtio_pci_device.rs @@ -46,9 +46,10 @@ use vm_control::VmMemoryDestination; use vm_control::VmMemoryRegionId; use vm_control::VmMemorySource; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use self::virtio_pci_common_config::VirtioPciCommonConfig; use super::*; @@ -110,7 +111,7 @@ pub enum PciCapabilityType { #[allow(dead_code)] #[repr(C)] -#[derive(Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VirtioPciCap { // cap_vndr and cap_next are autofilled based on id() in pci configuration pub cap_vndr: u8, // Generic PCI field: PCI_CAP_ID_VNDR @@ -160,7 +161,7 @@ impl VirtioPciCap { #[allow(dead_code)] #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VirtioPciNotifyCap { cap: VirtioPciCap, notify_off_multiplier: Le32, @@ -206,7 +207,7 @@ impl VirtioPciNotifyCap { } #[repr(C)] -#[derive(Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VirtioPciShmCap { cap: VirtioPciCap, offset_hi: Le32, // Most sig 32 bits of offset diff --git a/devices/src/virtio/vsock/sys/windows/protocol.rs b/devices/src/virtio/vsock/sys/windows/protocol.rs index e7d73b150..7e7d3f14c 100644 --- a/devices/src/virtio/vsock/sys/windows/protocol.rs +++ b/devices/src/virtio/vsock/sys/windows/protocol.rs @@ -5,21 +5,22 @@ use data_model::Le16; use data_model::Le32; use data_model::Le64; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const TYPE_STREAM_SOCKET: u16 = 1; /// virtio_vsock_config is the vsock device configuration space defined by the virtio spec. -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_vsock_config { pub guest_cid: Le64, } /// The message header for data packets sent on the tx/rx queues -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] #[allow(non_camel_case_types)] pub struct virtio_vsock_hdr { @@ -28,7 +29,7 @@ pub struct virtio_vsock_hdr { pub src_port: Le32, pub dst_port: Le32, pub len: Le32, - pub r#type: Le16, + pub type_: Le16, pub op: Le16, pub flags: Le32, pub buf_alloc: Le32, @@ -36,7 +37,7 @@ pub struct virtio_vsock_hdr { } /// An event sent to the event queue -#[derive(Copy, Clone, Debug, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct virtio_vsock_event { // ID from the virtio_vsock_event_id struct in the virtio spec diff --git a/devices/src/virtio/vsock/sys/windows/vsock.rs b/devices/src/virtio/vsock/sys/windows/vsock.rs index 8d19346da..a2d0f586e 100644 --- a/devices/src/virtio/vsock/sys/windows/vsock.rs +++ b/devices/src/virtio/vsock/sys/windows/vsock.rs @@ -55,9 +55,9 @@ use serde::Serialize; use snapshot::AnySnapshot; use thiserror::Error as ThisError; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::FromZeros; +use zerocopy::IntoBytes; use crate::virtio::async_utils; use crate::virtio::copy_config; @@ -610,7 +610,7 @@ impl Worker { src_port: Le32::from(port.host), dst_port: guest_port, len: Le32::from(data_size as u32), - r#type: TYPE_STREAM_SOCKET.into(), + type_: TYPE_STREAM_SOCKET.into(), op: vsock_op::VIRTIO_VSOCK_OP_RW.into(), buf_alloc: Le32::from(connection.buf_alloc as u32), fwd_cnt: Le32::from(connection.recv_cnt as u32), @@ -1104,7 +1104,7 @@ impl Worker { src_port: { header.dst_port }, dst_port: { header.src_port }, len: 0.into(), - r#type: TYPE_STREAM_SOCKET.into(), + type_: TYPE_STREAM_SOCKET.into(), op: resp_op.into(), buf_alloc: Le32::from(buf_alloc), fwd_cnt: Le32::from(fwd_cnt), @@ -1148,7 +1148,7 @@ impl Worker { src_port: { header.dst_port }, dst_port: { header.src_port }, len: 0.into(), - r#type: TYPE_STREAM_SOCKET.into(), + type_: TYPE_STREAM_SOCKET.into(), op: vsock_op::VIRTIO_VSOCK_OP_RST.into(), // There is no buffer on a closed connection buf_alloc: 0.into(), @@ -1161,7 +1161,7 @@ impl Worker { self.write_bytes_to_queue( &mut *send_queue.lock().await, rx_queue_evt, - response.as_bytes_mut(), + response.as_mut_bytes(), ) .await .expect("vsock: failed to write to queue"); @@ -1261,7 +1261,7 @@ impl Worker { src_port: { header.dst_port }, dst_port: { header.src_port }, len: 0.into(), - r#type: TYPE_STREAM_SOCKET.into(), + type_: TYPE_STREAM_SOCKET.into(), op: vsock_op::VIRTIO_VSOCK_OP_CREDIT_UPDATE.into(), buf_alloc: Le32::from(connection.buf_alloc as u32), fwd_cnt: Le32::from(connection.recv_cnt as u32), @@ -1275,7 +1275,7 @@ impl Worker { self.write_bytes_to_queue( &mut *send_queue.lock().await, rx_queue_evt, - response.as_bytes_mut(), + response.as_mut_bytes(), ) .await .unwrap_or_else(|_| panic!("vsock: port {}: failed to write to queue", port)); @@ -1302,7 +1302,7 @@ impl Worker { src_port: { header.dst_port }, dst_port: { header.src_port }, len: 0.into(), - r#type: TYPE_STREAM_SOCKET.into(), + type_: TYPE_STREAM_SOCKET.into(), op: vsock_op::VIRTIO_VSOCK_OP_RST.into(), buf_alloc: Le32::from(connection.buf_alloc as u32), fwd_cnt: Le32::from(connection.recv_cnt as u32), @@ -1314,7 +1314,7 @@ impl Worker { self.write_bytes_to_queue( &mut *send_queue.lock().await, rx_queue_evt, - response.as_bytes_mut(), + response.as_mut_bytes(), ) .await .expect("failed to write to queue"); diff --git a/devices/src/virtio/wl.rs b/devices/src/virtio/wl.rs index e6d1d3af4..28f4db77c 100644 --- a/devices/src/virtio/wl.rs +++ b/devices/src/virtio/wl.rs @@ -129,9 +129,10 @@ use thiserror::Error as ThisError; use vm_control::VmMemorySource; use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[cfg(feature = "gpu")] use super::resource_bridge::get_resource_info; @@ -621,14 +622,14 @@ impl VmRequester { } #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlHeader { type_: Le32, flags: Le32, } #[repr(C)] -#[derive(Copy, Clone, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfdNew { hdr: CtrlHeader, id: Le32, @@ -639,7 +640,7 @@ struct CtrlVfdNew { } #[repr(C)] -#[derive(Copy, Clone, Default, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfdNewCtxNamed { hdr: CtrlHeader, id: Le32, @@ -652,7 +653,7 @@ struct CtrlVfdNewCtxNamed { const_assert_eq!(size_of::(), 64); #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[cfg(feature = "minigbm")] struct CtrlVfdNewDmabuf { hdr: CtrlHeader, @@ -673,7 +674,7 @@ struct CtrlVfdNewDmabuf { #[cfg(feature = "minigbm")] #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfdDmabufSync { hdr: CtrlHeader, id: Le32, @@ -681,7 +682,7 @@ struct CtrlVfdDmabufSync { } #[repr(C)] -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfdRecv { hdr: CtrlHeader, id: Le32, @@ -689,14 +690,14 @@ struct CtrlVfdRecv { } #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfd { hdr: CtrlHeader, id: Le32, } #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfdSend { hdr: CtrlHeader, id: Le32, @@ -705,21 +706,21 @@ struct CtrlVfdSend { } #[repr(C)] -#[derive(Copy, Clone, Default, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct CtrlVfdSendVfd { kind: Le32, id: Le32, } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] union CtrlVfdSendVfdV2Payload { id: Le32, seqno: Le64, } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] struct CtrlVfdSendVfdV2 { kind: Le32, payload: CtrlVfdSendVfdV2Payload, diff --git a/disk/Cargo.toml b/disk/Cargo.toml index 973ca5346..26c7aedd5 100644 --- a/disk/Cargo.toml +++ b/disk/Cargo.toml @@ -30,7 +30,7 @@ sync = { path = "../common/sync" } thiserror = "1" uuid = { version = "1", features = ["v4"], optional = true } vm_memory = { path = "../vm_memory" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } zstd = { version = "0.13", optional = true } [target.'cfg(windows)'.dependencies] diff --git a/disk/src/android_sparse.rs b/disk/src/android_sparse.rs index 5a1d3dc39..291cb568e 100644 --- a/disk/src/android_sparse.rs +++ b/disk/src/android_sparse.rs @@ -28,9 +28,11 @@ use data_model::Le16; use data_model::Le32; use remain::sorted; use thiserror::Error; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::FromZeros; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::AsyncDisk; use crate::DiskFile; @@ -56,7 +58,7 @@ pub const SPARSE_HEADER_MAGIC: u32 = 0xed26ff3a; const MAJOR_VERSION: u16 = 1; #[repr(C)] -#[derive(Clone, Copy, Debug, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] struct SparseHeader { magic: Le32, // SPARSE_HEADER_MAGIC major_version: Le16, // (0x1) - reject images with higher major versions @@ -77,7 +79,7 @@ const CHUNK_TYPE_DONT_CARE: u16 = 0xCAC3; const CHUNK_TYPE_CRC32: u16 = 0xCAC4; #[repr(C)] -#[derive(Clone, Copy, Debug, AsBytes, FromZeroes, FromBytes)] +#[derive(Clone, Copy, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] struct ChunkHeader { chunk_type: Le16, /* 0xCAC1 -> raw; 0xCAC2 -> fill; 0xCAC3 -> don't care */ reserved1: u16, @@ -117,7 +119,7 @@ fn parse_chunk(input: &mut T, blk_sz: u64) -> Result io::Result> { let mut table = vec![0; count as usize]; self.file.seek(SeekFrom::Start(offset))?; - self.file.read_exact(table.as_bytes_mut())?; + self.file.read_exact(table.as_mut_bytes())?; let mask = mask.unwrap_or(u64::MAX); for ptr in &mut table { *ptr = u64::from_be(*ptr) & mask; @@ -93,7 +93,7 @@ impl QcowRawFile { let count = self.cluster_size / size_of::() as u64; let mut table = vec![0; count as usize]; self.file.seek(SeekFrom::Start(offset))?; - self.file.read_exact(table.as_bytes_mut())?; + self.file.read_exact(table.as_mut_bytes())?; for refcount in &mut table { *refcount = u16::from_be(*refcount); } diff --git a/ext2/Cargo.toml b/ext2/Cargo.toml index a7181c403..3e56406e7 100644 --- a/ext2/Cargo.toml +++ b/ext2/Cargo.toml @@ -10,7 +10,7 @@ base = { path = "../base/" } enumn = "0.1" libc = "0.2" uuid = { version = "1", features = ["v4"] } -zerocopy = "0.7.29" # >=0.7.29 is required for our 'AsBytes' +zerocopy = { version = "0.8.13", features = ["derive"] } [[example]] name = "mkfs" diff --git a/ext2/src/arena.rs b/ext2/src/arena.rs index dbe628036..e2ef94491 100644 --- a/ext2/src/arena.rs +++ b/ext2/src/arena.rs @@ -14,8 +14,10 @@ use anyhow::Context; use anyhow::Result; use base::MappedRegion; use base::MemoryMapping; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] struct Region { @@ -143,7 +145,7 @@ fn test_region_manager() { assert_eq!(rm.to_vec(), vec![&Region { start: 0, len: 30 },]); } -#[derive(Debug, Clone, Copy, AsBytes)] +#[derive(Debug, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] /// Represents a ID of a disk block. pub struct BlockId(u32); @@ -262,16 +264,16 @@ impl<'a> Arena<'a> { } /// Allocate a new region for a value with type `T`. - pub fn allocate( + pub fn allocate( &self, block: BlockId, block_offset: usize, ) -> Result<&'a mut T> { let slice = self.allocate_slice(block, block_offset, std::mem::size_of::())?; - T::mut_from(slice).ok_or_else(|| anyhow!("failed to interpret")) + T::mut_from_bytes(slice).map_err(|_| anyhow!("failed to interpret")) } - pub fn write_to_mem( + pub fn write_to_mem( &self, block_id: BlockId, block_offset: usize, diff --git a/ext2/src/blockgroup.rs b/ext2/src/blockgroup.rs index 1367b64a4..a80961654 100644 --- a/ext2/src/blockgroup.rs +++ b/ext2/src/blockgroup.rs @@ -7,9 +7,10 @@ use std::collections::BTreeMap; use anyhow::Result; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::arena::Arena; use crate::arena::BlockId; @@ -26,7 +27,7 @@ pub const BLOCK_SIZE: usize = 4096; /// /// See [the specification](https://www.nongnu.org/ext2-doc/ext2.html#block-group-descriptor-table) for the details. #[repr(C)] -#[derive(Default, Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct BlockGroupDescriptor { /// Index of the first block of the block bitmap. pub block_bitmap: u32, diff --git a/ext2/src/fs.rs b/ext2/src/fs.rs index af7b35bf6..9fbdfa785 100644 --- a/ext2/src/fs.rs +++ b/ext2/src/fs.rs @@ -18,9 +18,10 @@ use anyhow::bail; use anyhow::Context; use anyhow::Result; use base::info; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::arena::Arena; use crate::arena::BlockId; @@ -37,7 +38,7 @@ use crate::superblock::SuperBlock; use crate::xattr::InlineXattrs; #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes, Debug)] +#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] struct DirEntryRaw { inode: u32, rec_len: u16, diff --git a/ext2/src/inode.rs b/ext2/src/inode.rs index 1f90c171c..3c20a9593 100644 --- a/ext2/src/inode.rs +++ b/ext2/src/inode.rs @@ -10,9 +10,10 @@ use std::os::unix::fs::MetadataExt; use anyhow::bail; use anyhow::Result; use enumn::N; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::arena::Arena; use crate::arena::BlockId; @@ -87,7 +88,7 @@ const INODE_BLOCK_LEN: usize = 60; /// /// This is a wrapper of `[u8; 60]` to implement `Default` manually. #[repr(C)] -#[derive(Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct InodeBlock(pub [u8; INODE_BLOCK_LEN]); impl Default for InodeBlock { @@ -172,7 +173,7 @@ impl InodeBlock { /// /// The field names are based on [the specification](https://www.nongnu.org/ext2-doc/ext2.html#inode-table). #[repr(C)] -#[derive(Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct Inode { mode: u16, uid: u16, @@ -221,7 +222,7 @@ impl Default for Inode { /// The block size '512' byte is fixed and not related to the actual block size of the file system. /// For more details, see notes for `i_blocks_lo` in the specification. #[repr(C)] -#[derive(Default, Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InodeBlocksCount(u32); impl InodeBlocksCount { diff --git a/ext2/src/superblock.rs b/ext2/src/superblock.rs index 96f6b7bbd..e3d62a208 100644 --- a/ext2/src/superblock.rs +++ b/ext2/src/superblock.rs @@ -5,9 +5,10 @@ //! Defines the superblock structure. use anyhow::Result; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::arena::Arena; use crate::arena::BlockId; @@ -21,7 +22,7 @@ use crate::inode::Inode; /// Note that this struct only holds the fields at the beginning of the superblock. All fields after /// the fields supported by this structure are filled with zeros. #[repr(C)] -#[derive(Default, Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct SuperBlock { pub inodes_count: u32, pub blocks_count: u32, diff --git a/ext2/src/xattr.rs b/ext2/src/xattr.rs index 36ec06341..3d49792d8 100644 --- a/ext2/src/xattr.rs +++ b/ext2/src/xattr.rs @@ -12,9 +12,10 @@ use std::path::Path; use anyhow::bail; use anyhow::Context; use anyhow::Result; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::inode::Inode; @@ -152,7 +153,7 @@ pub fn set_xattr(path: &Path, key: &str, value: &str) -> Result<()> { } #[repr(C)] -#[derive(Default, Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub(crate) struct XattrEntry { name_len: u8, name_index: u8, diff --git a/fuse/Cargo.toml b/fuse/Cargo.toml index b41dc8fb6..5e5fdf2eb 100644 --- a/fuse/Cargo.toml +++ b/fuse/Cargo.toml @@ -16,4 +16,4 @@ enumn = "0.1.0" libc = { version = "0.2", features = ["extra_traits"] } remain = "0.2" thiserror = "1.0.20" -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/fuse/src/server.rs b/fuse/src/server.rs index cee394964..9c1cadb9f 100644 --- a/fuse/src/server.rs +++ b/fuse/src/server.rs @@ -15,9 +15,9 @@ use std::time::Duration; use base::error; use base::pagesize; use base::Protection; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::filesystem::Context; use crate::filesystem::DirEntry; @@ -39,9 +39,9 @@ const SELINUX_XATTR_CSTR: &[u8] = b"security.selinux\0"; /// A trait for reading from the underlying FUSE endpoint. pub trait Reader: io::Read { - fn read_struct(&mut self) -> Result { + fn read_struct(&mut self) -> Result { let mut out = T::new_zeroed(); - self.read_exact(out.as_bytes_mut()) + self.read_exact(out.as_mut_bytes()) .map_err(Error::DecodeMessage)?; Ok(out) } @@ -1813,7 +1813,7 @@ fn reply_readdir(len: usize, unique: u64, mut w: W) -> Result Ok(out.len as usize) } -fn reply_ok( +fn reply_ok( out: Option, data: Option<&[u8]>, unique: u64, @@ -1963,9 +1963,8 @@ fn parse_selinux_xattr(buf: &[u8]) -> Result> { // Because the security context data block may have been preceded by variable-length strings, // `SecctxHeader` and the subsequent `Secctx` structs may not be correctly byte-aligned // within `buf`. - let secctx_header = SecctxHeader::read_from_prefix(buf).ok_or(Error::DecodeMessage( - io::Error::from_raw_os_error(libc::EINVAL), - ))?; + let (secctx_header, _) = SecctxHeader::read_from_prefix(buf) + .map_err(|_| Error::DecodeMessage(io::Error::from_raw_os_error(libc::EINVAL)))?; // FUSE 7.38 introduced a generic request extension with the same structure as `SecctxHeader`. // A `nr_secctx` value above `MAX_NR_SECCTX` indicates that this data block does not contain @@ -1986,9 +1985,8 @@ fn parse_selinux_xattr(buf: &[u8]) -> Result> { } let secctx = - Secctx::read_from(&buf[cur_secctx_pos..(cur_secctx_pos + size_of::())]).ok_or( - Error::DecodeMessage(io::Error::from_raw_os_error(libc::EINVAL)), - )?; + Secctx::read_from_bytes(&buf[cur_secctx_pos..(cur_secctx_pos + size_of::())]) + .map_err(|_| Error::DecodeMessage(io::Error::from_raw_os_error(libc::EINVAL)))?; cur_secctx_pos += size_of::(); diff --git a/fuse/src/sys.rs b/fuse/src/sys.rs index 891071dc7..93e1add7b 100644 --- a/fuse/src/sys.rs +++ b/fuse/src/sys.rs @@ -6,9 +6,11 @@ use std::mem; use bitflags::bitflags; use enumn::N; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; +use zerocopy::TryFromBytes; /// Version number of this interface. pub const KERNEL_VERSION: u32 = 7; @@ -501,7 +503,7 @@ bitflags! { pub const MAX_NR_SECCTX: u32 = 31; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Attr { pub ino: u64, pub size: u64, @@ -546,7 +548,7 @@ impl From for Attr { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Kstatfs { pub blocks: u64, pub bfree: u64, @@ -578,7 +580,7 @@ impl From for Kstatfs { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct FileLock { pub start: u64, pub end: u64, @@ -587,7 +589,7 @@ pub struct FileLock { } #[repr(u32)] -#[derive(Debug, Copy, Clone, N, AsBytes)] +#[derive(Debug, Copy, Clone, N, IntoBytes, Immutable, KnownLayout, TryFromBytes)] pub enum Opcode { Lookup = 1, Forget = 2, /* No Reply */ @@ -655,7 +657,7 @@ pub enum NotifyOpcode { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct EntryOut { pub nodeid: u64, /* Inode ID */ pub generation: u64, /* Inode generation: nodeid:gen must be unique for the fs's lifetime */ @@ -667,27 +669,27 @@ pub struct EntryOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ForgetIn { pub nlookup: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ForgetOne { pub nodeid: u64, pub nlookup: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct BatchForgetIn { pub count: u32, pub dummy: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct GetattrIn { pub flags: u32, pub dummy: u32, @@ -695,7 +697,7 @@ pub struct GetattrIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct AttrOut { pub attr_valid: u64, /* Cache timeout for the attributes */ pub attr_valid_nsec: u32, @@ -704,7 +706,7 @@ pub struct AttrOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct MknodIn { pub mode: u32, pub rdev: u32, @@ -713,27 +715,27 @@ pub struct MknodIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct MkdirIn { pub mode: u32, pub umask: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ChromeOsTmpfileIn { pub mode: u32, pub umask: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct RenameIn { pub newdir: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Rename2In { pub newdir: u64, pub flags: u32, @@ -741,13 +743,13 @@ pub struct Rename2In { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct LinkIn { pub oldnodeid: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SetattrIn { pub valid: u32, pub padding: u32, @@ -787,14 +789,14 @@ impl From for libc::stat64 { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct OpenIn { pub flags: u32, pub unused: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct CreateIn { pub flags: u32, pub mode: u32, @@ -803,7 +805,7 @@ pub struct CreateIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct OpenOut { pub fh: u64, pub open_flags: u32, @@ -811,7 +813,7 @@ pub struct OpenOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ReleaseIn { pub fh: u64, pub flags: u32, @@ -820,7 +822,7 @@ pub struct ReleaseIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct FlushIn { pub fh: u64, pub unused: u32, @@ -829,7 +831,7 @@ pub struct FlushIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ReadIn { pub fh: u64, pub offset: u64, @@ -841,7 +843,7 @@ pub struct ReadIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct WriteIn { pub fh: u64, pub offset: u64, @@ -853,20 +855,20 @@ pub struct WriteIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct WriteOut { pub size: u32, pub padding: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct StatfsOut { pub st: Kstatfs, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct FsyncIn { pub fh: u64, pub fsync_flags: u32, @@ -874,28 +876,28 @@ pub struct FsyncIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SetxattrIn { pub size: u32, pub flags: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct GetxattrIn { pub size: u32, pub padding: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct GetxattrOut { pub size: u32, pub padding: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct LkIn { pub fh: u64, pub owner: u64, @@ -905,20 +907,20 @@ pub struct LkIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct LkOut { pub lk: FileLock, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct AccessIn { pub mask: u32, pub padding: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InitIn { pub major: u32, pub minor: u32, @@ -927,14 +929,14 @@ pub struct InitIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InitInExt { pub flags2: u32, pub unused: [u32; 11], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InitOut { pub major: u32, pub minor: u32, @@ -951,13 +953,13 @@ pub struct InitOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InterruptIn { pub unique: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct BmapIn { pub block: u64, pub blocksize: u32, @@ -965,13 +967,13 @@ pub struct BmapIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct BmapOut { pub block: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct IoctlIn { pub fh: u64, pub flags: u32, @@ -984,7 +986,7 @@ pub struct IoctlIn { /// Describes a region of memory in the address space of the process that made the ioctl syscall. /// Similar to `libc::iovec` but uses `u64`s for the address and the length. #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct IoctlIovec { /// The start address of the memory region. This must be in the address space of the process /// that made the ioctl syscall. @@ -995,7 +997,7 @@ pub struct IoctlIovec { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct IoctlOut { pub result: i32, pub flags: u32, @@ -1004,7 +1006,7 @@ pub struct IoctlOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct PollIn { pub fh: u64, pub kh: u64, @@ -1013,20 +1015,20 @@ pub struct PollIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct PollOut { pub revents: u32, pub padding: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NotifyPollWakeupOut { pub kh: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct FallocateIn { pub fh: u64, pub offset: u64, @@ -1036,7 +1038,7 @@ pub struct FallocateIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct InHeader { pub len: u32, pub opcode: u32, @@ -1049,7 +1051,7 @@ pub struct InHeader { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct OutHeader { pub len: u32, pub error: i32, @@ -1057,7 +1059,7 @@ pub struct OutHeader { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Dirent { pub ino: u64, pub off: u64, @@ -1067,14 +1069,14 @@ pub struct Dirent { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Direntplus { pub entry_out: EntryOut, pub dirent: Dirent, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NotifyInvalInodeOut { pub ino: u64, pub off: i64, @@ -1082,7 +1084,7 @@ pub struct NotifyInvalInodeOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NotifyInvalEntryOut { pub parent: u64, pub namelen: u32, @@ -1090,7 +1092,7 @@ pub struct NotifyInvalEntryOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NotifyDeleteOut { pub parent: u64, pub child: u64, @@ -1099,7 +1101,7 @@ pub struct NotifyDeleteOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NotifyStoreOut { pub nodeid: u64, pub offset: u64, @@ -1108,7 +1110,7 @@ pub struct NotifyStoreOut { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Notify_Retrieve_Out { pub notify_unique: u64, pub nodeid: u64, @@ -1119,7 +1121,7 @@ pub struct Notify_Retrieve_Out { /* Matches the size of fuse_write_in */ #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct NotifyRetrieveIn { pub dummy1: u64, pub offset: u64, @@ -1130,7 +1132,7 @@ pub struct NotifyRetrieveIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct LseekIn { pub fh: u64, pub offset: u64, @@ -1139,13 +1141,13 @@ pub struct LseekIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct LseekOut { pub offset: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct CopyFileRangeIn { pub fh_src: u64, pub off_src: u64, @@ -1157,7 +1159,7 @@ pub struct CopyFileRangeIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SetUpMappingIn { /* An already open handle */ pub fh: u64, @@ -1172,14 +1174,14 @@ pub struct SetUpMappingIn { } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct RemoveMappingIn { /* number of fuse_removemapping_one follows */ pub count: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct RemoveMappingOne { /* Offset into the dax window start the unmapping */ pub moffset: u64, @@ -1192,7 +1194,7 @@ pub struct RemoveMappingOne { /// will be followed by actual context label. /// fuse_secctx, name, context #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Secctx { pub size: u32, pub padding: u32, @@ -1202,7 +1204,7 @@ pub struct Secctx { /// sent and what's the total size of all security contexts (including /// size of fuse_secctx_header). #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SecctxHeader { pub size: u32, pub nr_secctx: u32, diff --git a/gpu_display/Cargo.toml b/gpu_display/Cargo.toml index 0d89f4349..4bfde7dec 100644 --- a/gpu_display/Cargo.toml +++ b/gpu_display/Cargo.toml @@ -26,7 +26,7 @@ thiserror = "1" cfg-if = "1" serde = { version = "1", features = [ "derive" ] } vm_control = { path = "../vm_control", features = ["gpu"] } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } vulkano = { version = "0.31.1", optional = true } ash = { version = "0.37.0", optional = true } rand = { version = "0.8.5", optional = true } diff --git a/gpu_display/src/event_device.rs b/gpu_display/src/event_device.rs index f048078fe..64e07364b 100644 --- a/gpu_display/src/event_device.rs +++ b/gpu_display/src/event_device.rs @@ -17,8 +17,8 @@ use linux_input_sys::virtio_input_event; use linux_input_sys::InputEventDecoder; use serde::Deserialize; use serde::Serialize; -use zerocopy::AsBytes; -use zerocopy::FromZeroes; +use zerocopy::FromZeros; +use zerocopy::IntoBytes; const EVENT_SIZE: usize = virtio_input_event::SIZE; const EVENT_BUFFER_LEN_MAX: usize = 64 * EVENT_SIZE; @@ -150,7 +150,7 @@ impl EventDevice { pub fn recv_event_encoded(&self) -> io::Result { let mut event = virtio_input_event::new_zeroed(); - (&self.event_socket).read_exact(event.as_bytes_mut())?; + (&self.event_socket).read_exact(event.as_mut_bytes())?; Ok(event) } } diff --git a/hypervisor/Cargo.toml b/hypervisor/Cargo.toml index 0df585ddc..474b48ece 100644 --- a/hypervisor/Cargo.toml +++ b/hypervisor/Cargo.toml @@ -36,7 +36,7 @@ kvm_sys = { path = "../kvm_sys" } [target.'cfg(target_arch = "x86_64")'.dev-dependencies] hypervisor_test_macro = { path = "hypervisor_test_macro" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(windows)'.dependencies] thiserror = "1" diff --git a/hypervisor/tests/hypervisor_virtualization.rs b/hypervisor/tests/hypervisor_virtualization.rs index fb12833a3..cc02530c0 100644 --- a/hypervisor/tests/hypervisor_virtualization.rs +++ b/hypervisor/tests/hypervisor_virtualization.rs @@ -36,7 +36,10 @@ use vm_memory::GuestMemory; use windows::Win32::System::Memory::VirtualLock; #[cfg(windows)] use windows::Win32::System::Memory::VirtualUnlock; -use zerocopy::AsBytes; +use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; const FLAGS_IF_BIT: u64 = 0x200; @@ -49,7 +52,7 @@ pub enum HypervisorType { } #[repr(C, packed)] -#[derive(AsBytes)] +#[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] /// Define IDTR value used in real mode or 32bit protected mode. struct Idtr32 { // The lower 2 bytes are limit. @@ -59,7 +62,7 @@ struct Idtr32 { } #[repr(C, packed)] -#[derive(AsBytes, Debug, Copy, Clone)] +#[derive(Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] /// IDT entries for long mode. struct IdtEntry64 { address_low: u16, @@ -503,7 +506,7 @@ impl ModeConfig { if long_mode && s == 0 { // 64 bit system segment descriptor. #[repr(C, packed)] - #[derive(AsBytes)] + #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] struct Descriptor { limit_lo: u16, base_lo: u16, @@ -529,7 +532,7 @@ impl ModeConfig { .to_owned() } else { #[repr(C, packed)] - #[derive(AsBytes)] + #[derive(FromBytes, Immutable, IntoBytes, KnownLayout)] struct Descriptor { limit_lo: u16, base_lo: u16, diff --git a/jail/Cargo.toml b/jail/Cargo.toml index 4ac0dcc51..f7f1e0072 100644 --- a/jail/Cargo.toml +++ b/jail/Cargo.toml @@ -23,7 +23,7 @@ once_cell = "1.7" serde = "1" serde_keyvalue = { path = "../serde_keyvalue", features = ["argh_derive"] } static_assertions = "1.1" -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(any(target_os = "android", target_os = "linux"))'.dependencies] minijail = "*" diff --git a/jail/src/helpers.rs b/jail/src/helpers.rs index f93858982..ce8ec0e62 100644 --- a/jail/src/helpers.rs +++ b/jail/src/helpers.rs @@ -23,7 +23,9 @@ use once_cell::sync::Lazy; #[cfg(feature = "seccomp_trace")] use static_assertions::const_assert; #[cfg(feature = "seccomp_trace")] -use zerocopy::AsBytes; +use zerocopy::Immutable; +#[cfg(feature = "seccomp_trace")] +use zerocopy::IntoBytes; use crate::config::JailConfig; @@ -260,7 +262,7 @@ pub fn create_sandbox_minijail( #[cfg(feature = "seccomp_trace")] { #[repr(C)] - #[derive(AsBytes)] + #[derive(Immutable, IntoBytes)] struct sock_filter { /* Filter block */ code: u16, /* Actual filter code */ diff --git a/kernel_loader/Cargo.toml b/kernel_loader/Cargo.toml index c18b212d2..9031b1e99 100644 --- a/kernel_loader/Cargo.toml +++ b/kernel_loader/Cargo.toml @@ -12,7 +12,7 @@ remain = "0.2" resources = { path = "../resources" } thiserror = "1" vm_memory = { path = "../vm_memory" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [dev-dependencies] tempfile = "3" diff --git a/kernel_loader/bindgen.sh b/kernel_loader/bindgen.sh index 6c1e5c973..de85e4f57 100755 --- a/kernel_loader/bindgen.sh +++ b/kernel_loader/bindgen.sh @@ -11,9 +11,10 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.." source tools/impl/bindgen-common.sh KERNEL_LOADER_EXTRA="// Added by kernel_loader/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes;" +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout;" bindgen_generate \ --raw-line "${KERNEL_LOADER_EXTRA}" \ @@ -25,10 +26,10 @@ bindgen_generate \ --allowlist-type='Elf64_Ehdr' \ --allowlist-type='Elf64_Phdr' \ --allowlist-var='.+' \ - --with-derive-custom "elf32_hdr=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "elf64_hdr=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "elf32_phdr=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "elf64_phdr=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "elf32_hdr=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "elf64_hdr=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "elf32_phdr=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "elf64_phdr=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX}/include/uapi/linux/elf.h" \ -- \ -isystem "${BINDGEN_LINUX}/include" \ diff --git a/kernel_loader/src/arm64.rs b/kernel_loader/src/arm64.rs index 89823ade1..6b8632ff7 100644 --- a/kernel_loader/src/arm64.rs +++ b/kernel_loader/src/arm64.rs @@ -23,15 +23,17 @@ use lz4_flex::frame::FrameDecoder as Lz4FrameDecoder; use resources::AddressRange; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::FromZeros; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::Error; use crate::LoadedKernel; use crate::Result; -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] #[allow(unused)] #[repr(C)] struct Arm64ImageHeader { @@ -92,7 +94,7 @@ where { let mut header = Arm64ImageHeader::new_zeroed(); kernel_image - .read_exact_at_volatile(VolatileSlice::new(header.as_bytes_mut()), 0) + .read_exact_at_volatile(VolatileSlice::new(header.as_mut_bytes()), 0) .map_err(|_| Error::ReadHeader)?; let load_addr = header.parse_load_addr(kernel_start)?; @@ -125,7 +127,7 @@ fn load_arm64_kernel_from_reader( // Read and parse the kernel header. kernel_image - .read_exact(header.as_bytes_mut()) + .read_exact(header.as_mut_bytes()) .map_err(|_| Error::ReadHeader)?; let load_addr = header.parse_load_addr(kernel_start)?; diff --git a/kernel_loader/src/elf.rs b/kernel_loader/src/elf.rs index aa6afebea..7170e7d89 100644 --- a/kernel_loader/src/elf.rs +++ b/kernel_loader/src/elf.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by kernel_loader/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const EM_NONE: u32 = 0; pub const EM_M32: u32 = 1; @@ -296,7 +297,7 @@ pub type Elf64_Off = u64; pub type Elf64_Word = u32; pub type Elf64_Xword = u64; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct elf32_hdr { pub e_ident: [::std::os::raw::c_uchar; 16usize], pub e_type: Elf32_Half, @@ -315,7 +316,7 @@ pub struct elf32_hdr { } pub type Elf32_Ehdr = elf32_hdr; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct elf64_hdr { pub e_ident: [::std::os::raw::c_uchar; 16usize], pub e_type: Elf64_Half, @@ -334,7 +335,7 @@ pub struct elf64_hdr { } pub type Elf64_Ehdr = elf64_hdr; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct elf32_phdr { pub p_type: Elf32_Word, pub p_offset: Elf32_Off, @@ -347,7 +348,7 @@ pub struct elf32_phdr { } pub type Elf32_Phdr = elf32_phdr; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct elf64_phdr { pub p_type: Elf64_Word, pub p_flags: Elf64_Word, diff --git a/kernel_loader/src/lib.rs b/kernel_loader/src/lib.rs index 822751755..4abb96ef4 100644 --- a/kernel_loader/src/lib.rs +++ b/kernel_loader/src/lib.rs @@ -13,8 +13,8 @@ use resources::AddressRange; use thiserror::Error; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::IntoBytes; mod multiboot; @@ -303,11 +303,11 @@ where fn read_elf_by_type(file: &mut F) -> Result where F: FileReadWriteAtVolatile, - FileHeader: AsBytes + FromBytes + Default + Into, - ProgramHeader: AsBytes + FromBytes + Clone + Default + Into, + FileHeader: IntoBytes + FromBytes + Default + Into, + ProgramHeader: IntoBytes + FromBytes + Clone + Default + Into, { let mut ehdr = FileHeader::new_zeroed(); - file.read_exact_at_volatile(VolatileSlice::new(ehdr.as_bytes_mut()), 0) + file.read_exact_at_volatile(VolatileSlice::new(ehdr.as_mut_bytes()), 0) .map_err(|_| Error::ReadHeader)?; let ehdr: elf::Elf64_Ehdr = ehdr.into(); @@ -321,7 +321,7 @@ where let num_phdrs = ehdr.e_phnum as usize; let mut phdrs = vec![ProgramHeader::default(); num_phdrs]; - file.read_exact_at_volatile(VolatileSlice::new(phdrs.as_bytes_mut()), ehdr.e_phoff) + file.read_exact_at_volatile(VolatileSlice::new(phdrs.as_mut_bytes()), ehdr.e_phoff) .map_err(|_| Error::ReadProgramHeader)?; Ok(Elf64 { diff --git a/kvm/Cargo.toml b/kvm/Cargo.toml index 05488b4f0..23c23e064 100644 --- a/kvm/Cargo.toml +++ b/kvm/Cargo.toml @@ -12,4 +12,4 @@ base = { path = "../base" } static_assertions = "1.1" sync = { path = "../common/sync" } vm_memory = { path = "../vm_memory" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/kvm/src/lib.rs b/kvm/src/lib.rs index 4cb6ef09b..c42814d26 100644 --- a/kvm/src/lib.rs +++ b/kvm/src/lib.rs @@ -89,18 +89,20 @@ use sync::Mutex; use vm_memory::GuestAddress; use vm_memory::GuestMemory; #[cfg(target_arch = "x86_64")] -use zerocopy::AsBytes; -#[cfg(target_arch = "x86_64")] use zerocopy::FromBytes; #[cfg(target_arch = "x86_64")] -use zerocopy::FromZeroes; +use zerocopy::Immutable; +#[cfg(target_arch = "x86_64")] +use zerocopy::IntoBytes; +#[cfg(target_arch = "x86_64")] +use zerocopy::KnownLayout; pub use crate::cap::*; /// A structure with the same layout as `kvm_ioapic_state` but without the union, making it /// zerocopy-able. #[cfg(target_arch = "x86_64")] -#[derive(Copy, Clone, Default, Debug, AsBytes, FromBytes, FromZeroes)] +#[derive(Copy, Clone, Default, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C)] pub struct IoapicState { pub base_address: u64, diff --git a/kvm_sys/Cargo.toml b/kvm_sys/Cargo.toml index 3d79d17e3..ec9f770b3 100644 --- a/kvm_sys/Cargo.toml +++ b/kvm_sys/Cargo.toml @@ -8,4 +8,4 @@ edition = "2021" data_model = { path = "../common/data_model" } libc = "0.2" base = { path = "../base" } -zerocopy = {version = "0.7", features = ["derive"]} +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/kvm_sys/bindgen.sh b/kvm_sys/bindgen.sh index 43a751102..dd5f19498 100755 --- a/kvm_sys/bindgen.sh +++ b/kvm_sys/bindgen.sh @@ -11,9 +11,10 @@ cd "$(dirname "${BASH_SOURCE[0]}")/.." source tools/impl/bindgen-common.sh KVM_EXTRAS="// Added by kvm_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; // TODO(b/388092267): Replace this with an upstream equivalent when available. // The original index (236) used in the ChromeOS v6.6 kernel was reused upstream for another @@ -52,26 +53,26 @@ bindgen_generate \ --blocklist-item='__BITS_PER_.*' \ --blocklist-item='__FD_SETSIZE' \ --blocklist-item='_?IOC.*' \ - --with-derive-custom "kvm_regs=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_sregs=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_fpu=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_debugregs=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_xcr=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_xcrs=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_lapic_state=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_mp_state=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events__bindgen_ty_1=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events__bindgen_ty_2=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events__bindgen_ty_3=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events__bindgen_ty_4=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events__bindgen_ty_5=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_dtable=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_segment=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_pic_state=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_pit_state2=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_clock_data=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_pit_channel_state=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "kvm_regs=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_sregs=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_fpu=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_debugregs=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_xcr=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_xcrs=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_lapic_state=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_mp_state=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events__bindgen_ty_1=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events__bindgen_ty_2=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events__bindgen_ty_3=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events__bindgen_ty_4=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events__bindgen_ty_5=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_dtable=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_segment=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_pic_state=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_pit_state2=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_clock_data=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_pit_channel_state=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX_X86_HEADERS}/include/linux/kvm.h" \ -- \ -isystem "${BINDGEN_LINUX_X86_HEADERS}/include" \ @@ -84,14 +85,14 @@ bindgen_generate \ --blocklist-item='__BITS_PER_.*' \ --blocklist-item='__FD_SETSIZE' \ --blocklist-item='_?IOC.*' \ - --with-derive-custom "kvm_regs=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_sregs=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_fpu=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_vcpu_events__bindgen_ty_1=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "kvm_mp_state=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "user_fpsimd_state=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "user_pt_regs=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "kvm_regs=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_sregs=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_fpu=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_vcpu_events__bindgen_ty_1=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "kvm_mp_state=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "user_fpsimd_state=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "user_pt_regs=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX_ARM64_HEADERS}/include/linux/kvm.h" \ -- \ -isystem "${BINDGEN_LINUX_ARM64_HEADERS}/include" \ diff --git a/kvm_sys/src/aarch64/bindings.rs b/kvm_sys/src/aarch64/bindings.rs index 980532dec..512d66246 100644 --- a/kvm_sys/src/aarch64/bindings.rs +++ b/kvm_sys/src/aarch64/bindings.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by kvm_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; // TODO(b/388092267): Replace this with an upstream equivalent when available. // The original index (236) used in the ChromeOS v6.6 kernel was reused upstream for another @@ -828,7 +829,7 @@ pub type __sum16 = u16; pub type __wsum = u32; pub type __poll_t = ::std::os::raw::c_uint; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct user_pt_regs { pub regs: [u64; 31usize], pub sp: u64, @@ -837,7 +838,7 @@ pub struct user_pt_regs { } #[repr(C)] #[repr(align(16))] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct user_fpsimd_state { pub vregs: [__uint128_t; 32usize], pub fpsr: u32, @@ -901,7 +902,7 @@ pub struct user_za_header { } #[repr(C)] #[repr(align(16))] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_regs { pub regs: user_pt_regs, pub sp_el1: u64, @@ -917,10 +918,10 @@ pub struct kvm_vcpu_init { pub features: [u32; 7usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_sregs {} #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_fpu {} #[repr(C)] #[derive(Debug, Default, Copy, Clone)] @@ -951,13 +952,13 @@ pub struct kvm_pmu_event_filter { pub pad: [u8; 3usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events { pub exception: kvm_vcpu_events__bindgen_ty_1, pub reserved: [u32; 12usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events__bindgen_ty_1 { pub serror_pending: u8, pub serror_has_esr: u8, @@ -1726,7 +1727,7 @@ pub struct kvm_vapic_addr { pub vapic_addr: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_mp_state { pub mp_state: u32, } diff --git a/kvm_sys/src/riscv64/bindings.rs b/kvm_sys/src/riscv64/bindings.rs index 0bc628d57..f062cf45c 100644 --- a/kvm_sys/src/riscv64/bindings.rs +++ b/kvm_sys/src/riscv64/bindings.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by kvm_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; // TODO(b/388092267): Replace this with an upstream equivalent when available. // The original index (236) used in the ChromeOS v6.6 kernel was reused upstream for another diff --git a/kvm_sys/src/x86/bindings.rs b/kvm_sys/src/x86/bindings.rs index 4b6366731..d87d3391a 100644 --- a/kvm_sys/src/x86/bindings.rs +++ b/kvm_sys/src/x86/bindings.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by kvm_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; // TODO(b/388092267): Replace this with an upstream equivalent when available. // The original index (236) used in the ChromeOS v6.6 kernel was reused upstream for another @@ -758,7 +759,7 @@ pub type __sum16 = u16; pub type __wsum = u32; pub type __poll_t = ::std::os::raw::c_uint; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_pic_state { pub last_irr: u8, pub irr: u8, @@ -957,7 +958,7 @@ impl Default for kvm_ioapic_state { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_regs { pub rax: u64, pub rbx: u64, @@ -979,7 +980,7 @@ pub struct kvm_regs { pub rflags: u64, } #[repr(C)] -#[derive(Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_lapic_state { pub regs: [::std::os::raw::c_char; 1024usize], } @@ -993,7 +994,7 @@ impl Default for kvm_lapic_state { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_segment { pub base: u64, pub limit: u32, @@ -1010,14 +1011,14 @@ pub struct kvm_segment { pub padding: u8, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_dtable { pub base: u64, pub limit: u16, pub padding: [u16; 3usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_sregs { pub cs: kvm_segment, pub ds: kvm_segment, @@ -1062,7 +1063,7 @@ pub struct kvm_sregs2 { pub pdptrs: [u64; 4usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_fpu { pub fpr: [[u8; 16usize]; 8usize], pub fcw: u16, @@ -1165,7 +1166,7 @@ pub struct kvm_cpuid2 { pub entries: __IncompleteArrayField, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_pit_channel_state { pub count: u32, pub latched_count: u16, @@ -1201,7 +1202,7 @@ pub struct kvm_pit_state { pub channels: [kvm_pit_channel_state; 3usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_pit_state2 { pub channels: [kvm_pit_channel_state; 3usize], pub flags: u32, @@ -1214,7 +1215,7 @@ pub struct kvm_reinject_control { pub reserved: [u8; 31usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events { pub exception: kvm_vcpu_events__bindgen_ty_1, pub interrupt: kvm_vcpu_events__bindgen_ty_2, @@ -1228,7 +1229,7 @@ pub struct kvm_vcpu_events { pub exception_payload: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events__bindgen_ty_1 { pub injected: u8, pub nr: u8, @@ -1237,7 +1238,7 @@ pub struct kvm_vcpu_events__bindgen_ty_1 { pub error_code: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events__bindgen_ty_2 { pub injected: u8, pub nr: u8, @@ -1245,7 +1246,7 @@ pub struct kvm_vcpu_events__bindgen_ty_2 { pub shadow: u8, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events__bindgen_ty_3 { pub injected: u8, pub pending: u8, @@ -1253,7 +1254,7 @@ pub struct kvm_vcpu_events__bindgen_ty_3 { pub pad: u8, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events__bindgen_ty_4 { pub smm: u8, pub pending: u8, @@ -1261,12 +1262,12 @@ pub struct kvm_vcpu_events__bindgen_ty_4 { pub latched_init: u8, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_vcpu_events__bindgen_ty_5 { pub pending: u8, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_debugregs { pub db: [u64; 4usize], pub dr6: u64, @@ -1290,14 +1291,14 @@ impl Default for kvm_xsave { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_xcr { pub xcr: u32, pub reserved: u32, pub value: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_xcrs { pub nr_xcrs: u32, pub flags: u32, @@ -2545,7 +2546,7 @@ pub struct kvm_vapic_addr { pub vapic_addr: u64, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_mp_state { pub mp_state: u32, } @@ -2721,7 +2722,7 @@ pub struct kvm_irqfd { pub pad: [u8; 16usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct kvm_clock_data { pub clock: u64, pub flags: u32, diff --git a/linux_input_sys/Cargo.toml b/linux_input_sys/Cargo.toml index 6036868c7..a8c273f13 100644 --- a/linux_input_sys/Cargo.toml +++ b/linux_input_sys/Cargo.toml @@ -8,4 +8,4 @@ edition = "2021" data_model = { path = "../common/data_model" } libc = "0.2" base = { path = "../base" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/linux_input_sys/src/lib.rs b/linux_input_sys/src/lib.rs index 06df9871d..3ac7accc8 100644 --- a/linux_input_sys/src/lib.rs +++ b/linux_input_sys/src/lib.rs @@ -11,9 +11,10 @@ use std::mem::size_of; use constants::*; use data_model::Le16; use data_model::SLe32; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; /// Allows a raw input event of the implementor's type to be decoded into /// a virtio_input_event. @@ -22,7 +23,9 @@ pub trait InputEventDecoder { fn decode(data: &[u8]) -> virtio_input_event; } -#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, FromZeroes, FromBytes, AsBytes)] +#[derive( + Copy, Clone, Debug, Default, Eq, PartialEq, FromBytes, Immutable, IntoBytes, KnownLayout, +)] #[repr(C)] pub struct input_event { pub timestamp_fields: [u64; 2], @@ -46,7 +49,7 @@ impl InputEventDecoder for input_event { const SIZE: usize = size_of::(); fn decode(data: &[u8]) -> virtio_input_event { - let e = input_event::read_from(data).unwrap(); + let e = input_event::read_from_bytes(data).unwrap(); virtio_input_event { type_: Le16::from(e.type_), code: Le16::from(e.code), @@ -55,7 +58,9 @@ impl InputEventDecoder for input_event { } } -#[derive(Copy, Clone, Debug, Default, Eq, PartialEq, AsBytes, FromZeroes, FromBytes)] +#[derive( + Copy, Clone, Debug, Default, Eq, PartialEq, FromBytes, Immutable, IntoBytes, KnownLayout, +)] #[repr(C)] pub struct virtio_input_event { pub type_: Le16, @@ -67,7 +72,7 @@ impl InputEventDecoder for virtio_input_event { const SIZE: usize = size_of::(); fn decode(data: &[u8]) -> virtio_input_event { - virtio_input_event::read_from(data).unwrap() + virtio_input_event::read_from_bytes(data).unwrap() } } diff --git a/net_util/Cargo.toml b/net_util/Cargo.toml index 3d11c4145..7b573e2a1 100644 --- a/net_util/Cargo.toml +++ b/net_util/Cargo.toml @@ -22,7 +22,7 @@ serde = { version = "1", features = [ "derive" ] } smallvec = "1" thiserror = "1" virtio_sys = { path = "../virtio_sys" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(any(target_os = "android", target_os = "linux"))'.dependencies] net_sys = { path = "../net_sys" } diff --git a/net_util/src/slirp/sys/windows/handler.rs b/net_util/src/slirp/sys/windows/handler.rs index 9ac679a6e..6409c125b 100644 --- a/net_util/src/slirp/sys/windows/handler.rs +++ b/net_util/src/slirp/sys/windows/handler.rs @@ -55,7 +55,7 @@ use winapi::um::winsock2::SOCKET; use winapi::um::winsock2::SOCKET_ERROR; use winapi::um::winsock2::WSADATA; use winapi::um::winsock2::WSAPOLLFD; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::slirp::context::CallbackHandler; use crate::slirp::context::Context; diff --git a/perfetto/Cargo.toml b/perfetto/Cargo.toml index f4ac3824d..27a2f9ccd 100644 --- a/perfetto/Cargo.toml +++ b/perfetto/Cargo.toml @@ -22,7 +22,7 @@ protobuf = "3.2" serde = { version = "1", features = [ "derive" ] } sha2 = { version = "0.10", optional = true } sync = { path = "../common/sync" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [build-dependencies] proto_build_tools = { path = "../proto_build_tools" } diff --git a/perfetto/src/lib.rs b/perfetto/src/lib.rs index b9af3c74a..229a7e60d 100644 --- a/perfetto/src/lib.rs +++ b/perfetto/src/lib.rs @@ -26,16 +26,17 @@ use protos::perfetto_config::trace_config::IncrementalStateConfig; use protos::perfetto_config::DataSourceConfig; use protos::perfetto_config::TraceConfig; use protos::perfetto_config::TrackEventConfig; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; /// Randomly generated GUID to help locate the AOT header. const HEADER_MAGIC: &[u8; 16] = b"\x8d\x10\xa3\xee\x79\x1f\x47\x25\xb2\xb8\xb8\x9f\x85\xe7\xd6\x7c"; /// The optional header written ahead of the trace data. #[repr(C)] -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] struct TraceHeader { magic: [u8; 16], data_size: u64, diff --git a/src/crosvm/plugin/process.rs b/src/crosvm/plugin/process.rs index 70b44d40b..36defcbab 100644 --- a/src/crosvm/plugin/process.rs +++ b/src/crosvm/plugin/process.rs @@ -58,8 +58,8 @@ use protobuf::Message; use protos::plugin::*; use sync::Mutex; use vm_memory::GuestAddress; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::IntoBytes; use super::*; @@ -84,23 +84,28 @@ fn set_vm_state( ) -> SysResult<()> { match state_set.enum_value().map_err(|_| SysError::new(EINVAL))? { main_request::StateSet::PIC0 => { - let pic_state = kvm_pic_state::read_from(state).ok_or(SysError::new(EINVAL))?; + let pic_state = + kvm_pic_state::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vm.set_pic_state(PicId::Primary, &pic_state) } main_request::StateSet::PIC1 => { - let pic_state = kvm_pic_state::read_from(state).ok_or(SysError::new(EINVAL))?; + let pic_state = + kvm_pic_state::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vm.set_pic_state(PicId::Secondary, &pic_state) } main_request::StateSet::IOAPIC => { - let ioapic_state = IoapicState::read_from(state).ok_or(SysError::new(EINVAL))?; + let ioapic_state = + IoapicState::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vm.set_ioapic_state(&ioapic_state) } main_request::StateSet::PIT => { - let pit_state = kvm_pit_state2::read_from(state).ok_or(SysError::new(EINVAL))?; + let pit_state = + kvm_pit_state2::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vm.set_pit_state(&pit_state) } main_request::StateSet::CLOCK => { - let clock_data = kvm_clock_data::read_from(state).ok_or(SysError::new(EINVAL))?; + let clock_data = + kvm_clock_data::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vm.set_clock(&clock_data) } } diff --git a/src/crosvm/plugin/vcpu.rs b/src/crosvm/plugin/vcpu.rs index 54d85bc3e..98218bebe 100644 --- a/src/crosvm/plugin/vcpu.rs +++ b/src/crosvm/plugin/vcpu.rs @@ -45,8 +45,8 @@ use protobuf::Message; use protos::plugin::*; use static_assertions::const_assert; use sync::Mutex; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::IntoBytes; use super::*; @@ -118,35 +118,39 @@ fn set_vcpu_state_enum_or_unknown( fn set_vcpu_state(vcpu: &Vcpu, state_set: vcpu_request::StateSet, state: &[u8]) -> SysResult<()> { match state_set { vcpu_request::StateSet::REGS => { - let regs = kvm_regs::read_from(state).ok_or(SysError::new(EINVAL))?; + let regs = kvm_regs::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_regs(®s) } vcpu_request::StateSet::SREGS => { - let sregs = kvm_sregs::read_from(state).ok_or(SysError::new(EINVAL))?; + let sregs = kvm_sregs::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_sregs(&sregs) } vcpu_request::StateSet::FPU => { - let fpu = kvm_fpu::read_from(state).ok_or(SysError::new(EINVAL))?; + let fpu = kvm_fpu::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_fpu(&fpu) } vcpu_request::StateSet::DEBUGREGS => { - let debugregs = kvm_debugregs::read_from(state).ok_or(SysError::new(EINVAL))?; + let debugregs = + kvm_debugregs::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_debugregs(&debugregs) } vcpu_request::StateSet::XCREGS => { - let xcrs = kvm_xcrs::read_from(state).ok_or(SysError::new(EINVAL))?; + let xcrs = kvm_xcrs::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_xcrs(&xcrs) } vcpu_request::StateSet::LAPIC => { - let lapic_state = kvm_lapic_state::read_from(state).ok_or(SysError::new(EINVAL))?; + let lapic_state = + kvm_lapic_state::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_lapic(&lapic_state) } vcpu_request::StateSet::MP => { - let mp_state = kvm_mp_state::read_from(state).ok_or(SysError::new(EINVAL))?; + let mp_state = + kvm_mp_state::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_mp_state(&mp_state) } vcpu_request::StateSet::EVENTS => { - let vcpu_events = kvm_vcpu_events::read_from(state).ok_or(SysError::new(EINVAL))?; + let vcpu_events = + kvm_vcpu_events::read_from_bytes(state).map_err(|_| SysError::new(EINVAL))?; vcpu.set_vcpu_events(&vcpu_events) } } diff --git a/third_party/vmm_vhost/Cargo.toml b/third_party/vmm_vhost/Cargo.toml index 304817e64..50d69b22a 100644 --- a/third_party/vmm_vhost/Cargo.toml +++ b/third_party/vmm_vhost/Cargo.toml @@ -22,7 +22,7 @@ enumn = "0.1.0" libc = ">=0.2.39" remain = "0.2" thiserror = { version = "1.0.20" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(windows)'.dependencies] serde = { version = "1", features = [ "derive" ] } diff --git a/third_party/vmm_vhost/src/backend_client.rs b/third_party/vmm_vhost/src/backend_client.rs index fd6ae3b3d..a44d01027 100644 --- a/third_party/vmm_vhost/src/backend_client.rs +++ b/third_party/vmm_vhost/src/backend_client.rs @@ -11,8 +11,9 @@ use base::Event; use base::RawDescriptor; use base::ReadNotifier; use base::INVALID_DESCRIPTOR; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::backend::VhostUserMemoryRegionInfo; use crate::backend::VringConfigData; @@ -518,8 +519,10 @@ impl BackendClient { for _ in 0..body_reply.value { regions.push( // Can't fail because the input is the correct size. - VhostSharedMemoryRegion::read_from(&buf_reply[offset..(offset + struct_size)]) - .unwrap(), + VhostSharedMemoryRegion::read_from_bytes( + &buf_reply[offset..(offset + struct_size)], + ) + .unwrap(), ); offset += struct_size; } @@ -536,7 +539,7 @@ impl BackendClient { Ok(hdr) } - fn send_request_with_body( + fn send_request_with_body( &self, code: FrontendReq, msg: &T, @@ -547,7 +550,7 @@ impl BackendClient { Ok(hdr) } - fn send_request_with_payload( + fn send_request_with_payload( &self, code: FrontendReq, msg: &T, @@ -588,7 +591,7 @@ impl BackendClient { Ok(hdr) } - fn recv_reply( + fn recv_reply( &self, hdr: &VhostUserMsgHeader, ) -> VhostUserResult { @@ -604,7 +607,7 @@ impl BackendClient { Ok(body) } - fn recv_reply_with_files( + fn recv_reply_with_files( &self, hdr: &VhostUserMsgHeader, ) -> VhostUserResult<(T, Vec)> { @@ -621,7 +624,9 @@ impl BackendClient { Ok((body, files)) } - fn recv_reply_with_payload( + fn recv_reply_with_payload< + T: Sized + IntoBytes + FromBytes + Default + VhostUserMsgValidator, + >( &self, hdr: &VhostUserMsgHeader, ) -> VhostUserResult<(T, Vec, Vec)> { diff --git a/third_party/vmm_vhost/src/backend_server.rs b/third_party/vmm_vhost/src/backend_server.rs index e910c94b7..b03debd1d 100644 --- a/third_party/vmm_vhost/src/backend_server.rs +++ b/third_party/vmm_vhost/src/backend_server.rs @@ -7,8 +7,9 @@ use std::mem; use base::AsRawDescriptor; use base::RawDescriptor; use base::SafeDescriptor; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use zerocopy::Ref; use crate::into_single_file; @@ -695,7 +696,7 @@ impl BackendServer { Ok(()) } - fn send_reply_message( + fn send_reply_message( &mut self, req: &VhostUserMsgHeader, msg: &T, @@ -705,7 +706,7 @@ impl BackendServer { Ok(()) } - fn send_reply_with_payload( + fn send_reply_with_payload( &mut self, req: &VhostUserMsgHeader, msg: &T, @@ -727,7 +728,7 @@ impl BackendServer { self.check_request_size(hdr, size, hdr.get_size() as usize)?; let (msg, regions) = - Ref::<_, VhostUserMemory>::new_from_prefix(buf).ok_or(Error::InvalidMessage)?; + Ref::<_, VhostUserMemory>::from_prefix(buf).map_err(|_| Error::InvalidMessage)?; if !msg.is_valid() { return Err(Error::InvalidMessage); } @@ -737,11 +738,11 @@ impl BackendServer { return Err(Error::InvalidMessage); } - let (regions, excess) = Ref::<_, [VhostUserMemoryRegion]>::new_slice_from_prefix( + let (regions, excess) = Ref::<_, [VhostUserMemoryRegion]>::from_prefix_with_elems( regions, msg.num_regions as usize, ) - .ok_or(Error::InvalidMessage)?; + .map_err(|_| Error::InvalidMessage)?; if !excess.is_empty() { return Err(Error::InvalidMessage); } @@ -758,7 +759,7 @@ impl BackendServer { fn get_config(&mut self, hdr: &VhostUserMsgHeader, buf: &[u8]) -> Result<()> { let (msg, payload) = - Ref::<_, VhostUserConfig>::new_from_prefix(buf).ok_or(Error::InvalidMessage)?; + Ref::<_, VhostUserConfig>::from_prefix(buf).map_err(|_| Error::InvalidMessage)?; if !msg.is_valid() { return Err(Error::InvalidMessage); } @@ -792,7 +793,7 @@ impl BackendServer { fn set_config(&mut self, buf: &[u8]) -> Result<()> { let (msg, payload) = - Ref::<_, VhostUserConfig>::new_from_prefix(buf).ok_or(Error::InvalidMessage)?; + Ref::<_, VhostUserConfig>::from_prefix(buf).map_err(|_| Error::InvalidMessage)?; if !msg.is_valid() { return Err(Error::InvalidMessage); } @@ -822,7 +823,7 @@ impl BackendServer { buf: &[u8], files: Vec, ) -> Result<(u8, Option)> { - let msg = VhostUserU64::read_from_prefix(buf).ok_or(Error::InvalidMessage)?; + let (msg, _) = VhostUserU64::read_from_prefix(buf).map_err(|_| Error::InvalidMessage)?; if !msg.is_valid() { return Err(Error::InvalidMessage); } @@ -889,9 +890,12 @@ impl BackendServer { buf: &[u8], ) -> Result { self.check_request_size(hdr, size, mem::size_of::())?; - T::read_from_prefix(buf) - .filter(T::is_valid) - .ok_or(Error::InvalidMessage) + let (body, _) = T::read_from_prefix(buf).map_err(|_| Error::InvalidMessage)?; + if body.is_valid() { + Ok(body) + } else { + Err(Error::InvalidMessage) + } } fn update_reply_ack_flag(&mut self) { diff --git a/third_party/vmm_vhost/src/connection.rs b/third_party/vmm_vhost/src/connection.rs index 4b0442164..354241fce 100644 --- a/third_party/vmm_vhost/src/connection.rs +++ b/third_party/vmm_vhost/src/connection.rs @@ -9,8 +9,9 @@ use std::mem; use base::AsRawDescriptor; use base::RawDescriptor; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::connection::Req; use crate::message::FrontendReq; @@ -75,7 +76,7 @@ impl Connection { /// Send a message with header and body. Optional file descriptors may be attached to /// the message. - pub fn send_message( + pub fn send_message( &self, hdr: &VhostUserMsgHeader, body: &T, @@ -87,7 +88,7 @@ impl Connection { /// Send a message with header and body. `payload` is appended to the end of the body. Optional /// file descriptors may also be attached to the message. - pub fn send_message_with_payload( + pub fn send_message_with_payload( &self, hdr: &VhostUserMsgHeader, body: &T, @@ -148,7 +149,7 @@ impl Connection { /// other file descriptor will be discard silently. pub fn recv_header(&self) -> Result<(VhostUserMsgHeader, Vec)> { let mut hdr_raw = [0u32; 3]; - let files = self.recv_into_bufs_all(&mut [hdr_raw.as_bytes_mut()])?; + let files = self.recv_into_bufs_all(&mut [hdr_raw.as_mut_bytes()])?; let hdr = VhostUserMsgHeader::from_raw(hdr_raw); if !hdr.is_valid() { return Err(Error::InvalidMessage); @@ -174,12 +175,12 @@ impl Connection { /// /// Note, only the first MAX_ATTACHED_FD_ENTRIES file descriptors will be /// accepted and all other file descriptor will be discard silently. - pub fn recv_message( + pub fn recv_message( &self, ) -> Result<(VhostUserMsgHeader, T, Vec)> { let mut hdr_raw = [0u32; 3]; let mut body = T::new_zeroed(); - let mut slices = [hdr_raw.as_bytes_mut(), body.as_bytes_mut()]; + let mut slices = [hdr_raw.as_mut_bytes(), body.as_mut_bytes()]; let files = self.recv_into_bufs_all(&mut slices)?; let hdr = VhostUserMsgHeader::from_raw(hdr_raw); @@ -197,7 +198,7 @@ impl Connection { /// /// Note, only the first MAX_ATTACHED_FD_ENTRIES file descriptors will be accepted and all /// other file descriptor will be discard silently. - pub fn recv_message_with_payload( + pub fn recv_message_with_payload( &self, ) -> Result<(VhostUserMsgHeader, T, Vec, Vec)> { let (hdr, files) = self.recv_header()?; @@ -205,7 +206,7 @@ impl Connection { let mut body = T::new_zeroed(); let payload_size = hdr.get_size() as usize - mem::size_of::(); let mut buf: Vec = vec![0; payload_size]; - let mut slices = [body.as_bytes_mut(), buf.as_bytes_mut()]; + let mut slices = [body.as_mut_bytes(), buf.as_mut_bytes()]; let more_files = self.recv_into_bufs_all(&mut slices)?; if !body.is_valid() || !more_files.is_empty() { return Err(Error::InvalidMessage); diff --git a/third_party/vmm_vhost/src/frontend_client.rs b/third_party/vmm_vhost/src/frontend_client.rs index 593ec27ef..549addd0f 100644 --- a/third_party/vmm_vhost/src/frontend_client.rs +++ b/third_party/vmm_vhost/src/frontend_client.rs @@ -6,7 +6,8 @@ use std::string::ToString; use base::AsRawDescriptor; use base::RawDescriptor; -use zerocopy::AsBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::message::*; use crate::BackendReq; @@ -44,7 +45,7 @@ impl FrontendClient { fds: Option<&[RawDescriptor]>, ) -> HandlerResult where - T: AsBytes, + T: IntoBytes + Immutable, { let len = mem::size_of::(); let mut hdr = VhostUserMsgHeader::new(request, 0, len as u32); diff --git a/third_party/vmm_vhost/src/message.rs b/third_party/vmm_vhost/src/message.rs index 40d795fda..c6553fda2 100644 --- a/third_party/vmm_vhost/src/message.rs +++ b/third_party/vmm_vhost/src/message.rs @@ -14,9 +14,10 @@ use std::marker::PhantomData; use base::Protection; use bitflags::bitflags; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::VringConfigData; @@ -461,7 +462,7 @@ bitflags! { /// A generic message to encapsulate a 64-bit value. #[repr(C, packed)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserU64 { /// The encapsulated 64-bit common value. pub value: u64, @@ -478,7 +479,7 @@ impl VhostUserMsgValidator for VhostUserU64 {} /// An empty message. #[repr(C)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserEmptyMsg; impl VhostUserMsgValidator for VhostUserEmptyMsg {} @@ -486,14 +487,14 @@ impl VhostUserMsgValidator for VhostUserEmptyMsg {} /// A generic message for empty message. /// ZST in repr(C) has same type layout as repr(rust) #[repr(C)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserEmptyMessage; impl VhostUserMsgValidator for VhostUserEmptyMessage {} /// Memory region descriptor for the SET_MEM_TABLE request. #[repr(C, packed)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserMemory { /// Number of memory regions in the payload. pub num_regions: u32, @@ -525,7 +526,7 @@ impl VhostUserMsgValidator for VhostUserMemory { /// Memory region descriptors as payload for the SET_MEM_TABLE request. #[repr(C, packed)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserMemoryRegion { /// Guest physical address of the memory region. pub guest_phys_addr: u64, @@ -568,7 +569,7 @@ pub type VhostUserMemoryPayload = Vec; /// Single memory region descriptor as payload for ADD_MEM_REG and REM_MEM_REG /// requests. #[repr(C)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserSingleMemoryRegion { /// Padding for correct alignment padding: u64, @@ -610,7 +611,7 @@ impl VhostUserMsgValidator for VhostUserSingleMemoryRegion { /// Vring state descriptor. #[repr(C, packed)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserVringState { /// Vring index. pub index: u32, @@ -641,7 +642,7 @@ bitflags! { /// Vring address descriptor. #[repr(C, packed)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserVringAddr { /// Vring index. pub index: u32, @@ -722,7 +723,7 @@ bitflags! { /// Message to read/write device configuration space. #[repr(C, packed)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserConfig { /// Offset of virtio device's configuration space. pub offset: u32, @@ -768,7 +769,7 @@ pub type VhostUserConfigPayload = Vec; /// Interestingly, all our supported archs (arm, aarch64, x86_64) has same /// data layout for this type. #[repr(C)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserInflight { /// Size of the area to track inflight I/O. pub mmap_size: u64, @@ -806,7 +807,7 @@ impl VhostUserMsgValidator for VhostUserInflight { /// VHOST_USER_SET_DEVICE_STATE_FD request payload. #[repr(C)] -#[derive(Default, Clone, Copy, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct DeviceStateTransferParameters { /// Direction in which the state is transferred pub transfer_direction: u32, @@ -850,9 +851,10 @@ pub struct VhostUserIotlb { /// Flags for SHMEM_MAP messages. #[repr(transparent)] #[derive( - AsBytes, - FromZeroes, FromBytes, + Immutable, + IntoBytes, + KnownLayout, Copy, Clone, Debug, @@ -900,7 +902,7 @@ impl From for Protection { /// Backend request message to map a file into a shared memory region. #[repr(C, packed)] -#[derive(Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserShmemMapMsg { /// Flags for the mmap operation pub flags: VhostUserShmemMapMsgFlags, @@ -945,7 +947,7 @@ impl VhostUserShmemMapMsg { /// Backend request message to map GPU memory into a shared memory region. #[repr(C, packed)] -#[derive(Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserGpuMapMsg { /// Shared memory region id. pub shmid: u8, @@ -996,7 +998,7 @@ impl VhostUserGpuMapMsg { /// Backend request message to map external memory into a shared memory region. #[repr(C, packed)] -#[derive(Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserExternalMapMsg { /// Shared memory region id. pub shmid: u8, @@ -1030,7 +1032,7 @@ impl VhostUserExternalMapMsg { /// Backend request message to unmap part of a shared memory region. #[repr(C, packed)] -#[derive(Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostUserShmemUnmapMsg { /// Shared memory region id. pub shmid: u8, @@ -1192,7 +1194,7 @@ impl QueueRegionPacked { /// Virtio shared memory descriptor. #[repr(C, packed)] -#[derive(Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct VhostSharedMemoryRegion { /// The shared memory region's shmid. pub id: u8, diff --git a/usb_util/Cargo.toml b/usb_util/Cargo.toml index aa92d3898..c34644c2f 100644 --- a/usb_util/Cargo.toml +++ b/usb_util/Cargo.toml @@ -13,4 +13,4 @@ thiserror = "1" base = { path = "../base" } usb_sys = { path = "../usb_sys" } sync = { path = "../common/sync" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/usb_util/src/descriptor.rs b/usb_util/src/descriptor.rs index 626e5b136..ecc4d91ec 100644 --- a/usb_util/src/descriptor.rs +++ b/usb_util/src/descriptor.rs @@ -131,11 +131,11 @@ pub fn parse_usbfs_descriptors(data: &[u8]) -> Result { ) -> Result<(T, usize)> { let desc_type = T::descriptor_type() as u8; loop { - let hdr = DescriptorHeader::read_from( + let hdr = DescriptorHeader::read_from_bytes( data.get(*offset..*offset + size_of::()) .ok_or(Error::DescriptorParse)?, ) - .ok_or(Error::DescriptorParse)?; + .map_err(|_| Error::DescriptorParse)?; if hdr.bDescriptorType == desc_type { if usize::from(hdr.bLength) < size_of::() + size_of::() { return Err(Error::DescriptorParse); @@ -144,11 +144,11 @@ pub fn parse_usbfs_descriptors(data: &[u8]) -> Result { let desc_offset = *offset; *offset += size_of::(); - let desc = T::read_from( + let desc = T::read_from_bytes( data.get(*offset..*offset + size_of::()) .ok_or(Error::DescriptorParse)?, ) - .ok_or(Error::DescriptorParse)?; + .map_err(|_| Error::DescriptorParse)?; *offset += hdr.bLength as usize - size_of::(); return Ok((desc, desc_offset)); } else { diff --git a/usb_util/src/types.rs b/usb_util/src/types.rs index 125c05489..9aad2d7fb 100644 --- a/usb_util/src/types.rs +++ b/usb_util/src/types.rs @@ -5,9 +5,10 @@ use std::mem::size_of; use static_assertions::const_assert; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; /// Standard USB descriptor types. pub enum DescriptorType { @@ -25,7 +26,7 @@ pub trait Descriptor { /// Standard USB descriptor header common to all descriptor types. #[allow(non_snake_case)] -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct DescriptorHeader { pub bLength: u8, @@ -39,7 +40,7 @@ fn _assert_descriptor_header() { /// Standard USB device descriptor as defined in USB 2.0 chapter 9, /// not including the standard header. #[allow(non_snake_case)] -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct DeviceDescriptor { pub bcdUSB: u16, @@ -69,7 +70,7 @@ fn _assert_device_descriptor() { /// Standard USB configuration descriptor as defined in USB 2.0 chapter 9, /// not including the standard header. #[allow(non_snake_case)] -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct ConfigDescriptor { pub wTotalLength: u16, @@ -99,7 +100,7 @@ impl ConfigDescriptor { /// Standard USB interface descriptor as defined in USB 2.0 chapter 9, /// not including the standard header. #[allow(non_snake_case)] -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct InterfaceDescriptor { pub bInterfaceNumber: u8, @@ -124,7 +125,7 @@ fn _assert_interface_descriptor() { /// Standard USB endpoint descriptor as defined in USB 2.0 chapter 9, /// not including the standard header. #[allow(non_snake_case)] -#[derive(Copy, Clone, Debug, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct EndpointDescriptor { pub bEndpointAddress: u8, @@ -248,7 +249,7 @@ pub enum StandardControlRequest { /// RequestSetup is first part of control transfer buffer. #[repr(C, packed)] -#[derive(Copy, Clone, Debug, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Debug, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct UsbRequestSetup { // USB Device Request. USB spec. rev. 2.0 9.3 pub request_type: u8, // bmRequestType diff --git a/vfio_sys/Cargo.toml b/vfio_sys/Cargo.toml index d6733a0da..a187ba693 100644 --- a/vfio_sys/Cargo.toml +++ b/vfio_sys/Cargo.toml @@ -6,4 +6,4 @@ edition = "2021" [dependencies] base = { path = "../base" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/vfio_sys/bindgen.sh b/vfio_sys/bindgen.sh index 80af56a60..adbc7c428 100755 --- a/vfio_sys/bindgen.sh +++ b/vfio_sys/bindgen.sh @@ -17,9 +17,10 @@ fix_vfio_type() { } VFIO_EXTRA="// Added by vfio_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; // TODO(b/292077398): Upstream or remove ACPI notification forwarding support pub const VFIO_PCI_ACPI_NTFY_IRQ_INDEX: std::os::raw::c_uint = 5; @@ -47,9 +48,9 @@ pub struct vfio_region_info_with_cap { } // vfio_iommu_type1_info_cap_iova_range minus the incomplete iova_ranges -// array, so that Copy/AsBytes/FromBytes can be implemented. +// array, so that zerocopy traits can be implemented. #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct vfio_iommu_type1_info_cap_iova_range_header { pub header: vfio_info_cap_header, pub nr_iovas: u32, @@ -64,8 +65,8 @@ bindgen_generate \ --allowlist-var='VFIO_.*' \ --blocklist-item='VFIO_DEVICE_API_.*_STRING' \ --allowlist-type='vfio_.*' \ - --with-derive-custom "vfio_info_cap_header=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "vfio_iova_range=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "vfio_info_cap_header=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "vfio_iova_range=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX}/include/uapi/linux/vfio.h" \ -- \ -D__user= \ diff --git a/vfio_sys/src/vfio.rs b/vfio_sys/src/vfio.rs index 927a1325a..c4558541d 100644 --- a/vfio_sys/src/vfio.rs +++ b/vfio_sys/src/vfio.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by vfio_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; // TODO(b/292077398): Upstream or remove ACPI notification forwarding support pub const VFIO_PCI_ACPI_NTFY_IRQ_INDEX: std::os::raw::c_uint = 5; @@ -39,9 +40,9 @@ pub struct vfio_region_info_with_cap { } // vfio_iommu_type1_info_cap_iova_range minus the incomplete iova_ranges -// array, so that Copy/AsBytes/FromBytes can be implemented. +// array, so that zerocopy traits can be implemented. #[repr(C)] -#[derive(Debug, Default, Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct vfio_iommu_type1_info_cap_iova_range_header { pub header: vfio_info_cap_header, pub nr_iovas: u32, @@ -219,7 +220,7 @@ pub const VFIO_EEH_PE_RESET_FUNDAMENTAL: u32 = 7; pub const VFIO_EEH_PE_CONFIGURE: u32 = 8; pub const VFIO_EEH_PE_INJECT_ERR: u32 = 9; #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct vfio_info_cap_header { pub id: u16, pub version: u16, @@ -572,7 +573,7 @@ pub struct vfio_iommu_type1_info { pub pad: u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct vfio_iova_range { pub start: u64, pub end: u64, diff --git a/virtio_sys/Cargo.toml b/virtio_sys/Cargo.toml index 0a0565b18..67dd93991 100644 --- a/virtio_sys/Cargo.toml +++ b/virtio_sys/Cargo.toml @@ -7,4 +7,4 @@ edition = "2021" [dependencies] base = { path = "../base" } data_model = { path = "../common/data_model" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } diff --git a/virtio_sys/bindgen.sh b/virtio_sys/bindgen.sh index b3d9609c6..37d88f91f 100755 --- a/virtio_sys/bindgen.sh +++ b/virtio_sys/bindgen.sh @@ -35,15 +35,16 @@ bindgen_generate \ VIRTIO_FS_EXTRA="// Added by virtio_sys/bindgen.sh use data_model::Le32; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes;" +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout;" bindgen_generate \ --raw-line "${VIRTIO_FS_EXTRA}" \ --allowlist-var='VIRTIO_FS_.*' \ --allowlist-type='virtio_fs_.*' \ - --with-derive-custom "virtio_fs_config=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "virtio_fs_config=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX_X86_HEADERS}/include/linux/virtio_fs.h" \ -- \ -isystem "${BINDGEN_LINUX_X86_HEADERS}/include" \ @@ -74,17 +75,18 @@ bindgen_generate \ > virtio_sys/src/virtio_ids.rs VIRTIO_NET_EXTRA="// Added by virtio_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes;" +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout;" bindgen_generate \ --raw-line "${VIRTIO_NET_EXTRA}" \ --allowlist-var='VIRTIO_NET_.*' \ --allowlist-type='virtio_net_.*' \ --blocklist-type='virtio_net_ctrl_mac' \ - --with-derive-custom "virtio_net_hdr=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_net_hdr_mrg_rxbuf=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "virtio_net_hdr=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_net_hdr_mrg_rxbuf=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX_X86_HEADERS}/include/linux/virtio_net.h" \ -- \ -isystem "${BINDGEN_LINUX_X86_HEADERS}/include" \ @@ -114,13 +116,16 @@ VIRTIO_VSOCK_EXTRA="// Added by virtio_sys/bindgen.sh use data_model::Le16; use data_model::Le32; use data_model::Le64; -use zerocopy::AsBytes;" +use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout;" bindgen_generate \ --raw-line "${VIRTIO_VSOCK_EXTRA}" \ --allowlist-var='VIRTIO_VSOCK_.*' \ --allowlist-type='virtio_vsock_.*' \ - --with-derive-custom "virtio_vsock_event=AsBytes" \ + --with-derive-custom "virtio_vsock_event=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX_X86_HEADERS}/include/linux/virtio_vsock.h" \ -- \ -isystem "${BINDGEN_LINUX_X86_HEADERS}/include" \ @@ -129,22 +134,23 @@ bindgen_generate \ > virtio_sys/src/virtio_vsock.rs VIRTIO_SCSI_EXTRA="// Added by virtio_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes;" +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout;" bindgen_generate \ --raw-line "${VIRTIO_SCSI_EXTRA}" \ --allowlist-var='VIRTIO_SCSI_.*' \ --allowlist-type='virtio_scsi_.*' \ --blocklist-type='virtio_scsi_cmd_req_pi' \ - --with-derive-custom "virtio_scsi_config=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_scsi_cmd_req=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_scsi_cmd_resp=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_scsi_ctrl_tmf_req=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_scsi_ctrl_an_req=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_scsi_ctrl_tmf_resp=FromZeroes,FromBytes,AsBytes" \ - --with-derive-custom "virtio_scsi_ctrl_an_resp=FromZeroes,FromBytes,AsBytes" \ + --with-derive-custom "virtio_scsi_config=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_scsi_cmd_req=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_scsi_cmd_resp=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_scsi_ctrl_tmf_req=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_scsi_ctrl_an_req=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_scsi_ctrl_tmf_resp=FromBytes,Immutable,IntoBytes,KnownLayout" \ + --with-derive-custom "virtio_scsi_ctrl_an_resp=FromBytes,Immutable,IntoBytes,KnownLayout" \ "${BINDGEN_LINUX_X86_HEADERS}/include/linux/virtio_scsi.h" \ -- \ -isystem "${BINDGEN_LINUX_X86_HEADERS}/include" \ diff --git a/virtio_sys/src/virtio_fs.rs b/virtio_sys/src/virtio_fs.rs index 5e82925a7..a87e4419e 100644 --- a/virtio_sys/src/virtio_fs.rs +++ b/virtio_sys/src/virtio_fs.rs @@ -10,13 +10,14 @@ // Added by virtio_sys/bindgen.sh use data_model::Le32; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const VIRTIO_FS_SHMCAP_ID_CACHE: u32 = 0; #[repr(C, packed)] -#[derive(Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_fs_config { pub tag: [u8; 36usize], pub num_request_queues: Le32, diff --git a/virtio_sys/src/virtio_net.rs b/virtio_sys/src/virtio_net.rs index db88af231..336d700c2 100644 --- a/virtio_sys/src/virtio_net.rs +++ b/virtio_sys/src/virtio_net.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by virtio_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[repr(C)] #[derive(Default)] @@ -248,7 +249,7 @@ impl Default for virtio_net_hdr_v1_hash { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_net_hdr { pub flags: u8, pub gso_type: u8, @@ -258,7 +259,7 @@ pub struct virtio_net_hdr { pub csum_offset: __virtio16, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_net_hdr_mrg_rxbuf { pub hdr: virtio_net_hdr, pub num_buffers: __virtio16, diff --git a/virtio_sys/src/virtio_scsi.rs b/virtio_sys/src/virtio_scsi.rs index f2142d629..60cd52b55 100644 --- a/virtio_sys/src/virtio_scsi.rs +++ b/virtio_sys/src/virtio_scsi.rs @@ -9,9 +9,10 @@ #![allow(dead_code)] // Added by virtio_sys/bindgen.sh -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const VIRTIO_SCSI_CDB_DEFAULT_SIZE: u32 = 32; pub const VIRTIO_SCSI_SENSE_DEFAULT_SIZE: u32 = 96; @@ -61,7 +62,7 @@ pub type __virtio16 = u16; pub type __virtio32 = u32; pub type __virtio64 = u64; #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_cmd_req { pub lun: [u8; 8usize], pub tag: __virtio64, @@ -71,7 +72,7 @@ pub struct virtio_scsi_cmd_req { pub cdb: [u8; 32usize], } #[repr(C, packed)] -#[derive(Debug, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_cmd_resp { pub sense_len: __virtio32, pub resid: __virtio32, @@ -90,7 +91,7 @@ impl Default for virtio_scsi_cmd_resp { } } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_ctrl_tmf_req { pub type_: __virtio32, pub subtype: __virtio32, @@ -98,19 +99,19 @@ pub struct virtio_scsi_ctrl_tmf_req { pub tag: __virtio64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_ctrl_tmf_resp { pub response: u8, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_ctrl_an_req { pub type_: __virtio32, pub lun: [u8; 8usize], pub event_requested: __virtio32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_ctrl_an_resp { pub event_actual: __virtio32, pub response: u8, @@ -123,7 +124,7 @@ pub struct virtio_scsi_event { pub reason: __virtio32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_scsi_config { pub num_queues: __virtio32, pub seg_max: __virtio32, diff --git a/virtio_sys/src/virtio_vsock.rs b/virtio_sys/src/virtio_vsock.rs index 804333de9..4f95034b1 100644 --- a/virtio_sys/src/virtio_vsock.rs +++ b/virtio_sys/src/virtio_vsock.rs @@ -12,7 +12,10 @@ use data_model::Le16; use data_model::Le32; use data_model::Le64; -use zerocopy::AsBytes; +use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const VIRTIO_VSOCK_F_SEQPACKET: u32 = 1; #[repr(C, packed)] @@ -23,7 +26,7 @@ pub struct virtio_vsock_config { pub const virtio_vsock_event_id_VIRTIO_VSOCK_EVENT_TRANSPORT_RESET: virtio_vsock_event_id = 0; pub type virtio_vsock_event_id = ::std::os::raw::c_uint; #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct virtio_vsock_event { pub id: Le32, } diff --git a/vm_memory/Cargo.toml b/vm_memory/Cargo.toml index 80b96c35b..5e1f9be5d 100644 --- a/vm_memory/Cargo.toml +++ b/vm_memory/Cargo.toml @@ -20,7 +20,7 @@ serde_json = "1" serde_keyvalue = { path = "../serde_keyvalue", features = ["argh_derive"] } snapshot = { workspace = true } thiserror = "1" -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [dev-dependencies] tempfile = "3" diff --git a/vm_memory/src/guest_memory.rs b/vm_memory/src/guest_memory.rs index c4a260a1d..f469b925a 100644 --- a/vm_memory/src/guest_memory.rs +++ b/vm_memory/src/guest_memory.rs @@ -37,8 +37,9 @@ use serde::Serialize; use serde_keyvalue::FromKeyValues; use snapshot::AnySnapshot; use thiserror::Error; -use zerocopy::AsBytes; use zerocopy::FromBytes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; use crate::guest_address::GuestAddress; @@ -719,7 +720,11 @@ impl GuestMemory { /// .map_err(|_| ()) /// # } /// ``` - pub fn write_obj_at_addr(&self, val: T, guest_addr: GuestAddress) -> Result<()> { + pub fn write_obj_at_addr( + &self, + val: T, + guest_addr: GuestAddress, + ) -> Result<()> { let (mapping, offset, _) = self.find_region(guest_addr)?; mapping .write_obj(val, offset) @@ -744,7 +749,7 @@ impl GuestMemory { /// .map_err(|_| ()) /// # } /// ``` - pub fn write_obj_at_addr_volatile( + pub fn write_obj_at_addr_volatile( &self, val: T, guest_addr: GuestAddress, diff --git a/x86_64/Cargo.toml b/x86_64/Cargo.toml index a94631e28..efadf0fe2 100644 --- a/x86_64/Cargo.toml +++ b/x86_64/Cargo.toml @@ -34,7 +34,7 @@ base = { path = "../base" } swap = { path = "../swap" } vm_control = { path = "../vm_control" } vm_memory = { path = "../vm_memory" } -zerocopy = { version = "0.7", features = ["derive"] } +zerocopy = { version = "0.8.13", features = ["derive"] } [target.'cfg(any(target_os = "android", target_os = "linux"))'.dependencies] minijail = "*" diff --git a/x86_64/src/acpi.rs b/x86_64/src/acpi.rs index 7b770ad82..1fe5bdf27 100644 --- a/x86_64/src/acpi.rs +++ b/x86_64/src/acpi.rs @@ -23,9 +23,10 @@ use devices::PciRoot; use sync::Mutex; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub struct AcpiDevResource { pub amls: Vec, @@ -36,7 +37,7 @@ pub struct AcpiDevResource { } #[repr(C, packed)] -#[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct GenericAddress { _space_id: u8, _bit_width: u8, @@ -46,7 +47,7 @@ struct GenericAddress { } #[repr(C)] -#[derive(Clone, Copy, Default, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct LocalApic { _type: u8, _length: u8, @@ -56,7 +57,7 @@ struct LocalApic { } #[repr(C)] -#[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct Ioapic { _type: u8, _length: u8, @@ -67,7 +68,7 @@ struct Ioapic { } #[repr(C, packed)] -#[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct IoapicInterruptSourceOverride { _type: u8, _length: u8, @@ -78,7 +79,7 @@ struct IoapicInterruptSourceOverride { } #[repr(C)] -#[derive(Clone, Copy, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Clone, Copy, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct Localx2Apic { _type: u8, _length: u8, diff --git a/x86_64/src/bootparam.rs b/x86_64/src/bootparam.rs index 6d92eb8c0..d26e61e6e 100644 --- a/x86_64/src/bootparam.rs +++ b/x86_64/src/bootparam.rs @@ -16,9 +16,10 @@ // only support deriving custom traits with build.rs, and we don't want // to run build.rs bindgen on kernel. -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; /// Set if kernel image has a 64-bit entry point at 0x200. pub const XLF_KERNEL_64: u16 = 1 << 0; @@ -82,7 +83,7 @@ pub type __u16 = ::std::os::raw::c_ushort; pub type __u32 = ::std::os::raw::c_uint; pub type __u64 = ::std::os::raw::c_ulonglong; #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct screen_info { pub orig_x: __u8, pub orig_y: __u8, @@ -122,7 +123,7 @@ pub struct screen_info { pub _reserved: [__u8; 2usize], } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct apm_bios_info { pub version: __u16, pub cseg: __u16, @@ -135,7 +136,7 @@ pub struct apm_bios_info { pub dseg_len: __u16, } #[repr(C, packed)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params { pub length: __u16, pub info_flags: __u16, @@ -151,13 +152,13 @@ pub struct edd_device_params { pub reserved3: __u16, pub host_bus_type: [__u8; 4usize], pub interface_type: [__u8; 8usize], - pub interface_path: edd_device_params__bindgen_ty_1, - pub device_path: edd_device_params__bindgen_ty_2, + pub interface_path: [__u8; 8usize], + pub device_path: [__u8; 16usize], pub reserved4: __u8, pub checksum: __u8, } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] pub union edd_device_params__bindgen_ty_1 { pub isa: edd_device_params__bindgen_ty_1__bindgen_ty_1, pub pci: edd_device_params__bindgen_ty_1__bindgen_ty_2, @@ -168,14 +169,14 @@ pub union edd_device_params__bindgen_ty_1 { _bindgen_union_align: [u8; 8usize], } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_1__bindgen_ty_1 { pub base_address: __u16, pub reserved1: __u16, pub reserved2: __u32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_1__bindgen_ty_2 { pub bus: __u8, pub slot: __u8, @@ -184,22 +185,22 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_2 { pub reserved: __u32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_1__bindgen_ty_3 { pub reserved: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_1__bindgen_ty_4 { pub reserved: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_1__bindgen_ty_5 { pub reserved: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_1__bindgen_ty_6 { pub reserved: __u64, } @@ -210,7 +211,7 @@ impl Default for edd_device_params__bindgen_ty_1 { } } #[repr(C)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, KnownLayout)] pub union edd_device_params__bindgen_ty_2 { pub ata: edd_device_params__bindgen_ty_2__bindgen_ty_1, pub atapi: edd_device_params__bindgen_ty_2__bindgen_ty_2, @@ -225,7 +226,7 @@ pub union edd_device_params__bindgen_ty_2 { _bindgen_union_align: [u8; 16usize], } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_1 { pub device: __u8, pub reserved1: __u8, @@ -234,7 +235,7 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_1 { pub reserved4: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_2 { pub device: __u8, pub lun: __u8, @@ -244,7 +245,7 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_2 { pub reserved4: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_3 { pub id: __u16, pub lun: __u64, @@ -252,38 +253,38 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_3 { pub reserved2: __u32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_4 { pub serial_number: __u64, pub reserved: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_5 { pub eui: __u64, pub reserved: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_6 { pub wwid: __u64, pub lun: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_7 { pub identity_tag: __u64, pub reserved: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_8 { pub array_number: __u32, pub reserved1: __u32, pub reserved2: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_9 { pub device: __u8, pub reserved1: __u8, @@ -292,7 +293,7 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_9 { pub reserved4: __u64, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_device_params__bindgen_ty_2__bindgen_ty_10 { pub reserved1: __u64, pub reserved2: __u64, @@ -310,7 +311,7 @@ impl Default for edd_device_params { } } #[repr(C, packed)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edd_info { pub device: __u8, pub version: __u8, @@ -327,7 +328,7 @@ impl Default for edd_info { } } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct ist_info { pub signature: __u32, pub command: __u32, @@ -335,7 +336,7 @@ pub struct ist_info { pub perf_level: __u32, } #[repr(C)] -#[derive(Copy, Clone, AsBytes, FromZeroes, FromBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct edid_info { pub dummy: [::std::os::raw::c_uchar; 128usize], } @@ -354,7 +355,7 @@ pub struct setup_data { pub data: __IncompleteArrayField<__u8>, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct setup_header { pub setup_sects: __u8, pub root_flags: __u16, @@ -396,13 +397,13 @@ pub struct setup_header { pub handover_offset: __u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct sys_desc_table { pub length: __u16, pub table: [__u8; 14usize], } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct olpc_ofw_header { pub ofw_magic: __u32, pub ofw_version: __u32, @@ -410,7 +411,7 @@ pub struct olpc_ofw_header { pub irq_desc_table: __u32, } #[repr(C)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct efi_info { pub efi_loader_signature: __u32, pub efi_systab: __u32, @@ -422,14 +423,14 @@ pub struct efi_info { pub efi_memmap_hi: __u32, } #[repr(C, packed)] -#[derive(Debug, Default, Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct boot_e820_entry { pub addr: __u64, pub size: __u64, pub type_: __u32, } #[repr(C, packed)] -#[derive(Copy, Clone, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct boot_params { pub screen_info: screen_info, pub apm_bios_info: apm_bios_info, diff --git a/x86_64/src/bzimage.rs b/x86_64/src/bzimage.rs index 7b30697ac..1811a59a9 100644 --- a/x86_64/src/bzimage.rs +++ b/x86_64/src/bzimage.rs @@ -19,7 +19,7 @@ use thiserror::Error; use vm_memory::GuestAddress; use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::bootparam::boot_params; use crate::bootparam::XLF_KERNEL_64; @@ -99,7 +99,7 @@ where // rather than reading into `params.hdr`. The bounds check in `.get_mut()` will ensure we do not // read beyond the end of `boot_params`. let setup_header_slice = params - .as_bytes_mut() + .as_mut_bytes() .get_mut(setup_header_start..setup_header_end) .ok_or(Error::InvalidSetupHeaderEnd(setup_header_end))?; diff --git a/x86_64/src/lib.rs b/x86_64/src/lib.rs index 9735d213e..e2986b2f5 100644 --- a/x86_64/src/lib.rs +++ b/x86_64/src/lib.rs @@ -145,9 +145,10 @@ use vm_memory::GuestMemory; use vm_memory::GuestMemoryError; use vm_memory::MemoryRegionOptions; use vm_memory::MemoryRegionPurpose; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; use crate::bootparam::boot_params; use crate::bootparam::setup_header; @@ -328,7 +329,7 @@ pub struct X8664arch; // Like `bootparam::setup_data` without the incomplete array field at the end, which allows us to // safely implement Copy, Clone #[repr(C)] -#[derive(Copy, Clone, Default, FromZeroes, FromBytes, AsBytes)] +#[derive(Copy, Clone, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] struct setup_data_hdr { pub next: u64, pub type_: u32, diff --git a/x86_64/src/mpspec.rs b/x86_64/src/mpspec.rs index bc121bfe4..edaa0daed 100644 --- a/x86_64/src/mpspec.rs +++ b/x86_64/src/mpspec.rs @@ -7,9 +7,10 @@ /* automatically generated by rust-bindgen */ // manually added, needs to be included when this crate gets automated bindgen -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; pub const MPC_SIGNATURE: &'static [u8; 5usize] = b"PCMP\x00"; pub const MP_PROCESSOR: ::std::os::raw::c_uint = 0; @@ -49,7 +50,7 @@ pub const MP_LEVEL_TRIGGER: ::std::os::raw::c_uint = 0xc; pub const MP_APIC_ALL: ::std::os::raw::c_uint = 255; pub const MPC_OEM_SIGNATURE: &'static [u8; 5usize] = b"_OEM\x00"; #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpf_intel { pub signature: [::std::os::raw::c_uchar; 4usize], pub physptr: ::std::os::raw::c_uint, @@ -191,7 +192,7 @@ impl Clone for mpf_intel { } } #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpc_table { pub signature: [::std::os::raw::c_uchar; 4usize], pub length: ::std::os::raw::c_ushort, @@ -345,7 +346,7 @@ impl Clone for mpc_table { } } #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpc_cpu { pub type_: ::std::os::raw::c_uchar, pub apicid: ::std::os::raw::c_uchar, @@ -451,7 +452,7 @@ impl Clone for mpc_cpu { } } #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpc_bus { pub type_: ::std::os::raw::c_uchar, pub busid: ::std::os::raw::c_uchar, @@ -509,7 +510,7 @@ impl Clone for mpc_bus { } } #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpc_ioapic { pub type_: ::std::os::raw::c_uchar, pub apicid: ::std::os::raw::c_uchar, @@ -591,7 +592,7 @@ impl Clone for mpc_ioapic { } } #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpc_intsrc { pub type_: ::std::os::raw::c_uchar, pub irqtype: ::std::os::raw::c_uchar, @@ -702,7 +703,7 @@ pub const mp_irq_source_types_mp_SMI: mp_irq_source_types = 2; pub const mp_irq_source_types_mp_ExtINT: mp_irq_source_types = 3; pub type mp_irq_source_types = ::std::os::raw::c_uint; #[repr(C)] -#[derive(Debug, Default, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Debug, Default, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct mpc_lintsrc { pub type_: ::std::os::raw::c_uchar, pub irqtype: ::std::os::raw::c_uchar, diff --git a/x86_64/src/mptable.rs b/x86_64/src/mptable.rs index 05c6a7766..e09f3d91d 100644 --- a/x86_64/src/mptable.rs +++ b/x86_64/src/mptable.rs @@ -12,7 +12,7 @@ use remain::sorted; use thiserror::Error; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; +use zerocopy::IntoBytes; use crate::mpspec::*; @@ -71,16 +71,16 @@ const CPU_FEATURE_APIC: u32 = 0x200; const CPU_FEATURE_FPU: u32 = 0x001; pub const MPTABLE_START: u64 = 0x400 * 639; // Last 1k of Linux's 640k base RAM. -fn compute_checksum(v: &T) -> u8 { +fn compute_checksum(v: &[u8]) -> u8 { let mut checksum: u8 = 0; - for i in v.as_bytes() { + for i in v { checksum = checksum.wrapping_add(*i); } checksum } fn mpf_intel_compute_checksum(v: &mpf_intel) -> u8 { - let checksum = compute_checksum(v).wrapping_sub(v.checksum); + let checksum = compute_checksum(v.as_bytes()).wrapping_sub(v.checksum); (!checksum).wrapping_add(1) } @@ -165,7 +165,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_cpu, base_mp) .map_err(|_| Error::WriteMpcCpu)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_cpu)); + checksum = checksum.wrapping_add(compute_checksum(mpc_cpu.as_bytes())); } { let size = mem::size_of::(); @@ -179,7 +179,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_ioapic, base_mp) .map_err(|_| Error::WriteMpcIoapic)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_ioapic)); + checksum = checksum.wrapping_add(compute_checksum(mpc_ioapic.as_bytes())); } for pci_bus_id in 0..isa_bus_id { let size = mem::size_of::(); @@ -191,7 +191,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_bus, base_mp) .map_err(|_| Error::WriteMpcBus)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_bus)); + checksum = checksum.wrapping_add(compute_checksum(mpc_bus.as_bytes())); } { let size = mem::size_of::(); @@ -203,7 +203,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_bus, base_mp) .map_err(|_| Error::WriteMpcBus)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_bus)); + checksum = checksum.wrapping_add(compute_checksum(mpc_bus.as_bytes())); } { let size = mem::size_of::(); @@ -219,7 +219,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_intsrc, base_mp) .map_err(|_| Error::WriteMpcIntsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_intsrc.as_bytes())); } let sci_irq = super::X86_64_SCI_IRQ as u8; // Per kvm_setup_default_irq_routing() in kernel @@ -237,7 +237,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_intsrc, base_mp) .map_err(|_| Error::WriteMpcIntsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_intsrc.as_bytes())); } // Insert SCI interrupt before PCI interrupts. Set the SCI interrupt // to be the default trigger/polarity of PCI bus, which is level/low. @@ -256,7 +256,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_intsrc, base_mp) .map_err(|_| Error::WriteMpcIntsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_intsrc.as_bytes())); } // Insert PCI interrupts after platform IRQs. @@ -274,7 +274,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_intsrc, base_mp) .map_err(|_| Error::WriteMpcIntsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_intsrc.as_bytes())); } let starting_isa_irq_num = pci_irqs @@ -297,7 +297,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_intsrc, base_mp) .map_err(|_| Error::WriteMpcIntsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_intsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_intsrc.as_bytes())); } { let size = mem::size_of::(); @@ -313,7 +313,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_lintsrc, base_mp) .map_err(|_| Error::WriteMpcLintsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_lintsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_lintsrc.as_bytes())); } { let size = mem::size_of::(); @@ -329,7 +329,7 @@ pub fn setup_mptable( mem.write_obj_at_addr(mpc_lintsrc, base_mp) .map_err(|_| Error::WriteMpcLintsrc)?; base_mp = base_mp.unchecked_add(size as u64); - checksum = checksum.wrapping_add(compute_checksum(&mpc_lintsrc)); + checksum = checksum.wrapping_add(compute_checksum(mpc_lintsrc.as_bytes())); } // At this point we know the size of the mp_table. @@ -345,7 +345,7 @@ pub fn setup_mptable( lapic: APIC_DEFAULT_PHYS_BASE, ..Default::default() }; - checksum = checksum.wrapping_add(compute_checksum(&mpc_table)); + checksum = checksum.wrapping_add(compute_checksum(mpc_table.as_bytes())); mpc_table.checksum = (!checksum).wrapping_add(1) as i8; mem.write_obj_at_addr(mpc_table, table_base) .map_err(|_| Error::WriteMpcTable)?; diff --git a/x86_64/src/multiboot_spec.rs b/x86_64/src/multiboot_spec.rs index 5c049e800..44c3672d8 100644 --- a/x86_64/src/multiboot_spec.rs +++ b/x86_64/src/multiboot_spec.rs @@ -6,14 +6,15 @@ //! //! -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; /// Magic value stored in EAX to indicate bootloader is Multiboot compliant. pub const MULTIBOOT_BOOTLOADER_MAGIC: u32 = 0x2BADB002; -#[derive(Debug, Default, AsBytes, FromBytes, FromZeroes)] +#[derive(Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct MultibootInfo { pub flags: u32, @@ -77,7 +78,7 @@ impl MultibootInfo { pub const F_FRAMEBUFFER: u32 = 1 << 12; } -#[derive(Debug, Default, AsBytes, FromBytes, FromZeroes)] +#[derive(Debug, Default, FromBytes, Immutable, IntoBytes, KnownLayout)] #[repr(C, packed)] pub struct MultibootMmapEntry { pub size: u32, diff --git a/x86_64/src/smbios.rs b/x86_64/src/smbios.rs index 87ec52d09..258d21089 100644 --- a/x86_64/src/smbios.rs +++ b/x86_64/src/smbios.rs @@ -12,9 +12,10 @@ use thiserror::Error; use uuid::Uuid; use vm_memory::GuestAddress; use vm_memory::GuestMemory; -use zerocopy::AsBytes; use zerocopy::FromBytes; -use zerocopy::FromZeroes; +use zerocopy::Immutable; +use zerocopy::IntoBytes; +use zerocopy::KnownLayout; #[sorted] #[derive(Error, Debug)] @@ -81,7 +82,7 @@ fn compute_checksum(v: &T) -> u8 { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Smbios23Intermediate { pub signature: [u8; 5usize], pub checksum: u8, @@ -92,7 +93,7 @@ pub struct Smbios23Intermediate { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Smbios23Entrypoint { pub signature: [u8; 4usize], pub checksum: u8, @@ -106,7 +107,7 @@ pub struct Smbios23Entrypoint { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct Smbios30Entrypoint { pub signature: [u8; 5usize], pub checksum: u8, @@ -121,7 +122,7 @@ pub struct Smbios30Entrypoint { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SmbiosBiosInfo { pub typ: u8, pub length: u8, @@ -137,7 +138,7 @@ pub struct SmbiosBiosInfo { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SmbiosSysInfo { pub typ: u8, pub length: u8, @@ -153,7 +154,7 @@ pub struct SmbiosSysInfo { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SmbiosOemStrings { pub typ: u8, pub length: u8, @@ -162,14 +163,14 @@ pub struct SmbiosOemStrings { } #[repr(C, packed)] -#[derive(Default, Clone, Copy, FromZeroes, FromBytes, AsBytes)] +#[derive(Default, Clone, Copy, FromBytes, Immutable, IntoBytes, KnownLayout)] pub struct SmbiosEndOfTable { pub typ: u8, pub length: u8, pub handle: u16, } -fn write_and_incr( +fn write_and_incr( mem: &GuestMemory, val: T, mut curptr: GuestAddress,