diff options
125 files changed, 16985 insertions, 10553 deletions
diff --git a/9s/src/main.rs b/9s/src/main.rs index 711e07f..ab3f291 100644 --- a/9s/src/main.rs +++ b/9s/src/main.rs @@ -70,23 +70,23 @@ impl FromStr for ListenAddress { fn from_str(s: &str) -> result::Result<Self, Self::Err> { if s.starts_with(VSOCK) { if s.len() > VSOCK.len() { - Ok(ListenAddress::Vsock(s[VSOCK.len()..] - .parse() - .map_err(ParseAddressError::Vsock)?)) + Ok(ListenAddress::Vsock( + s[VSOCK.len()..].parse().map_err(ParseAddressError::Vsock)?, + )) } else { Err(ParseAddressError::MissingVsockPort) } } else if s.starts_with(UNIX) { if s.len() > UNIX.len() { - Ok(ListenAddress::Unix(s[UNIX.len()..] - .parse() - .map_err(ParseAddressError::Unix)?)) + Ok(ListenAddress::Unix( + s[UNIX.len()..].parse().map_err(ParseAddressError::Unix)?, + )) } else { Err(ParseAddressError::MissingUnixPath) } } else { Ok(ListenAddress::Net( - s.parse().map_err(ParseAddressError::Net)? + s.parse().map_err(ParseAddressError::Net)?, )) } } @@ -171,7 +171,8 @@ fn main() -> Result<()> { ); opts.optflag("h", "help", "print this help menu"); - let matches = opts.parse(std::env::args_os().skip(1)) + let matches = opts + .parse(std::env::args_os().skip(1)) .map_err(Error::Argument)?; if matches.opt_present("h") || matches.free.len() == 0 { diff --git a/9s/src/vsock.rs b/9s/src/vsock.rs index 7957860..acf263e 100644 --- a/9s/src/vsock.rs +++ b/9s/src/vsock.rs @@ -147,7 +147,7 @@ impl VsockListener { return Err(io::Error::last_os_error()); } - Ok(VsockListener { fd: fd }) + Ok(VsockListener { fd }) } /// Accepts a new incoming connection on this listener. Blocks the calling thread until a @@ -179,7 +179,7 @@ impl VsockListener { } Ok(( - VsockStream { fd: fd }, + VsockStream { fd }, SocketAddr { cid: svm.svm_cid, port: svm.svm_port, diff --git a/aarch64/src/fdt.rs b/aarch64/src/fdt.rs index 358287c..c6e5f6a 100644 --- a/aarch64/src/fdt.rs +++ b/aarch64/src/fdt.rs @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use byteorder::{ByteOrder, BigEndian}; +use byteorder::{BigEndian, ByteOrder}; use libc::{c_char, c_int, c_void}; use std::error::{self, Error as FdtError}; +use std::ffi::{CStr, CString}; use std::fmt; -use std::ffi::{CString, CStr}; use std::ptr::null; use devices::PciInterruptPin; @@ -16,16 +16,16 @@ use sys_util::{GuestAddress, GuestMemory}; use AARCH64_PHYS_MEM_START; // These are GIC address-space location constants. -use AARCH64_GIC_DIST_SIZE; +use AARCH64_GIC_CPUI_BASE; use AARCH64_GIC_CPUI_SIZE; use AARCH64_GIC_DIST_BASE; -use AARCH64_GIC_CPUI_BASE; +use AARCH64_GIC_DIST_SIZE; // These are RTC related constants +use devices::pl030::PL030_AMBA_ID; use AARCH64_RTC_ADDR; -use AARCH64_RTC_SIZE; use AARCH64_RTC_IRQ; -use devices::pl030::PL030_AMBA_ID; +use AARCH64_RTC_SIZE; // These are serial device related constants. use AARCH64_SERIAL_ADDR; @@ -33,12 +33,12 @@ use AARCH64_SERIAL_SIZE; use AARCH64_SERIAL_SPEED; // These are related to guest virtio devices. -use AARCH64_PCI_CFG_BASE; -use AARCH64_PCI_CFG_SIZE; +use AARCH64_IRQ_BASE; use AARCH64_MMIO_BASE; -use AARCH64_MMIO_SIZE; use AARCH64_MMIO_LEN; -use AARCH64_IRQ_BASE; +use AARCH64_MMIO_SIZE; +use AARCH64_PCI_CFG_BASE; +use AARCH64_PCI_CFG_SIZE; // This is an arbitrary number to specify the node for the GIC. // If we had a more complex interrupt architecture, then we'd need an enum for @@ -59,15 +59,14 @@ const IRQ_TYPE_LEVEL_LOW: u32 = 0x00000008; // flattened device tree (fdt) that is passed to the kernel and indicates // the hardware configuration of the machine. #[link(name = "fdt")] -extern { +extern "C" { fn fdt_create(buf: *mut c_void, bufsize: c_int) -> c_int; fn fdt_finish_reservemap(fdt: *mut c_void) -> c_int; fn fdt_begin_node(fdt: *mut c_void, name: *const c_char) -> c_int; - fn fdt_property(fdt: *mut c_void, name: *const c_char, val: *const c_void, - len: c_int) -> c_int; + fn fdt_property(fdt: *mut c_void, name: *const c_char, val: *const c_void, len: c_int) + -> c_int; fn fdt_end_node(fdt: *mut c_void) -> c_int; - fn fdt_open_into(fdt: *const c_void, buf: *mut c_void, bufsize: c_int) - -> c_int; + fn fdt_open_into(fdt: *const c_void, buf: *mut c_void, bufsize: c_int) -> c_int; fn fdt_finish(fdt: *const c_void) -> c_int; fn fdt_pack(fdt: *mut c_void) -> c_int; } @@ -96,8 +95,7 @@ impl error::Error for Error { &Error::FdtOpenIntoError(_) => "Error copying FDT to Guest", &Error::FdtFinishError(_) => "Error performing FDT finish", &Error::FdtPackError(_) => "Error packing FDT", - &Error::FdtGuestMemoryWriteError => - "Error writing FDT to Guest Memory", + &Error::FdtGuestMemoryWriteError => "Error writing FDT to Guest Memory", } } } @@ -106,19 +104,23 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let prefix = "Libfdt Error: "; match self { - &Error::FdtCreateError(fdt_ret) | - &Error::FdtFinishReservemapError(fdt_ret) | - &Error::FdtBeginNodeError(fdt_ret) | - &Error::FdtPropertyError(fdt_ret) | - &Error::FdtEndNodeError(fdt_ret) | - &Error::FdtOpenIntoError(fdt_ret) | - &Error::FdtFinishError(fdt_ret) | - &Error::FdtPackError(fdt_ret) => { - write!(f, "{} {} code: {}", prefix, - Error::description(self), fdt_ret) - }, - &Error::FdtGuestMemoryWriteError => - write!(f, "{} {}", prefix, Error::description(self)), + &Error::FdtCreateError(fdt_ret) + | &Error::FdtFinishReservemapError(fdt_ret) + | &Error::FdtBeginNodeError(fdt_ret) + | &Error::FdtPropertyError(fdt_ret) + | &Error::FdtEndNodeError(fdt_ret) + | &Error::FdtOpenIntoError(fdt_ret) + | &Error::FdtFinishError(fdt_ret) + | &Error::FdtPackError(fdt_ret) => write!( + f, + "{} {} code: {}", + prefix, + Error::description(self), + fdt_ret + ), + &Error::FdtGuestMemoryWriteError => { + write!(f, "{} {}", prefix, Error::description(self)) + } } } } @@ -141,8 +143,7 @@ fn begin_node(fdt: &mut Vec<u8>, name: &str) -> Result<(), Box<Error>> { let cstr_name = CString::new(name).unwrap(); // Safe because we allocated fdt and converted name to a CString - let fdt_ret = unsafe { fdt_begin_node(fdt.as_mut_ptr() as *mut c_void, - cstr_name.as_ptr()) }; + let fdt_ret = unsafe { fdt_begin_node(fdt.as_mut_ptr() as *mut c_void, cstr_name.as_ptr()) }; if fdt_ret != 0 { return Err(Box::new(Error::FdtBeginNodeError(fdt_ret))); } @@ -158,31 +159,38 @@ fn end_node(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { Ok(()) } -fn property(fdt: &mut Vec<u8>, name: &str, val: &[u8]) - -> Result<(), Box<Error>> { +fn property(fdt: &mut Vec<u8>, name: &str, val: &[u8]) -> Result<(), Box<Error>> { let cstr_name = CString::new(name).unwrap(); let val_ptr = val.as_ptr() as *const c_void; // Safe because we allocated fdt and converted name to a CString - let fdt_ret = unsafe { fdt_property(fdt.as_mut_ptr() as *mut c_void, - cstr_name.as_ptr(), - val_ptr, val.len() as i32) }; + let fdt_ret = unsafe { + fdt_property( + fdt.as_mut_ptr() as *mut c_void, + cstr_name.as_ptr(), + val_ptr, + val.len() as i32, + ) + }; if fdt_ret != 0 { return Err(Box::new(Error::FdtPropertyError(fdt_ret))); } Ok(()) } -fn property_cstring(fdt: &mut Vec<u8>, name: &str, cstr_value: &CStr) - -> Result<(), Box<Error>> { +fn property_cstring(fdt: &mut Vec<u8>, name: &str, cstr_value: &CStr) -> Result<(), Box<Error>> { let value_bytes = cstr_value.to_bytes_with_nul(); - let cstr_name = CString::new(name).unwrap(); + let cstr_name = CString::new(name).unwrap(); // Safe because we allocated fdt, converted name and value to CStrings - let fdt_ret = unsafe { fdt_property(fdt.as_mut_ptr() as *mut c_void, - cstr_name.as_ptr(), - value_bytes.as_ptr() as *mut c_void, - value_bytes.len() as i32) }; + let fdt_ret = unsafe { + fdt_property( + fdt.as_mut_ptr() as *mut c_void, + cstr_name.as_ptr(), + value_bytes.as_ptr() as *mut c_void, + value_bytes.len() as i32, + ) + }; if fdt_ret != 0 { return Err(Box::new(Error::FdtPropertyError(fdt_ret))); } @@ -190,31 +198,33 @@ fn property_cstring(fdt: &mut Vec<u8>, name: &str, cstr_value: &CStr) } fn property_null(fdt: &mut Vec<u8>, name: &str) -> Result<(), Box<Error>> { - let cstr_name = CString::new(name).unwrap(); + let cstr_name = CString::new(name).unwrap(); // Safe because we allocated fdt, converted name to a CString - let fdt_ret = unsafe { fdt_property(fdt.as_mut_ptr() as *mut c_void, - cstr_name.as_ptr(), - null(), 0) }; + let fdt_ret = unsafe { + fdt_property( + fdt.as_mut_ptr() as *mut c_void, + cstr_name.as_ptr(), + null(), + 0, + ) + }; if fdt_ret != 0 { return Err(Box::new(Error::FdtPropertyError(fdt_ret))); } Ok(()) } -fn property_string(fdt: &mut Vec<u8>, name: &str, value: &str) - -> Result<(), Box<Error>> { +fn property_string(fdt: &mut Vec<u8>, name: &str, value: &str) -> Result<(), Box<Error>> { let cstr_value = CString::new(value).unwrap(); property_cstring(fdt, name, &cstr_value) } -fn property_u32(fdt: &mut Vec<u8>, name: &str, val: u32) - -> Result<(), Box<Error>> { +fn property_u32(fdt: &mut Vec<u8>, name: &str, val: u32) -> Result<(), Box<Error>> { property(fdt, name, &cpu_to_fdt32(val)) } -fn property_u64(fdt: &mut Vec<u8>, name: &str, val: u64) - -> Result<(), Box<Error>> { +fn property_u64(fdt: &mut Vec<u8>, name: &str, val: u64) -> Result<(), Box<Error>> { property(fdt, name, &cpu_to_fdt64(val)) } @@ -236,8 +246,7 @@ fn generate_prop64(cells: &[u64]) -> Vec<u8> { ret } -fn create_memory_node(fdt: &mut Vec<u8>, guest_mem: &GuestMemory) - -> Result<(), Box<Error>> { +fn create_memory_node(fdt: &mut Vec<u8>, guest_mem: &GuestMemory) -> Result<(), Box<Error>> { let mem_size = guest_mem.memory_size(); let mem_reg_prop = generate_prop64(&[AARCH64_PHYS_MEM_START, mem_size]); @@ -273,7 +282,8 @@ fn create_gic_node(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { AARCH64_GIC_DIST_BASE, AARCH64_GIC_DIST_SIZE, AARCH64_GIC_CPUI_BASE, - AARCH64_GIC_CPUI_SIZE]); + AARCH64_GIC_CPUI_SIZE, + ]); begin_node(fdt, "intc")?; property_string(fdt, "compatible", "arm,cortex-a15-gic")?; @@ -292,8 +302,8 @@ fn create_timer_node(fdt: &mut Vec<u8>, num_cpus: u32) -> Result<(), Box<Error>> // These are fixed interrupt numbers for the timer device. let irqs = [13, 14, 11, 10]; let compatible = "arm,armv8-timer"; - let cpu_mask: u32 = (((1 << num_cpus) - 1) << GIC_FDT_IRQ_PPI_CPU_SHIFT) & - GIC_FDT_IRQ_PPI_CPU_MASK; + let cpu_mask: u32 = + (((1 << num_cpus) - 1) << GIC_FDT_IRQ_PPI_CPU_SHIFT) & GIC_FDT_IRQ_PPI_CPU_MASK; let mut timer_reg_cells = Vec::new(); for &irq in irqs.iter() { @@ -313,14 +323,12 @@ fn create_timer_node(fdt: &mut Vec<u8>, num_cpus: u32) -> Result<(), Box<Error>> } fn create_serial_node(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { - let serial_reg_prop = generate_prop64(&[ - AARCH64_SERIAL_ADDR, AARCH64_SERIAL_SIZE]); + let serial_reg_prop = generate_prop64(&[AARCH64_SERIAL_ADDR, AARCH64_SERIAL_SIZE]); begin_node(fdt, "U6_16550A@3f8")?; property_string(fdt, "compatible", "ns16550a")?; property(fdt, "reg", &serial_reg_prop)?; - property_u32(fdt, "clock-frequency", - AARCH64_SERIAL_SPEED)?; + property_u32(fdt, "clock-frequency", AARCH64_SERIAL_SPEED)?; end_node(fdt)?; Ok(()) @@ -343,8 +351,7 @@ fn create_psci_node(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { Ok(()) } -fn create_chosen_node(fdt: &mut Vec<u8>, cmdline: &CStr) - -> Result<(), Box<Error>> { +fn create_chosen_node(fdt: &mut Vec<u8>, cmdline: &CStr) -> Result<(), Box<Error>> { begin_node(fdt, "chosen")?; property_u32(fdt, "linux,pci-probe-only", 1)?; property_cstring(fdt, "bootargs", cmdline)?; @@ -365,7 +372,8 @@ fn create_io_nodes(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { let irq = generate_prop32(&[ GIC_FDT_IRQ_TYPE_SPI, AARCH64_IRQ_BASE + i as u32, - IRQ_TYPE_EDGE_RISING]); + IRQ_TYPE_EDGE_RISING, + ]); begin_node(fdt, &node)?; property_string(fdt, "compatible", "virtio,mmio")?; @@ -386,11 +394,16 @@ fn create_pci_nodes( // and "PCI Bus Binding to IEEE Std 1275-1994". let ranges = generate_prop32(&[ // bus address (ss = 01: 32-bit memory space) - 0x2000000, (AARCH64_MMIO_BASE >> 32) as u32, AARCH64_MMIO_BASE as u32, + 0x2000000, + (AARCH64_MMIO_BASE >> 32) as u32, + AARCH64_MMIO_BASE as u32, // CPU address - (AARCH64_MMIO_BASE >> 32) as u32, AARCH64_MMIO_BASE as u32, + (AARCH64_MMIO_BASE >> 32) as u32, + AARCH64_MMIO_BASE as u32, // size - (AARCH64_MMIO_SIZE >> 32) as u32, AARCH64_MMIO_SIZE as u32]); + (AARCH64_MMIO_SIZE >> 32) as u32, + AARCH64_MMIO_SIZE as u32, + ]); let bus_range = generate_prop32(&[0, 0]); // Only bus 0 let reg = generate_prop64(&[AARCH64_PCI_CFG_BASE, AARCH64_PCI_CFG_SIZE]); @@ -459,8 +472,7 @@ fn create_rtc_node(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { let rtc_name = format!("rtc@{:x}", AARCH64_RTC_ADDR); let reg = generate_prop64(&[AARCH64_RTC_ADDR, AARCH64_RTC_SIZE]); - let irq = generate_prop32(&[GIC_FDT_IRQ_TYPE_SPI, AARCH64_RTC_IRQ, - IRQ_TYPE_LEVEL_HIGH]); + let irq = generate_prop32(&[GIC_FDT_IRQ_TYPE_SPI, AARCH64_RTC_IRQ, IRQ_TYPE_LEVEL_HIGH]); begin_node(fdt, &rtc_name)?; property_string(fdt, "compatible", "arm,primecell")?; @@ -484,17 +496,18 @@ fn create_rtc_node(fdt: &mut Vec<u8>) -> Result<(), Box<Error>> { /// * `num_cpus` - Number of virtual CPUs the guest will have /// * `fdt_load_offset` - The offset into physical memory for the device tree /// * `cmdline` - The kernel commandline -pub fn create_fdt(fdt_max_size: usize, - guest_mem: &GuestMemory, - pci_irqs: Vec<(u32, PciInterruptPin)>, - num_cpus: u32, - fdt_load_offset: u64, - cmdline: &CStr) -> Result<(), Box<Error>> { +pub fn create_fdt( + fdt_max_size: usize, + guest_mem: &GuestMemory, + pci_irqs: Vec<(u32, PciInterruptPin)>, + num_cpus: u32, + fdt_load_offset: u64, + cmdline: &CStr, +) -> Result<(), Box<Error>> { let mut fdt = vec![0; fdt_max_size]; // Safe since we allocated this array with fdt_max_size - let mut fdt_ret = unsafe { fdt_create(fdt.as_mut_ptr() as *mut c_void, - fdt_max_size as c_int) }; + let mut fdt_ret = unsafe { fdt_create(fdt.as_mut_ptr() as *mut c_void, fdt_max_size as c_int) }; if fdt_ret != 0 { return Err(Box::new(Error::FdtCreateError(fdt_ret))); @@ -539,9 +552,13 @@ pub fn create_fdt(fdt_max_size: usize, let mut fdt_final = vec![0; fdt_max_size]; // Safe because we allocated both arrays with the correct size - fdt_ret = unsafe { fdt_open_into(fdt.as_mut_ptr() as *mut c_void, - fdt_final.as_mut_ptr() as *mut c_void, - fdt_max_size as i32) }; + fdt_ret = unsafe { + fdt_open_into( + fdt.as_mut_ptr() as *mut c_void, + fdt_final.as_mut_ptr() as *mut c_void, + fdt_max_size as i32, + ) + }; if fdt_ret != 0 { return Err(Box::new(Error::FdtOpenIntoError(fdt_ret))); } @@ -552,9 +569,9 @@ pub fn create_fdt(fdt_max_size: usize, return Err(Box::new(Error::FdtPackError(fdt_ret))); } let fdt_address = GuestAddress(AARCH64_PHYS_MEM_START + fdt_load_offset); - let written = guest_mem.write_slice_at_addr(fdt_final.as_slice(), - fdt_address). - map_err(|_| Error::FdtGuestMemoryWriteError)?; + let written = guest_mem + .write_slice_at_addr(fdt_final.as_slice(), fdt_address) + .map_err(|_| Error::FdtGuestMemoryWriteError)?; if written < fdt_max_size { return Err(Box::new(Error::FdtGuestMemoryWriteError)); } diff --git a/aarch64/src/lib.rs b/aarch64/src/lib.rs index 8d71d44..d5bbc0d 100644 --- a/aarch64/src/lib.rs +++ b/aarch64/src/lib.rs @@ -10,22 +10,22 @@ extern crate kernel_cmdline; extern crate kvm; extern crate kvm_sys; extern crate libc; -extern crate sys_util; extern crate resources; +extern crate sys_util; use std::error::{self, Error as Aarch64Error}; use std::ffi::{CStr, CString}; use std::fmt::{self, Display}; use std::fs::File; use std::io::{self, stdout}; -use std::sync::{Arc, Mutex}; use std::os::unix::io::FromRawFd; use std::os::unix::net::UnixDatagram; +use std::sync::{Arc, Mutex}; use arch::{RunnableLinuxVm, VirtioDeviceStub, VmComponents}; use devices::{Bus, BusError, PciConfigMmio, PciInterruptPin}; -use sys_util::{EventFd, GuestAddress, GuestMemory}; use resources::{AddressRanges, SystemAllocator}; +use sys_util::{EventFd, GuestAddress, GuestMemory}; use kvm::*; use kvm_sys::kvm_device_attr; @@ -38,24 +38,23 @@ const AARCH64_KERNEL_OFFSET: u64 = 0x80000; const AARCH64_FDT_MAX_SIZE: u64 = 0x200000; // These constants indicate the address space used by the ARM vGIC. -const AARCH64_GIC_DIST_SIZE: u64 = 0x10000; -const AARCH64_GIC_CPUI_SIZE: u64 = 0x20000; +const AARCH64_GIC_DIST_SIZE: u64 = 0x10000; +const AARCH64_GIC_CPUI_SIZE: u64 = 0x20000; // This indicates the start of DRAM inside the physical address space. const AARCH64_PHYS_MEM_START: u64 = 0x80000000; -const AARCH64_AXI_BASE: u64 = 0x40000000; +const AARCH64_AXI_BASE: u64 = 0x40000000; // These constants indicate the placement of the GIC registers in the physical // address space. -const AARCH64_GIC_DIST_BASE: u64 = AARCH64_AXI_BASE - AARCH64_GIC_DIST_SIZE; -const AARCH64_GIC_CPUI_BASE: u64 = AARCH64_GIC_DIST_BASE - - AARCH64_GIC_CPUI_SIZE; +const AARCH64_GIC_DIST_BASE: u64 = AARCH64_AXI_BASE - AARCH64_GIC_DIST_SIZE; +const AARCH64_GIC_CPUI_BASE: u64 = AARCH64_GIC_DIST_BASE - AARCH64_GIC_CPUI_SIZE; // This is the minimum number of SPI interrupts aligned to 32 + 32 for the // PPI (16) and GSI (16). const AARCH64_GIC_NR_IRQS: u32 = 64; - // PSR (Processor State Register) bits +// PSR (Processor State Register) bits const PSR_MODE_EL1H: u64 = 0x00000005; const PSR_F_BIT: u64 = 0x00000040; const PSR_I_BIT: u64 = 0x00000080; @@ -68,14 +67,17 @@ macro_rules! offset__of { } } -const KVM_REG_ARM64: u64 = 0x6000000000000000; +const KVM_REG_ARM64: u64 = 0x6000000000000000; const KVM_REG_SIZE_U64: u64 = 0x0030000000000000; const KVM_REG_ARM_COPROC_SHIFT: u64 = 16; const KVM_REG_ARM_CORE: u64 = 0x0010 << KVM_REG_ARM_COPROC_SHIFT; macro_rules! arm64_core_reg { ($reg: tt) => { - KVM_REG_ARM64 | KVM_REG_SIZE_U64 | KVM_REG_ARM_CORE | ((offset__of!(kvm_sys::user_pt_regs, $reg) / 4) as u64) + KVM_REG_ARM64 + | KVM_REG_SIZE_U64 + | KVM_REG_ARM_CORE + | ((offset__of!(kvm_sys::user_pt_regs, $reg) / 4) as u64) }; } @@ -96,7 +98,7 @@ const AARCH64_RTC_ADDR: u64 = 0x2000; const AARCH64_RTC_SIZE: u64 = 0x1000; // The RTC device gets the first interrupt line // Which gets mapped to the first SPI interrupt (physical 32). -const AARCH64_RTC_IRQ: u32 = 0; +const AARCH64_RTC_IRQ: u32 = 0; // PCI MMIO configuration region base address. const AARCH64_PCI_CFG_BASE: u64 = 0x10000; @@ -153,18 +155,13 @@ impl error::Error for Error { &Error::CreatePciRoot(_) => "failed to create a PCI root hub", &Error::CreateSocket(_) => "failed to create socket", &Error::CreateVcpu(_) => "failed to create VCPU", - &Error::FDTCreateFailure(_) => - "FDT could not be created", - &Error::KernelLoadFailure => - "Kernel cound not be loaded", - &Error::CreateGICFailure(_) => - "Failure to create GIC", + &Error::FDTCreateFailure(_) => "FDT could not be created", + &Error::KernelLoadFailure => "Kernel cound not be loaded", + &Error::CreateGICFailure(_) => "Failure to create GIC", &Error::RegisterPci(_) => "error registering PCI bus", &Error::RegisterVsock(_) => "error registering virtual socket device", - &Error::VCPUInitFailure => - "Failed to initialize VCPU", - &Error::VCPUSetRegFailure => - "Failed to set register", + &Error::VCPUInitFailure => "Failed to initialize VCPU", + &Error::VCPUSetRegFailure => "Failed to set register", } } } @@ -192,11 +189,11 @@ pub struct AArch64; impl arch::LinuxArch for AArch64 { fn build_vm<F>(mut components: VmComponents, virtio_devs: F) -> Result<RunnableLinuxVm> - where - F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<VirtioDeviceStub>> + where + F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<VirtioDeviceStub>>, { - let mut resources = Self::get_resource_allocator(components.memory_mb, - components.wayland_dmabuf); + let mut resources = + Self::get_resource_allocator(components.memory_mb, components.wayland_dmabuf); let mem = Self::setup_memory(components.memory_mb)?; let kvm = Kvm::new().map_err(Error::CreateKvm)?; let mut vm = Self::create_vm(&kvm, mem.clone())?; @@ -204,10 +201,15 @@ impl arch::LinuxArch for AArch64 { let vcpu_count = components.vcpu_count; let mut vcpus = Vec::with_capacity(vcpu_count as usize); for cpu_id in 0..vcpu_count { - let vcpu = Vcpu::new(cpu_id as libc::c_ulong, &kvm, &vm) - .map_err(Error::CreateVcpu)?; - Self::configure_vcpu(vm.get_memory(), &kvm, &vm, &vcpu, - cpu_id as u64, vcpu_count as u64)?; + let vcpu = Vcpu::new(cpu_id as libc::c_ulong, &kvm, &vm).map_err(Error::CreateVcpu)?; + Self::configure_vcpu( + vm.get_memory(), + &kvm, + &vm, + &vcpu, + cpu_id as u64, + vcpu_count as u64, + )?; vcpus.push(vcpu); } @@ -216,11 +218,12 @@ impl arch::LinuxArch for AArch64 { let mut mmio_bus = devices::Bus::new(); - let (pci, pci_irqs) = arch::generate_pci_root(components.pci_devices, - &mut mmio_bus, - &mut resources, - &mut vm) - .map_err(Error::CreatePciRoot)?; + let (pci, pci_irqs) = arch::generate_pci_root( + components.pci_devices, + &mut mmio_bus, + &mut resources, + &mut vm, + ).map_err(Error::CreatePciRoot)?; let pci_bus = Arc::new(Mutex::new(PciConfigMmio::new(pci))); let exit_evt = EventFd::new().map_err(Error::CreateEventFd)?; @@ -232,13 +235,23 @@ impl arch::LinuxArch for AArch64 { Self::add_arch_devs(&mut vm, &mut mmio_bus)?; for stub in mmio_devs { - arch::register_mmio(&mut mmio_bus, &mut vm, stub.dev, stub.jail, - &mut resources, &mut cmdline) - .map_err(Error::RegisterVsock)?; + arch::register_mmio( + &mut mmio_bus, + &mut vm, + stub.dev, + stub.jail, + &mut resources, + &mut cmdline, + ).map_err(Error::RegisterVsock)?; } - mmio_bus.insert(pci_bus.clone(), AARCH64_PCI_CFG_BASE, AARCH64_PCI_CFG_SIZE, false) - .map_err(Error::RegisterPci)?; + mmio_bus + .insert( + pci_bus.clone(), + AARCH64_PCI_CFG_BASE, + AARCH64_PCI_CFG_SIZE, + false, + ).map_err(Error::RegisterPci)?; for param in components.extra_kernel_params { cmdline.insert_str(¶m).map_err(Error::Cmdline)?; @@ -247,8 +260,13 @@ impl arch::LinuxArch for AArch64 { // separate out load_kernel from other setup to get a specific error for // kernel loading Self::load_kernel(&mem, &mut components.kernel_image)?; - Self::setup_system_memory(&mem, components.memory_mb, vcpu_count, - &CString::new(cmdline).unwrap(), pci_irqs)?; + Self::setup_system_memory( + &mem, + components.memory_mb, + vcpu_count, + &CString::new(cmdline).unwrap(), + pci_irqs, + )?; Ok(RunnableLinuxVm { vm, @@ -275,22 +293,27 @@ impl AArch64 { let kernel_addr = get_kernel_addr(); let kernel_meta = kernel_image.metadata()?; let kernel_size = kernel_meta.len(); - guest_mem.read_to_memory(kernel_addr, &mut kernel_image, kernel_size as usize). - map_err(|_| Error::KernelLoadFailure)?; + guest_mem + .read_to_memory(kernel_addr, &mut kernel_image, kernel_size as usize) + .map_err(|_| Error::KernelLoadFailure)?; Ok(()) } - fn setup_system_memory(mem: &GuestMemory, - mem_size: u64, - vcpu_count: u32, - cmdline: &CStr, - pci_irqs: Vec<(u32, PciInterruptPin)>) -> Result<()> { - fdt::create_fdt(AARCH64_FDT_MAX_SIZE as usize, - mem, - pci_irqs, - vcpu_count, - fdt_offset(mem_size), - cmdline)?; + fn setup_system_memory( + mem: &GuestMemory, + mem_size: u64, + vcpu_count: u32, + cmdline: &CStr, + pci_irqs: Vec<(u32, PciInterruptPin)>, + ) -> Result<()> { + fdt::create_fdt( + AARCH64_FDT_MAX_SIZE as usize, + mem, + pci_irqs, + vcpu_count, + fdt_offset(mem_size), + cmdline, + )?; Ok(()) } @@ -312,8 +335,9 @@ impl AArch64 { /// This returns a base part of the kernel command for this architecture fn get_base_linux_cmdline() -> kernel_cmdline::Cmdline { let mut cmdline = kernel_cmdline::Cmdline::new(sys_util::pagesize()); - cmdline.insert_str("console=ttyS0 reboot=k panic=1"). - unwrap(); + cmdline + .insert_str("console=ttyS0 reboot=k panic=1") + .unwrap(); cmdline } @@ -323,7 +347,8 @@ impl AArch64 { AddressRanges::new() .add_device_addresses(device_addr_start, u64::max_value() - device_addr_start) .add_mmio_addresses(AARCH64_MMIO_BASE, AARCH64_MMIO_SIZE) - .create_allocator(AARCH64_IRQ_BASE, gpu_allocation).unwrap() + .create_allocator(AARCH64_IRQ_BASE, gpu_allocation) + .unwrap() } /// This adds any early platform devices for this architecture. @@ -339,9 +364,14 @@ impl AArch64 { let com_evt_1_3 = EventFd::new()?; let serial = Arc::new(Mutex::new(devices::Serial::new_out( com_evt_1_3.try_clone()?, - Box::new(stdout())))); - bus.insert(serial.clone(), AARCH64_SERIAL_ADDR, AARCH64_SERIAL_SIZE, false) - .expect("failed to add serial device"); + Box::new(stdout()), + ))); + bus.insert( + serial.clone(), + AARCH64_SERIAL_ADDR, + AARCH64_SERIAL_SIZE, + false, + ).expect("failed to add serial device"); let rtc = Arc::new(Mutex::new(devices::pl030::Pl030::new(rtc_evt))); bus.insert(rtc, AARCH64_RTC_ADDR, AARCH64_RTC_SIZE, false) @@ -379,7 +409,8 @@ impl AArch64 { fd: 0, flags: 0, }; - vm.create_device(&mut kcd).map_err(|e| Error::CreateGICFailure(e))?; + vm.create_device(&mut kcd) + .map_err(|e| Error::CreateGICFailure(e))?; // Safe because the kernel is passing us an FD back inside // the struct after we successfully did the create_device ioctl @@ -387,22 +418,18 @@ impl AArch64 { // Safe because we allocated the struct that's being passed in let ret = unsafe { - sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), - &cpu_if_attr) + sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), &cpu_if_attr) }; if ret != 0 { - return Err(Box::new(Error::CreateGICFailure( - sys_util::Error::new(ret)))) + return Err(Box::new(Error::CreateGICFailure(sys_util::Error::new(ret)))); } // Safe because we allocated the struct that's being passed in let ret = unsafe { - sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), - &dist_attr) + sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), &dist_attr) }; if ret != 0 { - return Err(Box::new(Error::CreateGICFailure( - sys_util::Error::new(ret)))) + return Err(Box::new(Error::CreateGICFailure(sys_util::Error::new(ret)))); } // We need to tell the kernel how many irqs to support with this vgic @@ -416,12 +443,10 @@ impl AArch64 { }; // Safe because we allocated the struct that's being passed in let ret = unsafe { - sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), - &nr_irqs_attr) + sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), &nr_irqs_attr) }; if ret != 0 { - return Err(Box::new(Error::CreateGICFailure( - sys_util::Error::new(ret)))) + return Err(Box::new(Error::CreateGICFailure(sys_util::Error::new(ret)))); } // Finalize the GIC @@ -434,17 +459,15 @@ impl AArch64 { // Safe because we allocated the struct that's being passed in let ret = unsafe { - sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), - &init_gic_attr) + sys_util::ioctl_with_ref(&vgic_fd, kvm_sys::KVM_SET_DEVICE_ATTR(), &init_gic_attr) }; if ret != 0 { - return Err(Box::new(sys_util::Error::new(ret))) + return Err(Box::new(sys_util::Error::new(ret))); } Ok(Some(vgic_fd)) } - fn setup_io_bus() - -> Result<(devices::Bus, Arc<Mutex<devices::Serial>>)> { + fn setup_io_bus() -> Result<(devices::Bus, Arc<Mutex<devices::Serial>>)> { // ARM doesn't really use the io bus like x86, instead we have a // separate serial device that is returned as a separate object. let io_bus = devices::Bus::new(); @@ -452,17 +475,19 @@ impl AArch64 { let serial = Arc::new(Mutex::new(devices::Serial::new_out( com_evt_1_3.try_clone()?, - Box::new(stdout())))); + Box::new(stdout()), + ))); Ok((io_bus, serial)) } - fn configure_vcpu(guest_mem: &GuestMemory, - _kvm: &Kvm, - vm: &Vm, - vcpu: &Vcpu, - cpu_id: u64, - _num_cpus: u64) - -> Result<()> { + fn configure_vcpu( + guest_mem: &GuestMemory, + _kvm: &Kvm, + vm: &Vm, + vcpu: &Vcpu, + cpu_id: u64, + _num_cpus: u64, + ) -> Result<()> { let mut kvi = kvm_sys::kvm_vcpu_init { target: kvm_sys::KVM_ARM_TARGET_GENERIC_V8, features: [0; 7], @@ -485,21 +510,21 @@ impl AArch64 { let mut reg_id: u64; // All interrupts masked - data = PSR_D_BIT | PSR_A_BIT | PSR_I_BIT | PSR_F_BIT | PSR_MODE_EL1H; - reg_id = arm64_core_reg!(pstate); + data = PSR_D_BIT | PSR_A_BIT | PSR_I_BIT | PSR_F_BIT | PSR_MODE_EL1H; + reg_id = arm64_core_reg!(pstate); vcpu.set_one_reg(reg_id, data)?; // Other cpus are powered off initially if cpu_id == 0 { - data = AARCH64_PHYS_MEM_START + AARCH64_KERNEL_OFFSET; - reg_id = arm64_core_reg!(pc); + data = AARCH64_PHYS_MEM_START + AARCH64_KERNEL_OFFSET; + reg_id = arm64_core_reg!(pc); vcpu.set_one_reg(reg_id, data)?; /* X0 -- fdt address */ let mem_size = guest_mem.memory_size(); - data = (AARCH64_PHYS_MEM_START + fdt_offset(mem_size)) as u64; + data = (AARCH64_PHYS_MEM_START + fdt_offset(mem_size)) as u64; // hack -- can't get this to do offsetof(regs[0]) but luckily it's at offset 0 - reg_id = arm64_core_reg!(regs); + reg_id = arm64_core_reg!(regs); vcpu.set_one_reg(reg_id, data)?; } Ok(()) diff --git a/arch/src/lib.rs b/arch/src/lib.rs index f83e404..f2c7639 100644 --- a/arch/src/lib.rs +++ b/arch/src/lib.rs @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +extern crate devices; extern crate io_jail; -extern crate sys_util; -extern crate resources; extern crate kernel_cmdline; extern crate kvm; extern crate libc; -extern crate devices; +extern crate resources; +extern crate sys_util; use std::fmt; use std::fs::File; @@ -16,20 +16,21 @@ use std::os::unix::io::{AsRawFd, RawFd}; use std::result; use std::sync::{Arc, Mutex}; -use devices::{Bus, BusError, PciDevice, PciDeviceError, PciInterruptPin, - PciRoot, ProxyDevice, Serial}; use devices::virtio::VirtioDevice; +use devices::{ + Bus, BusError, PciDevice, PciDeviceError, PciInterruptPin, PciRoot, ProxyDevice, Serial, +}; use io_jail::Minijail; -use kvm::{IoeventAddress, Kvm, NoDatamatch, Vm, Vcpu}; -use sys_util::{EventFd, GuestMemory, syslog}; +use kvm::{IoeventAddress, Kvm, NoDatamatch, Vcpu, Vm}; use resources::SystemAllocator; +use sys_util::{syslog, EventFd, GuestMemory}; pub type Result<T> = result::Result<T, Box<std::error::Error>>; /// Holds the pieces needed to build a VM. Passed to `build_vm` in the `LinuxArch` trait below to /// create a `RunnableLinuxVm`. pub struct VmComponents { - pub pci_devices: Vec<(Box<PciDevice + 'static>, Minijail)>, + pub pci_devices: Vec<(Box<PciDevice + 'static>, Minijail)>, pub memory_mb: u64, pub vcpu_count: u32, pub kernel_image: File, @@ -66,8 +67,8 @@ pub trait LinuxArch { /// * `components` - Parts to use to build the VM. /// * `virtio_devs` - Function to generate a list of virtio devices. fn build_vm<F>(components: VmComponents, virtio_devs: F) -> Result<RunnableLinuxVm> - where - F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<VirtioDeviceStub>>; + where + F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<VirtioDeviceStub>>; } /// Errors for device manager. @@ -103,9 +104,7 @@ impl fmt::Display for DeviceRegistrationError { &DeviceRegistrationError::AllocateIoAddrs(ref e) => { write!(f, "Allocating IO addresses: {:?}", e) } - &DeviceRegistrationError::AllocateIrq => { - write!(f, "Allocating IRQ number") - } + &DeviceRegistrationError::AllocateIrq => write!(f, "Allocating IRQ number"), &DeviceRegistrationError::CreateMmioDevice(ref e) => { write!(f, "failed to create mmio device: {:?}", e) } @@ -128,18 +127,20 @@ impl fmt::Display for DeviceRegistrationError { write!(f, "failed to create proxy device: {}", e) } &DeviceRegistrationError::IrqsExhausted => write!(f, "no more IRQs are available"), - &DeviceRegistrationError::AddrsExhausted => write!(f, "no more addresses are available"), + &DeviceRegistrationError::AddrsExhausted => { + write!(f, "no more addresses are available") + } } } } /// Creates a root PCI device for use by this Vm. -pub fn generate_pci_root(devices: Vec<(Box<PciDevice + 'static>, Minijail)>, - mmio_bus: &mut Bus, - resources: &mut SystemAllocator, - vm: &mut Vm) - -> std::result::Result<(PciRoot, Vec<(u32, PciInterruptPin)>), DeviceRegistrationError> -{ +pub fn generate_pci_root( + devices: Vec<(Box<PciDevice + 'static>, Minijail)>, + mmio_bus: &mut Bus, + resources: &mut SystemAllocator, + vm: &mut Vm, +) -> std::result::Result<(PciRoot, Vec<(u32, PciInterruptPin)>), DeviceRegistrationError> { let mut root = PciRoot::new(); let mut pci_irqs = Vec::new(); for (dev_idx, (mut device, jail)) in devices.into_iter().enumerate() { @@ -177,7 +178,8 @@ pub fn generate_pci_root(devices: Vec<(Box<PciDevice + 'static>, Minijail)>, let arced_dev = Arc::new(Mutex::new(proxy)); root.add_device(arced_dev.clone()); for range in &ranges { - mmio_bus.insert(arced_dev.clone(), range.0, range.1, true) + mmio_bus + .insert(arced_dev.clone(), range.0, range.1, true) .map_err(DeviceRegistrationError::MmioInsert)?; } } @@ -185,13 +187,14 @@ pub fn generate_pci_root(devices: Vec<(Box<PciDevice + 'static>, Minijail)>, } /// Register a device to be used via MMIO transport. -pub fn register_mmio(bus: &mut devices::Bus, - vm: &mut Vm, - device: Box<devices::virtio::VirtioDevice>, - jail: Option<Minijail>, - resources: &mut SystemAllocator, - cmdline: &mut kernel_cmdline::Cmdline) - -> std::result::Result<(), DeviceRegistrationError> { +pub fn register_mmio( + bus: &mut devices::Bus, + vm: &mut Vm, + device: Box<devices::virtio::VirtioDevice>, + jail: Option<Minijail>, + resources: &mut SystemAllocator, + cmdline: &mut kernel_cmdline::Cmdline, +) -> std::result::Result<(), DeviceRegistrationError> { let irq = match resources.allocate_irq() { None => return Err(DeviceRegistrationError::IrqsExhausted), Some(i) => i, @@ -204,19 +207,19 @@ pub fn register_mmio(bus: &mut devices::Bus, let mmio_device = devices::virtio::MmioDevice::new((*vm.get_memory()).clone(), device) .map_err(DeviceRegistrationError::CreateMmioDevice)?; let mmio_len = 0x1000; // TODO(dgreid) - configurable per arch? - let mmio_base = resources.allocate_mmio_addresses(mmio_len) + let mmio_base = resources + .allocate_mmio_addresses(mmio_len) .ok_or(DeviceRegistrationError::AddrsExhausted)?; for (i, queue_evt) in mmio_device.queue_evts().iter().enumerate() { - let io_addr = IoeventAddress::Mmio(mmio_base + - devices::virtio::NOTIFY_REG_OFFSET as u64); + let io_addr = IoeventAddress::Mmio(mmio_base + devices::virtio::NOTIFY_REG_OFFSET as u64); vm.register_ioevent(&queue_evt, io_addr, i as u32) - .map_err(DeviceRegistrationError::RegisterIoevent)?; + .map_err(DeviceRegistrationError::RegisterIoevent)?; keep_fds.push(queue_evt.as_raw_fd()); } if let Some(interrupt_evt) = mmio_device.interrupt_evt() { vm.register_irqfd(&interrupt_evt, irq) - .map_err(DeviceRegistrationError::RegisterIrqfd)?; + .map_err(DeviceRegistrationError::RegisterIrqfd)?; keep_fds.push(interrupt_evt.as_raw_fd()); } @@ -224,15 +227,22 @@ pub fn register_mmio(bus: &mut devices::Bus, let proxy_dev = devices::ProxyDevice::new(mmio_device, &jail, keep_fds) .map_err(DeviceRegistrationError::ProxyDeviceCreation)?; - bus.insert(Arc::new(Mutex::new(proxy_dev)), mmio_base, mmio_len, false).unwrap(); + bus.insert(Arc::new(Mutex::new(proxy_dev)), mmio_base, mmio_len, false) + .unwrap(); } else { - bus.insert(Arc::new(Mutex::new(mmio_device)), mmio_base, mmio_len, false).unwrap(); + bus.insert( + Arc::new(Mutex::new(mmio_device)), + mmio_base, + mmio_len, + false, + ).unwrap(); } cmdline - .insert("virtio_mmio.device", - &format!("4K@0x{:08x}:{}", mmio_base, irq)) - .map_err(DeviceRegistrationError::Cmdline)?; + .insert( + "virtio_mmio.device", + &format!("4K@0x{:08x}:{}", mmio_base, irq), + ).map_err(DeviceRegistrationError::Cmdline)?; Ok(()) } diff --git a/crosvm_plugin/src/lib.rs b/crosvm_plugin/src/lib.rs index 754f74c..8fd9623 100644 --- a/crosvm_plugin/src/lib.rs +++ b/crosvm_plugin/src/lib.rs @@ -15,38 +15,39 @@ //! connection's socket. Then, that socket is read for a `MainResponse` or `VcpuResponse`, which is //! translated to the appropriate return type for the C API. -extern crate libc; -extern crate sys_util; extern crate kvm; extern crate kvm_sys; +extern crate libc; extern crate plugin_proto; extern crate protobuf; +extern crate sys_util; use std::env; use std::fs::File; -use std::mem::{swap, size_of}; +use std::mem::{size_of, swap}; use std::os::raw::{c_int, c_void}; -use std::os::unix::io::{AsRawFd, IntoRawFd, FromRawFd, RawFd}; +use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::os::unix::net::UnixDatagram; use std::ptr::null_mut; use std::result; -use std::slice::{from_raw_parts, from_raw_parts_mut}; use std::slice; -use std::sync::Arc; +use std::slice::{from_raw_parts, from_raw_parts_mut}; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::time::Instant; -use libc::{E2BIG, ENOTCONN, EINVAL, EPROTO, ENOENT}; +use libc::{E2BIG, EINVAL, ENOENT, ENOTCONN, EPROTO}; -use protobuf::{Message, ProtobufEnum, RepeatedField, parse_from_bytes}; +use protobuf::{parse_from_bytes, Message, ProtobufEnum, RepeatedField}; use sys_util::ScmSocket; use kvm::dirty_log_bitmap_size; -use kvm_sys::{kvm_regs, kvm_sregs, kvm_fpu, kvm_debugregs, kvm_xcrs, kvm_msr_entry, - kvm_cpuid_entry2, kvm_lapic_state, kvm_mp_state, kvm_pic_state, kvm_ioapic_state, - kvm_pit_state2, kvm_vcpu_events}; +use kvm_sys::{ + kvm_cpuid_entry2, kvm_debugregs, kvm_fpu, kvm_ioapic_state, kvm_lapic_state, kvm_mp_state, + kvm_msr_entry, kvm_pic_state, kvm_pit_state2, kvm_regs, kvm_sregs, kvm_vcpu_events, kvm_xcrs, +}; use plugin_proto::*; @@ -197,8 +198,11 @@ struct GlobalStats { } static mut STATS: GlobalStats = GlobalStats { - entries: [ StatEntry { count: 0, total: 0, max: 0}; - Stat::Count as usize] + entries: [StatEntry { + count: 0, + total: 0, + max: 0, + }; Stat::Count as usize], }; impl GlobalStats { @@ -213,16 +217,23 @@ impl GlobalStats { // call to STATS.print() will print out max and average latencies for all // operations that were performed. fn record(&mut self, idx: Stat) -> StatUpdater { - StatUpdater { idx: idx as usize, start: Instant::now() } + StatUpdater { + idx: idx as usize, + start: Instant::now(), + } } fn print(&self) { - for idx in 0 .. Stat::Count as usize { + for idx in 0..Stat::Count as usize { let ref e = self.entries[idx as usize]; - let stat = unsafe { std::mem::transmute::<u8,Stat>(idx as u8) }; + let stat = unsafe { std::mem::transmute::<u8, Stat>(idx as u8) }; if e.count > 0 { - println!("Stat::{:?}: avg {}ns max {}ns", - stat, e.total / e.count, e.max); + println!( + "Stat::{:?}: avg {}ns max {}ns", + stat, + e.total / e.count, + e.max + ); } } } @@ -240,10 +251,11 @@ impl GlobalStats { impl Drop for StatUpdater { fn drop(&mut self) { let elapsed = self.start.elapsed(); - let elapsed_nanos = elapsed.as_secs() * 1000000000 + - elapsed.subsec_nanos() as u64; + let elapsed_nanos = elapsed.as_secs() * 1000000000 + elapsed.subsec_nanos() as u64; // Unsafe due to racy access - OK for stats - unsafe { STATS.update(self.idx, elapsed_nanos); } + unsafe { + STATS.update(self.idx, elapsed_nanos); + } } } @@ -268,10 +280,11 @@ impl crosvm { Ok(crosvm) } - fn new(id_allocator: Arc<IdAllocator>, - socket: UnixDatagram, - vcpus: Arc<Vec<crosvm_vcpu>>) - -> crosvm { + fn new( + id_allocator: Arc<IdAllocator>, + socket: UnixDatagram, + vcpus: Arc<Vec<crosvm_vcpu>>, + ) -> crosvm { crosvm { id_allocator, socket, @@ -285,10 +298,11 @@ impl crosvm { &*self.id_allocator } - fn main_transaction(&mut self, - request: &MainRequest, - fds: &[RawFd]) - -> result::Result<(MainResponse, Vec<File>), c_int> { + fn main_transaction( + &mut self, + request: &MainRequest, + fds: &[RawFd], + ) -> result::Result<(MainResponse, Vec<File>), c_int> { self.request_buffer.clear(); request .write_to_vec(&mut self.request_buffer) @@ -298,7 +312,8 @@ impl crosvm { .map_err(|e| -e.errno())?; let mut datagram_fds = [0; MAX_DATAGRAM_FD]; - let (msg_size, fd_count) = self.socket + let (msg_size, fd_count) = self + .socket .recv_with_fds(&mut self.response_buffer, &mut datagram_fds) .map_err(|e| -e.errno())?; // Safe because the first fd_count fds from recv_with_fds are owned by us and valid. @@ -307,8 +322,8 @@ impl crosvm { .map(|&fd| unsafe { File::from_raw_fd(fd) }) .collect(); - let response: MainResponse = parse_from_bytes(&self.response_buffer[..msg_size]) - .map_err(proto_error_to_int)?; + let response: MainResponse = + parse_from_bytes(&self.response_buffer[..msg_size]).map_err(proto_error_to_int)?; if response.errno != 0 { return Err(response.errno); } @@ -320,11 +335,11 @@ impl crosvm { r.mut_new_connection(); let mut files = self.main_transaction(&r, &[])?.1; match files.pop() { - Some(new_socket) => { - Ok(crosvm::new(self.id_allocator.clone(), - fd_cast(new_socket), - self.vcpus.clone())) - } + Some(new_socket) => Ok(crosvm::new( + self.id_allocator.clone(), + fd_cast(new_socket), + self.vcpus.clone(), + )), None => Err(EPROTO), } } @@ -336,7 +351,9 @@ impl crosvm { self.get_id_allocator().free(id); // Unsafe due to racy access - OK for stats if std::env::var("CROSVM_STATS").is_ok() { - unsafe { STATS.print(); } + unsafe { + STATS.print(); + } } Ok(()) } @@ -380,9 +397,11 @@ impl crosvm { Ok(response.get_check_extension().has_extension) } - fn get_supported_cpuid(&mut self, cpuid_entries: &mut [kvm_cpuid_entry2], - cpuid_count: &mut usize) - -> result::Result<(), c_int> { + fn get_supported_cpuid( + &mut self, + cpuid_entries: &mut [kvm_cpuid_entry2], + cpuid_count: &mut usize, + ) -> result::Result<(), c_int> { *cpuid_count = 0; let mut r = MainRequest::new(); @@ -400,18 +419,22 @@ impl crosvm { return Err(E2BIG); } - for (proto_entry, kvm_entry) in - supported_cpuids.get_entries().iter() - .zip(cpuid_entries.iter_mut()) { + for (proto_entry, kvm_entry) in supported_cpuids + .get_entries() + .iter() + .zip(cpuid_entries.iter_mut()) + { *kvm_entry = cpuid_proto_to_kvm(proto_entry); } Ok(()) } - fn get_emulated_cpuid(&mut self, cpuid_entries: &mut [kvm_cpuid_entry2], - cpuid_count: &mut usize) - -> result::Result<(), c_int> { + fn get_emulated_cpuid( + &mut self, + cpuid_entries: &mut [kvm_cpuid_entry2], + cpuid_count: &mut usize, + ) -> result::Result<(), c_int> { *cpuid_count = 0; let mut r = MainRequest::new(); @@ -429,17 +452,22 @@ impl crosvm { return Err(E2BIG); } - for (proto_entry, kvm_entry) in - emulated_cpuids.get_entries().iter() - .zip(cpuid_entries.iter_mut()) { + for (proto_entry, kvm_entry) in emulated_cpuids + .get_entries() + .iter() + .zip(cpuid_entries.iter_mut()) + { *kvm_entry = cpuid_proto_to_kvm(proto_entry); } Ok(()) } - fn get_msr_index_list(&mut self, msr_indices: &mut [u32], msr_count: &mut usize) - -> result::Result<(), c_int> { + fn get_msr_index_list( + &mut self, + msr_indices: &mut [u32], + msr_count: &mut usize, + ) -> result::Result<(), c_int> { *msr_count = 0; let mut r = MainRequest::new(); @@ -457,9 +485,7 @@ impl crosvm { return Err(E2BIG); } - for (proto_entry, kvm_entry) in - msr_list.get_indices().iter() - .zip(msr_indices.iter_mut()) { + for (proto_entry, kvm_entry) in msr_list.get_indices().iter().zip(msr_indices.iter_mut()) { *kvm_entry = *proto_entry; } @@ -520,8 +546,11 @@ impl crosvm { Ok(()) } - fn get_state(&mut self, state_set: MainRequest_StateSet, out: &mut [u8]) - -> result::Result<(), c_int> { + fn get_state( + &mut self, + state_set: MainRequest_StateSet, + out: &mut [u8], + ) -> result::Result<(), c_int> { let mut r = MainRequest::new(); r.mut_get_state().set = state_set; let (response, _) = self.main_transaction(&r, &[])?; @@ -536,8 +565,11 @@ impl crosvm { Ok(()) } - fn set_state(&mut self, state_set: MainRequest_StateSet, new_state: &[u8]) - -> result::Result<(), c_int> { + fn set_state( + &mut self, + state_set: MainRequest_StateSet, + new_state: &[u8], + ) -> result::Result<(), c_int> { let mut r = MainRequest::new(); { let set_state: &mut MainRequest_SetState = r.mut_set_state(); @@ -603,12 +635,12 @@ impl crosvm { let mac_addr = config.get_host_mac_address(); if mac_addr.len() != net_config.host_mac_address.len() { - return Err(EPROTO) + return Err(EPROTO); } net_config.host_mac_address.copy_from_slice(mac_addr); Ok(net_config) - }, + } None => Err(EPROTO), } } @@ -659,12 +691,13 @@ pub struct crosvm_io_event { } impl crosvm_io_event { - unsafe fn create(crosvm: &mut crosvm, - space: u32, - addr: u64, - length: u32, - datamatch: *const u8) - -> result::Result<crosvm_io_event, c_int> { + unsafe fn create( + crosvm: &mut crosvm, + space: u32, + addr: u64, + length: u32, + datamatch: *const u8, + ) -> result::Result<crosvm_io_event, c_int> { let datamatch = match length { 0 => 0, 1 => *(datamatch as *const u8) as u64, @@ -676,12 +709,13 @@ impl crosvm_io_event { Self::safe_create(crosvm, space, addr, length, datamatch) } - fn safe_create(crosvm: &mut crosvm, - space: u32, - addr: u64, - length: u32, - datamatch: u64) - -> result::Result<crosvm_io_event, c_int> { + fn safe_create( + crosvm: &mut crosvm, + space: u32, + addr: u64, + length: u32, + datamatch: u64, + ) -> result::Result<crosvm_io_event, c_int> { let id = crosvm.get_id_allocator().alloc(); let mut r = MainRequest::new(); { @@ -694,12 +728,10 @@ impl crosvm_io_event { io_event.datamatch = datamatch; } let ret = match crosvm.main_transaction(&r, &[]) { - Ok((_, mut files)) => { - match files.pop() { - Some(evt) => return Ok(crosvm_io_event { id, evt }), - None => EPROTO, - } - } + Ok((_, mut files)) => match files.pop() { + Some(evt) => return Ok(crosvm_io_event { id, evt }), + None => EPROTO, + }, Err(e) => e, }; crosvm.get_id_allocator().free(id); @@ -725,14 +757,15 @@ pub struct crosvm_memory { } impl crosvm_memory { - fn create(crosvm: &mut crosvm, - fd: c_int, - offset: u64, - length: u64, - start: u64, - read_only: bool, - dirty_log: bool) - -> result::Result<crosvm_memory, c_int> { + fn create( + crosvm: &mut crosvm, + fd: c_int, + offset: u64, + length: u64, + start: u64, + read_only: bool, + dirty_log: bool, + ) -> result::Result<crosvm_memory, c_int> { const PAGE_MASK: u64 = 0x0fff; if offset & PAGE_MASK != 0 || length & PAGE_MASK != 0 { return Err(EINVAL); @@ -770,15 +803,23 @@ impl crosvm_memory { impl_ctor_dtor!( crosvm_memory, - crosvm_create_memory(fd: c_int, offset: u64, length: u64, start: u64, read_only: bool, dirty_log: bool), + crosvm_create_memory( + fd: c_int, + offset: u64, + length: u64, + start: u64, + read_only: bool, + dirty_log: bool + ), crosvm_destroy_memory, ); #[no_mangle] -pub unsafe extern "C" fn crosvm_memory_get_dirty_log(crosvm: *mut crosvm, - this: *mut crosvm_memory, - log: *mut u8) - -> c_int { +pub unsafe extern "C" fn crosvm_memory_get_dirty_log( + crosvm: *mut crosvm, + this: *mut crosvm_memory, + log: *mut u8, +) -> c_int { let _u = STATS.record(Stat::MemoryGetDirtyLog); let crosvm = &mut *crosvm; let this = &mut *this; @@ -819,10 +860,10 @@ impl crosvm_irq_event { let resample_evt = files.pop().unwrap(); let trigger_evt = files.pop().unwrap(); return Ok(crosvm_irq_event { - id, - trigger_evt, - resample_evt, - }); + id, + trigger_evt, + resample_evt, + }); } EPROTO } @@ -851,7 +892,6 @@ pub unsafe extern "C" fn crosvm_irq_event_get_resample_fd(this: *mut crosvm_irq_ (*this).resample_evt.as_raw_fd() } - #[allow(dead_code)] #[derive(Copy, Clone)] #[repr(C)] @@ -906,12 +946,13 @@ impl crosvm_vcpu { .send(self.request_buffer.as_slice()) .map_err(|e| -e.raw_os_error().unwrap_or(EINVAL))?; - let msg_size = self.socket + let msg_size = self + .socket .recv(&mut self.response_buffer) .map_err(|e| -e.raw_os_error().unwrap_or(EINVAL))?; - let response: VcpuResponse = parse_from_bytes(&self.response_buffer[..msg_size]) - .map_err(proto_error_to_int)?; + let response: VcpuResponse = + parse_from_bytes(&self.response_buffer[..msg_size]).map_err(proto_error_to_int)?; if response.errno != 0 { return Err(response.errno); } @@ -963,10 +1004,11 @@ impl crosvm_vcpu { Ok(()) } - fn get_state(&mut self, - state_set: VcpuRequest_StateSet, - out: &mut [u8]) - -> result::Result<(), c_int> { + fn get_state( + &mut self, + state_set: VcpuRequest_StateSet, + out: &mut [u8], + ) -> result::Result<(), c_int> { let mut r = VcpuRequest::new(); r.mut_get_state().set = state_set; let response = self.vcpu_transaction(&r)?; @@ -981,10 +1023,11 @@ impl crosvm_vcpu { Ok(()) } - fn set_state(&mut self, - state_set: VcpuRequest_StateSet, - new_state: &[u8]) - -> result::Result<(), c_int> { + fn set_state( + &mut self, + state_set: VcpuRequest_StateSet, + new_state: &[u8], + ) -> result::Result<(), c_int> { let mut r = VcpuRequest::new(); { let set_state: &mut VcpuRequest_SetState = r.mut_set_state(); @@ -995,8 +1038,11 @@ impl crosvm_vcpu { Ok(()) } - fn get_msrs(&mut self, msr_entries: &mut [kvm_msr_entry], msr_count: &mut usize) - -> result::Result<(), c_int> { + fn get_msrs( + &mut self, + msr_entries: &mut [kvm_msr_entry], + msr_count: &mut usize, + ) -> result::Result<(), c_int> { *msr_count = 0; let mut r = VcpuRequest::new(); { @@ -1014,11 +1060,7 @@ impl crosvm_vcpu { if *msr_count > msr_entries.len() { return Err(E2BIG); } - for (&msr_data, msr_entry) in - get_msrs - .get_entry_data() - .iter() - .zip(msr_entries.iter_mut()) { + for (&msr_data, msr_entry) in get_msrs.get_entry_data().iter().zip(msr_entries.iter_mut()) { msr_entry.data = msr_data; } Ok(()) @@ -1027,8 +1069,8 @@ impl crosvm_vcpu { fn set_msrs(&mut self, msr_entries: &[kvm_msr_entry]) -> result::Result<(), c_int> { let mut r = VcpuRequest::new(); { - let set_msrs_entries: &mut RepeatedField<VcpuRequest_MsrEntry> = r.mut_set_msrs() - .mut_entries(); + let set_msrs_entries: &mut RepeatedField<VcpuRequest_MsrEntry> = + r.mut_set_msrs().mut_entries(); for msr_entry in msr_entries.iter() { let mut entry = VcpuRequest_MsrEntry::new(); entry.index = msr_entry.index; @@ -1090,11 +1132,11 @@ pub unsafe extern "C" fn crosvm_new_connection(self_: *mut crosvm, out: *mut *mu let _u = STATS.record(Stat::NewConnection); let self_ = &mut (*self_); match self_.try_clone() { - Ok(cloned) => { - *out = Box::into_raw(Box::new(cloned)); - 0 - } - Err(e) => -e + Ok(cloned) => { + *out = Box::into_raw(Box::new(cloned)); + 0 + } + Err(e) => -e, } } @@ -1117,10 +1159,11 @@ pub unsafe extern "C" fn crosvm_get_shutdown_eventfd(self_: *mut crosvm) -> c_in } #[no_mangle] -pub unsafe extern "C" fn crosvm_check_extension(self_: *mut crosvm, - extension: u32, - has_extension: *mut bool) - -> c_int { +pub unsafe extern "C" fn crosvm_check_extension( + self_: *mut crosvm, + extension: u32, + has_extension: *mut bool, +) -> c_int { let _u = STATS.record(Stat::CheckExtentsion); let self_ = &mut (*self_); let ret = self_.check_extension(extension); @@ -1132,12 +1175,12 @@ pub unsafe extern "C" fn crosvm_check_extension(self_: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" -fn crosvm_get_supported_cpuid(this: *mut crosvm, - entry_count: u32, - cpuid_entries: *mut kvm_cpuid_entry2, - out_count: *mut u32) - -> c_int { +pub unsafe extern "C" fn crosvm_get_supported_cpuid( + this: *mut crosvm, + entry_count: u32, + cpuid_entries: *mut kvm_cpuid_entry2, + out_count: *mut u32, +) -> c_int { let _u = STATS.record(Stat::GetSupportedCpuid); let this = &mut *this; let cpuid_entries = from_raw_parts_mut(cpuid_entries, entry_count as usize); @@ -1148,12 +1191,12 @@ fn crosvm_get_supported_cpuid(this: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" -fn crosvm_get_emulated_cpuid(this: *mut crosvm, - entry_count: u32, - cpuid_entries: *mut kvm_cpuid_entry2, - out_count: *mut u32) - -> c_int { +pub unsafe extern "C" fn crosvm_get_emulated_cpuid( + this: *mut crosvm, + entry_count: u32, + cpuid_entries: *mut kvm_cpuid_entry2, + out_count: *mut u32, +) -> c_int { let _u = STATS.record(Stat::GetEmulatedCpuid); let this = &mut *this; let cpuid_entries = from_raw_parts_mut(cpuid_entries, entry_count as usize); @@ -1164,12 +1207,12 @@ fn crosvm_get_emulated_cpuid(this: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" -fn crosvm_get_msr_index_list(this: *mut crosvm, - entry_count: u32, - msr_indices: *mut u32, - out_count: *mut u32) - -> c_int { +pub unsafe extern "C" fn crosvm_get_msr_index_list( + this: *mut crosvm, + entry_count: u32, + msr_indices: *mut u32, + out_count: *mut u32, +) -> c_int { let _u = STATS.record(Stat::GetMsrIndexList); let this = &mut *this; let msr_indices = from_raw_parts_mut(msr_indices, entry_count as usize); @@ -1179,11 +1222,11 @@ fn crosvm_get_msr_index_list(this: *mut crosvm, to_crosvm_rc(ret) } - #[no_mangle] -pub unsafe extern "C" fn crosvm_net_get_config(self_: *mut crosvm, - config: *mut crosvm_net_config) - -> c_int { +pub unsafe extern "C" fn crosvm_net_get_config( + self_: *mut crosvm, + config: *mut crosvm_net_config, +) -> c_int { let _u = STATS.record(Stat::NetGetConfig); let self_ = &mut (*self_); let ret = self_.get_net_config(); @@ -1196,11 +1239,12 @@ pub unsafe extern "C" fn crosvm_net_get_config(self_: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" fn crosvm_reserve_range(self_: *mut crosvm, - space: u32, - start: u64, - length: u64) - -> c_int { +pub unsafe extern "C" fn crosvm_reserve_range( + self_: *mut crosvm, + space: u32, + start: u64, + length: u64, +) -> c_int { let _u = STATS.record(Stat::ReserveRange); let self_ = &mut (*self_); let ret = self_.reserve_range(space, start, length); @@ -1216,10 +1260,11 @@ pub unsafe extern "C" fn crosvm_set_irq(self_: *mut crosvm, irq_id: u32, active: } #[no_mangle] -pub unsafe extern "C" fn crosvm_set_irq_routing(self_: *mut crosvm, - route_count: u32, - routes: *const crosvm_irq_route) - -> c_int { +pub unsafe extern "C" fn crosvm_set_irq_routing( + self_: *mut crosvm, + route_count: u32, + routes: *const crosvm_irq_route, +) -> c_int { let _u = STATS.record(Stat::SetIrqRouting); let self_ = &mut (*self_); let ret = self_.set_irq_routing(slice::from_raw_parts(routes, route_count as usize)); @@ -1227,35 +1272,46 @@ pub unsafe extern "C" fn crosvm_set_irq_routing(self_: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" fn crosvm_get_pic_state(this: *mut crosvm, - primary: bool, - state: *mut kvm_pic_state) - -> c_int { +pub unsafe extern "C" fn crosvm_get_pic_state( + this: *mut crosvm, + primary: bool, + state: *mut kvm_pic_state, +) -> c_int { let _u = STATS.record(Stat::GetPicState); let this = &mut *this; - let state_set = if primary { MainRequest_StateSet::PIC0 } else { MainRequest_StateSet::PIC1 }; + let state_set = if primary { + MainRequest_StateSet::PIC0 + } else { + MainRequest_StateSet::PIC1 + }; let state = from_raw_parts_mut(state as *mut u8, size_of::<kvm_pic_state>()); let ret = this.get_state(state_set, state); to_crosvm_rc(ret) } #[no_mangle] -pub unsafe extern "C" fn crosvm_set_pic_state(this: *mut crosvm, - primary: bool, - state: *mut kvm_pic_state) - -> c_int { +pub unsafe extern "C" fn crosvm_set_pic_state( + this: *mut crosvm, + primary: bool, + state: *mut kvm_pic_state, +) -> c_int { let _u = STATS.record(Stat::SetPicState); let this = &mut *this; - let state_set = if primary { MainRequest_StateSet::PIC0 } else { MainRequest_StateSet::PIC1 }; + let state_set = if primary { + MainRequest_StateSet::PIC0 + } else { + MainRequest_StateSet::PIC1 + }; let state = from_raw_parts(state as *mut u8, size_of::<kvm_pic_state>()); let ret = this.set_state(state_set, state); to_crosvm_rc(ret) } #[no_mangle] -pub unsafe extern "C" fn crosvm_get_ioapic_state(this: *mut crosvm, - state: *mut kvm_ioapic_state) - -> c_int { +pub unsafe extern "C" fn crosvm_get_ioapic_state( + this: *mut crosvm, + state: *mut kvm_ioapic_state, +) -> c_int { let _u = STATS.record(Stat::GetIoapicState); let this = &mut *this; let state = from_raw_parts_mut(state as *mut u8, size_of::<kvm_ioapic_state>()); @@ -1264,10 +1320,10 @@ pub unsafe extern "C" fn crosvm_get_ioapic_state(this: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" fn crosvm_set_ioapic_state(this: *mut crosvm, - state: *const kvm_ioapic_state) - -> c_int { - +pub unsafe extern "C" fn crosvm_set_ioapic_state( + this: *mut crosvm, + state: *const kvm_ioapic_state, +) -> c_int { let _u = STATS.record(Stat::SetIoapicState); let this = &mut *this; let state = from_raw_parts(state as *mut u8, size_of::<kvm_ioapic_state>()); @@ -1276,9 +1332,10 @@ pub unsafe extern "C" fn crosvm_set_ioapic_state(this: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" fn crosvm_get_pit_state(this: *mut crosvm, - state: *mut kvm_pit_state2) - -> c_int { +pub unsafe extern "C" fn crosvm_get_pit_state( + this: *mut crosvm, + state: *mut kvm_pit_state2, +) -> c_int { let _u = STATS.record(Stat::GetPitState); let this = &mut *this; let state = from_raw_parts_mut(state as *mut u8, size_of::<kvm_pit_state2>()); @@ -1287,9 +1344,10 @@ pub unsafe extern "C" fn crosvm_get_pit_state(this: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" fn crosvm_set_pit_state(this: *mut crosvm, - state: *const kvm_pit_state2) - -> c_int { +pub unsafe extern "C" fn crosvm_set_pit_state( + this: *mut crosvm, + state: *const kvm_pit_state2, +) -> c_int { let _u = STATS.record(Stat::SetPitState); let this = &mut *this; let state = from_raw_parts(state as *mut u8, size_of::<kvm_pit_state2>()); @@ -1306,10 +1364,11 @@ pub unsafe extern "C" fn crosvm_set_identity_map_addr(self_: *mut crosvm, addr: } #[no_mangle] -pub unsafe extern "C" fn crosvm_pause_vcpus(self_: *mut crosvm, - cpu_mask: u64, - user: *mut c_void) - -> c_int { +pub unsafe extern "C" fn crosvm_pause_vcpus( + self_: *mut crosvm, + cpu_mask: u64, + user: *mut c_void, +) -> c_int { let _u = STATS.record(Stat::PauseVcpus); let self_ = &mut (*self_); let ret = self_.pause_vcpus(cpu_mask, user); @@ -1325,10 +1384,11 @@ pub unsafe extern "C" fn crosvm_start(self_: *mut crosvm) -> c_int { } #[no_mangle] -pub unsafe extern "C" fn crosvm_get_vcpu(self_: *mut crosvm, - cpu_id: u32, - out: *mut *mut crosvm_vcpu) - -> c_int { +pub unsafe extern "C" fn crosvm_get_vcpu( + self_: *mut crosvm, + cpu_id: u32, + out: *mut *mut crosvm_vcpu, +) -> c_int { let _u = STATS.record(Stat::GetVcpu); let self_ = &mut (*self_); let ret = self_.get_vcpu(cpu_id); @@ -1340,9 +1400,10 @@ pub unsafe extern "C" fn crosvm_get_vcpu(self_: *mut crosvm, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_wait(this: *mut crosvm_vcpu, - event: *mut crosvm_vcpu_event) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_wait( + this: *mut crosvm_vcpu, + event: *mut crosvm_vcpu_event, +) -> c_int { let _u = STATS.record(Stat::VcpuWait); let this = &mut *this; let event = &mut *event; @@ -1359,9 +1420,10 @@ pub unsafe extern "C" fn crosvm_vcpu_resume(this: *mut crosvm_vcpu) -> c_int { } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_regs(this: *mut crosvm_vcpu, - regs: *mut kvm_regs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_regs( + this: *mut crosvm_vcpu, + regs: *mut kvm_regs, +) -> c_int { let _u = STATS.record(Stat::VcpuGetRegs); let this = &mut *this; let regs = from_raw_parts_mut(regs as *mut u8, size_of::<kvm_regs>()); @@ -1370,9 +1432,10 @@ pub unsafe extern "C" fn crosvm_vcpu_get_regs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_regs(this: *mut crosvm_vcpu, - regs: *const kvm_regs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_regs( + this: *mut crosvm_vcpu, + regs: *const kvm_regs, +) -> c_int { let _u = STATS.record(Stat::VcpuSetRegs); let this = &mut *this; let regs = from_raw_parts(regs as *mut u8, size_of::<kvm_regs>()); @@ -1381,9 +1444,10 @@ pub unsafe extern "C" fn crosvm_vcpu_set_regs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_sregs(this: *mut crosvm_vcpu, - sregs: *mut kvm_sregs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_sregs( + this: *mut crosvm_vcpu, + sregs: *mut kvm_sregs, +) -> c_int { let _u = STATS.record(Stat::VcpuGetSregs); let this = &mut *this; let sregs = from_raw_parts_mut(sregs as *mut u8, size_of::<kvm_sregs>()); @@ -1392,9 +1456,10 @@ pub unsafe extern "C" fn crosvm_vcpu_get_sregs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_sregs(this: *mut crosvm_vcpu, - sregs: *const kvm_sregs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_sregs( + this: *mut crosvm_vcpu, + sregs: *const kvm_sregs, +) -> c_int { let _u = STATS.record(Stat::VcpuSetSregs); let this = &mut *this; let sregs = from_raw_parts(sregs as *mut u8, size_of::<kvm_sregs>()); @@ -1421,9 +1486,10 @@ pub unsafe extern "C" fn crosvm_vcpu_set_fpu(this: *mut crosvm_vcpu, fpu: *const } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_debugregs(this: *mut crosvm_vcpu, - dregs: *mut kvm_debugregs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_debugregs( + this: *mut crosvm_vcpu, + dregs: *mut kvm_debugregs, +) -> c_int { let _u = STATS.record(Stat::GetDebugRegs); let this = &mut *this; let dregs = from_raw_parts_mut(dregs as *mut u8, size_of::<kvm_debugregs>()); @@ -1432,9 +1498,10 @@ pub unsafe extern "C" fn crosvm_vcpu_get_debugregs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_debugregs(this: *mut crosvm_vcpu, - dregs: *const kvm_debugregs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_debugregs( + this: *mut crosvm_vcpu, + dregs: *const kvm_debugregs, +) -> c_int { let _u = STATS.record(Stat::SetDebugRegs); let this = &mut *this; let dregs = from_raw_parts(dregs as *mut u8, size_of::<kvm_debugregs>()); @@ -1443,9 +1510,10 @@ pub unsafe extern "C" fn crosvm_vcpu_set_debugregs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_xcrs(this: *mut crosvm_vcpu, - xcrs: *mut kvm_xcrs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_xcrs( + this: *mut crosvm_vcpu, + xcrs: *mut kvm_xcrs, +) -> c_int { let _u = STATS.record(Stat::GetXCRegs); let this = &mut *this; let xcrs = from_raw_parts_mut(xcrs as *mut u8, size_of::<kvm_xcrs>()); @@ -1454,9 +1522,10 @@ pub unsafe extern "C" fn crosvm_vcpu_get_xcrs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_xcrs(this: *mut crosvm_vcpu, - xcrs: *const kvm_xcrs) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_xcrs( + this: *mut crosvm_vcpu, + xcrs: *const kvm_xcrs, +) -> c_int { let _u = STATS.record(Stat::SetXCRegs); let this = &mut *this; let xcrs = from_raw_parts(xcrs as *mut u8, size_of::<kvm_xcrs>()); @@ -1465,11 +1534,12 @@ pub unsafe extern "C" fn crosvm_vcpu_set_xcrs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_msrs(this: *mut crosvm_vcpu, - msr_count: u32, - msr_entries: *mut kvm_msr_entry, - out_count: *mut u32) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_msrs( + this: *mut crosvm_vcpu, + msr_count: u32, + msr_entries: *mut kvm_msr_entry, + out_count: *mut u32, +) -> c_int { let _u = STATS.record(Stat::VcpuGetMsrs); let this = &mut *this; let msr_entries = from_raw_parts_mut(msr_entries, msr_count as usize); @@ -1480,10 +1550,11 @@ pub unsafe extern "C" fn crosvm_vcpu_get_msrs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_msrs(this: *mut crosvm_vcpu, - msr_count: u32, - msr_entries: *const kvm_msr_entry) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_msrs( + this: *mut crosvm_vcpu, + msr_count: u32, + msr_entries: *const kvm_msr_entry, +) -> c_int { let _u = STATS.record(Stat::VcpuSetMsrs); let this = &mut *this; let msr_entries = from_raw_parts(msr_entries, msr_count as usize); @@ -1492,10 +1563,11 @@ pub unsafe extern "C" fn crosvm_vcpu_set_msrs(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_cpuid(this: *mut crosvm_vcpu, - cpuid_count: u32, - cpuid_entries: *const kvm_cpuid_entry2) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_cpuid( + this: *mut crosvm_vcpu, + cpuid_count: u32, + cpuid_entries: *const kvm_cpuid_entry2, +) -> c_int { let _u = STATS.record(Stat::VcpuSetCpuid); let this = &mut *this; let cpuid_entries = from_raw_parts(cpuid_entries, cpuid_count as usize); @@ -1504,9 +1576,10 @@ pub unsafe extern "C" fn crosvm_vcpu_set_cpuid(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_lapic_state(this: *mut crosvm_vcpu, - state: *mut kvm_lapic_state) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_lapic_state( + this: *mut crosvm_vcpu, + state: *mut kvm_lapic_state, +) -> c_int { let _u = STATS.record(Stat::VcpuGetLapicState); let this = &mut *this; let state = from_raw_parts_mut(state as *mut u8, size_of::<kvm_lapic_state>()); @@ -1515,10 +1588,10 @@ pub unsafe extern "C" fn crosvm_vcpu_get_lapic_state(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_lapic_state(this: *mut crosvm_vcpu, - state: *const kvm_lapic_state) - -> c_int { - +pub unsafe extern "C" fn crosvm_vcpu_set_lapic_state( + this: *mut crosvm_vcpu, + state: *const kvm_lapic_state, +) -> c_int { let _u = STATS.record(Stat::VcpuSetLapicState); let this = &mut *this; let state = from_raw_parts(state as *mut u8, size_of::<kvm_lapic_state>()); @@ -1527,9 +1600,10 @@ pub unsafe extern "C" fn crosvm_vcpu_set_lapic_state(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_mp_state(this: *mut crosvm_vcpu, - state: *mut kvm_mp_state) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_mp_state( + this: *mut crosvm_vcpu, + state: *mut kvm_mp_state, +) -> c_int { let _u = STATS.record(Stat::VcpuGetMpState); let this = &mut *this; let state = from_raw_parts_mut(state as *mut u8, size_of::<kvm_mp_state>()); @@ -1538,9 +1612,10 @@ pub unsafe extern "C" fn crosvm_vcpu_get_mp_state(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_mp_state(this: *mut crosvm_vcpu, - state: *const kvm_mp_state) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_mp_state( + this: *mut crosvm_vcpu, + state: *const kvm_mp_state, +) -> c_int { let _u = STATS.record(Stat::VcpuSetMpState); let this = &mut *this; let state = from_raw_parts(state as *mut u8, size_of::<kvm_mp_state>()); @@ -1549,25 +1624,25 @@ pub unsafe extern "C" fn crosvm_vcpu_set_mp_state(this: *mut crosvm_vcpu, } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_get_vcpu_events(this: *mut crosvm_vcpu, - events: *mut kvm_vcpu_events) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_get_vcpu_events( + this: *mut crosvm_vcpu, + events: *mut kvm_vcpu_events, +) -> c_int { let _u = STATS.record(Stat::VcpuGetVcpuEvents); let this = &mut *this; - let events = from_raw_parts_mut(events as *mut u8, - size_of::<kvm_vcpu_events>()); + let events = from_raw_parts_mut(events as *mut u8, size_of::<kvm_vcpu_events>()); let ret = this.get_state(VcpuRequest_StateSet::EVENTS, events); to_crosvm_rc(ret) } #[no_mangle] -pub unsafe extern "C" fn crosvm_vcpu_set_vcpu_events(this: *mut crosvm_vcpu, - events: *const kvm_vcpu_events) - -> c_int { +pub unsafe extern "C" fn crosvm_vcpu_set_vcpu_events( + this: *mut crosvm_vcpu, + events: *const kvm_vcpu_events, +) -> c_int { let _u = STATS.record(Stat::VcpuSetVcpuEvents); let this = &mut *this; - let events = from_raw_parts(events as *mut u8, - size_of::<kvm_vcpu_events>()); + let events = from_raw_parts(events as *mut u8, size_of::<kvm_vcpu_events>()); let ret = this.set_state(VcpuRequest_StateSet::EVENTS, events); to_crosvm_rc(ret) } diff --git a/data_model/src/endian.rs b/data_model/src/endian.rs index 97d1b72..82799b8 100644 --- a/data_model/src/endian.rs +++ b/data_model/src/endian.rs @@ -33,7 +33,7 @@ use DataInit; macro_rules! endian_type { - ($old_type:ident, $new_type:ident, $to_new:ident, $from_new:ident) => ( + ($old_type:ident, $new_type:ident, $to_new:ident, $from_new:ident) => { /// An unsigned integer type of with an explicit endianness. /// /// See module level documentation for examples. @@ -72,7 +72,7 @@ macro_rules! endian_type { $new_type($old_type::$to_new(v)) } } - ) + }; } endian_type!(u16, Le16, to_le, from_le); @@ -89,7 +89,7 @@ mod tests { use super::*; use std::convert::From; - use std::mem::{size_of, align_of, transmute}; + use std::mem::{align_of, size_of, transmute}; #[cfg(target_endian = "little")] const NATIVE_LITTLE: bool = true; @@ -98,7 +98,7 @@ mod tests { const NATIVE_BIG: bool = !NATIVE_LITTLE; macro_rules! endian_test { - ($old_type:ty, $new_type:ty, $test_name:ident, $native:expr) => ( + ($old_type:ty, $new_type:ty, $test_name:ident, $native:expr) => { mod $test_name { use super::*; @@ -131,7 +131,7 @@ mod tests { assert!(endian_v == v); } } - ) + }; } endian_test!(u16, Le16, test_le16, NATIVE_LITTLE); diff --git a/data_model/src/lib.rs b/data_model/src/lib.rs index 6f0e1c2..4b86340 100644 --- a/data_model/src/lib.rs +++ b/data_model/src/lib.rs @@ -99,7 +99,7 @@ macro_rules! data_init_type { 20 21 22 23 24 25 26 27 28 29 30 31 32 } - } + }; } data_init_type!(u8); data_init_type!(u16); diff --git a/data_model/src/volatile_memory.rs b/data_model/src/volatile_memory.rs index d448fd1..5081fc6 100644 --- a/data_model/src/volatile_memory.rs +++ b/data_model/src/volatile_memory.rs @@ -23,13 +23,13 @@ use std::cmp::min; use std::fmt; use std::io::Result as IoResult; use std::io::{Read, Write}; -use std::{isize, usize}; use std::marker::PhantomData; use std::mem::size_of; use std::ptr::copy; -use std::ptr::{write_volatile, read_volatile, null_mut}; +use std::ptr::{null_mut, read_volatile, write_volatile}; use std::result; use std::slice::{from_raw_parts, from_raw_parts_mut}; +use std::{isize, usize}; use DataInit; @@ -47,12 +47,11 @@ impl fmt::Display for VolatileMemoryError { &VolatileMemoryError::OutOfBounds { addr } => { write!(f, "address 0x{:x} is out of bounds", addr) } - &VolatileMemoryError::Overflow { base, offset } => { - write!(f, - "address 0x{:x} offset by 0x{:x} would overflow", - base, - offset) - } + &VolatileMemoryError::Overflow { base, offset } => write!( + f, + "address 0x{:x} offset by 0x{:x} would overflow", + base, offset + ), } } } @@ -80,12 +79,7 @@ type Result<T> = VolatileMemoryResult<T>; /// ``` pub fn calc_offset(base: u64, offset: u64) -> Result<u64> { match base.checked_add(offset) { - None => { - Err(Error::Overflow { - base: base, - offset: offset, - }) - } + None => Err(Error::Overflow { base, offset }), Some(m) => Ok(m), } } @@ -100,9 +94,9 @@ pub trait VolatileMemory { fn get_ref<T: DataInit>(&self, offset: u64) -> Result<VolatileRef<T>> { let slice = self.get_slice(offset, size_of::<T>() as u64)?; Ok(VolatileRef { - addr: slice.addr as *mut T, - phantom: PhantomData, - }) + addr: slice.addr as *mut T, + phantom: PhantomData, + }) } } @@ -143,8 +137,8 @@ impl<'a> VolatileSlice<'a> { /// accesses. pub unsafe fn new(addr: *mut u8, size: u64) -> VolatileSlice<'a> { VolatileSlice { - addr: addr, - size: size, + addr, + size, phantom: PhantomData, } } @@ -162,19 +156,21 @@ impl<'a> VolatileSlice<'a> { /// Creates a copy of this slice with the address increased by `count` bytes, and the size /// reduced by `count` bytes. pub fn offset(self, count: u64) -> Result<VolatileSlice<'a>> { - let new_addr = (self.addr as u64) - .checked_add(count) - .ok_or(VolatileMemoryError::Overflow { - base: self.addr as u64, - offset: count, - })?; + let new_addr = + (self.addr as u64) + .checked_add(count) + .ok_or(VolatileMemoryError::Overflow { + base: self.addr as u64, + offset: count, + })?; if new_addr > usize::MAX as u64 { return Err(VolatileMemoryError::Overflow { - base: self.addr as u64, - offset: count, - })?; + base: self.addr as u64, + offset: count, + })?; } - let new_size = self.size + let new_size = self + .size .checked_sub(count) .ok_or(VolatileMemoryError::OutOfBounds { addr: new_addr })?; // Safe because the memory has the same lifetime and points to a subset of the memory of the @@ -206,7 +202,8 @@ impl<'a> VolatileSlice<'a> { /// # } /// ``` pub fn copy_to<T>(&self, buf: &mut [T]) - where T: DataInit + where + T: DataInit, { let mut addr = self.addr; for v in buf.iter_mut().take(self.size as usize / size_of::<T>()) { @@ -262,7 +259,8 @@ impl<'a> VolatileSlice<'a> { /// # } /// ``` pub fn copy_from<T>(&self, buf: &[T]) - where T: DataInit + where + T: DataInit, { let mut addr = self.addr; for &v in buf.iter().take(self.size as usize / size_of::<T>()) { @@ -326,7 +324,6 @@ impl<'a> VolatileSlice<'a> { w.write_all(unsafe { self.as_slice() }) } - /// Reads up to this slice's size to memory from a readable object and returns how many bytes /// were actually read on success. /// @@ -397,10 +394,10 @@ impl<'a> VolatileMemory for VolatileSlice<'a> { return Err(Error::OutOfBounds { addr: mem_end }); } Ok(VolatileSlice { - addr: (self.addr as u64 + offset) as *mut _, - size: count, - phantom: PhantomData, - }) + addr: (self.addr as u64 + offset) as *mut _, + size: count, + phantom: PhantomData, + }) } } @@ -418,7 +415,8 @@ impl<'a> VolatileMemory for VolatileSlice<'a> { /// assert_eq!(v, 500); #[derive(Debug)] pub struct VolatileRef<'a, T: DataInit> - where T: 'a +where + T: 'a, { addr: *mut T, phantom: PhantomData<&'a T>, @@ -433,7 +431,7 @@ impl<'a, T: DataInit> VolatileRef<'a, T> { /// accesses. pub unsafe fn new(addr: *mut T) -> VolatileRef<'a, T> { VolatileRef { - addr: addr, + addr, phantom: PhantomData, } } @@ -483,7 +481,7 @@ mod tests { use super::*; use std::sync::Arc; - use std::thread::{spawn, sleep}; + use std::thread::{sleep, spawn}; use std::time::Duration; #[derive(Clone)] @@ -505,9 +503,7 @@ mod tests { if mem_end > self.mem.len() as u64 { return Err(Error::OutOfBounds { addr: mem_end }); } - Ok(unsafe { - VolatileSlice::new((self.mem.as_ptr() as u64 + offset) as *mut _, count) - }) + Ok(unsafe { VolatileSlice::new((self.mem.as_ptr() as u64 + offset) as *mut _, count) }) } } @@ -558,10 +554,10 @@ mod tests { let v_ref = a.get_ref::<u8>(0).unwrap(); v_ref.store(99); spawn(move || { - sleep(Duration::from_millis(10)); - let clone_v_ref = a_clone.get_ref::<u8>(0).unwrap(); - clone_v_ref.store(0); - }); + sleep(Duration::from_millis(10)); + let clone_v_ref = a_clone.get_ref::<u8>(0).unwrap(); + clone_v_ref.store(0); + }); // Technically this is a race condition but we have to observe the v_ref's value changing // somehow and this helps to ensure the sleep actually happens before the store rather then @@ -607,11 +603,13 @@ mod tests { use std::u64::MAX; let a = VecMem::new(1); let res = a.get_slice(MAX, 1).unwrap_err(); - assert_eq!(res, - Error::Overflow { - base: MAX, - offset: 1, - }); + assert_eq!( + res, + Error::Overflow { + base: MAX, + offset: 1, + } + ); } #[test] @@ -627,11 +625,13 @@ mod tests { use std::u64::MAX; let a = VecMem::new(1); let res = a.get_ref::<u8>(MAX).unwrap_err(); - assert_eq!(res, - Error::Overflow { - base: MAX, - offset: 1, - }); + assert_eq!( + res, + Error::Overflow { + base: MAX, + offset: 1, + } + ); } #[test] diff --git a/devices/src/bus.rs b/devices/src/bus.rs index d884658..db7fa92 100644 --- a/devices/src/bus.rs +++ b/devices/src/bus.rs @@ -4,7 +4,7 @@ //! Handles routing to devices in an address space. -use std::cmp::{Ord, PartialOrd, PartialEq, Ordering}; +use std::cmp::{Ord, Ordering, PartialEq, PartialOrd}; use std::collections::btree_map::BTreeMap; use std::result; use std::sync::{Arc, Mutex}; @@ -25,7 +25,9 @@ pub trait BusDevice: Send { fn config_register_write(&mut self, reg_idx: usize, offset: u64, data: &[u8]) {} /// Gets a register from the configuration space. Only used by PCI. /// * `reg_idx` - The index of the config register to read. - fn config_register_read(&self, reg_idx: usize) -> u32 { 0 } + fn config_register_read(&self, reg_idx: usize) -> u32 { + 0 + } } #[derive(Debug)] @@ -93,13 +95,22 @@ pub struct Bus { impl Bus { /// Constructs an a bus with an empty address space. pub fn new() -> Bus { - Bus { devices: BTreeMap::new() } + Bus { + devices: BTreeMap::new(), + } } fn first_before(&self, addr: u64) -> Option<(BusRange, &Mutex<BusDevice>)> { - let(range, dev) = self.devices.range(..=BusRange {base:addr, len:1, full_addr: false}) - .rev() - .next()?; + let (range, dev) = self + .devices + .range( + ..=BusRange { + base: addr, + len: 1, + full_addr: false, + }, + ).rev() + .next()?; Some((*range, dev)) } @@ -118,21 +129,37 @@ impl Bus { } /// Puts the given device at the given address space. - pub fn insert(&mut self, device: Arc<Mutex<BusDevice>>, base: u64, len: u64, full_addr: bool) - -> Result<()> - { + pub fn insert( + &mut self, + device: Arc<Mutex<BusDevice>>, + base: u64, + len: u64, + full_addr: bool, + ) -> Result<()> { if len == 0 { return Err(Error::Overlap); } // Reject all cases where the new device's range overlaps with an existing device. - if self.devices.iter().any(|(range, _dev)| range.overlaps(base, len)) { + if self + .devices + .iter() + .any(|(range, _dev)| range.overlaps(base, len)) + { return Err(Error::Overlap); } - if self.devices - .insert(BusRange{base, len, full_addr}, device) - .is_some() { + if self + .devices + .insert( + BusRange { + base, + len, + full_addr, + }, + device, + ).is_some() + { return Err(Error::Overlap); } @@ -269,7 +296,11 @@ mod tests { #[test] fn bus_range_contains() { - let a = BusRange { base: 0x1000, len: 0x400, full_addr: false }; + let a = BusRange { + base: 0x1000, + len: 0x400, + full_addr: false, + }; assert!(a.contains(0x1000)); assert!(a.contains(0x13ff)); assert!(!a.contains(0xfff)); @@ -279,7 +310,11 @@ mod tests { #[test] fn bus_range_overlap() { - let a = BusRange { base: 0x1000, len: 0x400, full_addr: false }; + let a = BusRange { + base: 0x1000, + len: 0x400, + full_addr: false, + }; assert!(a.overlaps(0x1000, 0x400)); assert!(a.overlaps(0xf00, 0x400)); assert!(a.overlaps(0x1000, 0x01)); diff --git a/devices/src/cmos.rs b/devices/src/cmos.rs index 70caff7..cf5dd7e 100644 --- a/devices/src/cmos.rs +++ b/devices/src/cmos.rs @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use libc::{gmtime_r, time, time_t, tm}; use std::mem; -use libc::{tm, time_t, time, gmtime_r}; use BusDevice; diff --git a/devices/src/i8042.rs b/devices/src/i8042.rs index c23dd03..8981e02 100644 --- a/devices/src/i8042.rs +++ b/devices/src/i8042.rs @@ -14,7 +14,7 @@ pub struct I8042Device { impl I8042Device { /// Constructs a i8042 device that will signal the given event when the guest requests it. pub fn new(reset_evt: EventFd) -> I8042Device { - I8042Device { reset_evt: reset_evt } + I8042Device { reset_evt } } } diff --git a/devices/src/lib.rs b/devices/src/lib.rs index 25cb94f..c6bf785 100644 --- a/devices/src/lib.rs +++ b/devices/src/lib.rs @@ -22,18 +22,20 @@ mod bus; mod cmos; mod i8042; mod pci; +pub mod pl030; mod proxy; mod serial; -pub mod pl030; pub mod virtio; -pub use self::bus::{Bus, BusDevice, BusRange}; pub use self::bus::Error as BusError; +pub use self::bus::{Bus, BusDevice, BusRange}; pub use self::cmos::Cmos; -pub use self::pl030::Pl030; pub use self::i8042::I8042Device; -pub use self::pci::{PciConfigIo, PciConfigMmio, PciDevice, PciDeviceError, PciInterruptPin, PciRoot}; -pub use self::proxy::ProxyDevice; +pub use self::pci::{ + PciConfigIo, PciConfigMmio, PciDevice, PciDeviceError, PciInterruptPin, PciRoot, +}; +pub use self::pl030::Pl030; pub use self::proxy::Error as ProxyError; +pub use self::proxy::ProxyDevice; pub use self::serial::Serial; pub use self::virtio::VirtioPciDevice; diff --git a/devices/src/pci/mod.rs b/devices/src/pci/mod.rs index a9cdeac..2579ba7 100644 --- a/devices/src/pci/mod.rs +++ b/devices/src/pci/mod.rs @@ -8,7 +8,10 @@ mod pci_configuration; mod pci_device; mod pci_root; -pub use self::pci_configuration::{PciCapability, PciCapabilityID, PciClassCode, PciConfiguration, PciHeaderType, PciProgrammingInterface, PciSubclass}; +pub use self::pci_configuration::{ + PciCapability, PciCapabilityID, PciClassCode, PciConfiguration, PciHeaderType, + PciProgrammingInterface, PciSubclass, +}; pub use self::pci_device::Error as PciDeviceError; pub use self::pci_device::PciDevice; pub use self::pci_root::{PciConfigIo, PciConfigMmio, PciRoot}; diff --git a/devices/src/pci/pci_configuration.rs b/devices/src/pci/pci_configuration.rs index 5cc62e1..bf6c3d1 100644 --- a/devices/src/pci/pci_configuration.rs +++ b/devices/src/pci/pci_configuration.rs @@ -201,12 +201,12 @@ impl PciConfiguration { PciHeaderType::Device => { registers[3] = 0x0000_0000; // Header type 0 (device) writable_bits[15] = 0x0000_00ff; // Interrupt line (r/w) - }, + } PciHeaderType::Bridge => { registers[3] = 0x0001_0000; // Header type 1 (bridge) writable_bits[9] = 0xfff0_fff0; // Memory base and limit writable_bits[15] = 0xffff_00ff; // Bridge control (r/w), interrupt line (r/w) - }, + } }; registers[11] = u32::from(subsystem_id) << 16 | u32::from(subsystem_vendor_id); @@ -290,7 +290,7 @@ impl PciConfiguration { // TODO(dgreid) Allow 64 bit address and size. if addr.checked_add(size)? > u64::from(u32::max_value()) { - return None; + return None; } let this_bar = self.num_bars; @@ -330,7 +330,8 @@ impl PciConfiguration { // `pin` is 1-based in the pci config space. let pin_idx = (pin as u32) + 1; self.registers[INTERRUPT_LINE_PIN_REG] = (self.registers[INTERRUPT_LINE_PIN_REG] - & 0xffff_0000) | (pin_idx << 8) + & 0xffff_0000) + | (pin_idx << 8) | u32::from(line); } @@ -413,7 +414,10 @@ mod tests { let cap1_offset = cfg.add_capability(&cap1).unwrap(); assert_eq!(cap1_offset % 4, 0); - let cap2 = TestCap { len: 0x04, foo: 0x55 }; + let cap2 = TestCap { + len: 0x04, + foo: 0x55, + }; let cap2_offset = cfg.add_capability(&cap2).unwrap(); assert_eq!(cap2_offset % 4, 0); diff --git a/devices/src/pci/pci_device.rs b/devices/src/pci/pci_device.rs index 80d99e3..edc1b5c 100644 --- a/devices/src/pci/pci_device.rs +++ b/devices/src/pci/pci_device.rs @@ -9,8 +9,8 @@ use std::os::unix::io::RawFd; use pci::pci_configuration::PciConfiguration; use pci::PciInterruptPin; -use sys_util::EventFd; use resources::SystemAllocator; +use sys_util::EventFd; use BusDevice; @@ -31,10 +31,7 @@ pub trait PciDevice: Send { fn assign_irq(&mut self, _irq_evt: EventFd, _irq_num: u32, _irq_pin: PciInterruptPin) {} /// Allocates the needed IO BAR space using the `allocate` function which takes a size and /// returns an address. Returns a Vec of (address, length) tuples. - fn allocate_io_bars( - &mut self, - _resources: &mut SystemAllocator, - ) -> Result<Vec<(u64, u64)>> { + fn allocate_io_bars(&mut self, _resources: &mut SystemAllocator) -> Result<Vec<(u64, u64)>> { Ok(Vec::new()) } /// Gets a list of ioeventfds that should be registered with the running VM. The list is @@ -93,14 +90,11 @@ impl<T: PciDevice + ?Sized> PciDevice for Box<T> { (**self).keep_fds() } fn assign_irq(&mut self, irq_evt: EventFd, irq_num: u32, irq_pin: PciInterruptPin) { - (**self).assign_irq(irq_evt, irq_num, irq_pin) + (**self).assign_irq(irq_evt, irq_num, irq_pin) } /// Allocates the needed IO BAR space using the `allocate` function which takes a size and /// returns an address. Returns a Vec of (address, length) tuples. - fn allocate_io_bars( - &mut self, - resources: &mut SystemAllocator, - ) -> Result<Vec<(u64, u64)>> { + fn allocate_io_bars(&mut self, resources: &mut SystemAllocator) -> Result<Vec<(u64, u64)>> { (**self).allocate_io_bars(resources) } /// Gets a list of ioeventfds that should be registered with the running VM. The list is diff --git a/devices/src/pci/pci_root.rs b/devices/src/pci/pci_root.rs index 5b43cf0..d6ed5ce 100644 --- a/devices/src/pci/pci_root.rs +++ b/devices/src/pci/pci_root.rs @@ -10,8 +10,7 @@ use byteorder::{ByteOrder, LittleEndian}; use BusDevice; use ProxyDevice; -use pci::pci_configuration::{PciBridgeSubclass, PciClassCode, PciConfiguration, - PciHeaderType}; +use pci::pci_configuration::{PciBridgeSubclass, PciClassCode, PciConfiguration, PciHeaderType}; use pci::pci_device::PciDevice; // A PciDevice that holds the root hub's configuration. @@ -50,15 +49,15 @@ impl PciRoot { PciRoot { root_configuration: PciRootConfiguration { config: PciConfiguration::new( - 0, - 0, - PciClassCode::BridgeDevice, - &PciBridgeSubclass::HostBridge, - None, - PciHeaderType::Bridge, - 0, - 0, - ), + 0, + 0, + PciClassCode::BridgeDevice, + &PciBridgeSubclass::HostBridge, + None, + PciHeaderType::Bridge, + 0, + 0, + ), }, devices: Vec::new(), } @@ -86,12 +85,9 @@ impl PciRoot { // If bus and device are both zero, then read from the root config. self.root_configuration.config_register_read(register) } - dev_num => self - .devices - .get(dev_num - 1) - .map_or(0xffff_ffff, |d| { - d.lock().unwrap().config_register_read(register) - }), + dev_num => self.devices.get(dev_num - 1).map_or(0xffff_ffff, |d| { + d.lock().unwrap().config_register_read(register) + }), } } @@ -116,17 +112,19 @@ impl PciRoot { match device { 0 => { // If bus and device are both zero, then read from the root config. - self.root_configuration.config_register_write(register, offset, data); + self.root_configuration + .config_register_write(register, offset, data); } dev_num => { // dev_num is 1-indexed here. if let Some(d) = self.devices.get(dev_num - 1) { - d.lock().unwrap().config_register_write(register, offset, data); + d.lock() + .unwrap() + .config_register_write(register, offset, data); } } } } - } /// Emulates PCI configuration access mechanism #1 (I/O ports 0xcf8 and 0xcfc). @@ -230,19 +228,19 @@ pub struct PciConfigMmio { impl PciConfigMmio { pub fn new(pci_root: PciRoot) -> Self { - PciConfigMmio { - pci_root, - } + PciConfigMmio { pci_root } } fn config_space_read(&self, config_address: u32) -> u32 { let (bus, device, function, register) = parse_config_address(config_address); - self.pci_root.config_space_read(bus, device, function, register) + self.pci_root + .config_space_read(bus, device, function, register) } fn config_space_write(&mut self, config_address: u32, offset: u64, data: &[u8]) { let (bus, device, function, register) = parse_config_address(config_address); - self.pci_root.config_space_write(bus, device, function, register, offset, data) + self.pci_root + .config_space_write(bus, device, function, register, offset, data) } } @@ -290,10 +288,5 @@ fn parse_config_address(config_address: u32) -> (usize, usize, usize, usize) { let register_number = ((config_address >> REGISTER_NUMBER_OFFSET) & REGISTER_NUMBER_MASK) as usize; - ( - bus_number, - device_number, - function_number, - register_number, - ) + (bus_number, device_number, function_number, register_number) } diff --git a/devices/src/pl030.rs b/devices/src/pl030.rs index b555114..6710b5e 100644 --- a/devices/src/pl030.rs +++ b/devices/src/pl030.rs @@ -9,17 +9,17 @@ use BusDevice; // Register offsets // Data register -const RTCDR: u64 = 0x0; +const RTCDR: u64 = 0x0; // Match register -const RTCMR: u64 = 0x4; +const RTCMR: u64 = 0x4; // Interrupt status register const RTCSTAT: u64 = 0x8; // Interrupt clear register -const RTCEOI: u64 = 0x8; +const RTCEOI: u64 = 0x8; // Counter load register -const RTCLR: u64 = 0xC; +const RTCLR: u64 = 0xC; // Counter register -const RTCCR: u64 = 0x10; +const RTCCR: u64 = 0x10; // A single 4K page is mapped for this device pub const PL030_AMBA_IOMEM_SIZE: u64 = 0x1000; @@ -29,7 +29,7 @@ const AMBA_ID_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x20; const AMBA_MASK_OFFSET: u64 = PL030_AMBA_IOMEM_SIZE - 0x28; // This is the AMBA id for this device -pub const PL030_AMBA_ID: u32 = 0x00041030; +pub const PL030_AMBA_ID: u32 = 0x00041030; pub const PL030_AMBA_MASK: u32 = 0x000FFFFF; /// An emulated ARM pl030 RTC @@ -51,13 +51,12 @@ pub struct Pl030 { } fn get_epoch_time() -> u32 { - let epoch_time = - SystemTime::now().duration_since(UNIX_EPOCH). - expect("SystemTime::duration_since failed"); + let epoch_time = SystemTime::now() + .duration_since(UNIX_EPOCH) + .expect("SystemTime::duration_since failed"); epoch_time.as_secs() as u32 } - impl Pl030 { /// Constructs a Pl030 device pub fn new(evt: EventFd) -> Pl030 { @@ -77,19 +76,21 @@ impl BusDevice for Pl030 { return; } - let reg_val: u32 = (data[0] as u32) << 24 | (data[1] as u32) << 16 | - (data[2] as u32) << 8 | (data[3] as u32); + let reg_val: u32 = (data[0] as u32) << 24 + | (data[1] as u32) << 16 + | (data[2] as u32) << 8 + | (data[3] as u32); match offset { RTCDR => { warn!("invalid write to read-only RTCDR register"); - }, + } RTCMR => { self.match_value = reg_val; // TODO(sonnyrao): here we need to set up a timer for // when host time equals the value written here and // fire the interrupt warn!("Not implemented: VM tried to set an RTC alarm"); - }, + } RTCEOI => { if reg_val == 0 { self.interrupt_active = false; @@ -97,18 +98,18 @@ impl BusDevice for Pl030 { self.alarm_evt.write(1).unwrap(); self.interrupt_active = true; } - }, + } RTCLR => { // TODO(sonnyrao): if we ever need to let the VM set it's own time // then we'll need to keep track of the delta between // the rtc time it sets and the host's rtc time and // record that here warn!("Not implemented: VM tried to set the RTC"); - }, + } RTCCR => { self.counter_delta_time = get_epoch_time(); - }, - o => panic!("pl030: bad write offset {}", o) + } + o => panic!("pl030: bad write offset {}", o), } } @@ -119,30 +120,18 @@ impl BusDevice for Pl030 { } let reg_content: u32 = match offset { - RTCDR => { - get_epoch_time() - }, - RTCMR => { - self.match_value - }, - RTCSTAT => { - self.interrupt_active as u32 - }, + RTCDR => get_epoch_time(), + RTCMR => self.match_value, + RTCSTAT => self.interrupt_active as u32, RTCLR => { warn!("invalid read of RTCLR register"); 0 - }, - RTCCR => { - get_epoch_time() - self.counter_delta_time - }, - AMBA_ID_OFFSET => { - PL030_AMBA_ID - }, - AMBA_MASK_OFFSET => { - PL030_AMBA_MASK - }, - - o => panic!("pl030: bad read offset {}", o) + } + RTCCR => get_epoch_time() - self.counter_delta_time, + AMBA_ID_OFFSET => PL030_AMBA_ID, + AMBA_MASK_OFFSET => PL030_AMBA_MASK, + + o => panic!("pl030: bad read offset {}", o), }; data[0] = reg_content as u8; data[1] = (reg_content >> 8) as u8; diff --git a/devices/src/proxy.rs b/devices/src/proxy.rs index 673a3c7..478625b 100644 --- a/devices/src/proxy.rs +++ b/devices/src/proxy.rs @@ -6,16 +6,16 @@ use libc::pid_t; -use std::{self, fmt, io}; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixDatagram; use std::process; use std::time::Duration; +use std::{self, fmt, io}; -use byteorder::{LittleEndian, NativeEndian, ByteOrder}; +use byteorder::{ByteOrder, LittleEndian, NativeEndian}; -use BusDevice; use io_jail::{self, Minijail}; +use BusDevice; /// Errors for proxy devices. #[derive(Debug)] @@ -52,9 +52,11 @@ fn child_proc(sock: UnixDatagram, device: &mut BusDevice) { let mut buf = [0; MSG_SIZE]; match handle_eintr!(sock.recv(&mut buf)) { Ok(c) if c != buf.len() => { - error!("child device process incorrect recv size: got {}, expected {}", - c, - buf.len()); + error!( + "child device process incorrect recv size: got {}, expected {}", + c, + buf.len() + ); break; } Err(e) => { @@ -123,9 +125,11 @@ impl ProxyDevice { /// # Arguments /// * `device` - The device to isolate to another process. /// * `keep_fds` - File descriptors that will be kept open in the child - pub fn new<D: BusDevice>(mut device: D, jail: &Minijail, mut keep_fds: Vec<RawFd>) - -> Result<ProxyDevice> - { + pub fn new<D: BusDevice>( + mut device: D, + jail: &Minijail, + mut keep_fds: Vec<RawFd>, + ) -> Result<ProxyDevice> { let (child_sock, parent_sock) = UnixDatagram::pair().map_err(Error::Io)?; keep_fds.push(child_sock.as_raw_fd()); @@ -136,7 +140,7 @@ impl ProxyDevice { child_proc(child_sock, &mut device); // ! Never returns process::exit(0); - }, + } p => p, } }; @@ -148,9 +152,9 @@ impl ProxyDevice { .set_read_timeout(Some(Duration::from_millis(SOCKET_TIMEOUT_MS))) .map_err(Error::Io)?; Ok(ProxyDevice { - sock: parent_sock, - pid: pid, - }) + sock: parent_sock, + pid, + }) } pub fn pid(&self) -> pid_t { @@ -163,12 +167,12 @@ impl ProxyDevice { NativeEndian::write_u32(&mut buf[4..], len); NativeEndian::write_u64(&mut buf[8..], offset); buf[16..16 + data.len()].clone_from_slice(data); - handle_eintr!(self.sock.send(&buf)).map(|_| ()).map_err(Error::Io) + handle_eintr!(self.sock.send(&buf)) + .map(|_| ()) + .map_err(Error::Io) } - fn send_config_cmd(&self, cmd: Command, reg_idx: u32, offset: u64, data: &[u8]) - -> Result<()> - { + fn send_config_cmd(&self, cmd: Command, reg_idx: u32, offset: u64, data: &[u8]) -> Result<()> { let mut buf = [0; MSG_SIZE]; NativeEndian::write_u32(&mut buf[0..], cmd as u32); NativeEndian::write_u32(&mut buf[4..], reg_idx); @@ -190,7 +194,9 @@ impl ProxyDevice { fn wait(&self) -> Result<()> { let mut buf = [0; MSG_SIZE]; - handle_eintr!(self.sock.recv(&mut buf)).map(|_| ()).map_err(Error::Io) + handle_eintr!(self.sock.recv(&mut buf)) + .map(|_| ()) + .map_err(Error::Io) } pub fn config_register_write(&mut self, reg_idx: usize, offset: u64, data: &[u8]) { @@ -216,7 +222,8 @@ impl ProxyDevice { impl BusDevice for ProxyDevice { fn read(&mut self, offset: u64, data: &mut [u8]) { - let res = self.send_cmd(Command::Read, offset, data.len() as u32, &[]) + let res = self + .send_cmd(Command::Read, offset, data.len() as u32, &[]) .and_then(|_| self.recv_resp(data)); if let Err(e) = res { error!("failed read from child device process: {}", e); @@ -224,7 +231,8 @@ impl BusDevice for ProxyDevice { } fn write(&mut self, offset: u64, data: &[u8]) { - let res = self.send_cmd(Command::Write, offset, data.len() as u32, data) + let res = self + .send_cmd(Command::Write, offset, data.len() as u32, data) .and_then(|_| self.wait()); if let Err(e) = res { error!("failed write to child device process: {}", e); diff --git a/devices/src/serial.rs b/devices/src/serial.rs index 6d7512f..39ecbe5 100644 --- a/devices/src/serial.rs +++ b/devices/src/serial.rs @@ -2,8 +2,8 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::io; use std::collections::VecDeque; +use std::io; use sys_util::{EventFd, Result}; @@ -67,7 +67,7 @@ impl Serial { Serial { interrupt_enable: 0, interrupt_identification: DEFAULT_INTERRUPT_IDENTIFICATION, - interrupt_evt: interrupt_evt, + interrupt_evt, line_control: DEFAULT_LINE_CONTROL, line_status: DEFAULT_LINE_STATUS, modem_control: DEFAULT_MODEM_CONTROL, @@ -75,7 +75,7 @@ impl Serial { scratch: 0, baud_divisor: DEFAULT_BAUD_DIVISOR, in_buffer: VecDeque::new(), - out: out, + out, } } @@ -229,8 +229,8 @@ impl BusDevice for Serial { #[cfg(test)] mod tests { use super::*; - use std::sync::{Arc, Mutex}; use std::io; + use std::sync::{Arc, Mutex}; #[derive(Clone)] struct SharedBuffer { @@ -239,7 +239,9 @@ mod tests { impl SharedBuffer { fn new() -> SharedBuffer { - SharedBuffer { buf: Arc::new(Mutex::new(Vec::new())) } + SharedBuffer { + buf: Arc::new(Mutex::new(Vec::new())), + } } } @@ -262,8 +264,10 @@ mod tests { serial.write(DATA as u64, &['a' as u8]); serial.write(DATA as u64, &['b' as u8]); serial.write(DATA as u64, &['c' as u8]); - assert_eq!(serial_out.buf.lock().unwrap().as_slice(), - &['a' as u8, 'b' as u8, 'c' as u8]); + assert_eq!( + serial_out.buf.lock().unwrap().as_slice(), + &['a' as u8, 'b' as u8, 'c' as u8] + ); } #[test] @@ -271,11 +275,13 @@ mod tests { let intr_evt = EventFd::new().unwrap(); let serial_out = SharedBuffer::new(); - let mut serial = Serial::new_out(intr_evt.try_clone().unwrap(), - Box::new(serial_out.clone())); + let mut serial = + Serial::new_out(intr_evt.try_clone().unwrap(), Box::new(serial_out.clone())); serial.write(IER as u64, &[IER_RECV_BIT]); - serial.queue_input_bytes(&['a' as u8, 'b' as u8, 'c' as u8]).unwrap(); + serial + .queue_input_bytes(&['a' as u8, 'b' as u8, 'c' as u8]) + .unwrap(); assert_eq!(intr_evt.read(), Ok(1)); let mut data = [0u8; 1]; diff --git a/devices/src/virtio/balloon.rs b/devices/src/virtio/balloon.rs index 2943359..76cbc33 100644 --- a/devices/src/virtio/balloon.rs +++ b/devices/src/virtio/balloon.rs @@ -8,15 +8,17 @@ use std::io::Write; use std::mem; use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixDatagram; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use byteorder::{ByteOrder, LittleEndian, ReadBytesExt, WriteBytesExt}; use sys_util::{self, EventFd, GuestAddress, GuestMemory, PollContext, PollToken}; -use super::{VirtioDevice, Queue, DescriptorChain, INTERRUPT_STATUS_CONFIG_CHANGED, - INTERRUPT_STATUS_USED_RING, TYPE_BALLOON}; +use super::{ + DescriptorChain, Queue, VirtioDevice, INTERRUPT_STATUS_CONFIG_CHANGED, + INTERRUPT_STATUS_USED_RING, TYPE_BALLOON, +}; #[derive(Debug)] pub enum BalloonError { @@ -85,7 +87,8 @@ impl Worker { let guest_address = GuestAddress((guest_input as u64) << VIRTIO_BALLOON_PFN_SHIFT); - if self.mem + if self + .mem .remove_range(guest_address, 1 << VIRTIO_BALLOON_PFN_SHIFT) .is_err() { @@ -107,19 +110,14 @@ impl Worker { } fn signal_used_queue(&self) { - self.interrupt_status.fetch_or( - INTERRUPT_STATUS_USED_RING as usize, - Ordering::SeqCst, - ); + self.interrupt_status + .fetch_or(INTERRUPT_STATUS_USED_RING as usize, Ordering::SeqCst); self.interrupt_evt.write(1).unwrap(); } fn signal_config_changed(&self) { - self.interrupt_status.fetch_or( - INTERRUPT_STATUS_CONFIG_CHANGED as - usize, - Ordering::SeqCst, - ); + self.interrupt_status + .fetch_or(INTERRUPT_STATUS_CONFIG_CHANGED as usize, Ordering::SeqCst); self.interrupt_evt.write(1).unwrap(); } @@ -135,18 +133,20 @@ impl Worker { let inflate_queue_evt = queue_evts.remove(0); let deflate_queue_evt = queue_evts.remove(0); - let poll_ctx: PollContext<Token> = - match PollContext::new() - .and_then(|pc| pc.add(&inflate_queue_evt, Token::Inflate).and(Ok(pc))) - .and_then(|pc| pc.add(&deflate_queue_evt, Token::Deflate).and(Ok(pc))) - .and_then(|pc| pc.add(&self.command_socket, Token::CommandSocket).and(Ok(pc))) - .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) { - Ok(pc) => pc, - Err(e) => { - error!("failed creating PollContext: {:?}", e); - return; - } - }; + let poll_ctx: PollContext<Token> = match PollContext::new() + .and_then(|pc| pc.add(&inflate_queue_evt, Token::Inflate).and(Ok(pc))) + .and_then(|pc| pc.add(&deflate_queue_evt, Token::Deflate).and(Ok(pc))) + .and_then(|pc| { + pc.add(&self.command_socket, Token::CommandSocket) + .and(Ok(pc)) + }).and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) + { + Ok(pc) => pc, + Err(e) => { + error!("failed creating PollContext: {:?}", e); + return; + } + }; 'poll: loop { let events = match poll_ctx.wait() { @@ -279,10 +279,9 @@ impl VirtioDevice for Balloon { } // This read can't fail as it fits in the declared array so unwrap is fine. let new_actual: u32 = data.read_u32::<LittleEndian>().unwrap(); - self.config.actual_pages.store( - new_actual as usize, - Ordering::Relaxed, - ); + self.config + .actual_pages + .store(new_actual as usize, Ordering::Relaxed); } fn features(&self, page: u32) -> u32 { @@ -311,14 +310,13 @@ impl VirtioDevice for Balloon { return; } - let (self_kill_evt, kill_evt) = - match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { - Ok(v) => v, - Err(e) => { - error!("failed to create kill EventFd pair: {:?}", e); - return; - } - }; + let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { + Ok(v) => v, + Err(e) => { + error!("failed to create kill EventFd pair: {:?}", e); + return; + } + }; self.kill_evt = Some(self_kill_evt); let config = self.config.clone(); @@ -327,13 +325,13 @@ impl VirtioDevice for Balloon { .name("virtio_balloon".to_string()) .spawn(move || { let mut worker = Worker { - mem: mem, + mem, inflate_queue: queues.remove(0), deflate_queue: queues.remove(0), interrupt_status: status, - interrupt_evt: interrupt_evt, - command_socket: command_socket, - config: config, + interrupt_evt, + command_socket, + config, }; worker.run(queue_evts, kill_evt); }); diff --git a/devices/src/virtio/block.rs b/devices/src/virtio/block.rs index 2502171..a6594ec 100644 --- a/devices/src/virtio/block.rs +++ b/devices/src/virtio/block.rs @@ -3,12 +3,12 @@ // found in the LICENSE file. use std::cmp; -use std::io::{self, Seek, SeekFrom, Read, Write}; +use std::io::{self, Read, Seek, SeekFrom, Write}; use std::mem::{size_of, size_of_val}; use std::os::unix::io::{AsRawFd, RawFd}; use std::result; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use std::time::Duration; use std::u32; @@ -22,7 +22,7 @@ use sys_util::{ use data_model::{DataInit, Le16, Le32, Le64}; -use super::{VirtioDevice, Queue, DescriptorChain, INTERRUPT_STATUS_USED_RING, TYPE_BLOCK}; +use super::{DescriptorChain, Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_BLOCK}; const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE]; @@ -137,10 +137,12 @@ enum ParseError { DescriptorLengthTooSmall, } -fn request_type(mem: &GuestMemory, - desc_addr: GuestAddress) - -> result::Result<RequestType, ParseError> { - let type_ = mem.read_obj_from_addr(desc_addr) +fn request_type( + mem: &GuestMemory, + desc_addr: GuestAddress, +) -> result::Result<RequestType, ParseError> { + let type_ = mem + .read_obj_from_addr(desc_addr) .map_err(ParseError::GuestMemory)?; match type_ { VIRTIO_BLK_T_IN => Ok(RequestType::In), @@ -179,18 +181,18 @@ enum ExecuteError { addr: GuestAddress, length: u32, sector: u64, - guestmemerr: GuestMemoryError + guestmemerr: GuestMemoryError, }, Seek { ioerr: io::Error, - sector: u64 + sector: u64, }, TimerFd(SysError), Write { addr: GuestAddress, length: u32, sector: u64, - guestmemerr: GuestMemoryError + guestmemerr: GuestMemoryError, }, DiscardWriteZeroes { ioerr: Option<io::Error>, @@ -208,12 +210,12 @@ impl ExecuteError { fn status(&self) -> u8 { match self { &ExecuteError::Flush(_) => VIRTIO_BLK_S_IOERR, - &ExecuteError::Read{ .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::Seek{ .. } => VIRTIO_BLK_S_IOERR, + &ExecuteError::Read { .. } => VIRTIO_BLK_S_IOERR, + &ExecuteError::Seek { .. } => VIRTIO_BLK_S_IOERR, &ExecuteError::TimerFd(_) => VIRTIO_BLK_S_IOERR, - &ExecuteError::Write{ .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::DiscardWriteZeroes{ .. } => VIRTIO_BLK_S_IOERR, - &ExecuteError::ReadOnly{ .. } => VIRTIO_BLK_S_IOERR, + &ExecuteError::Write { .. } => VIRTIO_BLK_S_IOERR, + &ExecuteError::DiscardWriteZeroes { .. } => VIRTIO_BLK_S_IOERR, + &ExecuteError::ReadOnly { .. } => VIRTIO_BLK_S_IOERR, &ExecuteError::Unsupported(_) => VIRTIO_BLK_S_UNSUPP, } } @@ -229,9 +231,10 @@ struct Request { } impl Request { - fn parse(avail_desc: &DescriptorChain, - mem: &GuestMemory) - -> result::Result<Request, ParseError> { + fn parse( + avail_desc: &DescriptorChain, + mem: &GuestMemory, + ) -> result::Result<Request, ParseError> { // The head contains the request type which MUST be readable. if avail_desc.is_write_only() { return Err(ParseError::UnexpectedWriteOnlyDescriptor); @@ -247,10 +250,10 @@ impl Request { } } - fn parse_flush(avail_desc: &DescriptorChain, - mem: &GuestMemory) - -> result::Result<Request, ParseError> - { + fn parse_flush( + avail_desc: &DescriptorChain, + mem: &GuestMemory, + ) -> result::Result<Request, ParseError> { let sector = sector(&mem, avail_desc.addr)?; let status_desc = avail_desc .next_descriptor() @@ -266,13 +269,13 @@ impl Request { } Ok(Request { - request_type: RequestType::Flush, - sector: sector, - data_addr: GuestAddress(0), - data_len: 0, - status_addr: status_desc.addr, - discard_write_zeroes_seg: None, - }) + request_type: RequestType::Flush, + sector, + data_addr: GuestAddress(0), + data_len: 0, + status_addr: status_desc.addr, + discard_write_zeroes_seg: None, + }) } fn parse_discard_write_zeroes( @@ -319,11 +322,11 @@ impl Request { }) } - fn parse_read_write(avail_desc: &DescriptorChain, - mem: &GuestMemory, - req_type: RequestType) - -> result::Result<Request, ParseError> - { + fn parse_read_write( + avail_desc: &DescriptorChain, + mem: &GuestMemory, + req_type: RequestType, + ) -> result::Result<Request, ParseError> { let sector = sector(&mem, avail_desc.addr)?; let data_desc = avail_desc .next_descriptor() @@ -350,13 +353,13 @@ impl Request { } Ok(Request { - request_type: req_type, - sector: sector, - data_addr: data_desc.addr, - data_len: data_desc.len, - status_addr: status_desc.addr, - discard_write_zeroes_seg: None, - }) + request_type: req_type, + sector, + data_addr: data_desc.addr, + data_len: data_desc.len, + status_addr: status_desc.addr, + discard_write_zeroes_seg: None, + }) } fn execute<T: DiskFile>( @@ -377,14 +380,19 @@ impl Request { } disk.seek(SeekFrom::Start(self.sector << SECTOR_SHIFT)) - .map_err(|e| ExecuteError::Seek{ ioerr: e, sector: self.sector })?; + .map_err(|e| ExecuteError::Seek { + ioerr: e, + sector: self.sector, + })?; match self.request_type { RequestType::In => { mem.read_to_memory(self.data_addr, disk, self.data_len as usize) - .map_err(|e| ExecuteError::Read{ addr: self.data_addr, - length: self.data_len, - sector: self.sector, - guestmemerr: e })?; + .map_err(|e| ExecuteError::Read { + addr: self.data_addr, + length: self.data_len, + sector: self.sector, + guestmemerr: e, + })?; return Ok(self.data_len); } RequestType::Out => { @@ -415,22 +423,22 @@ impl Request { }; if (flags & !valid_flags) != 0 { - return Err(ExecuteError::DiscardWriteZeroes{ - ioerr: None, - sector, - num_sectors, - flags - }); + return Err(ExecuteError::DiscardWriteZeroes { + ioerr: None, + sector, + num_sectors, + flags, + }); } disk.seek(SeekFrom::Start(sector << SECTOR_SHIFT)) - .map_err(|e| ExecuteError::Seek{ ioerr: e, sector })?; + .map_err(|e| ExecuteError::Seek { ioerr: e, sector })?; disk.write_zeroes((num_sectors as usize) << SECTOR_SHIFT) .map_err(|e| ExecuteError::DiscardWriteZeroes { ioerr: Some(e), sector, num_sectors, - flags + flags, })?; } } @@ -530,17 +538,17 @@ impl<T: DiskFile> Worker<T> { }; let mut flush_timer_armed = false; - let poll_ctx: PollContext<Token> = - match PollContext::new() - .and_then(|pc| pc.add(&flush_timer, Token::FlushTimer).and(Ok(pc))) - .and_then(|pc| pc.add(&queue_evt, Token::QueueAvailable).and(Ok(pc))) - .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) { - Ok(pc) => pc, - Err(e) => { - error!("failed creating PollContext: {:?}", e); - return; - } - }; + let poll_ctx: PollContext<Token> = match PollContext::new() + .and_then(|pc| pc.add(&flush_timer, Token::FlushTimer).and(Ok(pc))) + .and_then(|pc| pc.add(&queue_evt, Token::QueueAvailable).and(Ok(pc))) + .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) + { + Ok(pc) => pc, + Err(e) => { + error!("failed creating PollContext: {:?}", e); + return; + } + }; 'poll: loop { let events = match poll_ctx.wait() { @@ -613,10 +621,11 @@ impl<T: DiskFile> Block<T> { pub fn new(mut disk_image: T, read_only: bool) -> SysResult<Block<T>> { let disk_size = disk_image.seek(SeekFrom::End(0))? as u64; if disk_size % SECTOR_SIZE != 0 { - warn!("Disk size {} is not a multiple of sector size {}; \ - the remainder will not be visible to the guest.", - disk_size, - SECTOR_SIZE); + warn!( + "Disk size {} is not a multiple of sector size {}; \ + the remainder will not be visible to the guest.", + disk_size, SECTOR_SIZE + ); } let mut avail_features: u64 = 1 << VIRTIO_BLK_F_FLUSH; @@ -628,12 +637,12 @@ impl<T: DiskFile> Block<T> { } Ok(Block { - kill_evt: None, - disk_image: Some(disk_image), - config_space: build_config_space(disk_size), - avail_features, - read_only, - }) + kill_evt: None, + disk_image: Some(disk_image), + config_space: build_config_space(disk_size), + avail_features, + read_only, + }) } } @@ -687,41 +696,43 @@ impl<T: 'static + AsRawFd + DiskFile + Send> VirtioDevice for Block<T> { } } - fn activate(&mut self, - mem: GuestMemory, - interrupt_evt: EventFd, - status: Arc<AtomicUsize>, - queues: Vec<Queue>, - mut queue_evts: Vec<EventFd>) { + fn activate( + &mut self, + mem: GuestMemory, + interrupt_evt: EventFd, + status: Arc<AtomicUsize>, + queues: Vec<Queue>, + mut queue_evts: Vec<EventFd>, + ) { if queues.len() != 1 || queue_evts.len() != 1 { return; } - let (self_kill_evt, kill_evt) = - match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { - Ok(v) => v, - Err(e) => { - error!("failed creating kill EventFd pair: {:?}", e); - return; - } - }; + let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { + Ok(v) => v, + Err(e) => { + error!("failed creating kill EventFd pair: {:?}", e); + return; + } + }; self.kill_evt = Some(self_kill_evt); let read_only = self.read_only; if let Some(disk_image) = self.disk_image.take() { - let worker_result = thread::Builder::new() - .name("virtio_blk".to_string()) - .spawn(move || { - let mut worker = Worker { - queues: queues, - mem: mem, - disk_image: disk_image, - read_only: read_only, - interrupt_status: status, - interrupt_evt: interrupt_evt, - }; - worker.run(queue_evts.remove(0), kill_evt); - }); + let worker_result = + thread::Builder::new() + .name("virtio_blk".to_string()) + .spawn(move || { + let mut worker = Worker { + queues, + mem, + disk_image, + read_only, + interrupt_status: status, + interrupt_evt, + }; + worker.run(queue_evts.remove(0), kill_evt); + }); if let Err(e) = worker_result { error!("failed to spawn virtio_blk worker: {}", e); diff --git a/devices/src/virtio/gpu/backend.rs b/devices/src/virtio/gpu/backend.rs index 62cceb2..9c27712 100644 --- a/devices/src/virtio/gpu/backend.rs +++ b/devices/src/virtio/gpu/backend.rs @@ -15,12 +15,12 @@ use data_model::*; use sys_util::{GuestAddress, GuestMemory}; -use super::gpu_buffer::{Device, Buffer, Format, Flags}; +use super::gpu_buffer::{Buffer, Device, Flags, Format}; use super::gpu_display::*; -use super::gpu_renderer::{Box3, Renderer, Context as RendererContext, - Image as RendererImage, - Resource as GpuRendererResource, ResourceCreateArgs, - format_fourcc as renderer_fourcc}; +use super::gpu_renderer::{ + format_fourcc as renderer_fourcc, Box3, Context as RendererContext, Image as RendererImage, + Renderer, Resource as GpuRendererResource, ResourceCreateArgs, +}; use super::protocol::GpuResponse; use super::protocol::{VIRTIO_GPU_CAPSET_VIRGL, VIRTIO_GPU_CAPSET_VIRGL2}; @@ -59,13 +59,15 @@ trait VirglResource { /// Copies the given rectangle of pixels from guest memory, using the backing specified from a /// call to `attach_guest_backing`. - fn write_from_guest_memory(&mut self, - x: u32, - y: u32, - width: u32, - height: u32, - src_offset: u64, - mem: &GuestMemory); + fn write_from_guest_memory( + &mut self, + x: u32, + y: u32, + width: u32, + height: u32, + src_offset: u64, + mem: &GuestMemory, + ); /// Reads from the given rectangle of pixels in the resource to the `dst` slice of memory. fn read_to_volatile(&mut self, x: u32, y: u32, width: u32, height: u32, dst: VolatileSlice); @@ -99,53 +101,56 @@ impl VirglResource for GpuRendererResource { Some(self) } - fn write_from_guest_memory(&mut self, - x: u32, - y: u32, - width: u32, - height: u32, - src_offset: u64, - _mem: &GuestMemory) { - let res = self.transfer_write(None, - 0, - 0, - 0, - Box3 { - x, - y, - z: 0, - w: width, - h: height, - d: 0, - }, - src_offset); + fn write_from_guest_memory( + &mut self, + x: u32, + y: u32, + width: u32, + height: u32, + src_offset: u64, + _mem: &GuestMemory, + ) { + let res = self.transfer_write( + None, + 0, + 0, + 0, + Box3 { + x, + y, + z: 0, + w: width, + h: height, + d: 0, + }, + src_offset, + ); if let Err(e) = res { - error!("failed to write to resource (x={} y={} w={} h={}, src_offset={}): {}", - x, - y, - width, - height, - src_offset, - e); + error!( + "failed to write to resource (x={} y={} w={} h={}, src_offset={}): {}", + x, y, width, height, src_offset, e + ); } } fn read_to_volatile(&mut self, x: u32, y: u32, width: u32, height: u32, dst: VolatileSlice) { - let res = GpuRendererResource::read_to_volatile(self, - None, - 0, - 0, - 0, - Box3 { - x, - y, - z: 0, - w: width, - h: height, - d: 0, - }, - 0, - dst); + let res = GpuRendererResource::read_to_volatile( + self, + None, + 0, + 0, + 0, + Box3 { + x, + y, + z: 0, + w: width, + h: height, + d: 0, + }, + 0, + dst, + ); if let Err(e) = res { error!("failed to read from resource: {}", e); } @@ -162,9 +167,11 @@ struct BackedBuffer { } impl BackedBuffer { - fn new_renderer_registered(buffer: Buffer, - gpu_renderer_resource: GpuRendererResource, - image: RendererImage) -> BackedBuffer { + fn new_renderer_registered( + buffer: Buffer, + gpu_renderer_resource: GpuRendererResource, + image: RendererImage, + ) -> BackedBuffer { BackedBuffer { display_import: None, backing: Vec::new(), @@ -226,15 +233,15 @@ impl VirglResource for BackedBuffer { } }; - match display - .borrow_mut() - .import_dmabuf(dmabuf.as_raw_fd(), - 0, /* offset */ - self.buffer.stride(), - self.buffer.format_modifier(), - self.buffer.width(), - self.buffer.height(), - self.buffer.format().into()) { + match display.borrow_mut().import_dmabuf( + dmabuf.as_raw_fd(), + 0, /* offset */ + self.buffer.stride(), + self.buffer.format_modifier(), + self.buffer.width(), + self.buffer.height(), + self.buffer.format().into(), + ) { Ok(import_id) => { self.display_import = Some((display.clone(), import_id)); Some(import_id) @@ -246,29 +253,33 @@ impl VirglResource for BackedBuffer { } } - fn write_from_guest_memory(&mut self, - x: u32, - y: u32, - width: u32, - height: u32, - src_offset: u64, - mem: &GuestMemory) { + fn write_from_guest_memory( + &mut self, + x: u32, + y: u32, + width: u32, + height: u32, + src_offset: u64, + mem: &GuestMemory, + ) { if src_offset >= usize::MAX as u64 { - error!("failed to write to resource with given offset: {}", src_offset); - return - } - let res = self.buffer - .write_from_sg(x, - y, - width, - height, - 0, // plane - src_offset as usize, - self.backing - .iter() - .map(|&(addr, len)| { - mem.get_slice(addr.offset(), len as u64).unwrap_or_default() - })); + error!( + "failed to write to resource with given offset: {}", + src_offset + ); + return; + } + let res = self.buffer.write_from_sg( + x, + y, + width, + height, + 0, // plane + src_offset as usize, + self.backing + .iter() + .map(|&(addr, len)| mem.get_slice(addr.offset(), len as u64).unwrap_or_default()), + ); if let Err(e) = res { error!("failed to write to resource from guest memory: {:?}", e) } @@ -336,22 +347,24 @@ impl Backend { } /// Creates a 2D resource with the given properties and associated it with the given id. - pub fn create_resource_2d(&mut self, - id: u32, - width: u32, - height: u32, - fourcc: u32) - -> GpuResponse { + pub fn create_resource_2d( + &mut self, + id: u32, + width: u32, + height: u32, + fourcc: u32, + ) -> GpuResponse { if id == 0 { return GpuResponse::ErrInvalidResourceId; } match self.resources.entry(id) { Entry::Vacant(slot) => { - let res = self.device - .create_buffer(width, - height, - Format::from(fourcc), - Flags::empty().use_scanout(true).use_linear(true)); + let res = self.device.create_buffer( + width, + height, + Format::from(fourcc), + Flags::empty().use_scanout(true).use_linear(true), + ); match res { Ok(res) => { slot.insert(Box::from(BackedBuffer::from(res))); @@ -403,14 +416,15 @@ impl Backend { } } - fn flush_resource_to_surface(&mut self, - resource_id: u32, - surface_id: u32, - x: u32, - y: u32, - width: u32, - height: u32) - -> GpuResponse { + fn flush_resource_to_surface( + &mut self, + resource_id: u32, + surface_id: u32, + x: u32, + y: u32, + width: u32, + height: u32, + ) -> GpuResponse { let resource = match self.resources.get_mut(&resource_id) { Some(r) => r, None => return GpuResponse::ErrInvalidResourceId, @@ -442,13 +456,14 @@ impl Backend { } /// Flushes the given rectangle of pixels of the given resource to the display. - pub fn flush_resource(&mut self, - id: u32, - x: u32, - y: u32, - width: u32, - height: u32) - -> GpuResponse { + pub fn flush_resource( + &mut self, + id: u32, + x: u32, + y: u32, + width: u32, + height: u32, + ) -> GpuResponse { if id == 0 { return GpuResponse::OkNoData; } @@ -476,15 +491,16 @@ impl Backend { /// Copes the given rectangle of pixels of the given resource's backing memory to the host side /// resource. - pub fn transfer_to_resource_2d(&mut self, - id: u32, - x: u32, - y: u32, - width: u32, - height: u32, - src_offset: u64, - mem: &GuestMemory) - -> GpuResponse { + pub fn transfer_to_resource_2d( + &mut self, + id: u32, + x: u32, + y: u32, + width: u32, + height: u32, + src_offset: u64, + mem: &GuestMemory, + ) -> GpuResponse { match self.resources.get_mut(&id) { Some(res) => { res.write_from_guest_memory(x, y, width, height, src_offset, mem); @@ -496,11 +512,12 @@ impl Backend { /// Attaches backing memory to the given resource, represented by a `Vec` of `(address, size)` /// tuples in the guest's physical address space. - pub fn attach_backing(&mut self, - id: u32, - mem: &GuestMemory, - vecs: Vec<(GuestAddress, usize)>) - -> GpuResponse { + pub fn attach_backing( + &mut self, + id: u32, + mem: &GuestMemory, + vecs: Vec<(GuestAddress, usize)>, + ) -> GpuResponse { match self.resources.get_mut(&id) { Some(resource) => { resource.attach_guest_backing(mem, vecs); @@ -532,11 +549,11 @@ impl Backend { } else if let Some(resource) = self.resources.get_mut(&id) { self.cursor_resource = id; if self.cursor_surface.is_none() { - match self.display - .borrow_mut() - .create_surface(self.scanout_surface, - resource.width(), - resource.height()) { + match self.display.borrow_mut().create_surface( + self.scanout_surface, + resource.width(), + resource.height(), + ) { Ok(surface) => self.cursor_surface = Some(surface), Err(e) => { error!("failed to create cursor surface: {:?}", e); @@ -546,30 +563,21 @@ impl Backend { } let cursor_surface = self.cursor_surface.unwrap(); - self.display - .borrow_mut() - .set_position(cursor_surface, x, y); + self.display.borrow_mut().set_position(cursor_surface, x, y); // Gets the resource's pixels into the display by importing the buffer. if let Some(import_id) = resource.import_to_display(&self.display) { - self.display - .borrow_mut() - .flip_to(cursor_surface, import_id); + self.display.borrow_mut().flip_to(cursor_surface, import_id); return GpuResponse::OkNoData; } // Importing failed, so try copying the pixels into the surface's slower shared memory // framebuffer. if let Some(buffer) = resource.buffer() { - if let Some(fb) = self.display - .borrow_mut() - .framebuffer_memory(cursor_surface) { - if let Err(e) = buffer.read_to_volatile(0, - 0, - buffer.width(), - buffer.height(), - 0, - fb) { + if let Some(fb) = self.display.borrow_mut().framebuffer_memory(cursor_surface) { + if let Err(e) = + buffer.read_to_volatile(0, 0, buffer.width(), buffer.height(), 0, fb) + { error!("failed to copy resource to cursor: {:?}", e); return GpuResponse::ErrInvalidParameter; } @@ -617,18 +625,16 @@ impl Backend { } match self.contexts.entry(id) { Entry::Occupied(_) => GpuResponse::ErrInvalidContextId, - Entry::Vacant(slot) => { - match self.renderer.create_context(id) { - Ok(ctx) => { - slot.insert(ctx); - GpuResponse::OkNoData - } - Err(e) => { - error!("failed to create renderer ctx: {}", e); - GpuResponse::ErrUnspec - } + Entry::Vacant(slot) => match self.renderer.create_context(id) { + Ok(ctx) => { + slot.insert(ctx); + GpuResponse::OkNoData } - } + Err(e) => { + error!("failed to create renderer ctx: {}", e); + GpuResponse::ErrUnspec + } + }, } } @@ -642,10 +648,12 @@ impl Backend { /// Attaches the indicated resource to the given context. pub fn context_attach_resource(&mut self, ctx_id: u32, res_id: u32) -> GpuResponse { - match (self.contexts.get_mut(&ctx_id), - self.resources - .get_mut(&res_id) - .and_then(|res| res.gpu_renderer_resource())) { + match ( + self.contexts.get_mut(&ctx_id), + self.resources + .get_mut(&res_id) + .and_then(|res| res.gpu_renderer_resource()), + ) { (Some(ctx), Some(res)) => { ctx.attach(res); GpuResponse::OkNoData @@ -657,10 +665,12 @@ impl Backend { /// detaches the indicated resource to the given context. pub fn context_detach_resource(&mut self, ctx_id: u32, res_id: u32) -> GpuResponse { - match (self.contexts.get_mut(&ctx_id), - self.resources - .get_mut(&res_id) - .and_then(|res| res.gpu_renderer_resource())) { + match ( + self.contexts.get_mut(&ctx_id), + self.resources + .get_mut(&res_id) + .and_then(|res| res.gpu_renderer_resource()), + ) { (Some(ctx), Some(res)) => { ctx.detach(res); GpuResponse::OkNoData @@ -671,10 +681,7 @@ impl Backend { } pub fn validate_args_as_fourcc(args: ResourceCreateArgs) -> Option<u32> { - if args.depth == 1 && - args.array_size == 1 && - args.last_level == 0 && - args.nr_samples == 0 { + if args.depth == 1 && args.array_size == 1 && args.last_level == 0 && args.nr_samples == 0 { renderer_fourcc(args.format) } else { None @@ -682,19 +689,20 @@ impl Backend { } /// Creates a 3D resource with the given properties and associated it with the given id. - pub fn resource_create_3d(&mut self, - id: u32, - target: u32, - format: u32, - bind: u32, - width: u32, - height: u32, - depth: u32, - array_size: u32, - last_level: u32, - nr_samples: u32, - flags: u32) - -> GpuResponse { + pub fn resource_create_3d( + &mut self, + id: u32, + target: u32, + format: u32, + bind: u32, + width: u32, + height: u32, + depth: u32, + array_size: u32, + last_level: u32, + nr_samples: u32, + flags: u32, + ) -> GpuResponse { if id == 0 { return GpuResponse::ErrInvalidResourceId; } @@ -715,192 +723,173 @@ impl Backend { match self.resources.entry(id) { Entry::Occupied(_) => GpuResponse::ErrInvalidResourceId, - Entry::Vacant(slot) => { - match Backend::validate_args_as_fourcc(create_args) { - Some(fourcc) => { - let buffer = match self.device - .create_buffer(width, - height, - Format::from(fourcc), - Flags::empty().use_scanout(true).use_linear(true)) { - Ok(buffer) => buffer, - Err(e) => { - error!("failed to create buffer for 3d resource {}: {}", format, e); - return GpuResponse::ErrUnspec; - } - }; - - let dma_buf_fd = match buffer.export_plane_fd(0) { - Ok(dma_buf_fd) => dma_buf_fd, - Err(e) => { - error!("failed to export plane fd: {}", e); - return GpuResponse::ErrUnspec - } - }; - - let image = match self.renderer - .image_from_dmabuf(fourcc, - width, - height, - dma_buf_fd.as_raw_fd(), - buffer.plane_offset(0), - buffer.plane_stride(0)) { - Ok(image) => image, - Err(e) => { - error!("failed to create egl image: {}", e); - return GpuResponse::ErrUnspec - } - }; - - let res = self.renderer - .import_resource(create_args, &image); - match res { - Ok(res) => { - let mut backed = - BackedBuffer::new_renderer_registered(buffer, - res, - image); - slot.insert(Box::new(backed)); - GpuResponse::OkNoData - } - Err(e) => { - error!("failed to import renderer resource: {}", - e); - GpuResponse::ErrUnspec - } + Entry::Vacant(slot) => match Backend::validate_args_as_fourcc(create_args) { + Some(fourcc) => { + let buffer = match self.device.create_buffer( + width, + height, + Format::from(fourcc), + Flags::empty().use_scanout(true).use_linear(true), + ) { + Ok(buffer) => buffer, + Err(e) => { + error!("failed to create buffer for 3d resource {}: {}", format, e); + return GpuResponse::ErrUnspec; + } + }; + + let dma_buf_fd = match buffer.export_plane_fd(0) { + Ok(dma_buf_fd) => dma_buf_fd, + Err(e) => { + error!("failed to export plane fd: {}", e); + return GpuResponse::ErrUnspec; + } + }; + + let image = match self.renderer.image_from_dmabuf( + fourcc, + width, + height, + dma_buf_fd.as_raw_fd(), + buffer.plane_offset(0), + buffer.plane_stride(0), + ) { + Ok(image) => image, + Err(e) => { + error!("failed to create egl image: {}", e); + return GpuResponse::ErrUnspec; } - }, - None => { - let res = self.renderer.create_resource(create_args); - match res { - Ok(res) => { - slot.insert(Box::new(res)); - GpuResponse::OkNoData - } - Err(e) => { - error!("failed to create renderer resource: {}", - e); - GpuResponse::ErrUnspec - } + }; + + let res = self.renderer.import_resource(create_args, &image); + match res { + Ok(res) => { + let mut backed = + BackedBuffer::new_renderer_registered(buffer, res, image); + slot.insert(Box::new(backed)); + GpuResponse::OkNoData + } + Err(e) => { + error!("failed to import renderer resource: {}", e); + GpuResponse::ErrUnspec } } } - } + None => { + let res = self.renderer.create_resource(create_args); + match res { + Ok(res) => { + slot.insert(Box::new(res)); + GpuResponse::OkNoData + } + Err(e) => { + error!("failed to create renderer resource: {}", e); + GpuResponse::ErrUnspec + } + } + } + }, } } /// Copes the given 3D rectangle of pixels of the given resource's backing memory to the host /// side resource. - pub fn transfer_to_resource_3d(&mut self, - ctx_id: u32, - res_id: u32, - x: u32, - y: u32, - z: u32, - width: u32, - height: u32, - depth: u32, - level: u32, - stride: u32, - layer_stride: u32, - offset: u64) - -> GpuResponse { + pub fn transfer_to_resource_3d( + &mut self, + ctx_id: u32, + res_id: u32, + x: u32, + y: u32, + z: u32, + width: u32, + height: u32, + depth: u32, + level: u32, + stride: u32, + layer_stride: u32, + offset: u64, + ) -> GpuResponse { let ctx = match ctx_id { 0 => None, - id => { - match self.contexts.get(&id) { - None => return GpuResponse::ErrInvalidContextId, - ctx => ctx, - } - } + id => match self.contexts.get(&id) { + None => return GpuResponse::ErrInvalidContextId, + ctx => ctx, + }, }; match self.resources.get_mut(&res_id) { - Some(res) => { - match res.gpu_renderer_resource() { - Some(res) => { - let transfer_box = Box3 { - x, - y, - z, - w: width, - h: height, - d: depth, - }; - let res = res.transfer_write(ctx, - level, - stride, - layer_stride, - transfer_box, - offset); - match res { - Ok(_) => GpuResponse::OkNoData, - Err(e) => { - error!("failed to transfer to host: {}", e); - GpuResponse::ErrUnspec - } + Some(res) => match res.gpu_renderer_resource() { + Some(res) => { + let transfer_box = Box3 { + x, + y, + z, + w: width, + h: height, + d: depth, + }; + let res = + res.transfer_write(ctx, level, stride, layer_stride, transfer_box, offset); + match res { + Ok(_) => GpuResponse::OkNoData, + Err(e) => { + error!("failed to transfer to host: {}", e); + GpuResponse::ErrUnspec } } - None => GpuResponse::ErrInvalidResourceId, } - } + None => GpuResponse::ErrInvalidResourceId, + }, None => GpuResponse::ErrInvalidResourceId, } } /// Copes the given rectangle of pixels from the resource to the given resource's backing /// memory. - pub fn transfer_from_resource_3d(&mut self, - ctx_id: u32, - res_id: u32, - x: u32, - y: u32, - z: u32, - width: u32, - height: u32, - depth: u32, - level: u32, - stride: u32, - layer_stride: u32, - offset: u64) - -> GpuResponse { + pub fn transfer_from_resource_3d( + &mut self, + ctx_id: u32, + res_id: u32, + x: u32, + y: u32, + z: u32, + width: u32, + height: u32, + depth: u32, + level: u32, + stride: u32, + layer_stride: u32, + offset: u64, + ) -> GpuResponse { let ctx = match ctx_id { 0 => None, - id => { - match self.contexts.get(&id) { - None => return GpuResponse::ErrInvalidContextId, - ctx => ctx, - } - } + id => match self.contexts.get(&id) { + None => return GpuResponse::ErrInvalidContextId, + ctx => ctx, + }, }; match self.resources.get_mut(&res_id) { - Some(res) => { - match res.gpu_renderer_resource() { - Some(res) => { - let transfer_box = Box3 { - x, - y, - z, - w: width, - h: height, - d: depth, - }; - let res = res.transfer_read(ctx, - level, - stride, - layer_stride, - transfer_box, - offset); - match res { - Ok(_) => GpuResponse::OkNoData, - Err(e) => { - error!("failed to transfer from host: {}", e); - GpuResponse::ErrUnspec - } + Some(res) => match res.gpu_renderer_resource() { + Some(res) => { + let transfer_box = Box3 { + x, + y, + z, + w: width, + h: height, + d: depth, + }; + let res = + res.transfer_read(ctx, level, stride, layer_stride, transfer_box, offset); + match res { + Ok(_) => GpuResponse::OkNoData, + Err(e) => { + error!("failed to transfer from host: {}", e); + GpuResponse::ErrUnspec } } - None => GpuResponse::ErrInvalidResourceId, } - } + None => GpuResponse::ErrInvalidResourceId, + }, None => GpuResponse::ErrInvalidResourceId, } } @@ -908,15 +897,13 @@ impl Backend { /// Submits a command buffer to the given rendering context. pub fn submit_command(&mut self, ctx_id: u32, commands: &mut [u8]) -> GpuResponse { match self.contexts.get_mut(&ctx_id) { - Some(ctx) => { - match ctx.submit(&mut commands[..]) { - Ok(_) => GpuResponse::OkNoData, - Err(e) => { - error!("failed to submit command buffer: {}", e); - GpuResponse::ErrUnspec - } + Some(ctx) => match ctx.submit(&mut commands[..]) { + Ok(_) => GpuResponse::OkNoData, + Err(e) => { + error!("failed to submit command buffer: {}", e); + GpuResponse::ErrUnspec } - } + }, None => GpuResponse::ErrInvalidContextId, } } diff --git a/devices/src/virtio/gpu/mod.rs b/devices/src/virtio/gpu/mod.rs index 0b6f05e..ec60634 100644 --- a/devices/src/virtio/gpu/mod.rs +++ b/devices/src/virtio/gpu/mod.rs @@ -6,8 +6,8 @@ extern crate gpu_buffer; extern crate gpu_display; extern crate gpu_renderer; -mod protocol; mod backend; +mod protocol; use std::cell::RefCell; use std::collections::VecDeque; @@ -16,24 +16,25 @@ use std::mem::size_of; use std::os::unix::io::{AsRawFd, RawFd}; use std::path::{Path, PathBuf}; use std::rc::Rc; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread::spawn; use std::time::Duration; use data_model::*; -use sys_util::{EventFd, PollContext, PollToken, GuestAddress, GuestMemory}; +use sys_util::{EventFd, GuestAddress, GuestMemory, PollContext, PollToken}; use self::gpu_buffer::Device; use self::gpu_display::*; -use self::gpu_renderer::{Renderer, format_fourcc}; +use self::gpu_renderer::{format_fourcc, Renderer}; -use super::{VirtioDevice, Queue, AvailIter, VIRTIO_F_VERSION_1, INTERRUPT_STATUS_USED_RING, - TYPE_GPU}; +use super::{ + AvailIter, Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_GPU, VIRTIO_F_VERSION_1, +}; -use self::protocol::*; use self::backend::Backend; +use self::protocol::*; // First queue is for virtio gpu commands. Second queue is for cursor commands, which we expect // there to be fewer of. @@ -88,11 +89,12 @@ impl Frontend { self.backend.process_display() } - fn process_gpu_command(&mut self, - mem: &GuestMemory, - cmd: GpuCommand, - data: Option<VolatileSlice>) - -> GpuResponse { + fn process_gpu_command( + &mut self, + mem: &GuestMemory, + cmd: GpuCommand, + data: Option<VolatileSlice>, + ) -> GpuResponse { self.backend.force_ctx_0(); match cmd { @@ -102,50 +104,49 @@ impl Frontend { GpuCommand::ResourceCreate2d(info) => { let format = info.format.to_native(); match format_fourcc(format) { - Some(fourcc) => { - self.backend - .create_resource_2d(info.resource_id.to_native(), - info.width.to_native(), - info.height.to_native(), - fourcc) - } + Some(fourcc) => self.backend.create_resource_2d( + info.resource_id.to_native(), + info.width.to_native(), + info.height.to_native(), + fourcc, + ), None => { - warn!("failed to create resource with unrecognized pipe format {}", - format); + warn!( + "failed to create resource with unrecognized pipe format {}", + format + ); GpuResponse::ErrInvalidParameter } } - } GpuCommand::ResourceUnref(info) => { self.backend.unref_resource(info.resource_id.to_native()) } GpuCommand::SetScanout(info) => self.backend.set_scanout(info.resource_id.to_native()), - GpuCommand::ResourceFlush(info) => { - self.backend - .flush_resource(info.resource_id.to_native(), - info.r.x.to_native(), - info.r.y.to_native(), - info.r.width.to_native(), - info.r.height.to_native()) - } - GpuCommand::TransferToHost2d(info) => { - self.backend - .transfer_to_resource_2d(info.resource_id.to_native(), - info.r.x.to_native(), - info.r.y.to_native(), - info.r.width.to_native(), - info.r.height.to_native(), - info.offset.to_native(), - mem) - } + GpuCommand::ResourceFlush(info) => self.backend.flush_resource( + info.resource_id.to_native(), + info.r.x.to_native(), + info.r.y.to_native(), + info.r.width.to_native(), + info.r.height.to_native(), + ), + GpuCommand::TransferToHost2d(info) => self.backend.transfer_to_resource_2d( + info.resource_id.to_native(), + info.r.x.to_native(), + info.r.y.to_native(), + info.r.width.to_native(), + info.r.height.to_native(), + info.offset.to_native(), + mem, + ), GpuCommand::ResourceAttachBacking(info) if data.is_some() => { let data = data.unwrap(); let entry_count = info.nr_entries.to_native() as usize; let mut iovecs = Vec::with_capacity(entry_count); for i in 0..entry_count { - if let Ok(entry_ref) = data.get_ref((i * size_of::<virtio_gpu_mem_entry>()) as - u64) { + if let Ok(entry_ref) = + data.get_ref((i * size_of::<virtio_gpu_mem_entry>()) as u64) + { let entry: virtio_gpu_mem_entry = entry_ref.load(); let addr = GuestAddress(entry.addr.to_native()); let len = entry.length.to_native() as usize; @@ -160,42 +161,32 @@ impl Frontend { GpuCommand::ResourceDetachBacking(info) => { self.backend.detach_backing(info.resource_id.to_native()) } - GpuCommand::UpdateCursor(info) => { - self.backend - .update_cursor(info.resource_id.to_native(), - info.pos.x.into(), - info.pos.y.into()) - } - GpuCommand::MoveCursor(info) => { - self.backend - .move_cursor(info.pos.x.into(), info.pos.y.into()) - } + GpuCommand::UpdateCursor(info) => self.backend.update_cursor( + info.resource_id.to_native(), + info.pos.x.into(), + info.pos.y.into(), + ), + GpuCommand::MoveCursor(info) => self + .backend + .move_cursor(info.pos.x.into(), info.pos.y.into()), GpuCommand::GetCapsetInfo(info) => { - self.backend - .get_capset_info(info.capset_index.to_native()) - } - GpuCommand::GetCapset(info) => { - self.backend - .get_capset(info.capset_id.to_native(), info.capset_version.to_native()) - } - GpuCommand::CtxCreate(info) => { - self.backend - .create_renderer_context(info.hdr.ctx_id.to_native()) - } - GpuCommand::CtxDestroy(info) => { - self.backend - .destroy_renderer_context(info.hdr.ctx_id.to_native()) - } - GpuCommand::CtxAttachResource(info) => { - self.backend - .context_attach_resource(info.hdr.ctx_id.to_native(), - info.resource_id.to_native()) - } - GpuCommand::CtxDetachResource(info) => { - self.backend - .context_detach_resource(info.hdr.ctx_id.to_native(), - info.resource_id.to_native()) + self.backend.get_capset_info(info.capset_index.to_native()) } + GpuCommand::GetCapset(info) => self + .backend + .get_capset(info.capset_id.to_native(), info.capset_version.to_native()), + GpuCommand::CtxCreate(info) => self + .backend + .create_renderer_context(info.hdr.ctx_id.to_native()), + GpuCommand::CtxDestroy(info) => self + .backend + .destroy_renderer_context(info.hdr.ctx_id.to_native()), + GpuCommand::CtxAttachResource(info) => self + .backend + .context_attach_resource(info.hdr.ctx_id.to_native(), info.resource_id.to_native()), + GpuCommand::CtxDetachResource(info) => self + .backend + .context_detach_resource(info.hdr.ctx_id.to_native(), info.resource_id.to_native()), GpuCommand::ResourceCreate3d(info) => { let id = info.resource_id.to_native(); let target = info.target.to_native(); @@ -208,18 +199,10 @@ impl Frontend { let last_level = info.last_level.to_native(); let nr_samples = info.nr_samples.to_native(); let flags = info.flags.to_native(); - self.backend - .resource_create_3d(id, - target, - format, - bind, - width, - height, - depth, - array_size, - last_level, - nr_samples, - flags) + self.backend.resource_create_3d( + id, target, format, bind, width, height, depth, array_size, last_level, + nr_samples, flags, + ) } GpuCommand::TransferToHost3d(info) => { let ctx_id = info.hdr.ctx_id.to_native(); @@ -234,20 +217,20 @@ impl Frontend { let stride = info.stride.to_native(); let layer_stride = info.layer_stride.to_native(); let offset = info.offset.to_native(); - self.backend - .transfer_to_resource_3d(ctx_id, - res_id, - x, - y, - z, - width, - height, - depth, - level, - stride, - layer_stride, - offset) - + self.backend.transfer_to_resource_3d( + ctx_id, + res_id, + x, + y, + z, + width, + height, + depth, + level, + stride, + layer_stride, + offset, + ) } GpuCommand::TransferFromHost3d(info) => { let ctx_id = info.hdr.ctx_id.to_native(); @@ -262,19 +245,20 @@ impl Frontend { let stride = info.stride.to_native(); let layer_stride = info.layer_stride.to_native(); let offset = info.offset.to_native(); - self.backend - .transfer_from_resource_3d(ctx_id, - res_id, - x, - y, - z, - width, - height, - depth, - level, - stride, - layer_stride, - offset) + self.backend.transfer_from_resource_3d( + ctx_id, + res_id, + x, + y, + z, + width, + height, + depth, + level, + stride, + layer_stride, + offset, + ) } GpuCommand::CmdSubmit3d(info) if data.is_some() => { let data = data.unwrap(); // guarded by this match arm @@ -296,10 +280,12 @@ impl Frontend { } } - fn take_descriptors(mem: &GuestMemory, - desc_iter: AvailIter, - descriptors: &mut VecDeque<QueueDescriptor>, - return_descriptors: &mut VecDeque<ReturnDescriptor>) { + fn take_descriptors( + mem: &GuestMemory, + desc_iter: AvailIter, + descriptors: &mut VecDeque<QueueDescriptor>, + return_descriptors: &mut VecDeque<ReturnDescriptor>, + ) { for desc in desc_iter { if desc.len as usize >= size_of::<virtio_gpu_ctrl_hdr>() && !desc.is_write_only() { let mut q_desc = QueueDescriptor { @@ -323,38 +309,45 @@ impl Frontend { } descriptors.push_back(q_desc); } else { - let likely_type = mem.read_obj_from_addr(desc.addr) - .unwrap_or(Le32::from(0)); - debug!("ctrl queue bad descriptor index = {} len = {} write = {} type = {}", - desc.index, - desc.len, - desc.is_write_only(), - virtio_gpu_cmd_str(likely_type.to_native())); + let likely_type = mem.read_obj_from_addr(desc.addr).unwrap_or(Le32::from(0)); + debug!( + "ctrl queue bad descriptor index = {} len = {} write = {} type = {}", + desc.index, + desc.len, + desc.is_write_only(), + virtio_gpu_cmd_str(likely_type.to_native()) + ); return_descriptors.push_back(ReturnDescriptor { - index: desc.index, - len: 0, - }); + index: desc.index, + len: 0, + }); } } } fn take_ctrl_descriptors(&mut self, mem: &GuestMemory, desc_iter: AvailIter) { - Frontend::take_descriptors(mem, - desc_iter, - &mut self.ctrl_descriptors, - &mut self.return_ctrl_descriptors); + Frontend::take_descriptors( + mem, + desc_iter, + &mut self.ctrl_descriptors, + &mut self.return_ctrl_descriptors, + ); } fn take_cursor_descriptors(&mut self, mem: &GuestMemory, desc_iter: AvailIter) { - Frontend::take_descriptors(mem, - desc_iter, - &mut self.cursor_descriptors, - &mut self.return_cursor_descriptors); + Frontend::take_descriptors( + mem, + desc_iter, + &mut self.cursor_descriptors, + &mut self.return_cursor_descriptors, + ); } - fn process_descriptor(&mut self, - mem: &GuestMemory, - desc: QueueDescriptor) -> Option<ReturnDescriptor> { + fn process_descriptor( + &mut self, + mem: &GuestMemory, + desc: QueueDescriptor, + ) -> Option<ReturnDescriptor> { let mut resp = GpuResponse::ErrUnspec; let mut gpu_cmd = None; let mut len = 0; @@ -392,17 +385,14 @@ impl Frontend { ctx_id = ctrl_hdr.ctx_id.to_native(); flags = VIRTIO_GPU_FLAG_FENCE; - let fence_resp = self.backend - .create_fence(ctx_id, fence_id as u32); + let fence_resp = self.backend.create_fence(ctx_id, fence_id as u32); if fence_resp.is_err() { - warn!("create_fence {} -> {:?}", - fence_id, fence_resp); + warn!("create_fence {} -> {:?}", fence_id, fence_resp); resp = fence_resp; } } } - // Prepare the response now, even if it is going to wait until // fence is complete. match resp.encode(flags, fence_id, ctx_id, ret_desc_mem) { @@ -417,7 +407,7 @@ impl Frontend { desc, }); - return None + return None; } // No fence, respond now. @@ -430,23 +420,19 @@ impl Frontend { } fn process_ctrl(&mut self, mem: &GuestMemory) -> Option<ReturnDescriptor> { - self.return_ctrl_descriptors - .pop_front() - .or_else(|| { - self.ctrl_descriptors - .pop_front() - .and_then(|desc| self.process_descriptor(mem, desc)) - }) + self.return_ctrl_descriptors.pop_front().or_else(|| { + self.ctrl_descriptors + .pop_front() + .and_then(|desc| self.process_descriptor(mem, desc)) + }) } fn process_cursor(&mut self, mem: &GuestMemory) -> Option<ReturnDescriptor> { - self.return_cursor_descriptors - .pop_front() - .or_else(|| { - self.cursor_descriptors - .pop_front() - .and_then(|desc| self.process_descriptor(mem, desc)) - }) + self.return_cursor_descriptors.pop_front().or_else(|| { + self.cursor_descriptors + .pop_front() + .and_then(|desc| self.process_descriptor(mem, desc)) + }) } fn fence_poll(&mut self) { @@ -457,9 +443,9 @@ impl Frontend { true } else { return_descs.push_back(ReturnDescriptor { - index: f_desc.desc.index, - len: f_desc.len - }); + index: f_desc.desc.index, + len: f_desc.len, + }); false } }) @@ -486,7 +472,6 @@ impl Worker { let _ = self.interrupt_evt.write(1); } - fn run(&mut self) { #[derive(PollToken)] enum Token { @@ -496,23 +481,20 @@ impl Worker { Kill, } - let poll_ctx: PollContext<Token> = - match PollContext::new() - .and_then(|pc| pc.add(&self.ctrl_evt, Token::CtrlQueue).and(Ok(pc))) - .and_then(|pc| { - pc.add(&self.cursor_evt, Token::CursorQueue).and(Ok(pc)) - }) - .and_then(|pc| { - pc.add(&*self.state.display().borrow(), Token::Display) - .and(Ok(pc)) - }) - .and_then(|pc| pc.add(&self.kill_evt, Token::Kill).and(Ok(pc))) { - Ok(pc) => pc, - Err(e) => { - error!("failed creating PollContext: {:?}", e); - return; - } - }; + let poll_ctx: PollContext<Token> = match PollContext::new() + .and_then(|pc| pc.add(&self.ctrl_evt, Token::CtrlQueue).and(Ok(pc))) + .and_then(|pc| pc.add(&self.cursor_evt, Token::CursorQueue).and(Ok(pc))) + .and_then(|pc| { + pc.add(&*self.state.display().borrow(), Token::Display) + .and(Ok(pc)) + }).and_then(|pc| pc.add(&self.kill_evt, Token::Kill).and(Ok(pc))) + { + Ok(pc) => pc, + Err(e) => { + error!("failed creating PollContext: {:?}", e); + return; + } + }; 'poll: loop { // If there are outstanding fences, wake up early to poll them. @@ -653,7 +635,6 @@ impl VirtioDevice for Gpu { let _ = value; } - fn read_config(&self, offset: u64, data: &mut [u8]) { let offset = offset as usize; let len = data.len(); @@ -679,12 +660,14 @@ impl VirtioDevice for Gpu { } } - fn activate(&mut self, - mem: GuestMemory, - interrupt_evt: EventFd, - interrupt_status: Arc<AtomicUsize>, - mut queues: Vec<Queue>, - mut queue_evts: Vec<EventFd>) { + fn activate( + &mut self, + mem: GuestMemory, + interrupt_evt: EventFd, + interrupt_status: Arc<AtomicUsize>, + mut queues: Vec<Queue>, + mut queue_evts: Vec<EventFd>, + ) { if queues.len() != QUEUE_SIZES.len() || queue_evts.len() != QUEUE_SIZES.len() { return; } @@ -697,14 +680,13 @@ impl VirtioDevice for Gpu { } }; - let (self_kill_evt, kill_evt) = - match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { - Ok(v) => v, - Err(e) => { - error!("error creating kill EventFd pair: {:?}", e); - return; - } - }; + let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { + Ok(v) => v, + Err(e) => { + error!("error creating kill EventFd pair: {:?}", e); + return; + } + }; self.kill_evt = Some(self_kill_evt); let ctrl_queue = queues.remove(0); @@ -726,7 +708,7 @@ impl VirtioDevice for Gpu { Ok(d) => d, Err(()) => { error!("failed to open device"); - return + return; } }; @@ -747,18 +729,17 @@ impl VirtioDevice for Gpu { }; Worker { - exit_evt, - mem, - interrupt_evt, - interrupt_status, - ctrl_queue, - ctrl_evt, - cursor_queue, - cursor_evt, - kill_evt, - state: Frontend::new(Backend::new(device, display, renderer)), - } - .run() + exit_evt, + mem, + interrupt_evt, + interrupt_status, + ctrl_queue, + ctrl_evt, + cursor_queue, + cursor_evt, + kill_evt, + state: Frontend::new(Backend::new(device, display, renderer)), + }.run() }); } } diff --git a/devices/src/virtio/gpu/protocol.rs b/devices/src/virtio/gpu/protocol.rs index 1c9b1c3..2001cd7 100644 --- a/devices/src/virtio/gpu/protocol.rs +++ b/devices/src/virtio/gpu/protocol.rs @@ -7,7 +7,7 @@ use std::marker::PhantomData; use std::mem::{size_of, size_of_val}; use std::str::from_utf8; -use data_model::{DataInit, Le32, Le64, VolatileMemory, VolatileSlice, VolatileMemoryError}; +use data_model::{DataInit, Le32, Le64, VolatileMemory, VolatileMemoryError, VolatileSlice}; pub const VIRTIO_GPU_F_VIRGL: u32 = 0; @@ -122,9 +122,9 @@ unsafe impl DataInit for virtio_gpu_cursor_pos {} pub struct virtio_gpu_update_cursor { pub hdr: virtio_gpu_ctrl_hdr, pub pos: virtio_gpu_cursor_pos, /* update & move */ - pub resource_id: Le32, /* update only */ - pub hot_x: Le32, /* update only */ - pub hot_y: Le32, /* update only */ + pub resource_id: Le32, /* update only */ + pub hot_x: Le32, /* update only */ + pub hot_y: Le32, /* update only */ pub padding: Le32, } @@ -417,7 +417,6 @@ pub struct virtio_gpu_resp_capset { unsafe impl DataInit for virtio_gpu_resp_capset {} - pub const VIRTIO_GPU_EVENT_DISPLAY: u32 = 1 << 0; #[derive(Copy, Clone, Debug)] @@ -516,32 +515,28 @@ impl GpuCommand { use self::GpuCommand::*; let hdr: virtio_gpu_ctrl_hdr = cmd.get_ref(0)?.load(); Ok(match hdr.type_.into() { - VIRTIO_GPU_CMD_GET_DISPLAY_INFO => GetDisplayInfo(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_RESOURCE_CREATE_2D => ResourceCreate2d(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_RESOURCE_UNREF => ResourceUnref(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_SET_SCANOUT => SetScanout(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_RESOURCE_FLUSH => ResourceFlush(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D => TransferToHost2d(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING => { - ResourceAttachBacking(cmd.get_ref(0)?.load()) - } - VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING => { - ResourceDetachBacking(cmd.get_ref(0)?.load()) - } - VIRTIO_GPU_CMD_GET_CAPSET_INFO => GetCapsetInfo(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_GET_CAPSET => GetCapset(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_CTX_CREATE => CtxCreate(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_CTX_DESTROY => CtxDestroy(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE => CtxAttachResource(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE => CtxDetachResource(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_RESOURCE_CREATE_3D => ResourceCreate3d(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D => TransferToHost3d(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D => TransferFromHost3d(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_SUBMIT_3D => CmdSubmit3d(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_UPDATE_CURSOR => UpdateCursor(cmd.get_ref(0)?.load()), - VIRTIO_GPU_CMD_MOVE_CURSOR => MoveCursor(cmd.get_ref(0)?.load()), - _ => return Err(GpuCommandDecodeError::InvalidType(hdr.type_.into())), - }) + VIRTIO_GPU_CMD_GET_DISPLAY_INFO => GetDisplayInfo(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_RESOURCE_CREATE_2D => ResourceCreate2d(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_RESOURCE_UNREF => ResourceUnref(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_SET_SCANOUT => SetScanout(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_RESOURCE_FLUSH => ResourceFlush(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_TRANSFER_TO_HOST_2D => TransferToHost2d(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_RESOURCE_ATTACH_BACKING => ResourceAttachBacking(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_RESOURCE_DETACH_BACKING => ResourceDetachBacking(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_GET_CAPSET_INFO => GetCapsetInfo(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_GET_CAPSET => GetCapset(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_CTX_CREATE => CtxCreate(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_CTX_DESTROY => CtxDestroy(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_CTX_ATTACH_RESOURCE => CtxAttachResource(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_CTX_DETACH_RESOURCE => CtxDetachResource(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_RESOURCE_CREATE_3D => ResourceCreate3d(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_TRANSFER_TO_HOST_3D => TransferToHost3d(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_TRANSFER_FROM_HOST_3D => TransferFromHost3d(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_SUBMIT_3D => CmdSubmit3d(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_UPDATE_CURSOR => UpdateCursor(cmd.get_ref(0)?.load()), + VIRTIO_GPU_CMD_MOVE_CURSOR => MoveCursor(cmd.get_ref(0)?.load()), + _ => return Err(GpuCommandDecodeError::InvalidType(hdr.type_.into())), + }) } /// Gets the generic `virtio_gpu_ctrl_hdr` from this command. @@ -604,12 +599,13 @@ impl From<VolatileMemoryError> for GpuResponseEncodeError { impl GpuResponse { /// Encodes a this `GpuResponse` into `resp` and the given set of metadata. - pub fn encode(&self, - flags: u32, - fence_id: u64, - ctx_id: u32, - resp: VolatileSlice) - -> Result<u32, GpuResponseEncodeError> { + pub fn encode( + &self, + flags: u32, + fence_id: u64, + ctx_id: u32, + resp: VolatileSlice, + ) -> Result<u32, GpuResponseEncodeError> { let hdr = virtio_gpu_ctrl_hdr { type_: Le32::from(self.get_type()), flags: Le32::from(flags), @@ -635,19 +631,19 @@ impl GpuResponse { size_of_val(&disp_info) } &GpuResponse::OkCapsetInfo { id, version, size } => { - resp.get_ref(0)? - .store(virtio_gpu_resp_capset_info { - hdr, - capset_id: Le32::from(id), - capset_max_version: Le32::from(version), - capset_max_size: Le32::from(size), - padding: Le32::from(0), - }); + resp.get_ref(0)?.store(virtio_gpu_resp_capset_info { + hdr, + capset_id: Le32::from(id), + capset_max_version: Le32::from(version), + capset_max_size: Le32::from(size), + padding: Le32::from(0), + }); size_of::<virtio_gpu_resp_capset_info>() } &GpuResponse::OkCapset(ref data) => { resp.get_ref(0)?.store(hdr); - let resp_data_slice = resp.get_slice(size_of_val(&hdr) as u64, data.len() as u64)?; + let resp_data_slice = + resp.get_slice(size_of_val(&hdr) as u64, data.len() as u64)?; resp_data_slice.copy_from(data); size_of_val(&hdr) + data.len() } diff --git a/devices/src/virtio/mmio.rs b/devices/src/virtio/mmio.rs index 5e7226f..400afd9 100644 --- a/devices/src/virtio/mmio.rs +++ b/devices/src/virtio/mmio.rs @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use byteorder::{ByteOrder, LittleEndian}; use super::*; +use sys_util::{EventFd, GuestAddress, GuestMemory, Result}; use BusDevice; -use sys_util::{Result, EventFd, GuestAddress, GuestMemory}; const VENDOR_ID: u32 = 0; @@ -59,19 +59,19 @@ impl MmioDevice { .map(|&s| Queue::new(s)) .collect(); Ok(MmioDevice { - device: device, - device_activated: false, - features_select: 0, - acked_features_select: 0, - queue_select: 0, - interrupt_status: Arc::new(AtomicUsize::new(0)), - interrupt_evt: Some(EventFd::new()?), - driver_status: 0, - config_generation: 0, - queues: queues, - queue_evts: queue_evts, - mem: Some(mem), - }) + device, + device_activated: false, + features_select: 0, + acked_features_select: 0, + queue_select: 0, + interrupt_status: Arc::new(AtomicUsize::new(0)), + interrupt_evt: Some(EventFd::new()?), + driver_status: 0, + config_generation: 0, + queues, + queue_evts, + mem: Some(mem), + }) } /// Gets the list of queue events that must be triggered whenever the VM writes to @@ -100,7 +100,8 @@ impl MmioDevice { } fn with_queue<U, F>(&self, d: U, f: F) -> U - where F: FnOnce(&Queue) -> U + where + F: FnOnce(&Queue) -> U, { match self.queues.get(self.queue_select as usize) { Some(queue) => f(queue), @@ -128,8 +129,8 @@ impl BusDevice for MmioDevice { 0x08 => self.device.device_type(), 0x0c => VENDOR_ID, // vendor id 0x10 => { - self.device.features(self.features_select) | - if self.features_select == 1 { 0x1 } else { 0x0 } + self.device.features(self.features_select) + | if self.features_select == 1 { 0x1 } else { 0x0 } } 0x34 => self.with_queue(0, |q| q.max_size as u32), 0x44 => self.with_queue(0, |q| q.ready as u32), @@ -145,10 +146,13 @@ impl BusDevice for MmioDevice { } 0x100...0xfff => self.device.read_config(offset - 0x100, data), _ => { - warn!("invalid virtio mmio read: 0x{:x}:0x{:x}", offset, data.len()); + warn!( + "invalid virtio mmio read: 0x{:x}:0x{:x}", + offset, + data.len() + ); } }; - } fn write(&mut self, offset: u64, data: &[u8]) { @@ -190,7 +194,11 @@ impl BusDevice for MmioDevice { } 0x100...0xfff => return self.device.write_config(offset - 0x100, data), _ => { - warn!("invalid virtio mmio write: 0x{:x}:0x{:x}", offset, data.len()); + warn!( + "invalid virtio mmio write: 0x{:x}:0x{:x}", + offset, + data.len() + ); return; } } @@ -202,12 +210,13 @@ impl BusDevice for MmioDevice { if !self.device_activated && self.is_driver_ready() && self.are_queues_valid() { if let Some(interrupt_evt) = self.interrupt_evt.take() { if let Some(mem) = self.mem.take() { - self.device - .activate(mem, - interrupt_evt, - self.interrupt_status.clone(), - self.queues.clone(), - self.queue_evts.split_off(0)); + self.device.activate( + mem, + interrupt_evt, + self.interrupt_status.clone(), + self.queues.clone(), + self.queue_evts.split_off(0), + ); self.device_activated = true; } } diff --git a/devices/src/virtio/mod.rs b/devices/src/virtio/mod.rs index a85b04b..c23c56d 100644 --- a/devices/src/virtio/mod.rs +++ b/devices/src/virtio/mod.rs @@ -5,14 +5,14 @@ //! Implements virtio devices, queues, and transport mechanisms. mod balloon; -mod queue; -mod mmio; mod block; -mod rng; -mod net; #[cfg(feature = "gpu")] mod gpu; +mod mmio; +mod net; mod p9; +mod queue; +mod rng; mod virtio_device; mod virtio_pci_common_config; mod virtio_pci_device; @@ -21,14 +21,14 @@ mod wl; pub mod vhost; pub use self::balloon::*; -pub use self::queue::*; -pub use self::mmio::*; pub use self::block::*; -pub use self::rng::*; -pub use self::net::*; #[cfg(feature = "gpu")] pub use self::gpu::*; +pub use self::mmio::*; +pub use self::net::*; pub use self::p9::*; +pub use self::queue::*; +pub use self::rng::*; pub use self::virtio_device::*; pub use self::virtio_pci_device::*; pub use self::wl::*; diff --git a/devices/src/virtio/net.rs b/devices/src/virtio/net.rs index 96f7199..e5b9650 100644 --- a/devices/src/virtio/net.rs +++ b/devices/src/virtio/net.rs @@ -6,8 +6,8 @@ use std::cmp; use std::mem; use std::net::Ipv4Addr; use std::os::unix::io::{AsRawFd, RawFd}; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use libc::EAGAIN; @@ -15,10 +15,10 @@ use net_sys; use net_util::{Error as TapError, MacAddress, TapT}; use sys_util::Error as SysError; use sys_util::{EventFd, GuestMemory, PollContext, PollToken}; -use virtio_sys::{vhost, virtio_net}; use virtio_sys::virtio_net::virtio_net_hdr_v1; +use virtio_sys::{vhost, virtio_net}; -use super::{VirtioDevice, Queue, INTERRUPT_STATUS_USED_RING, TYPE_NET}; +use super::{Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_NET}; /// The maximum buffer size when segmentation offload is enabled. This /// includes the 12-byte virtio net header. @@ -120,14 +120,17 @@ where next_desc = desc.next_descriptor(); } None => { - warn!("net: rx: buffer is too small to hold frame of size {}", - self.rx_count); + warn!( + "net: rx: buffer is too small to hold frame of size {}", + self.rx_count + ); break; } } } - self.rx_queue.add_used(&self.mem, head_index, write_count as u32); + self.rx_queue + .add_used(&self.mem, head_index, write_count as u32); // Interrupt the guest immediately for received frames to // reduce latency. @@ -178,7 +181,8 @@ where break; } let limit = cmp::min(read_count + desc.len as usize, frame.len()); - let read_result = self.mem + let read_result = self + .mem .read_slice_at_addr(&mut frame[read_count..limit as usize], desc.addr); match read_result { Ok(sz) => { @@ -199,7 +203,7 @@ where let write_result = self.tap.write(&frame[..read_count as usize]); match write_result { - Ok(_) => {}, + Ok(_) => {} Err(e) => { warn!("net: tx: error failed to write to tap: {:?}", e); } @@ -216,11 +220,12 @@ where self.signal_used_queue(); } - fn run(&mut self, - rx_queue_evt: EventFd, - tx_queue_evt: EventFd, - kill_evt: EventFd) - -> Result<(), NetError> { + fn run( + &mut self, + rx_queue_evt: EventFd, + tx_queue_evt: EventFd, + kill_evt: EventFd, + ) -> Result<(), NetError> { #[derive(PollToken)] enum Token { // A frame is available for reading from the tap device to receive in the guest. @@ -234,11 +239,11 @@ where } let poll_ctx: PollContext<Token> = PollContext::new() - .and_then(|pc| pc.add(&self.tap, Token::RxTap).and(Ok(pc))) - .and_then(|pc| pc.add(&rx_queue_evt, Token::RxQueue).and(Ok(pc))) - .and_then(|pc| pc.add(&tx_queue_evt, Token::TxQueue).and(Ok(pc))) - .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) - .map_err(NetError::CreatePollContext)?; + .and_then(|pc| pc.add(&self.tap, Token::RxTap).and(Ok(pc))) + .and_then(|pc| pc.add(&rx_queue_evt, Token::RxQueue).and(Ok(pc))) + .and_then(|pc| pc.add(&tx_queue_evt, Token::TxQueue).and(Ok(pc))) + .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) + .map_err(NetError::CreatePollContext)?; 'poll: loop { let events = poll_ctx.wait().map_err(NetError::PollError)?; @@ -335,9 +340,9 @@ where let kill_evt = EventFd::new().map_err(NetError::CreateKillEventFd)?; Ok(Net { workers_kill_evt: Some(kill_evt.try_clone().map_err(NetError::CloneKillEventFd)?), - kill_evt: kill_evt, + kill_evt, tap: Some(tap), - avail_features: avail_features, + avail_features, acked_features: 0u64, }) } @@ -398,8 +403,10 @@ where 0 => value as u64, 1 => (value as u64) << 32, _ => { - warn!("net: virtio net device cannot ack unknown feature page: {}", - page); + warn!( + "net: virtio net device cannot ack unknown feature page: {}", + page + ); 0u64 } }; @@ -415,12 +422,14 @@ where self.acked_features |= v; } - fn activate(&mut self, - mem: GuestMemory, - interrupt_evt: EventFd, - status: Arc<AtomicUsize>, - mut queues: Vec<Queue>, - mut queue_evts: Vec<EventFd>) { + fn activate( + &mut self, + mem: GuestMemory, + interrupt_evt: EventFd, + status: Arc<AtomicUsize>, + mut queues: Vec<Queue>, + mut queue_evts: Vec<EventFd>, + ) { if queues.len() != 2 || queue_evts.len() != 2 { error!("net: expected 2 queues, got {}", queues.len()); return; @@ -429,31 +438,32 @@ where if let Some(tap) = self.tap.take() { if let Some(kill_evt) = self.workers_kill_evt.take() { let acked_features = self.acked_features; - let worker_result = thread::Builder::new() - .name("virtio_net".to_string()) - .spawn(move || { - // First queue is rx, second is tx. - let rx_queue = queues.remove(0); - let tx_queue = queues.remove(0); - let mut worker = Worker { - mem: mem, - rx_queue: rx_queue, - tx_queue: tx_queue, - tap: tap, - interrupt_status: status, - interrupt_evt: interrupt_evt, - rx_buf: [0u8; MAX_BUFFER_SIZE], - rx_count: 0, - deferred_rx: false, - acked_features: acked_features, - }; - let rx_queue_evt = queue_evts.remove(0); - let tx_queue_evt = queue_evts.remove(0); - let result = worker.run(rx_queue_evt, tx_queue_evt, kill_evt); - if let Err(e) = result { - error!("net worker thread exited with error: {:?}", e); - } - }); + let worker_result = + thread::Builder::new() + .name("virtio_net".to_string()) + .spawn(move || { + // First queue is rx, second is tx. + let rx_queue = queues.remove(0); + let tx_queue = queues.remove(0); + let mut worker = Worker { + mem, + rx_queue, + tx_queue, + tap, + interrupt_status: status, + interrupt_evt, + rx_buf: [0u8; MAX_BUFFER_SIZE], + rx_count: 0, + deferred_rx: false, + acked_features, + }; + let rx_queue_evt = queue_evts.remove(0); + let tx_queue_evt = queue_evts.remove(0); + let result = worker.run(rx_queue_evt, tx_queue_evt, kill_evt); + if let Err(e) = result { + error!("net worker thread exited with error: {:?}", e); + } + }); if let Err(e) = worker_result { error!("failed to spawn virtio_net worker: {}", e); diff --git a/devices/src/virtio/p9.rs b/devices/src/virtio/p9.rs index 0ff4de1..12e4911 100644 --- a/devices/src/virtio/p9.rs +++ b/devices/src/virtio/p9.rs @@ -11,15 +11,15 @@ use std::mem; use std::os::unix::io::RawFd; use std::path::{Path, PathBuf}; use std::result; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use p9; use sys_util::{Error as SysError, EventFd, GuestAddress, GuestMemory, PollContext, PollToken}; use virtio_sys::vhost::VIRTIO_F_VERSION_1; -use super::{DescriptorChain, Queue, TYPE_9P, VirtioDevice, INTERRUPT_STATUS_USED_RING}; +use super::{DescriptorChain, Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_9P}; const QUEUE_SIZE: u16 = 128; const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE]; @@ -137,7 +137,8 @@ where ) })?; let len = min(buf.len(), (current.len - self.offset) as usize); - let count = self.mem + let count = self + .mem .read_slice_at_addr(&mut buf[..len], addr) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; @@ -192,7 +193,8 @@ where })?; let len = min(buf.len(), (current.len - self.offset) as usize); - let count = self.mem + let count = self + .mem .write_slice_at_addr(&buf[..len], addr) .map_err(|e| io::Error::new(io::ErrorKind::Other, e))?; @@ -237,21 +239,13 @@ impl Worker { let mut reader = Reader { mem: &self.mem, offset: 0, - iter: avail_desc - .clone() - .into_iter() - .readable() - .peekable(), + iter: avail_desc.clone().into_iter().readable().peekable(), }; let mut writer = Writer { mem: &self.mem, bytes_written: 0, offset: 0, - iter: avail_desc - .clone() - .into_iter() - .writable() - .peekable(), + iter: avail_desc.clone().into_iter().writable().peekable(), }; self.server @@ -422,19 +416,20 @@ impl VirtioDevice for P9 { self.kill_evt = Some(self_kill_evt); if let Some(server) = self.server.take() { - let worker_result = thread::Builder::new().name("virtio_9p".to_string()).spawn( - move || { - let mut worker = Worker { - mem: guest_mem, - queue: queues.remove(0), - server: server, - irq_status: status, - irq_evt: interrupt_evt, - }; - - worker.run(queue_evts.remove(0), kill_evt) - }, - ); + let worker_result = + thread::Builder::new() + .name("virtio_9p".to_string()) + .spawn(move || { + let mut worker = Worker { + mem: guest_mem, + queue: queues.remove(0), + server, + irq_status: status, + irq_evt: interrupt_evt, + }; + + worker.run(queue_evts.remove(0), kill_evt) + }); match worker_result { Ok(worker) => self.worker = Some(worker), diff --git a/devices/src/virtio/queue.rs b/devices/src/virtio/queue.rs index 41a745f..0f596ba 100644 --- a/devices/src/virtio/queue.rs +++ b/devices/src/virtio/queue.rs @@ -21,12 +21,12 @@ pub struct DescIter<'a> { impl<'a> DescIter<'a> { /// Returns an iterator that only yields the readable descriptors in the chain. - pub fn readable(self) -> impl Iterator<Item=DescriptorChain<'a>> { + pub fn readable(self) -> impl Iterator<Item = DescriptorChain<'a>> { self.take_while(DescriptorChain::is_read_only) } /// Returns an iterator that only yields the writable descriptors in the chain. - pub fn writable(self) -> impl Iterator<Item=DescriptorChain<'a>> { + pub fn writable(self) -> impl Iterator<Item = DescriptorChain<'a>> { self.skip_while(DescriptorChain::is_read_only) } } @@ -70,11 +70,12 @@ pub struct DescriptorChain<'a> { } impl<'a> DescriptorChain<'a> { - fn checked_new(mem: &GuestMemory, - desc_table: GuestAddress, - queue_size: u16, - index: u16) - -> Option<DescriptorChain> { + fn checked_new( + mem: &GuestMemory, + desc_table: GuestAddress, + queue_size: u16, + index: u16, + ) -> Option<DescriptorChain> { if index >= queue_size { return None; } @@ -88,31 +89,34 @@ impl<'a> DescriptorChain<'a> { if mem.checked_offset(desc_head, 16).is_none() { return None; } - let len: u32 = mem.read_obj_from_addr(desc_head.unchecked_add(8)) - .unwrap(); - let flags: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(12)) - .unwrap(); - let next: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(14)) - .unwrap(); + let len: u32 = mem.read_obj_from_addr(desc_head.unchecked_add(8)).unwrap(); + let flags: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(12)).unwrap(); + let next: u16 = mem.read_obj_from_addr(desc_head.unchecked_add(14)).unwrap(); let chain = DescriptorChain { - mem: mem, - desc_table: desc_table, - queue_size: queue_size, + mem, + desc_table, + queue_size, ttl: queue_size, - index: index, - addr: addr, - len: len, - flags: flags, - next: next, + index, + addr, + len, + flags, + next, }; - if chain.is_valid() { Some(chain) } else { None } + if chain.is_valid() { + Some(chain) + } else { + None + } } fn is_valid(&self) -> bool { - if self.mem - .checked_offset(self.addr, self.len as u64) - .is_none() { + if self + .mem + .checked_offset(self.addr, self.len as u64) + .is_none() + { false } else if self.has_next() && self.next >= self.queue_size { false @@ -148,11 +152,12 @@ impl<'a> DescriptorChain<'a> { /// the head of the next _available_ descriptor chain. pub fn next_descriptor(&self) -> Option<DescriptorChain<'a>> { if self.has_next() { - DescriptorChain::checked_new(self.mem, self.desc_table, self.queue_size, self.next) - .map(|mut c| { - c.ttl = self.ttl - 1; - c - }) + DescriptorChain::checked_new(self.mem, self.desc_table, self.queue_size, self.next).map( + |mut c| { + c.ttl = self.ttl - 1; + c + }, + ) } else { None } @@ -160,9 +165,7 @@ impl<'a> DescriptorChain<'a> { /// Produces an iterator over all the descriptors in this chain. pub fn into_iter(self) -> DescIter<'a> { - DescIter { - next: Some(self), - } + DescIter { next: Some(self) } } } @@ -233,7 +236,7 @@ impl Queue { /// Constructs an empty virtio queue with the given `max_size`. pub fn new(max_size: u16) -> Queue { Queue { - max_size: max_size, + max_size, size: max_size, ready: false, desc_table: GuestAddress(0), @@ -261,49 +264,57 @@ impl Queue { if !self.ready { error!("attempt to use virtio queue that is not marked ready"); false - } else if self.size > self.max_size || self.size == 0 || - (self.size & (self.size - 1)) != 0 { + } else if self.size > self.max_size || self.size == 0 || (self.size & (self.size - 1)) != 0 + { error!("virtio queue with invalid size: {}", self.size); false } else if desc_table - .checked_add(desc_table_size as u64) - .map_or(true, |v| !mem.address_in_range(v)) { - error!("virtio queue descriptor table goes out of bounds: start:0x{:08x} size:0x{:08x}", - desc_table.offset(), - desc_table_size); + .checked_add(desc_table_size as u64) + .map_or(true, |v| !mem.address_in_range(v)) + { + error!( + "virtio queue descriptor table goes out of bounds: start:0x{:08x} size:0x{:08x}", + desc_table.offset(), + desc_table_size + ); false } else if avail_ring - .checked_add(avail_ring_size as u64) - .map_or(true, |v| !mem.address_in_range(v)) { - error!("virtio queue available ring goes out of bounds: start:0x{:08x} size:0x{:08x}", - avail_ring.offset(), - avail_ring_size); + .checked_add(avail_ring_size as u64) + .map_or(true, |v| !mem.address_in_range(v)) + { + error!( + "virtio queue available ring goes out of bounds: start:0x{:08x} size:0x{:08x}", + avail_ring.offset(), + avail_ring_size + ); false } else if used_ring - .checked_add(used_ring_size as u64) - .map_or(true, |v| !mem.address_in_range(v)) { - error!("virtio queue used ring goes out of bounds: start:0x{:08x} size:0x{:08x}", - used_ring.offset(), - used_ring_size); + .checked_add(used_ring_size as u64) + .map_or(true, |v| !mem.address_in_range(v)) + { + error!( + "virtio queue used ring goes out of bounds: start:0x{:08x} size:0x{:08x}", + used_ring.offset(), + used_ring_size + ); false } else { true } - } /// A consuming iterator over all available descriptor chain heads offered by the driver. pub fn iter<'a, 'b>(&'b mut self, mem: &'a GuestMemory) -> AvailIter<'a, 'b> { if !self.is_valid(mem) { return AvailIter { - mem: mem, - desc_table: GuestAddress(0), - avail_ring: GuestAddress(0), - next_index: Wrapping(0), - last_index: Wrapping(0), - queue_size: 0, - next_avail: &mut self.next_avail, - }; + mem, + desc_table: GuestAddress(0), + avail_ring: GuestAddress(0), + next_index: Wrapping(0), + last_index: Wrapping(0), + queue_size: 0, + next_avail: &mut self.next_avail, + }; } let queue_size = self.actual_size(); let avail_ring = self.avail_ring; @@ -315,7 +326,7 @@ impl Queue { if queue_len.0 > queue_size { return AvailIter { - mem: mem, + mem, desc_table: GuestAddress(0), avail_ring: GuestAddress(0), next_index: Wrapping(0), @@ -326,12 +337,12 @@ impl Queue { } AvailIter { - mem: mem, + mem, desc_table: self.desc_table, - avail_ring: avail_ring, + avail_ring, next_index: self.next_avail, last_index: Wrapping(last_index), - queue_size: queue_size, + queue_size, next_avail: &mut self.next_avail, } } @@ -339,8 +350,10 @@ impl Queue { /// Puts an available descriptor head into the used ring for use by the guest. pub fn add_used(&mut self, mem: &GuestMemory, desc_index: u16, len: u32) { if desc_index >= self.actual_size() { - error!("attempted to add out of bounds descriptor to used ring: {}", - desc_index); + error!( + "attempted to add out of bounds descriptor to used ring: {}", + desc_index + ); return; } @@ -349,8 +362,7 @@ impl Queue { let used_elem = used_ring.unchecked_add((4 + next_used * 8) as u64); // These writes can't fail as we are guaranteed to be within the descriptor ring. - mem.write_obj_at_addr(desc_index as u32, used_elem) - .unwrap(); + mem.write_obj_at_addr(desc_index as u32, used_elem).unwrap(); mem.write_obj_at_addr(len as u32, used_elem.unchecked_add(4)) .unwrap(); diff --git a/devices/src/virtio/rng.rs b/devices/src/virtio/rng.rs index f1cfe0a..0c0dd13 100644 --- a/devices/src/virtio/rng.rs +++ b/devices/src/virtio/rng.rs @@ -6,13 +6,13 @@ use std; use std::fs::File; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use sys_util::{EventFd, GuestMemory, PollContext, PollToken}; -use super::{VirtioDevice, Queue, INTERRUPT_STATUS_USED_RING, TYPE_RNG}; +use super::{Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_RNG}; const QUEUE_SIZE: u16 = 256; const QUEUE_SIZES: &'static [u16] = &[QUEUE_SIZE]; @@ -44,10 +44,14 @@ impl Worker { // Drivers can only read from the random device. if avail_desc.is_write_only() { // Fill the read with data from the random device on the host. - if self.mem.read_to_memory(avail_desc.addr, - &mut self.random_file, - avail_desc.len as usize) - .is_ok() { + if self + .mem + .read_to_memory( + avail_desc.addr, + &mut self.random_file, + avail_desc.len as usize, + ).is_ok() + { len = avail_desc.len; } } @@ -75,16 +79,16 @@ impl Worker { Kill, } - let poll_ctx: PollContext<Token> = - match PollContext::new() - .and_then(|pc| pc.add(&queue_evt, Token::QueueAvailable).and(Ok(pc))) - .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) { - Ok(pc) => pc, - Err(e) => { - error!("failed creating PollContext: {:?}", e); - return; - } - }; + let poll_ctx: PollContext<Token> = match PollContext::new() + .and_then(|pc| pc.add(&queue_evt, Token::QueueAvailable).and(Ok(pc))) + .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) + { + Ok(pc) => pc, + Err(e) => { + error!("failed creating PollContext: {:?}", e); + return; + } + }; 'poll: loop { let events = match poll_ctx.wait() { @@ -124,12 +128,11 @@ pub struct Rng { impl Rng { /// Create a new virtio rng device that gets random data from /dev/urandom. pub fn new() -> Result<Rng> { - let random_file = File::open("/dev/urandom") - .map_err(RngError::AccessingRandomDev)?; + let random_file = File::open("/dev/urandom").map_err(RngError::AccessingRandomDev)?; Ok(Rng { - kill_evt: None, - random_file: Some(random_file), - }) + kill_evt: None, + random_file: Some(random_file), + }) } } @@ -161,41 +164,43 @@ impl VirtioDevice for Rng { QUEUE_SIZES } - fn activate(&mut self, - mem: GuestMemory, - interrupt_evt: EventFd, - status: Arc<AtomicUsize>, - mut queues: Vec<Queue>, - mut queue_evts: Vec<EventFd>) { + fn activate( + &mut self, + mem: GuestMemory, + interrupt_evt: EventFd, + status: Arc<AtomicUsize>, + mut queues: Vec<Queue>, + mut queue_evts: Vec<EventFd>, + ) { if queues.len() != 1 || queue_evts.len() != 1 { return; } - let (self_kill_evt, kill_evt) = - match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { - Ok(v) => v, - Err(e) => { - error!("failed to create kill EventFd pair: {:?}", e); - return; - } - }; + let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { + Ok(v) => v, + Err(e) => { + error!("failed to create kill EventFd pair: {:?}", e); + return; + } + }; self.kill_evt = Some(self_kill_evt); let queue = queues.remove(0); if let Some(random_file) = self.random_file.take() { - let worker_result = thread::Builder::new() - .name("virtio_rng".to_string()) - .spawn(move || { - let mut worker = Worker { - queue: queue, - mem: mem, - random_file: random_file, - interrupt_status: status, - interrupt_evt: interrupt_evt, - }; - worker.run(queue_evts.remove(0), kill_evt); - }); + let worker_result = + thread::Builder::new() + .name("virtio_rng".to_string()) + .spawn(move || { + let mut worker = Worker { + queue, + mem, + random_file, + interrupt_status: status, + interrupt_evt, + }; + worker.run(queue_evts.remove(0), kill_evt); + }); if let Err(e) = worker_result { error!("failed to spawn virtio_rng worker: {}", e); diff --git a/devices/src/virtio/vhost/net.rs b/devices/src/virtio/vhost/net.rs index 694dc6a..1f73863 100644 --- a/devices/src/virtio/vhost/net.rs +++ b/devices/src/virtio/vhost/net.rs @@ -5,8 +5,8 @@ use std::mem; use std::net::Ipv4Addr; use std::os::unix::io::{AsRawFd, RawFd}; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; +use std::sync::Arc; use std::thread; use net_sys; @@ -16,9 +16,9 @@ use sys_util::{EventFd, GuestMemory}; use vhost::NetT as VhostNetT; use virtio_sys::{vhost, virtio_net}; -use super::{Error, Result}; use super::super::{Queue, VirtioDevice, TYPE_NET}; use super::worker::Worker; +use super::{Error, Result}; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 2; @@ -41,16 +41,19 @@ where { /// Create a new virtio network device with the given IP address and /// netmask. - pub fn new(ip_addr: Ipv4Addr, - netmask: Ipv4Addr, - mac_addr: MacAddress, - mem: &GuestMemory) -> Result<Net<T, U>> { + pub fn new( + ip_addr: Ipv4Addr, + netmask: Ipv4Addr, + mac_addr: MacAddress, + mem: &GuestMemory, + ) -> Result<Net<T, U>> { let kill_evt = EventFd::new().map_err(Error::CreateKillEventFd)?; let tap: T = T::new(true).map_err(Error::TapOpen)?; tap.set_ip_addr(ip_addr).map_err(Error::TapSetIp)?; tap.set_netmask(netmask).map_err(Error::TapSetNetmask)?; - tap.set_mac_address(mac_addr).map_err(Error::TapSetMacAddress)?; + tap.set_mac_address(mac_addr) + .map_err(Error::TapSetMacAddress)?; // Set offload flags to match the virtio features below. tap.set_offload( @@ -59,29 +62,31 @@ where // We declare VIRTIO_NET_F_MRG_RXBUF, so set the vnet hdr size to match. let vnet_hdr_size = mem::size_of::<virtio_net::virtio_net_hdr_mrg_rxbuf>() as i32; - tap.set_vnet_hdr_size(vnet_hdr_size).map_err(Error::TapSetVnetHdrSize)?; + tap.set_vnet_hdr_size(vnet_hdr_size) + .map_err(Error::TapSetVnetHdrSize)?; tap.enable().map_err(Error::TapEnable)?; let vhost_net_handle = U::new(mem).map_err(Error::VhostOpen)?; - let avail_features = - 1 << virtio_net::VIRTIO_NET_F_GUEST_CSUM | 1 << virtio_net::VIRTIO_NET_F_CSUM | - 1 << virtio_net::VIRTIO_NET_F_GUEST_TSO4 | - 1 << virtio_net::VIRTIO_NET_F_GUEST_UFO | - 1 << virtio_net::VIRTIO_NET_F_HOST_TSO4 | - 1 << virtio_net::VIRTIO_NET_F_HOST_UFO | - 1 << virtio_net::VIRTIO_NET_F_MRG_RXBUF | - 1 << vhost::VIRTIO_RING_F_INDIRECT_DESC | - 1 << vhost::VIRTIO_RING_F_EVENT_IDX | - 1 << vhost::VIRTIO_F_NOTIFY_ON_EMPTY | 1 << vhost::VIRTIO_F_VERSION_1; + let avail_features = 1 << virtio_net::VIRTIO_NET_F_GUEST_CSUM + | 1 << virtio_net::VIRTIO_NET_F_CSUM + | 1 << virtio_net::VIRTIO_NET_F_GUEST_TSO4 + | 1 << virtio_net::VIRTIO_NET_F_GUEST_UFO + | 1 << virtio_net::VIRTIO_NET_F_HOST_TSO4 + | 1 << virtio_net::VIRTIO_NET_F_HOST_UFO + | 1 << virtio_net::VIRTIO_NET_F_MRG_RXBUF + | 1 << vhost::VIRTIO_RING_F_INDIRECT_DESC + | 1 << vhost::VIRTIO_RING_F_EVENT_IDX + | 1 << vhost::VIRTIO_F_NOTIFY_ON_EMPTY + | 1 << vhost::VIRTIO_F_VERSION_1; Ok(Net { workers_kill_evt: Some(kill_evt.try_clone().map_err(Error::CloneKillEventFd)?), - kill_evt: kill_evt, + kill_evt, tap: Some(tap), vhost_net_handle: Some(vhost_net_handle), vhost_interrupt: Some(EventFd::new().map_err(Error::VhostIrqCreate)?), - avail_features: avail_features, + avail_features, acked_features: 0u64, }) } @@ -143,7 +148,7 @@ where _ => { warn!("net: virtio net got request for features page: {}", page); 0u32 - }, + } } } @@ -157,7 +162,7 @@ where page ); 0u64 - }, + } }; // Check if the guest is ACK'ing a feature that we didn't claim to have. @@ -192,12 +197,14 @@ where let worker_result = thread::Builder::new() .name("vhost_net".to_string()) .spawn(move || { - let mut worker = Worker::new(queues, - vhost_net_handle, - vhost_interrupt, - status, - interrupt_evt, - acked_features); + let mut worker = Worker::new( + queues, + vhost_net_handle, + vhost_interrupt, + status, + interrupt_evt, + acked_features, + ); let activate_vqs = |handle: &U| -> Result<()> { for idx in 0..NUM_QUEUES { handle @@ -227,8 +234,8 @@ where #[cfg(test)] pub mod tests { use super::*; - use std::result; use net_util::fakes::FakeTap; + use std::result; use sys_util::{GuestAddress, GuestMemory, GuestMemoryError}; use vhost::net::fakes::FakeNet; diff --git a/devices/src/virtio/vhost/vsock.rs b/devices/src/virtio/vhost/vsock.rs index b55b6a0..694ea25 100644 --- a/devices/src/virtio/vhost/vsock.rs +++ b/devices/src/virtio/vhost/vsock.rs @@ -3,8 +3,8 @@ // found in the LICENSE file. use std::os::unix::io::{AsRawFd, RawFd}; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; +use std::sync::Arc; use std::thread; use byteorder::{ByteOrder, LittleEndian}; @@ -13,9 +13,9 @@ use sys_util::{EventFd, GuestMemory}; use vhost::Vsock as VhostVsockHandle; use virtio_sys::vhost; -use super::{Error, Result}; use super::super::{Queue, VirtioDevice, TYPE_VSOCK}; use super::worker::Worker; +use super::{Error, Result}; const QUEUE_SIZE: u16 = 256; const NUM_QUEUES: usize = 3; @@ -37,18 +37,20 @@ impl Vsock { let kill_evt = EventFd::new().map_err(Error::CreateKillEventFd)?; let handle = VhostVsockHandle::new(mem).map_err(Error::VhostOpen)?; - let avail_features = - 1 << vhost::VIRTIO_F_NOTIFY_ON_EMPTY | 1 << vhost::VIRTIO_RING_F_INDIRECT_DESC | - 1 << vhost::VIRTIO_RING_F_EVENT_IDX | 1 << vhost::VHOST_F_LOG_ALL | - 1 << vhost::VIRTIO_F_ANY_LAYOUT | 1 << vhost::VIRTIO_F_VERSION_1; + let avail_features = 1 << vhost::VIRTIO_F_NOTIFY_ON_EMPTY + | 1 << vhost::VIRTIO_RING_F_INDIRECT_DESC + | 1 << vhost::VIRTIO_RING_F_EVENT_IDX + | 1 << vhost::VHOST_F_LOG_ALL + | 1 << vhost::VIRTIO_F_ANY_LAYOUT + | 1 << vhost::VIRTIO_F_VERSION_1; Ok(Vsock { worker_kill_evt: Some(kill_evt.try_clone().map_err(Error::CloneKillEventFd)?), kill_evt: Some(kill_evt), vhost_handle: Some(handle), - cid: cid, + cid, interrupt: Some(EventFd::new().map_err(Error::VhostIrqCreate)?), - avail_features: avail_features, + avail_features, acked_features: 0, }) } @@ -58,7 +60,7 @@ impl Vsock { worker_kill_evt: None, kill_evt: None, vhost_handle: None, - cid: cid, + cid, interrupt: None, avail_features: features, acked_features: 0, @@ -121,7 +123,7 @@ impl VirtioDevice for Vsock { page ); 0u32 - }, + } } } @@ -131,7 +133,7 @@ impl VirtioDevice for Vsock { 0 if data.len() == 4 => LittleEndian::write_u32(data, (self.cid & 0xffffffff) as u32), 4 if data.len() == 4 => { LittleEndian::write_u32(data, ((self.cid >> 32) & 0xffffffff) as u32) - }, + } _ => warn!( "vsock: virtio-vsock received invalid read request of {} bytes at offset {}", data.len(), @@ -150,7 +152,7 @@ impl VirtioDevice for Vsock { page ); 0u64 - }, + } }; // Check if the guest is ACK'ing a feature that we didn't claim to have. @@ -188,12 +190,14 @@ impl VirtioDevice for Vsock { // The third vq is an event-only vq that is not handled by the vhost // subsystem (but still needs to exist). Split it off here. let vhost_queues = queues[..2].to_vec(); - let mut worker = Worker::new(vhost_queues, - vhost_handle, - interrupt, - status, - interrupt_evt, - acked_features); + let mut worker = Worker::new( + vhost_queues, + vhost_handle, + interrupt, + status, + interrupt_evt, + acked_features, + ); let activate_vqs = |handle: &VhostVsockHandle| -> Result<()> { handle.set_cid(cid).map_err(Error::VhostVsockSetCid)?; handle.start().map_err(Error::VhostVsockStart)?; @@ -242,12 +246,18 @@ mod tests { acked_features |= 1 << 60; unavailable_features |= 1 << 60; vsock.ack_features(1, (acked_features >> 32) as u32); - assert_eq!(acked_features & !unavailable_features, vsock.acked_features()); + assert_eq!( + acked_features & !unavailable_features, + vsock.acked_features() + ); acked_features |= 1 << 1; unavailable_features |= 1 << 1; vsock.ack_features(0, (acked_features & 0xffffffff) as u32); - assert_eq!(acked_features & !unavailable_features, vsock.acked_features()); + assert_eq!( + acked_features & !unavailable_features, + vsock.acked_features() + ); } #[test] diff --git a/devices/src/virtio/vhost/worker.rs b/devices/src/virtio/vhost/worker.rs index 6d4cab7..529ebc0 100644 --- a/devices/src/virtio/vhost/worker.rs +++ b/devices/src/virtio/vhost/worker.rs @@ -3,14 +3,14 @@ // found in the LICENSE file. use std::os::raw::c_ulonglong; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use sys_util::{EventFd, PollContext, PollToken}; use vhost::Vhost; -use super::{Error, Result}; use super::super::{Queue, INTERRUPT_STATUS_USED_RING}; +use super::{Error, Result}; /// Worker that takes care of running the vhost device. This mainly involves forwarding interrupts /// from the vhost driver to the guest VM because crosvm only supports the virtio-mmio transport, @@ -35,12 +35,12 @@ impl<T: Vhost> Worker<T> { acked_features: u64, ) -> Worker<T> { Worker { - queues: queues, - vhost_handle: vhost_handle, - vhost_interrupt: vhost_interrupt, - interrupt_status: interrupt_status, - interrupt_evt: interrupt_evt, - acked_features: acked_features, + queues, + vhost_handle, + vhost_interrupt, + interrupt_status, + interrupt_evt, + acked_features, } } @@ -61,14 +61,23 @@ impl<T: Vhost> Worker<T> { F: FnOnce(&T) -> Result<()>, { // Preliminary setup for vhost net. - self.vhost_handle.set_owner().map_err(Error::VhostSetOwner)?; + self.vhost_handle + .set_owner() + .map_err(Error::VhostSetOwner)?; - let avail_features = self.vhost_handle.get_features().map_err(Error::VhostGetFeatures)?; + let avail_features = self + .vhost_handle + .get_features() + .map_err(Error::VhostGetFeatures)?; let features: c_ulonglong = self.acked_features & avail_features; - self.vhost_handle.set_features(features).map_err(Error::VhostSetFeatures)?; + self.vhost_handle + .set_features(features) + .map_err(Error::VhostSetFeatures)?; - self.vhost_handle.set_mem_table().map_err(Error::VhostSetMemTable)?; + self.vhost_handle + .set_mem_table() + .map_err(Error::VhostSetMemTable)?; for (queue_index, ref queue) in self.queues.iter().enumerate() { self.vhost_handle @@ -85,8 +94,7 @@ impl<T: Vhost> Worker<T> { queue.used_ring, queue.avail_ring, None, - ) - .map_err(Error::VhostSetVringAddr)?; + ).map_err(Error::VhostSetVringAddr)?; self.vhost_handle .set_vring_base(queue_index, 0) .map_err(Error::VhostSetVringBase)?; @@ -107,9 +115,9 @@ impl<T: Vhost> Worker<T> { } let poll_ctx: PollContext<Token> = PollContext::new() - .and_then(|pc| pc.add(&self.vhost_interrupt, Token::VhostIrq).and(Ok(pc))) - .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) - .map_err(Error::CreatePollContext)?; + .and_then(|pc| pc.add(&self.vhost_interrupt, Token::VhostIrq).and(Ok(pc))) + .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) + .map_err(Error::CreatePollContext)?; 'poll: loop { let events = poll_ctx.wait().map_err(Error::PollError)?; @@ -120,7 +128,7 @@ impl<T: Vhost> Worker<T> { Token::VhostIrq => { needs_interrupt = true; self.vhost_interrupt.read().map_err(Error::VhostIrqRead)?; - }, + } Token::Kill => break 'poll, } } diff --git a/devices/src/virtio/virtio_device.rs b/devices/src/virtio/virtio_device.rs index 7458be8..3c6d868 100644 --- a/devices/src/virtio/virtio_device.rs +++ b/devices/src/virtio/virtio_device.rs @@ -3,8 +3,8 @@ // found in the LICENSE file. use std::os::unix::io::RawFd; -use std::sync::Arc; use std::sync::atomic::AtomicUsize; +use std::sync::Arc; use super::*; use sys_util::{EventFd, GuestMemory}; @@ -52,12 +52,14 @@ pub trait VirtioDevice: Send { } /// Activates this device for real usage. - fn activate(&mut self, - mem: GuestMemory, - interrupt_evt: EventFd, - status: Arc<AtomicUsize>, - queues: Vec<Queue>, - queue_evts: Vec<EventFd>); + fn activate( + &mut self, + mem: GuestMemory, + interrupt_evt: EventFd, + status: Arc<AtomicUsize>, + queues: Vec<Queue>, + queue_evts: Vec<EventFd>, + ); /// Optionally deactivates this device and returns ownership of the guest memory map, interrupt /// event, and queue events. diff --git a/devices/src/virtio/virtio_pci_common_config.rs b/devices/src/virtio/virtio_pci_common_config.rs index 8a50b35..2793052 100644 --- a/devices/src/virtio/virtio_pci_common_config.rs +++ b/devices/src/virtio/virtio_pci_common_config.rs @@ -138,9 +138,12 @@ impl VirtioPciCommonConfig { // TODO(dverkamp): This hack (copied from MmioDevice) unconditionally // reports support for VIRTIO_F_VERSION_1; once all devices have been // fixed to report VIRTIO_F_VERSION_1, remove this workaround. - device.features(self.device_feature_select) | - if self.device_feature_select == 1 { 0x1 } else { 0x0 } - }, + device.features(self.device_feature_select) | if self.device_feature_select == 1 { + 0x1 + } else { + 0x0 + } + } 0x08 => self.driver_feature_select, _ => 0, } @@ -211,8 +214,8 @@ mod tests { use super::*; use std::os::unix::io::RawFd; - use std::sync::Arc; use std::sync::atomic::AtomicUsize; + use std::sync::Arc; use sys_util::{EventFd, GuestMemory}; struct DummyDevice(u32); @@ -229,12 +232,14 @@ mod tests { fn queue_max_sizes(&self) -> &[u16] { QUEUE_SIZES } - fn activate(&mut self, - _mem: GuestMemory, - _interrupt_evt: EventFd, - _status: Arc<AtomicUsize>, - _queues: Vec<Queue>, - _queue_evts: Vec<EventFd>) { + fn activate( + &mut self, + _mem: GuestMemory, + _interrupt_evt: EventFd, + _status: Arc<AtomicUsize>, + _queues: Vec<Queue>, + _queue_evts: Vec<EventFd>, + ) { } fn features(&self, _page: u32) -> u32 { DUMMY_FEATURES diff --git a/devices/src/virtio/virtio_pci_device.rs b/devices/src/virtio/virtio_pci_device.rs index e9b57ac..10cbd32 100644 --- a/devices/src/virtio/virtio_pci_device.rs +++ b/devices/src/virtio/virtio_pci_device.rs @@ -266,8 +266,7 @@ impl VirtioPciDevice { //TODO(dgreid) - How will the configuration_cap work? let configuration_cap = VirtioPciCap::new(PciCapabilityType::PciConfig, 0, 0, 0); - self.config_regs - .add_capability(&configuration_cap); + self.config_regs.add_capability(&configuration_cap); self.settings_bar = settings_bar; } @@ -335,8 +334,12 @@ impl PciDevice for VirtioPciDevice { o if COMMON_CONFIG_BAR_OFFSET <= o && o < COMMON_CONFIG_BAR_OFFSET + COMMON_CONFIG_SIZE => { - self.common_config - .read(o - COMMON_CONFIG_BAR_OFFSET, data, &mut self.queues, &mut self.device) + self.common_config.read( + o - COMMON_CONFIG_BAR_OFFSET, + data, + &mut self.queues, + &mut self.device, + ) } o if ISR_CONFIG_BAR_OFFSET <= o && o < ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE => { if let Some(v) = data.get_mut(0) { @@ -364,8 +367,12 @@ impl PciDevice for VirtioPciDevice { o if COMMON_CONFIG_BAR_OFFSET <= o && o < COMMON_CONFIG_BAR_OFFSET + COMMON_CONFIG_SIZE => { - self.common_config - .write(o - COMMON_CONFIG_BAR_OFFSET, data, &mut self.queues, &mut self.device) + self.common_config.write( + o - COMMON_CONFIG_BAR_OFFSET, + data, + &mut self.queues, + &mut self.device, + ) } o if ISR_CONFIG_BAR_OFFSET <= o && o < ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE => { if let Some(v) = data.get(0) { diff --git a/devices/src/virtio/wl.rs b/devices/src/virtio/wl.rs index 7c6ae58..e1a9025 100644 --- a/devices/src/virtio/wl.rs +++ b/devices/src/virtio/wl.rs @@ -30,41 +30,43 @@ use std::cell::RefCell; use std::collections::btree_map::Entry; -use std::collections::{BTreeSet as Set, BTreeMap as Map, VecDeque}; +use std::collections::{BTreeMap as Map, BTreeSet as Set, VecDeque}; use std::convert::From; -use std::ffi::CStr; use std::error::{self, Error as StdError}; +use std::ffi::CStr; use std::fmt; use std::fs::File; -use std::io::{self, Seek, SeekFrom, Read}; +use std::io::{self, Read, Seek, SeekFrom}; use std::mem::{size_of, size_of_val}; #[cfg(feature = "wl-dmabuf")] use std::os::raw::{c_uint, c_ulonglong}; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::net::{UnixDatagram, UnixStream}; -use std::path::{PathBuf, Path}; +use std::path::{Path, PathBuf}; use std::rc::Rc; use std::result; -use std::sync::Arc; use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; use std::thread; use std::time::Duration; #[cfg(feature = "wl-dmabuf")] use libc::{dup, EBADF, EINVAL}; -use data_model::*; use data_model::VolatileMemoryError; +use data_model::*; use resources::GpuMemoryDesc; -use sys_util::{Error, Result, EventFd, ScmSocket, SharedMemory, GuestAddress, GuestMemory, - GuestMemoryError, PollContext, PollToken, FileFlags, pipe, round_up_to_page_size}; +use sys_util::{ + pipe, round_up_to_page_size, Error, EventFd, FileFlags, GuestAddress, GuestMemory, + GuestMemoryError, PollContext, PollToken, Result, ScmSocket, SharedMemory, +}; #[cfg(feature = "wl-dmabuf")] use sys_util::ioctl_with_ref; -use vm_control::{VmControlError, VmRequest, VmResponse, MaybeOwnedFd}; -use super::{VirtioDevice, Queue, DescriptorChain, INTERRUPT_STATUS_USED_RING, TYPE_WL}; +use super::{DescriptorChain, Queue, VirtioDevice, INTERRUPT_STATUS_USED_RING, TYPE_WL}; +use vm_control::{MaybeOwnedFd, VmControlError, VmRequest, VmResponse}; const VIRTWL_SEND_MAX_ALLOCS: usize = 28; const VIRTIO_WL_CMD_VFD_NEW: u32 = 256; @@ -122,33 +124,41 @@ fn parse_new(addr: GuestAddress, mem: &GuestMemory) -> WlResult<WlOp> { const FLAGS_OFFSET: u64 = 12; const SIZE_OFFSET: u64 = 24; - let id: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, ID_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let flags: Le32 = - mem.read_obj_from_addr(mem.checked_offset(addr, FLAGS_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let size: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, SIZE_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; + let id: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, ID_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let flags: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, FLAGS_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let size: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, SIZE_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; Ok(WlOp::NewAlloc { - id: id.into(), - flags: flags.into(), - size: size.into(), - }) + id: id.into(), + flags: flags.into(), + size: size.into(), + }) } fn parse_new_pipe(addr: GuestAddress, mem: &GuestMemory) -> WlResult<WlOp> { const ID_OFFSET: u64 = 8; const FLAGS_OFFSET: u64 = 12; - let id: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, ID_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let flags: Le32 = - mem.read_obj_from_addr(mem.checked_offset(addr, FLAGS_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; + let id: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, ID_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let flags: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, FLAGS_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; Ok(WlOp::NewPipe { - id: id.into(), - flags: flags.into(), - }) + id: id.into(), + flags: flags.into(), + }) } #[cfg(feature = "wl-dmabuf")] @@ -158,35 +168,46 @@ fn parse_new_dmabuf(addr: GuestAddress, mem: &GuestMemory) -> WlResult<WlOp> { const HEIGHT_OFFSET: u64 = 32; const FORMAT_OFFSET: u64 = 36; - let id: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, ID_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let width: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, WIDTH_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let height: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, HEIGHT_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let format: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, FORMAT_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; + let id: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, ID_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let width: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, WIDTH_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let height: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, HEIGHT_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let format: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, FORMAT_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; Ok(WlOp::NewDmabuf { - id: id.into(), - width: width.into(), - height: height.into(), - format: format.into(), - }) + id: id.into(), + width: width.into(), + height: height.into(), + format: format.into(), + }) } #[cfg(feature = "wl-dmabuf")] fn parse_dmabuf_sync(addr: GuestAddress, mem: &GuestMemory) -> WlResult<WlOp> { const ID_OFFSET: u64 = 8; const FLAGS_OFFSET: u64 = 12; - let id: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, ID_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let flags: Le32 = - mem.read_obj_from_addr(mem.checked_offset(addr, FLAGS_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; + let id: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, ID_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let flags: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, FLAGS_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; Ok(WlOp::DmabufSync { - id: id.into(), - flags: flags.into(), - }) + id: id.into(), + flags: flags.into(), + }) } fn parse_send(addr: GuestAddress, len: u32, mem: &GuestMemory) -> WlResult<WlOp> { @@ -194,29 +215,36 @@ fn parse_send(addr: GuestAddress, len: u32, mem: &GuestMemory) -> WlResult<WlOp> const VFD_COUNT_OFFSET: u64 = 12; const VFDS_OFFSET: u64 = 16; - let id: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, ID_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; - let vfd_count: Le32 = - mem.read_obj_from_addr(mem.checked_offset(addr, VFD_COUNT_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; + let id: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, ID_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; + let vfd_count: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, VFD_COUNT_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; let vfd_count: u32 = vfd_count.into(); - let vfds_addr = mem.checked_offset(addr, VFDS_OFFSET) + let vfds_addr = mem + .checked_offset(addr, VFDS_OFFSET) .ok_or(WlError::CheckedOffset)?; - let data_addr = mem.checked_offset(vfds_addr, (vfd_count * 4) as u64) + let data_addr = mem + .checked_offset(vfds_addr, (vfd_count * 4) as u64) .ok_or(WlError::CheckedOffset)?; Ok(WlOp::Send { - id: id.into(), - vfds_addr: vfds_addr, - vfd_count: vfd_count, - data_addr: data_addr, - data_len: len - (VFDS_OFFSET as u32) - vfd_count * 4, - }) + id: id.into(), + vfds_addr, + vfd_count, + data_addr, + data_len: len - (VFDS_OFFSET as u32) - vfd_count * 4, + }) } fn parse_id(addr: GuestAddress, mem: &GuestMemory) -> WlResult<u32> { const ID_OFFSET: u64 = 8; - let id: Le32 = mem.read_obj_from_addr(mem.checked_offset(addr, ID_OFFSET) - .ok_or(WlError::CheckedOffset)?)?; + let id: Le32 = mem.read_obj_from_addr( + mem.checked_offset(addr, ID_OFFSET) + .ok_or(WlError::CheckedOffset)?, + )?; Ok(id.into()) } @@ -224,9 +252,13 @@ fn parse_desc(desc: &DescriptorChain, mem: &GuestMemory) -> WlResult<WlOp> { let type_: Le32 = mem.read_obj_from_addr(desc.addr)?; match type_.into() { VIRTIO_WL_CMD_VFD_NEW => parse_new(desc.addr, mem), - VIRTIO_WL_CMD_VFD_CLOSE => Ok(WlOp::Close { id: parse_id(desc.addr, mem)? }), + VIRTIO_WL_CMD_VFD_CLOSE => Ok(WlOp::Close { + id: parse_id(desc.addr, mem)?, + }), VIRTIO_WL_CMD_VFD_SEND => parse_send(desc.addr, desc.len, mem), - VIRTIO_WL_CMD_VFD_NEW_CTX => Ok(WlOp::NewCtx { id: parse_id(desc.addr, mem)? }), + VIRTIO_WL_CMD_VFD_NEW_CTX => Ok(WlOp::NewCtx { + id: parse_id(desc.addr, mem)?, + }), VIRTIO_WL_CMD_VFD_NEW_PIPE => parse_new_pipe(desc.addr, mem), #[cfg(feature = "wl-dmabuf")] VIRTIO_WL_CMD_VFD_NEW_DMABUF => parse_new_dmabuf(desc.addr, mem), @@ -236,20 +268,21 @@ fn parse_desc(desc: &DescriptorChain, mem: &GuestMemory) -> WlResult<WlOp> { } } -fn encode_vfd_new(desc_mem: VolatileSlice, - resp: bool, - vfd_id: u32, - flags: u32, - pfn: u64, - size: u32) - -> WlResult<u32> { +fn encode_vfd_new( + desc_mem: VolatileSlice, + resp: bool, + vfd_id: u32, + flags: u32, + pfn: u64, + size: u32, +) -> WlResult<u32> { let ctrl_vfd_new = CtrlVfdNew { hdr: CtrlHeader { type_: Le32::from(if resp { - VIRTIO_WL_RESP_VFD_NEW - } else { - VIRTIO_WL_CMD_VFD_NEW - }), + VIRTIO_WL_RESP_VFD_NEW + } else { + VIRTIO_WL_CMD_VFD_NEW + }), flags: Le32::from(0), }, id: Le32::from(vfd_id), @@ -263,13 +296,14 @@ fn encode_vfd_new(desc_mem: VolatileSlice, } #[cfg(feature = "wl-dmabuf")] -fn encode_vfd_new_dmabuf(desc_mem: VolatileSlice, - vfd_id: u32, - flags: u32, - pfn: u64, - size: u32, - desc: GpuMemoryDesc) - -> WlResult<u32> { +fn encode_vfd_new_dmabuf( + desc_mem: VolatileSlice, + vfd_id: u32, + flags: u32, + pfn: u64, + size: u32, + desc: GpuMemoryDesc, +) -> WlResult<u32> { let ctrl_vfd_new_dmabuf = CtrlVfdNewDmabuf { hdr: CtrlHeader { type_: Le32::from(VIRTIO_WL_RESP_VFD_NEW_DMABUF), @@ -294,11 +328,12 @@ fn encode_vfd_new_dmabuf(desc_mem: VolatileSlice, Ok(size_of::<CtrlVfdNewDmabuf>() as u32) } -fn encode_vfd_recv(desc_mem: VolatileSlice, - vfd_id: u32, - data: &[u8], - vfd_ids: &[u32]) - -> WlResult<u32> { +fn encode_vfd_recv( + desc_mem: VolatileSlice, + vfd_id: u32, + data: &[u8], + vfd_ids: &[u32], +) -> WlResult<u32> { let ctrl_vfd_recv = CtrlVfdRecv { hdr: CtrlHeader { type_: Le32::from(VIRTIO_WL_CMD_VFD_RECV), @@ -309,18 +344,20 @@ fn encode_vfd_recv(desc_mem: VolatileSlice, }; desc_mem.get_ref(0)?.store(ctrl_vfd_recv); - let vfd_slice = desc_mem - .get_slice(size_of::<CtrlVfdRecv>() as u64, - (vfd_ids.len() * size_of::<Le32>()) as u64)?; + let vfd_slice = desc_mem.get_slice( + size_of::<CtrlVfdRecv>() as u64, + (vfd_ids.len() * size_of::<Le32>()) as u64, + )?; for (i, &recv_vfd_id) in vfd_ids.iter().enumerate() { vfd_slice .get_ref((size_of::<Le32>() * i) as u64)? .store(recv_vfd_id); } - let data_slice = desc_mem - .get_slice((size_of::<CtrlVfdRecv>() + vfd_ids.len() * size_of::<Le32>()) as u64, - data.len() as u64)?; + let data_slice = desc_mem.get_slice( + (size_of::<CtrlVfdRecv>() + vfd_ids.len() * size_of::<Le32>()) as u64, + data.len() as u64, + )?; data_slice.copy_from(data); Ok((size_of::<CtrlVfdRecv>() + vfd_ids.len() * size_of::<Le32>() + data.len()) as u32) @@ -435,7 +472,9 @@ struct VmRequester { impl VmRequester { fn new(vm_socket: UnixDatagram) -> VmRequester { - VmRequester { inner: Rc::new(RefCell::new(vm_socket)) } + VmRequester { + inner: Rc::new(RefCell::new(vm_socket)), + } } fn request(&self, request: VmRequest) -> WlResult<VmResponse> { @@ -509,8 +548,14 @@ unsafe impl DataInit for CtrlVfd {} #[derive(Debug)] enum WlOp { - NewAlloc { id: u32, flags: u32, size: u32 }, - Close { id: u32 }, + NewAlloc { + id: u32, + flags: u32, + size: u32, + }, + Close { + id: u32, + }, Send { id: u32, vfds_addr: GuestAddress, @@ -518,13 +563,28 @@ enum WlOp { data_addr: GuestAddress, data_len: u32, }, - NewCtx { id: u32 }, - NewPipe { id: u32, flags: u32 }, + NewCtx { + id: u32, + }, + NewPipe { + id: u32, + flags: u32, + }, #[cfg(feature = "wl-dmabuf")] - NewDmabuf { id: u32, width: u32, height: u32, format: u32 }, + NewDmabuf { + id: u32, + width: u32, + height: u32, + format: u32, + }, #[cfg(feature = "wl-dmabuf")] - DmabufSync { id: u32, flags: u32 }, - InvalidCommand { op_type: u32 }, + DmabufSync { + id: u32, + flags: u32, + }, + InvalidCommand { + op_type: u32, + }, } #[derive(Debug)] @@ -553,7 +613,9 @@ enum WlResp<'a> { data: &'a [u8], vfds: &'a [u32], }, - VfdHup { id: u32 }, + VfdHup { + id: u32, + }, Err(Box<error::Error>), OutOfMemory, InvalidId, @@ -619,8 +681,7 @@ impl fmt::Debug for WlVfd { impl WlVfd { fn connect<P: AsRef<Path>>(path: P) -> WlResult<WlVfd> { - let socket = UnixStream::connect(path) - .map_err(WlError::SocketConnect)?; + let socket = UnixStream::connect(path).map_err(WlError::SocketConnect)?; socket .set_nonblocking(true) .map_err(WlError::SocketNonBlock)?; @@ -631,15 +692,16 @@ impl WlVfd { fn allocate(vm: VmRequester, size: u64) -> WlResult<WlVfd> { let size_page_aligned = round_up_to_page_size(size as usize) as u64; - let mut vfd_shm = SharedMemory::new(Some(CStr::from_bytes_with_nul(b"virtwl_alloc\0") - .unwrap())) + let mut vfd_shm = + SharedMemory::new(Some(CStr::from_bytes_with_nul(b"virtwl_alloc\0").unwrap())) .map_err(WlError::NewAlloc)?; vfd_shm .set_size(size_page_aligned) .map_err(WlError::AllocSetSize)?; - let register_response = - vm.request(VmRequest::RegisterMemory(MaybeOwnedFd::Borrowed(vfd_shm.as_raw_fd()), - vfd_shm.size() as usize))?; + let register_response = vm.request(VmRequest::RegisterMemory( + MaybeOwnedFd::Borrowed(vfd_shm.as_raw_fd()), + vfd_shm.size() as usize, + ))?; match register_response { VmResponse::RegisterMemory { pfn, slot } => { let mut vfd = WlVfd::default(); @@ -652,14 +714,25 @@ impl WlVfd { } #[cfg(feature = "wl-dmabuf")] - fn dmabuf(vm: VmRequester, width: u32, height: u32, format: u32) -> - WlResult<(WlVfd, GpuMemoryDesc)> { + fn dmabuf( + vm: VmRequester, + width: u32, + height: u32, + format: u32, + ) -> WlResult<(WlVfd, GpuMemoryDesc)> { let allocate_and_register_gpu_memory_response = - vm.request(VmRequest::AllocateAndRegisterGpuMemory { width: width, - height: height, - format: format })?; + vm.request(VmRequest::AllocateAndRegisterGpuMemory { + width, + height, + format, + })?; match allocate_and_register_gpu_memory_response { - VmResponse::AllocateAndRegisterGpuMemory { fd, pfn, slot, desc } => { + VmResponse::AllocateAndRegisterGpuMemory { + fd, + pfn, + slot, + desc, + } => { let mut vfd = WlVfd::default(); // Duplicate FD for shared memory instance. let raw_fd = unsafe { File::from_raw_fd(dup(fd.as_raw_fd())) }; @@ -691,7 +764,7 @@ impl WlVfd { Ok(()) } } - None => Err(WlError::DmabufSync(io::Error::from_raw_os_error(EBADF))) + None => Err(WlError::DmabufSync(io::Error::from_raw_os_error(EBADF))), } } @@ -720,9 +793,10 @@ impl WlVfd { match fd.seek(SeekFrom::End(0)) { Ok(fd_size) => { let size = round_up_to_page_size(fd_size as usize) as u64; - let register_response = - vm.request(VmRequest::RegisterMemory(MaybeOwnedFd::Borrowed(fd.as_raw_fd()), - size as usize))?; + let register_response = vm.request(VmRequest::RegisterMemory( + MaybeOwnedFd::Borrowed(fd.as_raw_fd()), + size as usize, + ))?; match register_response { VmResponse::RegisterMemory { pfn, slot } => { @@ -792,26 +866,20 @@ impl WlVfd { self.socket .as_ref() .map(|s| s as &AsRawFd) - .or(self.local_pipe - .as_ref() - .map(|&(_, ref p)| p as &AsRawFd)) - + .or(self.local_pipe.as_ref().map(|&(_, ref p)| p as &AsRawFd)) } // Sends data/files from the guest to the host over this VFD. fn send(&mut self, fds: &[RawFd], data: VolatileSlice) -> WlResult<WlResp> { if let Some(ref socket) = self.socket { - socket - .send_with_fds(data, fds) - .map_err(WlError::SendVfd)?; + socket.send_with_fds(data, fds).map_err(WlError::SendVfd)?; Ok(WlResp::Ok) } else if let Some((_, ref mut local_pipe)) = self.local_pipe { // Impossible to send fds over a simple pipe. if !fds.is_empty() { return Ok(WlResp::InvalidType); } - data.write_all_to(local_pipe) - .map_err(WlError::WritePipe)?; + data.write_all_to(local_pipe).map_err(WlError::WritePipe)?; Ok(WlResp::Ok) } else { Ok(WlResp::InvalidType) @@ -834,18 +902,18 @@ impl WlVfd { self.socket = Some(socket); // Safe because the first file_counts fds from recv_with_fds are owned by us and // valid. - in_file_queue.extend(fd_buf[..file_count] - .iter() - .map(|&fd| unsafe { File::from_raw_fd(fd) })); + in_file_queue.extend( + fd_buf[..file_count] + .iter() + .map(|&fd| unsafe { File::from_raw_fd(fd) }), + ); return Ok(buf); } Ok(Vec::new()) } else if let Some((flags, mut local_pipe)) = self.local_pipe.take() { let mut buf = Vec::new(); buf.resize(IN_BUFFER_LEN, 0); - let len = local_pipe - .read(&mut buf[..]) - .map_err(WlError::ReadPipe)?; + let len = local_pipe.read(&mut buf[..]).map_err(WlError::ReadPipe)?; if len != 0 { buf.truncate(len); buf.shrink_to_fit(); @@ -904,7 +972,7 @@ struct WlState { impl WlState { fn new(wayland_path: PathBuf, vm_socket: UnixDatagram, use_transition_flags: bool) -> WlState { WlState { - wayland_path: wayland_path, + wayland_path, vm: VmRequester::new(vm_socket), poll_ctx: PollContext::new().expect("failed to create PollContext"), use_transition_flags, @@ -943,7 +1011,7 @@ impl WlState { .add(vfd.poll_fd().unwrap(), id) .map_err(WlError::PollContextAdd)?; let resp = WlResp::VfdNew { - id: id, + id, flags: 0, pfn: 0, size: 0, @@ -973,7 +1041,7 @@ impl WlState { Entry::Vacant(entry) => { let vfd = WlVfd::allocate(self.vm.clone(), size as u64)?; let resp = WlResp::VfdNew { - id: id, + id, flags, pfn: vfd.pfn().unwrap_or_default(), size: vfd.size().unwrap_or_default() as u32, @@ -994,12 +1062,9 @@ impl WlState { match self.vfds.entry(id) { Entry::Vacant(entry) => { - let (vfd, desc) = WlVfd::dmabuf(self.vm.clone(), - width, - height, - format)?; + let (vfd, desc) = WlVfd::dmabuf(self.vm.clone(), width, height, format)?; let resp = WlResp::VfdNewDmabuf { - id: id, + id, flags: 0, pfn: vfd.pfn().unwrap_or_default(), size: vfd.size().unwrap_or_default() as u32, @@ -1019,7 +1084,7 @@ impl WlState { } match self.vfds.get_mut(&vfd_id) { - Some(vfd) => { + Some(vfd) => { vfd.dmabuf_sync(flags)?; Ok(WlResp::Ok) } @@ -1045,12 +1110,12 @@ impl WlState { .add(vfd.poll_fd().unwrap(), id) .map_err(WlError::PollContextAdd)?; Ok(WlResp::VfdNew { - id: id, - flags, - pfn: 0, - size: 0, - resp: true, - }) + id, + flags, + pfn: 0, + size: 0, + resp: true, + }) } Entry::Occupied(_) => Ok(WlResp::InvalidId), } @@ -1114,23 +1179,19 @@ impl WlState { let mut fds = [0; VIRTWL_SEND_MAX_ALLOCS]; for (&id, fd) in vfd_ids[..vfd_count].iter().zip(fds.iter_mut()) { match self.vfds.get(&id.into()) { - Some(vfd) => { - match vfd.send_fd() { - Some(vfd_fd) => *fd = vfd_fd, - None => return Ok(WlResp::InvalidType), - } - } + Some(vfd) => match vfd.send_fd() { + Some(vfd_fd) => *fd = vfd_fd, + None => return Ok(WlResp::InvalidType), + }, None => return Ok(WlResp::InvalidId), } } match self.vfds.get_mut(&vfd_id) { - Some(vfd) => { - match vfd.send(&fds[..vfd_count], data)? { - WlResp::Ok => {} - _ => return Ok(WlResp::InvalidType), - } - } + Some(vfd) => match vfd.send(&fds[..vfd_count], data)? { + WlResp::Ok => {} + _ => return Ok(WlResp::InvalidType), + }, None => return Ok(WlResp::InvalidId), } // The vfds with remote FDs need to be closed so that the local side can receive @@ -1160,12 +1221,15 @@ impl WlState { .map_err(WlError::PollContextAdd)?; } self.vfds.insert(self.next_vfd_id, vfd); - self.in_queue - .push_back((vfd_id, WlRecv::Vfd { id: self.next_vfd_id })); + self.in_queue.push_back(( + vfd_id, + WlRecv::Vfd { + id: self.next_vfd_id, + }, + )); self.next_vfd_id += 1; } - self.in_queue - .push_back((vfd_id, WlRecv::Data { buf: buf })); + self.in_queue.push_back((vfd_id, WlRecv::Data { buf })); Ok(()) } @@ -1189,7 +1253,12 @@ impl WlState { WlOp::NewCtx { id } => self.new_context(id), WlOp::NewPipe { id, flags } => self.new_pipe(id, flags), #[cfg(feature = "wl-dmabuf")] - WlOp::NewDmabuf { id, width, height, format } => self.new_dmabuf(id, width, height, format), + WlOp::NewDmabuf { + id, + width, + height, + format, + } => self.new_dmabuf(id, width, height, format), #[cfg(feature = "wl-dmabuf")] WlOp::DmabufSync { id, flags } => self.dmabuf_sync(id, flags), WlOp::InvalidCommand { op_type } => { @@ -1205,53 +1274,48 @@ impl WlState { &(vfd_id, WlRecv::Vfd { id }) => { if self.current_recv_vfd.is_none() || self.current_recv_vfd == Some(vfd_id) { match self.vfds.get(&id) { - Some(vfd) => { - Some(WlResp::VfdNew { - id: id, - flags: vfd.flags(self.use_transition_flags), - pfn: vfd.pfn().unwrap_or_default(), - size: vfd.size().unwrap_or_default() as u32, - resp: false, - }) - } - _ => { - Some(WlResp::VfdNew { - id: id, - flags: 0, - pfn: 0, - size: 0, - resp: false, - }) - } + Some(vfd) => Some(WlResp::VfdNew { + id, + flags: vfd.flags(self.use_transition_flags), + pfn: vfd.pfn().unwrap_or_default(), + size: vfd.size().unwrap_or_default() as u32, + resp: false, + }), + _ => Some(WlResp::VfdNew { + id, + flags: 0, + pfn: 0, + size: 0, + resp: false, + }), } } else { Some(WlResp::VfdRecv { - id: self.current_recv_vfd.unwrap(), - data: &[], - vfds: &self.recv_vfds[..], - }) + id: self.current_recv_vfd.unwrap(), + data: &[], + vfds: &self.recv_vfds[..], + }) } } &(vfd_id, WlRecv::Data { ref buf }) => { if self.current_recv_vfd.is_none() || self.current_recv_vfd == Some(vfd_id) { Some(WlResp::VfdRecv { - id: vfd_id, - data: &buf[..], - vfds: &self.recv_vfds[..], - }) + id: vfd_id, + data: &buf[..], + vfds: &self.recv_vfds[..], + }) } else { Some(WlResp::VfdRecv { - id: self.current_recv_vfd.unwrap(), - data: &[], - vfds: &self.recv_vfds[..], - }) + id: self.current_recv_vfd.unwrap(), + data: &[], + vfds: &self.recv_vfds[..], + }) } } &(vfd_id, WlRecv::Hup) => Some(WlResp::VfdHup { id: vfd_id }), } } else { None - } } @@ -1296,21 +1360,22 @@ struct Worker { } impl Worker { - fn new(mem: GuestMemory, - interrupt_evt: EventFd, - interrupt_status: Arc<AtomicUsize>, - in_queue: Queue, - out_queue: Queue, - wayland_path: PathBuf, - vm_socket: UnixDatagram, - use_transition_flags: bool) - -> Worker { + fn new( + mem: GuestMemory, + interrupt_evt: EventFd, + interrupt_status: Arc<AtomicUsize>, + in_queue: Queue, + out_queue: Queue, + wayland_path: PathBuf, + vm_socket: UnixDatagram, + use_transition_flags: bool, + ) -> Worker { Worker { - mem: mem, - interrupt_evt: interrupt_evt, - interrupt_status: interrupt_status, - in_queue: in_queue, - out_queue: out_queue, + mem, + interrupt_evt, + interrupt_status, + in_queue, + out_queue, state: WlState::new(wayland_path, vm_socket, use_transition_flags), in_desc_chains: VecDeque::with_capacity(QUEUE_SIZE as usize), } @@ -1333,18 +1398,18 @@ impl Worker { State, } - let poll_ctx: PollContext<Token> = - match PollContext::new() - .and_then(|pc| pc.add(&in_queue_evt, Token::InQueue).and(Ok(pc))) - .and_then(|pc| pc.add(&out_queue_evt, Token::OutQueue).and(Ok(pc))) - .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) - .and_then(|pc| pc.add(&self.state.poll_ctx, Token::State).and(Ok(pc))) { - Ok(pc) => pc, - Err(e) => { - error!("failed creating PollContext: {:?}", e); - return; - } - }; + let poll_ctx: PollContext<Token> = match PollContext::new() + .and_then(|pc| pc.add(&in_queue_evt, Token::InQueue).and(Ok(pc))) + .and_then(|pc| pc.add(&out_queue_evt, Token::OutQueue).and(Ok(pc))) + .and_then(|pc| pc.add(&kill_evt, Token::Kill).and(Ok(pc))) + .and_then(|pc| pc.add(&self.state.poll_ctx, Token::State).and(Ok(pc))) + { + Ok(pc) => pc, + Err(e) => { + error!("failed creating PollContext: {:?}", e); + return; + } + }; 'poll: loop { let mut signal_used = false; @@ -1363,10 +1428,11 @@ impl Worker { // Used to buffer descriptor indexes that are invalid for our uses. let mut rejects = [0u16; QUEUE_SIZE as usize]; let mut rejects_len = 0; - let min_in_desc_len = (size_of::<CtrlVfdRecv>() + - size_of::<Le32>() * VIRTWL_SEND_MAX_ALLOCS) as - u32; - self.in_desc_chains.extend(self.in_queue.iter(&self.mem).filter_map(|d| { + let min_in_desc_len = (size_of::<CtrlVfdRecv>() + + size_of::<Le32>() * VIRTWL_SEND_MAX_ALLOCS) + as u32; + self.in_desc_chains + .extend(self.in_queue.iter(&self.mem).filter_map(|d| { if d.len >= min_in_desc_len && d.is_write_only() { Some((d.index, d.addr, d.len)) } else { @@ -1395,23 +1461,23 @@ impl Worker { // one "out" descriptor. if !desc.is_write_only() { if let Some(resp_desc) = desc.next_descriptor() { - if resp_desc.is_write_only() && - resp_desc.len >= min_resp_desc_len { + if resp_desc.is_write_only() + && resp_desc.len >= min_resp_desc_len + { let resp = match parse_desc(&desc, &self.mem) { - Ok(op) => { - match self.state.execute(&self.mem, op) { - Ok(r) => r, - Err(e) => WlResp::Err(Box::new(e)), - } - } + Ok(op) => match self.state.execute(&self.mem, op) { + Ok(r) => r, + Err(e) => WlResp::Err(Box::new(e)), + }, Err(e) => WlResp::Err(Box::new(e)), }; - let resp_mem = self.mem + let resp_mem = self + .mem .get_slice(resp_desc.addr.0, resp_desc.len as u64) .unwrap(); - let used_len = encode_resp(resp_mem, resp) - .unwrap_or_default(); + let used_len = + encode_resp(resp_mem, resp).unwrap_or_default(); used_descs[used_descs_len] = (desc.index, used_len); } @@ -1483,11 +1549,11 @@ impl Wl { // let kill_evt = EventFd::new()?; // workers_kill_evt: Some(kill_evt.try_clone()?), Ok(Wl { - kill_evt: None, - wayland_path: wayland_path.as_ref().to_owned(), - vm_socket: Some(vm_socket), - use_transition_flags: false, - }) + kill_evt: None, + wayland_path: wayland_path.as_ref().to_owned(), + vm_socket: Some(vm_socket), + use_transition_flags: false, + }) } } @@ -1532,42 +1598,45 @@ impl VirtioDevice for Wl { } } - fn activate(&mut self, - mem: GuestMemory, - interrupt_evt: EventFd, - status: Arc<AtomicUsize>, - mut queues: Vec<Queue>, - queue_evts: Vec<EventFd>) { + fn activate( + &mut self, + mem: GuestMemory, + interrupt_evt: EventFd, + status: Arc<AtomicUsize>, + mut queues: Vec<Queue>, + queue_evts: Vec<EventFd>, + ) { if queues.len() != QUEUE_SIZES.len() || queue_evts.len() != QUEUE_SIZES.len() { return; } - let (self_kill_evt, kill_evt) = - match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { - Ok(v) => v, - Err(e) => { - error!("failed creating kill EventFd pair: {:?}", e); - return; - } - }; + let (self_kill_evt, kill_evt) = match EventFd::new().and_then(|e| Ok((e.try_clone()?, e))) { + Ok(v) => v, + Err(e) => { + error!("failed creating kill EventFd pair: {:?}", e); + return; + } + }; self.kill_evt = Some(self_kill_evt); if let Some(vm_socket) = self.vm_socket.take() { let wayland_path = self.wayland_path.clone(); let use_transition_flags = self.use_transition_flags; - let worker_result = thread::Builder::new() - .name("virtio_wl".to_string()) - .spawn(move || { - Worker::new(mem, - interrupt_evt, - status, - queues.remove(0), - queues.remove(0), - wayland_path, - vm_socket, - use_transition_flags) - .run(queue_evts, kill_evt); - }); + let worker_result = + thread::Builder::new() + .name("virtio_wl".to_string()) + .spawn(move || { + Worker::new( + mem, + interrupt_evt, + status, + queues.remove(0), + queues.remove(0), + wayland_path, + vm_socket, + use_transition_flags, + ).run(queue_evts, kill_evt); + }); if let Err(e) = worker_result { error!("failed to spawn virtio_wl worker: {}", e); diff --git a/gpu_buffer/src/lib.rs b/gpu_buffer/src/lib.rs index aa57ea9..e57053d 100644 --- a/gpu_buffer/src/lib.rs +++ b/gpu_buffer/src/lib.rs @@ -34,9 +34,9 @@ extern crate data_model; #[macro_use] extern crate sys_util; -pub mod rendernode; -mod raw; mod drm_formats; +mod raw; +pub mod rendernode; use std::cmp::min; use std::fmt; @@ -48,10 +48,10 @@ use std::ptr::null_mut; use std::rc::Rc; use std::result::Result; -use data_model::{VolatileSlice, VolatileMemory, VolatileMemoryError}; +use data_model::{VolatileMemory, VolatileMemoryError, VolatileSlice}; -use raw::*; use drm_formats::*; +use raw::*; const MAP_FAILED: *mut c_void = (-1isize as *mut _); @@ -84,28 +84,20 @@ impl fmt::Display for Error { field1: (label1, value1), field2: (label2, value2), op, - } => { - write!(f, - "arithmetic failed: {}({}) {} {}({})", - label1, - value1, - op, - label2, - value2) - } + } => write!( + f, + "arithmetic failed: {}({}) {} {}({})", + label1, value1, op, label2, value2 + ), Error::InvalidPrecondition { field1: (label1, value1), field2: (label2, value2), op, - } => { - write!(f, - "invalid precondition: {}({}) {} {}({})", - label1, - value1, - op, - label2, - value2) - } + } => write!( + f, + "invalid precondition: {}({}) {} {}({})", + label1, value1, op, label2, value2 + ), Error::UnknownFormat(format) => write!(f, "unknown format {:?}", format), Error::Memcopy(ref e) => write!(f, "error copying memory: {}", e), } @@ -113,29 +105,39 @@ impl fmt::Display for Error { } macro_rules! checked_arithmetic { - ($x:ident $op:ident $y:ident $op_name:expr) => ($x.$op($y).ok_or_else(|| - Error::CheckedArithmetic { + ($x:ident $op:ident $y:ident $op_name:expr) => { + $x.$op($y).ok_or_else(|| Error::CheckedArithmetic { field1: (stringify!($x), $x as usize), field2: (stringify!($y), $y as usize), op: $op_name, - } - )); - ($x:ident + $y:ident) => (checked_arithmetic!($x checked_add $y "+")); - ($x:ident - $y:ident) => (checked_arithmetic!($x checked_sub $y "-")); - ($x:ident * $y:ident) => (checked_arithmetic!($x checked_mul $y "*")); + }) + }; + ($x:ident + $y:ident) => { + checked_arithmetic!($x checked_add $y "+") + }; + ($x:ident - $y:ident) => { + checked_arithmetic!($x checked_sub $y "-") + }; + ($x:ident * $y:ident) => { + checked_arithmetic!($x checked_mul $y "*") + }; } macro_rules! checked_range { - ($x:expr; <= $y:expr) => (if $x <= $y { + ($x:expr; <= $y:expr) => { + if $x <= $y { Ok(()) } else { Err(Error::InvalidPrecondition { field1: (stringify!($x), $x as usize), field2: (stringify!($y), $y as usize), - op: "<=" + op: "<=", }) - }); - ($x:ident <= $y:ident) => (check_range!($x; <= $y)); + } + }; + ($x:ident <= $y:ident) => { + check_range!($x; <= $y) + }; } /// A [fourcc](https://en.wikipedia.org/wiki/FourCC) format identifier. @@ -254,19 +256,17 @@ impl fmt::Debug for Format { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let b = self.to_bytes(); if b.iter().all(u8::is_ascii_graphic) { - write!(f, - "fourcc({}{}{}{})", - b[0] as char, - b[1] as char, - b[2] as char, - b[3] as char) + write!( + f, + "fourcc({}{}{}{})", + b[0] as char, b[1] as char, b[2] as char, b[3] as char + ) } else { - write!(f, - "fourcc(0x{:02x}{:02x}{:02x}{:02x})", - b[0], - b[1], - b[2], - b[3]) + write!( + f, + "fourcc(0x{:02x}{:02x}{:02x}{:02x})", + b[0], b[1], b[2], b[3] + ) } } } @@ -349,7 +349,6 @@ impl Flags { } } - struct DeviceInner { _fd: File, gbm: *mut gbm_device, @@ -383,12 +382,13 @@ impl Device { } /// Creates a new buffer with the given metadata. - pub fn create_buffer(&self, - width: u32, - height: u32, - format: Format, - usage: Flags) - -> Result<Buffer, Error> { + pub fn create_buffer( + &self, + width: u32, + height: u32, + format: Format, + usage: Flags, + ) -> Result<Buffer, Error> { // This is safe because only a valid gbm_device is used and the return value is checked. let bo = unsafe { gbm_bo_create(self.0.gbm, width, height, format.0, usage.0) }; if bo.is_null() { @@ -477,19 +477,21 @@ impl Buffer { } } - fn map(&self, - x: u32, - y: u32, - width: u32, - height: u32, - plane: usize, - flags: u32) - -> Result<BufferMapping, Error> { + fn map( + &self, + x: u32, + y: u32, + width: u32, + height: u32, + plane: usize, + flags: u32, + ) -> Result<BufferMapping, Error> { checked_range!(checked_arithmetic!(x + width)?; <= self.width())?; checked_range!(checked_arithmetic!(y + height)?; <= self.height())?; checked_range!(plane; <= self.num_planes())?; - let bytes_per_pixel = self.format() + let bytes_per_pixel = self + .format() .bytes_per_pixel(plane) .ok_or(Error::UnknownFormat(self.format()))? as u32; @@ -499,15 +501,17 @@ impl Buffer { // pointers coerced from stack references are used for returned values, and we trust gbm to // only write as many bytes as the size of the pointed to values. let mapping = unsafe { - gbm_bo_map(self.0, - x, - y, - width, - height, - flags, - &mut stride, - &mut map_data, - plane) + gbm_bo_map( + self.0, + x, + y, + width, + height, + flags, + &mut stride, + &mut map_data, + plane, + ) }; if mapping == MAP_FAILED { return Err(Error::MapFailed); @@ -541,14 +545,15 @@ impl Buffer { } /// Reads the given subsection of the buffer to `dst`. - pub fn read_to_volatile(&self, - x: u32, - y: u32, - width: u32, - height: u32, - plane: usize, - dst: VolatileSlice) - -> Result<(), Error> { + pub fn read_to_volatile( + &self, + x: u32, + y: u32, + width: u32, + height: u32, + plane: usize, + dst: VolatileSlice, + ) -> Result<(), Error> { if width == 0 || height == 0 { return Ok(()); } @@ -569,9 +574,11 @@ impl Buffer { let src = mapping.as_volatile_slice(); for yy in 0..(height as u64) { let line_offset = checked_arithmetic!(yy * stride)?; - let src_line = src.get_slice(line_offset, line_copy_size) + let src_line = src + .get_slice(line_offset, line_copy_size) .map_err(|e| Error::Memcopy(e))?; - let dst_line = dst.get_slice(line_offset, line_copy_size) + let dst_line = dst + .get_slice(line_offset, line_copy_size) .map_err(|e| Error::Memcopy(e))?; src_line.copy_to_volatile_slice(dst_line); } @@ -581,15 +588,16 @@ impl Buffer { } /// Writes to the given subsection of the buffer from `sgs`. - pub fn write_from_sg<'a, S: Iterator<Item = VolatileSlice<'a>>>(&self, - x: u32, - y: u32, - width: u32, - height: u32, - plane: usize, - src_offset: usize, - mut sgs: S) - -> Result<(), Error> { + pub fn write_from_sg<'a, S: Iterator<Item = VolatileSlice<'a>>>( + &self, + x: u32, + y: u32, + width: u32, + height: u32, + plane: usize, + src_offset: usize, + mut sgs: S, + ) -> Result<(), Error> { if width == 0 || height == 0 { return Ok(()); } @@ -617,7 +625,8 @@ impl Buffer { } }; let copy_sg_size = min(sg_size, copy_size); - let src_slice = sg.get_slice(src_offset, copy_sg_size) + let src_slice = sg + .get_slice(src_offset, copy_sg_size) .map_err(|e| Error::Memcopy(e))?; src_slice.copy_to_volatile_slice(dst_slice); @@ -651,7 +660,8 @@ impl Buffer { Some(sg_remaining_size) => sg_remaining_size, }; let copy_sg_size = min(sg_size, remaining_line_copy_size); - let src_slice = sg.get_slice(src_offset, copy_sg_size) + let src_slice = sg + .get_slice(src_offset, copy_sg_size) .map_err(|e| Error::Memcopy(e))?; src_slice.copy_to_volatile_slice(dst_slice); @@ -723,8 +733,8 @@ impl<'a> Drop for BufferMapping<'a> { #[cfg(test)] mod tests { use super::*; - use std::fmt::Write; use data_model::VolatileMemory; + use std::fmt::Write; #[test] fn format_debug() { @@ -774,11 +784,12 @@ mod tests { let drm_card = File::open("/dev/dri/card0").expect("failed to open card"); let device = Device::new(drm_card).expect("failed to create device with card"); let bo = device - .create_buffer(1024, - 512, - Format::new(b'X', b'R', b'2', b'4'), - Flags::empty().use_scanout(true)) - .expect("failed to create buffer"); + .create_buffer( + 1024, + 512, + Format::new(b'X', b'R', b'2', b'4'), + Flags::empty().use_scanout(true), + ).expect("failed to create buffer"); assert_eq!(bo.width(), 1024); assert_eq!(bo.height(), 512); @@ -792,46 +803,49 @@ mod tests { let drm_card = File::open("/dev/dri/card0").expect("failed to open card"); let device = Device::new(drm_card).expect("failed to create device with card"); let bo = device - .create_buffer(1024, - 1024, - Format::new(b'X', b'R', b'2', b'4'), - Flags::empty().use_scanout(true)) - .expect("failed to create buffer"); + .create_buffer( + 1024, + 1024, + Format::new(b'X', b'R', b'2', b'4'), + Flags::empty().use_scanout(true), + ).expect("failed to create buffer"); bo.export_plane_fd(0).expect("failed to export plane"); } - #[test] #[ignore] // no access to /dev/dri fn buffer_transfer() { let drm_card = File::open("/dev/dri/card0").expect("failed to open card"); let device = Device::new(drm_card).expect("failed to create device with card"); let bo = device - .create_buffer(1024, - 1024, - Format::new(b'X', b'R', b'2', b'4'), - Flags::empty().use_scanout(true).use_linear(true)) - .expect("failed to create buffer"); + .create_buffer( + 1024, + 1024, + Format::new(b'X', b'R', b'2', b'4'), + Flags::empty().use_scanout(true).use_linear(true), + ).expect("failed to create buffer"); let mut dst: Vec<u8> = Vec::new(); dst.resize((bo.stride() * bo.height()) as usize, 0x4A); let dst_len = dst.len() as u64; - bo.write_from_sg(0, - 0, - 1024, - 1024, - 0, - 0, - [dst.as_mut_slice().get_slice(0, dst_len).unwrap()] - .iter() - .cloned()) - .expect("failed to read bo"); - bo.read_to_volatile(0, - 0, - 1024, - 1024, - 0, - dst.as_mut_slice().get_slice(0, dst_len).unwrap()) - .expect("failed to read bo"); + bo.write_from_sg( + 0, + 0, + 1024, + 1024, + 0, + 0, + [dst.as_mut_slice().get_slice(0, dst_len).unwrap()] + .iter() + .cloned(), + ).expect("failed to read bo"); + bo.read_to_volatile( + 0, + 0, + 1024, + 1024, + 0, + dst.as_mut_slice().get_slice(0, dst_len).unwrap(), + ).expect("failed to read bo"); assert!(dst.iter().all(|&x| x == 0x4A)); } } diff --git a/gpu_buffer/src/raw.rs b/gpu_buffer/src/raw.rs index e5e258a..7fc5a9f 100644 --- a/gpu_buffer/src/raw.rs +++ b/gpu_buffer/src/raw.rs @@ -7,7 +7,7 @@ #![allow(dead_code)] -use std::os::raw::{c_int, c_char, c_void}; +use std::os::raw::{c_char, c_int, c_void}; /// \file gbm.h /// \brief Generic Buffer Manager @@ -96,23 +96,25 @@ extern "C" { pub fn gbm_device_is_format_supported(gbm: *mut gbm_device, format: u32, usage: u32) -> c_int; pub fn gbm_device_destroy(gbm: *mut gbm_device); pub fn gbm_create_device(fd: c_int) -> *mut gbm_device; - pub fn gbm_bo_create(gbm: *mut gbm_device, - width: u32, - height: u32, - format: u32, - flags: u32) - -> *mut gbm_bo; - pub fn gbm_bo_create_with_modifiers(gbm: *mut gbm_device, - width: u32, - height: u32, - format: u32, - modifiers: *const u64, - count: u32) - -> *mut gbm_bo; + pub fn gbm_bo_create( + gbm: *mut gbm_device, + width: u32, + height: u32, + format: u32, + flags: u32, + ) -> *mut gbm_bo; + pub fn gbm_bo_create_with_modifiers( + gbm: *mut gbm_device, + width: u32, + height: u32, + format: u32, + modifiers: *const u64, + count: u32, + ) -> *mut gbm_bo; } #[repr(C)] -#[derive(Debug, Copy, Clone )] +#[derive(Debug, Copy, Clone)] pub struct gbm_import_fd_data { pub fd: c_int, pub width: u32, @@ -122,7 +124,7 @@ pub struct gbm_import_fd_data { } #[repr(C)] -#[derive(Debug, Copy, Clone )] +#[derive(Debug, Copy, Clone)] pub struct gbm_import_fd_planar_data { pub fds: [c_int; 4usize], pub width: u32, @@ -134,11 +136,12 @@ pub struct gbm_import_fd_planar_data { } extern "C" { - pub fn gbm_bo_import(gbm: *mut gbm_device, - type_: u32, - buffer: *mut c_void, - usage: u32) - -> *mut gbm_bo; + pub fn gbm_bo_import( + gbm: *mut gbm_device, + type_: u32, + buffer: *mut c_void, + usage: u32, + ) -> *mut gbm_bo; } /// Buffer contents read back (or accessed directly) at transfer @@ -162,16 +165,17 @@ pub const GBM_BO_TRANSFER_READ_WRITE: gbm_bo_transfer_flags = 3; pub type gbm_bo_transfer_flags = u32; extern "C" { - pub fn gbm_bo_map(bo: *mut gbm_bo, - x: u32, - y: u32, - width: u32, - height: u32, - flags: u32, - stride: *mut u32, - map_data: *mut *mut c_void, - plane: usize) - -> *mut c_void; + pub fn gbm_bo_map( + bo: *mut gbm_bo, + x: u32, + y: u32, + width: u32, + height: u32, + flags: u32, + stride: *mut u32, + map_data: *mut *mut c_void, + plane: usize, + ) -> *mut c_void; pub fn gbm_bo_unmap(bo: *mut gbm_bo, map_data: *mut c_void); pub fn gbm_bo_get_width(bo: *mut gbm_bo) -> u32; pub fn gbm_bo_get_height(bo: *mut gbm_bo) -> u32; @@ -190,18 +194,20 @@ extern "C" { pub fn gbm_bo_get_plane_stride(bo: *mut gbm_bo, plane: usize) -> u32; pub fn gbm_bo_get_plane_format_modifier(bo: *mut gbm_bo, plane: usize) -> u64; // Did not generate cleanly by bindgen. Redone manually by zachr. - pub fn gbm_bo_set_user_data(bo: *mut gbm_bo, - data: *mut c_void, - destroy_user_data: extern "C" fn(bo: *mut gbm_bo, - data: *mut c_void)); + pub fn gbm_bo_set_user_data( + bo: *mut gbm_bo, + data: *mut c_void, + destroy_user_data: extern "C" fn(bo: *mut gbm_bo, data: *mut c_void), + ); pub fn gbm_bo_get_user_data(bo: *mut gbm_bo) -> *mut c_void; pub fn gbm_bo_destroy(bo: *mut gbm_bo); - pub fn gbm_surface_create(gbm: *mut gbm_device, - width: u32, - height: u32, - format: u32, - flags: u32) - -> *mut gbm_surface; + pub fn gbm_surface_create( + gbm: *mut gbm_device, + width: u32, + height: u32, + format: u32, + flags: u32, + ) -> *mut gbm_surface; pub fn gbm_surface_lock_front_buffer(surface: *mut gbm_surface) -> *mut gbm_bo; pub fn gbm_surface_release_buffer(surface: *mut gbm_surface, bo: *mut gbm_bo); pub fn gbm_surface_has_free_buffers(surface: *mut gbm_surface) -> c_int; diff --git a/gpu_buffer/src/rendernode.rs b/gpu_buffer/src/rendernode.rs index f8b0201..2c4c51b 100644 --- a/gpu_buffer/src/rendernode.rs +++ b/gpu_buffer/src/rendernode.rs @@ -4,9 +4,9 @@ use std::ffi::CString; use std::fs::{File, OpenOptions}; -use std::os::raw::{c_char, c_int, c_uint}; #[cfg(target_pointer_width = "64")] use std::os::raw::c_ulong; +use std::os::raw::{c_char, c_int, c_uint}; use std::path::Path; use std::ptr::null_mut; @@ -76,11 +76,11 @@ fn get_drm_device_name(fd: &File) -> Result<String, ()> { } Ok(CString::new(&name_bytes[..(version.name_len as usize)]) - .map_err(|_| ())? - .into_string().map_err(|_| ())?) + .map_err(|_| ())? + .into_string() + .map_err(|_| ())?) } - /// Returns a `fd` for an opened rendernode device, while filtering out specified /// undesired drivers. pub fn open_device(undesired: &[&str]) -> Result<File, ()> { diff --git a/gpu_display/build.rs b/gpu_display/build.rs index a1ce4f7..33a8653 100644 --- a/gpu_display/build.rs +++ b/gpu_display/build.rs @@ -45,9 +45,11 @@ fn find_protocol(name: &str) -> PathBuf { // Use bundled protocols as a fallback. let protocol_path = Path::new("protocol").join(protocol_file_name); - assert!(protocol_path.is_file(), - "unable to locate wayland protocol specification for `{}`", - name); + assert!( + protocol_path.is_file(), + "unable to locate wayland protocol specification for `{}`", + name + ); protocol_path } @@ -84,10 +86,12 @@ fn main() { build.file("src/display_wl.c"); println!("cargo:rerun-if-changed=src/display_wl.c"); - for protocol in &["aura-shell", - "linux-dmabuf-unstable-v1", - "xdg-shell-unstable-v6", - "viewporter"] { + for protocol in &[ + "aura-shell", + "linux-dmabuf-unstable-v1", + "xdg-shell-unstable-v6", + "viewporter", + ] { build.file(compile_protocol(protocol, &out_dir)); } build.compile("display_wl"); diff --git a/gpu_display/src/dwl.rs b/gpu_display/src/dwl.rs index cbe337d..41751a7 100644 --- a/gpu_display/src/dwl.rs +++ b/gpu_display/src/dwl.rs @@ -1,6 +1,5 @@ /* automatically generated by rust-bindgen */ - /// @page page_xdg_shell_unstable_v6 The xdg_shell_unstable_v6 protocol /// @section page_ifaces_xdg_shell_unstable_v6 Interfaces /// - @subpage page_iface_zxdg_shell_v6 - create desktop-style surfaces @@ -61,9 +60,10 @@ extern "C" { pub fn dwl_context_destroy(self_: *mut *mut dwl_context); } extern "C" { - pub fn dwl_context_setup(self_: *mut dwl_context, - socket_path: *const ::std::os::raw::c_char) - -> bool; + pub fn dwl_context_setup( + self_: *mut dwl_context, + socket_path: *const ::std::os::raw::c_char, + ) -> bool; } extern "C" { pub fn dwl_context_fd(self_: *mut dwl_context) -> ::std::os::raw::c_int; @@ -72,29 +72,31 @@ extern "C" { pub fn dwl_context_dispatch(self_: *mut dwl_context); } extern "C" { - pub fn dwl_context_dmabuf_new(self_: *mut dwl_context, - fd: ::std::os::raw::c_int, - offset: u32, - stride: u32, - modifiers: u64, - width: u32, - height: u32, - fourcc: u32) - -> *mut dwl_dmabuf; + pub fn dwl_context_dmabuf_new( + self_: *mut dwl_context, + fd: ::std::os::raw::c_int, + offset: u32, + stride: u32, + modifiers: u64, + width: u32, + height: u32, + fourcc: u32, + ) -> *mut dwl_dmabuf; } extern "C" { pub fn dwl_dmabuf_destroy(self_: *mut *mut dwl_dmabuf); } extern "C" { - pub fn dwl_context_surface_new(self_: *mut dwl_context, - parent: *mut dwl_surface, - shm_fd: ::std::os::raw::c_int, - shm_size: usize, - buffer_size: usize, - width: u32, - height: u32, - stride: u32) - -> *mut dwl_surface; + pub fn dwl_context_surface_new( + self_: *mut dwl_context, + parent: *mut dwl_surface, + shm_fd: ::std::os::raw::c_int, + shm_size: usize, + buffer_size: usize, + width: u32, + height: u32, + stride: u32, + ) -> *mut dwl_surface; } extern "C" { pub fn dwl_surface_destroy(self_: *mut *mut dwl_surface); diff --git a/gpu_display/src/lib.rs b/gpu_display/src/lib.rs index 7ff116a..da9d473 100644 --- a/gpu_display/src/lib.rs +++ b/gpu_display/src/lib.rs @@ -16,8 +16,8 @@ use std::os::unix::io::{AsRawFd, RawFd}; use std::path::Path; use std::ptr::null_mut; -use data_model::{VolatileSlice, VolatileMemory}; -use sys_util::{Error as SysError, SharedMemory, MemoryMapping, round_up_to_page_size}; +use data_model::{VolatileMemory, VolatileSlice}; +use sys_util::{round_up_to_page_size, Error as SysError, MemoryMapping, SharedMemory}; use dwl::*; @@ -127,18 +127,18 @@ impl GpuDisplay { }, None => return Err(GpuDisplayError::InvalidPath), }; - let setup_success = unsafe { dwl_context_setup(ctx.0, cstr_path.as_ptr() ) }; + let setup_success = unsafe { dwl_context_setup(ctx.0, cstr_path.as_ptr()) }; if !setup_success { return Err(GpuDisplayError::Connect); } Ok(GpuDisplay { - ctx, - dmabufs: Default::default(), - dmabuf_next_id: 0, - surfaces: Default::default(), - surface_next_id: 0, - }) + ctx, + dmabufs: Default::default(), + dmabuf_next_id: 0, + surfaces: Default::default(), + surface_next_id: 0, + }) } fn ctx(&self) -> *mut dwl_context { @@ -150,28 +150,31 @@ impl GpuDisplay { } /// Imports a dmabuf to the compositor for use as a surface buffer and returns a handle to it. - pub fn import_dmabuf(&mut self, - fd: RawFd, - offset: u32, - stride: u32, - modifiers: u64, - width: u32, - height: u32, - fourcc: u32) - -> Result<u32, GpuDisplayError> { + pub fn import_dmabuf( + &mut self, + fd: RawFd, + offset: u32, + stride: u32, + modifiers: u64, + width: u32, + height: u32, + fourcc: u32, + ) -> Result<u32, GpuDisplayError> { // Safe given that the context pointer is valid. Any other invalid parameters would be // rejected by dwl_context_dmabuf_new safely. We check that the resulting dmabuf is valid // before filing it away. let dmabuf = DwlDmabuf(unsafe { - dwl_context_dmabuf_new(self.ctx(), - fd, - offset, - stride, - modifiers, - width, - height, - fourcc) - }); + dwl_context_dmabuf_new( + self.ctx(), + fd, + offset, + stride, + modifiers, + width, + height, + fourcc, + ) + }); if dmabuf.0.is_null() { return Err(GpuDisplayError::FailedImport); } @@ -198,26 +201,25 @@ impl GpuDisplay { /// Creates a surface on the the compositor as either a top level window, or child of another /// surface, returning a handle to the new surface. - pub fn create_surface(&mut self, - parent_surface_id: Option<u32>, - width: u32, - height: u32) - -> Result<u32, GpuDisplayError> { + pub fn create_surface( + &mut self, + parent_surface_id: Option<u32>, + width: u32, + height: u32, + ) -> Result<u32, GpuDisplayError> { let parent_ptr = match parent_surface_id { - Some(id) => { - match self.get_surface(id).map(|p| p.surface()) { - Some(ptr) => ptr, - None => return Err(GpuDisplayError::InvalidSurfaceId), - } - } + Some(id) => match self.get_surface(id).map(|p| p.surface()) { + Some(ptr) => ptr, + None => return Err(GpuDisplayError::InvalidSurfaceId), + }, None => null_mut(), }; let row_size = width * BYTES_PER_PIXEL; let fb_size = row_size * height; let buffer_size = round_up_to_page_size(fb_size as usize * BUFFER_COUNT); - let mut buffer_shm = - SharedMemory::new(Some(CStr::from_bytes_with_nul(b"GpuDisplaySurface\0").unwrap())) - .map_err(GpuDisplayError::CreateShm)?; + let mut buffer_shm = SharedMemory::new(Some( + CStr::from_bytes_with_nul(b"GpuDisplaySurface\0").unwrap(), + )).map_err(GpuDisplayError::CreateShm)?; buffer_shm .set_size(buffer_size as u64) .map_err(GpuDisplayError::SetSize)?; @@ -226,29 +228,32 @@ impl GpuDisplay { // Safe because only a valid context, parent pointer (if not None), and buffer FD are used. // The returned surface is checked for validity before being filed away. let surface = DwlSurface(unsafe { - dwl_context_surface_new(self.ctx(), - parent_ptr, - buffer_shm.as_raw_fd(), - buffer_size, - fb_size as usize, - width, - height, - row_size) - }); + dwl_context_surface_new( + self.ctx(), + parent_ptr, + buffer_shm.as_raw_fd(), + buffer_size, + fb_size as usize, + width, + height, + row_size, + ) + }); if surface.0.is_null() { return Err(GpuDisplayError::CreateSurface); } let next_id = self.surface_next_id; - self.surfaces - .insert(next_id, - GpuDisplaySurface { - surface, - buffer_size: fb_size as usize, - buffer_index: Cell::new(0), - buffer_mem, - }); + self.surfaces.insert( + next_id, + GpuDisplaySurface { + surface, + buffer_size: fb_size as usize, + buffer_index: Cell::new(0), + buffer_mem, + }, + ); self.surface_next_id += 1; Ok(next_id) @@ -265,9 +270,10 @@ impl GpuDisplay { let buffer_index = (surface.buffer_index.get() + 1) % BUFFER_COUNT; surface .buffer_mem - .get_slice((buffer_index * surface.buffer_size) as u64, - surface.buffer_size as u64) - .ok() + .get_slice( + (buffer_index * surface.buffer_size) as u64, + surface.buffer_size as u64, + ).ok() } /// Commits any pending state for the identified surface. @@ -339,11 +345,9 @@ impl GpuDisplay { pub fn close_requested(&self, surface_id: u32) -> bool { match self.get_surface(surface_id) { Some(surface) => - // Safe because only a valid surface is used. - unsafe { - dwl_surface_close_requested(surface.surface()) - }, - None => false + // Safe because only a valid surface is used. + unsafe { dwl_surface_close_requested(surface.surface()) } + None => false, } } diff --git a/gpu_renderer/src/command_buffer.rs b/gpu_renderer/src/command_buffer.rs index 57b04c3..26ac656 100644 --- a/gpu_renderer/src/command_buffer.rs +++ b/gpu_renderer/src/command_buffer.rs @@ -21,8 +21,10 @@ impl AsRef<[u8]> for CommandBufferBuilder { // Safe because the returned slice is a trivial reinterpretation of the same number of // bytes. unsafe { - from_raw_parts(self.cbuf.as_ptr() as *const u8, - self.cbuf.len() * size_of::<u32>()) + from_raw_parts( + self.cbuf.as_ptr() as *const u8, + self.cbuf.len() * size_of::<u32>(), + ) } } } @@ -32,13 +34,14 @@ impl AsMut<[u8]> for CommandBufferBuilder { // Safe because the returned slice is a trivial reinterpretation of the same number of // bytes. unsafe { - from_raw_parts_mut(self.cbuf.as_mut_ptr() as *mut u8, - self.cbuf.len() * size_of::<u32>()) + from_raw_parts_mut( + self.cbuf.as_mut_ptr() as *mut u8, + self.cbuf.len() * size_of::<u32>(), + ) } } } - impl CommandBufferBuilder { /// Constructs an empty command pub fn new() -> CommandBufferBuilder { @@ -55,7 +58,8 @@ impl CommandBufferBuilder { } fn push_cmd(&mut self, cmd: u32, obj_type: u32, len: u32) { - self.cbuf.push((cmd & 0xff) | ((obj_type & 0xff) << 8) | ((len & 0xffff) << 16)); + self.cbuf + .push((cmd & 0xff) | ((obj_type & 0xff) << 8) | ((len & 0xffff) << 16)); } /// Gets the command buffer as a pointer to the beginning. @@ -95,16 +99,20 @@ impl CommandBufferBuilder { } /// Pushes a create surface command to this command buffer. - pub fn e_create_surface(&mut self, - new_id: u32, - res: &Resource, - format: u32, - level: u32, - first_layer: u32, - last_layer: u32) { - self.push_cmd(VIRGL_CCMD_CREATE_OBJECT, - VIRGL_OBJECT_SURFACE, - VIRGL_OBJ_SURFACE_SIZE); + pub fn e_create_surface( + &mut self, + new_id: u32, + res: &Resource, + format: u32, + level: u32, + first_layer: u32, + last_layer: u32, + ) { + self.push_cmd( + VIRGL_CCMD_CREATE_OBJECT, + VIRGL_OBJECT_SURFACE, + VIRGL_OBJ_SURFACE_SIZE, + ); self.push(new_id); self.push(res.id()); self.push(format); @@ -118,9 +126,11 @@ impl CommandBufferBuilder { fn cmd_set_fb_state_size(surface_count: u32) -> u32 { 2 + surface_count } - self.push_cmd(VIRGL_CCMD_SET_FRAMEBUFFER_STATE, - 0, - cmd_set_fb_state_size(surface_handles.len() as u32)); + self.push_cmd( + VIRGL_CCMD_SET_FRAMEBUFFER_STATE, + 0, + cmd_set_fb_state_size(surface_handles.len() as u32), + ); self.push(surface_handles.len() as u32); self.push(zbuf.unwrap_or(0)); for &surface_handle in surface_handles { diff --git a/gpu_renderer/src/generated/mod.rs b/gpu_renderer/src/generated/mod.rs index a836066..64e2263 100644 --- a/gpu_renderer/src/generated/mod.rs +++ b/gpu_renderer/src/generated/mod.rs @@ -3,8 +3,8 @@ #![allow(non_camel_case_types)] #![allow(non_snake_case)] #![allow(non_upper_case_globals)] -pub mod virglrenderer; pub mod epoxy_egl; -pub mod virgl_protocol; pub mod p_defines; pub mod p_format; +pub mod virgl_protocol; +pub mod virglrenderer; diff --git a/gpu_renderer/src/generated/p_defines.rs b/gpu_renderer/src/generated/p_defines.rs index b5ecb36..08946b7 100644 --- a/gpu_renderer/src/generated/p_defines.rs +++ b/gpu_renderer/src/generated/p_defines.rs @@ -1,66 +1,274 @@ /* automatically generated by rust-bindgen */ -pub const _POSIX_PIPE_BUF : u32 = 512 ; pub const PIPE_BUF : u32 = 4096 ; pub const PIPE_BLENDFACTOR_ONE : u32 = 1 ; pub const PIPE_BLENDFACTOR_SRC_COLOR : u32 = 2 ; pub const PIPE_BLENDFACTOR_SRC_ALPHA : u32 = 3 ; pub const PIPE_BLENDFACTOR_DST_ALPHA : u32 = 4 ; pub const PIPE_BLENDFACTOR_DST_COLOR : u32 = 5 ; pub const PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE : u32 = 6 ; pub const PIPE_BLENDFACTOR_CONST_COLOR : u32 = 7 ; pub const PIPE_BLENDFACTOR_CONST_ALPHA : u32 = 8 ; pub const PIPE_BLENDFACTOR_SRC1_COLOR : u32 = 9 ; pub const PIPE_BLENDFACTOR_SRC1_ALPHA : u32 = 10 ; pub const PIPE_BLENDFACTOR_ZERO : u32 = 17 ; pub const PIPE_BLENDFACTOR_INV_SRC_COLOR : u32 = 18 ; pub const PIPE_BLENDFACTOR_INV_SRC_ALPHA : u32 = 19 ; pub const PIPE_BLENDFACTOR_INV_DST_ALPHA : u32 = 20 ; pub const PIPE_BLENDFACTOR_INV_DST_COLOR : u32 = 21 ; pub const PIPE_BLENDFACTOR_INV_CONST_COLOR : u32 = 23 ; pub const PIPE_BLENDFACTOR_INV_CONST_ALPHA : u32 = 24 ; pub const PIPE_BLENDFACTOR_INV_SRC1_COLOR : u32 = 25 ; pub const PIPE_BLENDFACTOR_INV_SRC1_ALPHA : u32 = 26 ; pub const PIPE_BLEND_ADD : u32 = 0 ; pub const PIPE_BLEND_SUBTRACT : u32 = 1 ; pub const PIPE_BLEND_REVERSE_SUBTRACT : u32 = 2 ; pub const PIPE_BLEND_MIN : u32 = 3 ; pub const PIPE_BLEND_MAX : u32 = 4 ; pub const PIPE_LOGICOP_CLEAR : u32 = 0 ; pub const PIPE_LOGICOP_NOR : u32 = 1 ; pub const PIPE_LOGICOP_AND_INVERTED : u32 = 2 ; pub const PIPE_LOGICOP_COPY_INVERTED : u32 = 3 ; pub const PIPE_LOGICOP_AND_REVERSE : u32 = 4 ; pub const PIPE_LOGICOP_INVERT : u32 = 5 ; pub const PIPE_LOGICOP_XOR : u32 = 6 ; pub const PIPE_LOGICOP_NAND : u32 = 7 ; pub const PIPE_LOGICOP_AND : u32 = 8 ; pub const PIPE_LOGICOP_EQUIV : u32 = 9 ; pub const PIPE_LOGICOP_NOOP : u32 = 10 ; pub const PIPE_LOGICOP_OR_INVERTED : u32 = 11 ; pub const PIPE_LOGICOP_COPY : u32 = 12 ; pub const PIPE_LOGICOP_OR_REVERSE : u32 = 13 ; pub const PIPE_LOGICOP_OR : u32 = 14 ; pub const PIPE_LOGICOP_SET : u32 = 15 ; pub const PIPE_MASK_R : u32 = 1 ; pub const PIPE_MASK_G : u32 = 2 ; pub const PIPE_MASK_B : u32 = 4 ; pub const PIPE_MASK_A : u32 = 8 ; pub const PIPE_MASK_RGBA : u32 = 15 ; pub const PIPE_MASK_Z : u32 = 16 ; pub const PIPE_MASK_S : u32 = 32 ; pub const PIPE_MASK_ZS : u32 = 48 ; pub const PIPE_MASK_RGBAZS : u32 = 63 ; pub const PIPE_FUNC_NEVER : u32 = 0 ; pub const PIPE_FUNC_LESS : u32 = 1 ; pub const PIPE_FUNC_EQUAL : u32 = 2 ; pub const PIPE_FUNC_LEQUAL : u32 = 3 ; pub const PIPE_FUNC_GREATER : u32 = 4 ; pub const PIPE_FUNC_NOTEQUAL : u32 = 5 ; pub const PIPE_FUNC_GEQUAL : u32 = 6 ; pub const PIPE_FUNC_ALWAYS : u32 = 7 ; pub const PIPE_POLYGON_MODE_FILL : u32 = 0 ; pub const PIPE_POLYGON_MODE_LINE : u32 = 1 ; pub const PIPE_POLYGON_MODE_POINT : u32 = 2 ; pub const PIPE_FACE_NONE : u32 = 0 ; pub const PIPE_FACE_FRONT : u32 = 1 ; pub const PIPE_FACE_BACK : u32 = 2 ; pub const PIPE_FACE_FRONT_AND_BACK : u32 = 3 ; pub const PIPE_STENCIL_OP_KEEP : u32 = 0 ; pub const PIPE_STENCIL_OP_ZERO : u32 = 1 ; pub const PIPE_STENCIL_OP_REPLACE : u32 = 2 ; pub const PIPE_STENCIL_OP_INCR : u32 = 3 ; pub const PIPE_STENCIL_OP_DECR : u32 = 4 ; pub const PIPE_STENCIL_OP_INCR_WRAP : u32 = 5 ; pub const PIPE_STENCIL_OP_DECR_WRAP : u32 = 6 ; pub const PIPE_STENCIL_OP_INVERT : u32 = 7 ; pub const PIPE_TEX_FACE_POS_X : u32 = 0 ; pub const PIPE_TEX_FACE_NEG_X : u32 = 1 ; pub const PIPE_TEX_FACE_POS_Y : u32 = 2 ; pub const PIPE_TEX_FACE_NEG_Y : u32 = 3 ; pub const PIPE_TEX_FACE_POS_Z : u32 = 4 ; pub const PIPE_TEX_FACE_NEG_Z : u32 = 5 ; pub const PIPE_TEX_FACE_MAX : u32 = 6 ; pub const PIPE_TEX_WRAP_REPEAT : u32 = 0 ; pub const PIPE_TEX_WRAP_CLAMP : u32 = 1 ; pub const PIPE_TEX_WRAP_CLAMP_TO_EDGE : u32 = 2 ; pub const PIPE_TEX_WRAP_CLAMP_TO_BORDER : u32 = 3 ; pub const PIPE_TEX_WRAP_MIRROR_REPEAT : u32 = 4 ; pub const PIPE_TEX_WRAP_MIRROR_CLAMP : u32 = 5 ; pub const PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE : u32 = 6 ; pub const PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER : u32 = 7 ; pub const PIPE_TEX_MIPFILTER_NEAREST : u32 = 0 ; pub const PIPE_TEX_MIPFILTER_LINEAR : u32 = 1 ; pub const PIPE_TEX_MIPFILTER_NONE : u32 = 2 ; pub const PIPE_TEX_FILTER_NEAREST : u32 = 0 ; pub const PIPE_TEX_FILTER_LINEAR : u32 = 1 ; pub const PIPE_TEX_COMPARE_NONE : u32 = 0 ; pub const PIPE_TEX_COMPARE_R_TO_TEXTURE : u32 = 1 ; pub const PIPE_CLEAR_DEPTH : u32 = 1 ; pub const PIPE_CLEAR_STENCIL : u32 = 2 ; pub const PIPE_CLEAR_COLOR0 : u32 = 4 ; pub const PIPE_CLEAR_COLOR1 : u32 = 8 ; pub const PIPE_CLEAR_COLOR2 : u32 = 16 ; pub const PIPE_CLEAR_COLOR3 : u32 = 32 ; pub const PIPE_CLEAR_COLOR4 : u32 = 64 ; pub const PIPE_CLEAR_COLOR5 : u32 = 128 ; pub const PIPE_CLEAR_COLOR6 : u32 = 256 ; pub const PIPE_CLEAR_COLOR7 : u32 = 512 ; pub const PIPE_CLEAR_COLOR : u32 = 1020 ; pub const PIPE_CLEAR_DEPTHSTENCIL : u32 = 3 ; pub const PIPE_BARRIER_MAPPED_BUFFER : u32 = 1 ; pub const PIPE_BIND_DEPTH_STENCIL : u32 = 1 ; pub const PIPE_BIND_RENDER_TARGET : u32 = 2 ; pub const PIPE_BIND_BLENDABLE : u32 = 4 ; pub const PIPE_BIND_SAMPLER_VIEW : u32 = 8 ; pub const PIPE_BIND_VERTEX_BUFFER : u32 = 16 ; pub const PIPE_BIND_INDEX_BUFFER : u32 = 32 ; pub const PIPE_BIND_CONSTANT_BUFFER : u32 = 64 ; pub const PIPE_BIND_DISPLAY_TARGET : u32 = 256 ; pub const PIPE_BIND_TRANSFER_WRITE : u32 = 512 ; pub const PIPE_BIND_TRANSFER_READ : u32 = 1024 ; pub const PIPE_BIND_STREAM_OUTPUT : u32 = 2048 ; pub const PIPE_BIND_CURSOR : u32 = 65536 ; pub const PIPE_BIND_CUSTOM : u32 = 131072 ; pub const PIPE_BIND_GLOBAL : u32 = 262144 ; pub const PIPE_BIND_SHADER_RESOURCE : u32 = 524288 ; pub const PIPE_BIND_COMPUTE_RESOURCE : u32 = 1048576 ; pub const PIPE_BIND_COMMAND_ARGS_BUFFER : u32 = 2097152 ; pub const PIPE_BIND_SCANOUT : u32 = 16384 ; pub const PIPE_BIND_SHARED : u32 = 32768 ; pub const PIPE_BIND_LINEAR : u32 = 2097152 ; pub const PIPE_RESOURCE_FLAG_MAP_PERSISTENT : u32 = 1 ; pub const PIPE_RESOURCE_FLAG_MAP_COHERENT : u32 = 2 ; pub const PIPE_RESOURCE_FLAG_DRV_PRIV : u32 = 65536 ; pub const PIPE_RESOURCE_FLAG_ST_PRIV : u32 = 16777216 ; pub const PIPE_USAGE_DEFAULT : u32 = 0 ; pub const PIPE_USAGE_IMMUTABLE : u32 = 1 ; pub const PIPE_USAGE_DYNAMIC : u32 = 2 ; pub const PIPE_USAGE_STREAM : u32 = 3 ; pub const PIPE_USAGE_STAGING : u32 = 4 ; pub const PIPE_SHADER_VERTEX : u32 = 0 ; pub const PIPE_SHADER_FRAGMENT : u32 = 1 ; pub const PIPE_SHADER_GEOMETRY : u32 = 2 ; pub const PIPE_SHADER_TESS_CTRL : u32 = 3 ; pub const PIPE_SHADER_TESS_EVAL : u32 = 4 ; pub const PIPE_SHADER_COMPUTE : u32 = 5 ; pub const PIPE_SHADER_TYPES : u32 = 6 ; pub const PIPE_PRIM_POINTS : u32 = 0 ; pub const PIPE_PRIM_LINES : u32 = 1 ; pub const PIPE_PRIM_LINE_LOOP : u32 = 2 ; pub const PIPE_PRIM_LINE_STRIP : u32 = 3 ; pub const PIPE_PRIM_TRIANGLES : u32 = 4 ; pub const PIPE_PRIM_TRIANGLE_STRIP : u32 = 5 ; pub const PIPE_PRIM_TRIANGLE_FAN : u32 = 6 ; pub const PIPE_PRIM_QUADS : u32 = 7 ; pub const PIPE_PRIM_QUAD_STRIP : u32 = 8 ; pub const PIPE_PRIM_POLYGON : u32 = 9 ; pub const PIPE_PRIM_LINES_ADJACENCY : u32 = 10 ; pub const PIPE_PRIM_LINE_STRIP_ADJACENCY : u32 = 11 ; pub const PIPE_PRIM_TRIANGLES_ADJACENCY : u32 = 12 ; pub const PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY : u32 = 13 ; pub const PIPE_PRIM_PATCHES : u32 = 14 ; pub const PIPE_PRIM_MAX : u32 = 15 ; pub const PIPE_TESS_SPACING_FRACTIONAL_ODD : u32 = 0 ; pub const PIPE_TESS_SPACING_FRACTIONAL_EVEN : u32 = 1 ; pub const PIPE_TESS_SPACING_EQUAL : u32 = 2 ; pub const PIPE_QUERY_OCCLUSION_COUNTER : u32 = 0 ; pub const PIPE_QUERY_OCCLUSION_PREDICATE : u32 = 1 ; pub const PIPE_QUERY_TIMESTAMP : u32 = 2 ; pub const PIPE_QUERY_TIMESTAMP_DISJOINT : u32 = 3 ; pub const PIPE_QUERY_TIME_ELAPSED : u32 = 4 ; pub const PIPE_QUERY_PRIMITIVES_GENERATED : u32 = 5 ; pub const PIPE_QUERY_PRIMITIVES_EMITTED : u32 = 6 ; pub const PIPE_QUERY_SO_STATISTICS : u32 = 7 ; pub const PIPE_QUERY_SO_OVERFLOW_PREDICATE : u32 = 8 ; pub const PIPE_QUERY_GPU_FINISHED : u32 = 9 ; pub const PIPE_QUERY_PIPELINE_STATISTICS : u32 = 10 ; pub const PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE : u32 = 11 ; pub const PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE : u32 = 12 ; pub const PIPE_QUERY_TYPES : u32 = 13 ; pub const PIPE_QUERY_DRIVER_SPECIFIC : u32 = 256 ; pub const PIPE_RENDER_COND_WAIT : u32 = 0 ; pub const PIPE_RENDER_COND_NO_WAIT : u32 = 1 ; pub const PIPE_RENDER_COND_BY_REGION_WAIT : u32 = 2 ; pub const PIPE_RENDER_COND_BY_REGION_NO_WAIT : u32 = 3 ; pub const PIPE_SPRITE_COORD_UPPER_LEFT : u32 = 0 ; pub const PIPE_SPRITE_COORD_LOWER_LEFT : u32 = 1 ; pub const PIPE_SWIZZLE_RED : u32 = 0 ; pub const PIPE_SWIZZLE_GREEN : u32 = 1 ; pub const PIPE_SWIZZLE_BLUE : u32 = 2 ; pub const PIPE_SWIZZLE_ALPHA : u32 = 3 ; pub const PIPE_SWIZZLE_ZERO : u32 = 4 ; pub const PIPE_SWIZZLE_ONE : u32 = 5 ; pub const PIPE_TIMEOUT_INFINITE : i32 = -1 ; pub const PIPE_QUIRK_TEXTURE_BORDER_COLOR_SWIZZLE_NV50 : u32 = 1 ; pub const PIPE_QUIRK_TEXTURE_BORDER_COLOR_SWIZZLE_R600 : u32 = 2 ; pub type boolean = :: std :: os :: raw :: c_uchar ; pub const PIPE_OK : pipe_error = 0 ; - /// < Generic error - pub const PIPE_ERROR : pipe_error = -1 ; pub const PIPE_ERROR_BAD_INPUT : pipe_error = -2 ; pub const PIPE_ERROR_OUT_OF_MEMORY : pipe_error = -3 ; pub const PIPE_ERROR_RETRY : pipe_error = -4 ; - /// Gallium error codes. +pub const _POSIX_PIPE_BUF: u32 = 512; +pub const PIPE_BUF: u32 = 4096; +pub const PIPE_BLENDFACTOR_ONE: u32 = 1; +pub const PIPE_BLENDFACTOR_SRC_COLOR: u32 = 2; +pub const PIPE_BLENDFACTOR_SRC_ALPHA: u32 = 3; +pub const PIPE_BLENDFACTOR_DST_ALPHA: u32 = 4; +pub const PIPE_BLENDFACTOR_DST_COLOR: u32 = 5; +pub const PIPE_BLENDFACTOR_SRC_ALPHA_SATURATE: u32 = 6; +pub const PIPE_BLENDFACTOR_CONST_COLOR: u32 = 7; +pub const PIPE_BLENDFACTOR_CONST_ALPHA: u32 = 8; +pub const PIPE_BLENDFACTOR_SRC1_COLOR: u32 = 9; +pub const PIPE_BLENDFACTOR_SRC1_ALPHA: u32 = 10; +pub const PIPE_BLENDFACTOR_ZERO: u32 = 17; +pub const PIPE_BLENDFACTOR_INV_SRC_COLOR: u32 = 18; +pub const PIPE_BLENDFACTOR_INV_SRC_ALPHA: u32 = 19; +pub const PIPE_BLENDFACTOR_INV_DST_ALPHA: u32 = 20; +pub const PIPE_BLENDFACTOR_INV_DST_COLOR: u32 = 21; +pub const PIPE_BLENDFACTOR_INV_CONST_COLOR: u32 = 23; +pub const PIPE_BLENDFACTOR_INV_CONST_ALPHA: u32 = 24; +pub const PIPE_BLENDFACTOR_INV_SRC1_COLOR: u32 = 25; +pub const PIPE_BLENDFACTOR_INV_SRC1_ALPHA: u32 = 26; +pub const PIPE_BLEND_ADD: u32 = 0; +pub const PIPE_BLEND_SUBTRACT: u32 = 1; +pub const PIPE_BLEND_REVERSE_SUBTRACT: u32 = 2; +pub const PIPE_BLEND_MIN: u32 = 3; +pub const PIPE_BLEND_MAX: u32 = 4; +pub const PIPE_LOGICOP_CLEAR: u32 = 0; +pub const PIPE_LOGICOP_NOR: u32 = 1; +pub const PIPE_LOGICOP_AND_INVERTED: u32 = 2; +pub const PIPE_LOGICOP_COPY_INVERTED: u32 = 3; +pub const PIPE_LOGICOP_AND_REVERSE: u32 = 4; +pub const PIPE_LOGICOP_INVERT: u32 = 5; +pub const PIPE_LOGICOP_XOR: u32 = 6; +pub const PIPE_LOGICOP_NAND: u32 = 7; +pub const PIPE_LOGICOP_AND: u32 = 8; +pub const PIPE_LOGICOP_EQUIV: u32 = 9; +pub const PIPE_LOGICOP_NOOP: u32 = 10; +pub const PIPE_LOGICOP_OR_INVERTED: u32 = 11; +pub const PIPE_LOGICOP_COPY: u32 = 12; +pub const PIPE_LOGICOP_OR_REVERSE: u32 = 13; +pub const PIPE_LOGICOP_OR: u32 = 14; +pub const PIPE_LOGICOP_SET: u32 = 15; +pub const PIPE_MASK_R: u32 = 1; +pub const PIPE_MASK_G: u32 = 2; +pub const PIPE_MASK_B: u32 = 4; +pub const PIPE_MASK_A: u32 = 8; +pub const PIPE_MASK_RGBA: u32 = 15; +pub const PIPE_MASK_Z: u32 = 16; +pub const PIPE_MASK_S: u32 = 32; +pub const PIPE_MASK_ZS: u32 = 48; +pub const PIPE_MASK_RGBAZS: u32 = 63; +pub const PIPE_FUNC_NEVER: u32 = 0; +pub const PIPE_FUNC_LESS: u32 = 1; +pub const PIPE_FUNC_EQUAL: u32 = 2; +pub const PIPE_FUNC_LEQUAL: u32 = 3; +pub const PIPE_FUNC_GREATER: u32 = 4; +pub const PIPE_FUNC_NOTEQUAL: u32 = 5; +pub const PIPE_FUNC_GEQUAL: u32 = 6; +pub const PIPE_FUNC_ALWAYS: u32 = 7; +pub const PIPE_POLYGON_MODE_FILL: u32 = 0; +pub const PIPE_POLYGON_MODE_LINE: u32 = 1; +pub const PIPE_POLYGON_MODE_POINT: u32 = 2; +pub const PIPE_FACE_NONE: u32 = 0; +pub const PIPE_FACE_FRONT: u32 = 1; +pub const PIPE_FACE_BACK: u32 = 2; +pub const PIPE_FACE_FRONT_AND_BACK: u32 = 3; +pub const PIPE_STENCIL_OP_KEEP: u32 = 0; +pub const PIPE_STENCIL_OP_ZERO: u32 = 1; +pub const PIPE_STENCIL_OP_REPLACE: u32 = 2; +pub const PIPE_STENCIL_OP_INCR: u32 = 3; +pub const PIPE_STENCIL_OP_DECR: u32 = 4; +pub const PIPE_STENCIL_OP_INCR_WRAP: u32 = 5; +pub const PIPE_STENCIL_OP_DECR_WRAP: u32 = 6; +pub const PIPE_STENCIL_OP_INVERT: u32 = 7; +pub const PIPE_TEX_FACE_POS_X: u32 = 0; +pub const PIPE_TEX_FACE_NEG_X: u32 = 1; +pub const PIPE_TEX_FACE_POS_Y: u32 = 2; +pub const PIPE_TEX_FACE_NEG_Y: u32 = 3; +pub const PIPE_TEX_FACE_POS_Z: u32 = 4; +pub const PIPE_TEX_FACE_NEG_Z: u32 = 5; +pub const PIPE_TEX_FACE_MAX: u32 = 6; +pub const PIPE_TEX_WRAP_REPEAT: u32 = 0; +pub const PIPE_TEX_WRAP_CLAMP: u32 = 1; +pub const PIPE_TEX_WRAP_CLAMP_TO_EDGE: u32 = 2; +pub const PIPE_TEX_WRAP_CLAMP_TO_BORDER: u32 = 3; +pub const PIPE_TEX_WRAP_MIRROR_REPEAT: u32 = 4; +pub const PIPE_TEX_WRAP_MIRROR_CLAMP: u32 = 5; +pub const PIPE_TEX_WRAP_MIRROR_CLAMP_TO_EDGE: u32 = 6; +pub const PIPE_TEX_WRAP_MIRROR_CLAMP_TO_BORDER: u32 = 7; +pub const PIPE_TEX_MIPFILTER_NEAREST: u32 = 0; +pub const PIPE_TEX_MIPFILTER_LINEAR: u32 = 1; +pub const PIPE_TEX_MIPFILTER_NONE: u32 = 2; +pub const PIPE_TEX_FILTER_NEAREST: u32 = 0; +pub const PIPE_TEX_FILTER_LINEAR: u32 = 1; +pub const PIPE_TEX_COMPARE_NONE: u32 = 0; +pub const PIPE_TEX_COMPARE_R_TO_TEXTURE: u32 = 1; +pub const PIPE_CLEAR_DEPTH: u32 = 1; +pub const PIPE_CLEAR_STENCIL: u32 = 2; +pub const PIPE_CLEAR_COLOR0: u32 = 4; +pub const PIPE_CLEAR_COLOR1: u32 = 8; +pub const PIPE_CLEAR_COLOR2: u32 = 16; +pub const PIPE_CLEAR_COLOR3: u32 = 32; +pub const PIPE_CLEAR_COLOR4: u32 = 64; +pub const PIPE_CLEAR_COLOR5: u32 = 128; +pub const PIPE_CLEAR_COLOR6: u32 = 256; +pub const PIPE_CLEAR_COLOR7: u32 = 512; +pub const PIPE_CLEAR_COLOR: u32 = 1020; +pub const PIPE_CLEAR_DEPTHSTENCIL: u32 = 3; +pub const PIPE_BARRIER_MAPPED_BUFFER: u32 = 1; +pub const PIPE_BIND_DEPTH_STENCIL: u32 = 1; +pub const PIPE_BIND_RENDER_TARGET: u32 = 2; +pub const PIPE_BIND_BLENDABLE: u32 = 4; +pub const PIPE_BIND_SAMPLER_VIEW: u32 = 8; +pub const PIPE_BIND_VERTEX_BUFFER: u32 = 16; +pub const PIPE_BIND_INDEX_BUFFER: u32 = 32; +pub const PIPE_BIND_CONSTANT_BUFFER: u32 = 64; +pub const PIPE_BIND_DISPLAY_TARGET: u32 = 256; +pub const PIPE_BIND_TRANSFER_WRITE: u32 = 512; +pub const PIPE_BIND_TRANSFER_READ: u32 = 1024; +pub const PIPE_BIND_STREAM_OUTPUT: u32 = 2048; +pub const PIPE_BIND_CURSOR: u32 = 65536; +pub const PIPE_BIND_CUSTOM: u32 = 131072; +pub const PIPE_BIND_GLOBAL: u32 = 262144; +pub const PIPE_BIND_SHADER_RESOURCE: u32 = 524288; +pub const PIPE_BIND_COMPUTE_RESOURCE: u32 = 1048576; +pub const PIPE_BIND_COMMAND_ARGS_BUFFER: u32 = 2097152; +pub const PIPE_BIND_SCANOUT: u32 = 16384; +pub const PIPE_BIND_SHARED: u32 = 32768; +pub const PIPE_BIND_LINEAR: u32 = 2097152; +pub const PIPE_RESOURCE_FLAG_MAP_PERSISTENT: u32 = 1; +pub const PIPE_RESOURCE_FLAG_MAP_COHERENT: u32 = 2; +pub const PIPE_RESOURCE_FLAG_DRV_PRIV: u32 = 65536; +pub const PIPE_RESOURCE_FLAG_ST_PRIV: u32 = 16777216; +pub const PIPE_USAGE_DEFAULT: u32 = 0; +pub const PIPE_USAGE_IMMUTABLE: u32 = 1; +pub const PIPE_USAGE_DYNAMIC: u32 = 2; +pub const PIPE_USAGE_STREAM: u32 = 3; +pub const PIPE_USAGE_STAGING: u32 = 4; +pub const PIPE_SHADER_VERTEX: u32 = 0; +pub const PIPE_SHADER_FRAGMENT: u32 = 1; +pub const PIPE_SHADER_GEOMETRY: u32 = 2; +pub const PIPE_SHADER_TESS_CTRL: u32 = 3; +pub const PIPE_SHADER_TESS_EVAL: u32 = 4; +pub const PIPE_SHADER_COMPUTE: u32 = 5; +pub const PIPE_SHADER_TYPES: u32 = 6; +pub const PIPE_PRIM_POINTS: u32 = 0; +pub const PIPE_PRIM_LINES: u32 = 1; +pub const PIPE_PRIM_LINE_LOOP: u32 = 2; +pub const PIPE_PRIM_LINE_STRIP: u32 = 3; +pub const PIPE_PRIM_TRIANGLES: u32 = 4; +pub const PIPE_PRIM_TRIANGLE_STRIP: u32 = 5; +pub const PIPE_PRIM_TRIANGLE_FAN: u32 = 6; +pub const PIPE_PRIM_QUADS: u32 = 7; +pub const PIPE_PRIM_QUAD_STRIP: u32 = 8; +pub const PIPE_PRIM_POLYGON: u32 = 9; +pub const PIPE_PRIM_LINES_ADJACENCY: u32 = 10; +pub const PIPE_PRIM_LINE_STRIP_ADJACENCY: u32 = 11; +pub const PIPE_PRIM_TRIANGLES_ADJACENCY: u32 = 12; +pub const PIPE_PRIM_TRIANGLE_STRIP_ADJACENCY: u32 = 13; +pub const PIPE_PRIM_PATCHES: u32 = 14; +pub const PIPE_PRIM_MAX: u32 = 15; +pub const PIPE_TESS_SPACING_FRACTIONAL_ODD: u32 = 0; +pub const PIPE_TESS_SPACING_FRACTIONAL_EVEN: u32 = 1; +pub const PIPE_TESS_SPACING_EQUAL: u32 = 2; +pub const PIPE_QUERY_OCCLUSION_COUNTER: u32 = 0; +pub const PIPE_QUERY_OCCLUSION_PREDICATE: u32 = 1; +pub const PIPE_QUERY_TIMESTAMP: u32 = 2; +pub const PIPE_QUERY_TIMESTAMP_DISJOINT: u32 = 3; +pub const PIPE_QUERY_TIME_ELAPSED: u32 = 4; +pub const PIPE_QUERY_PRIMITIVES_GENERATED: u32 = 5; +pub const PIPE_QUERY_PRIMITIVES_EMITTED: u32 = 6; +pub const PIPE_QUERY_SO_STATISTICS: u32 = 7; +pub const PIPE_QUERY_SO_OVERFLOW_PREDICATE: u32 = 8; +pub const PIPE_QUERY_GPU_FINISHED: u32 = 9; +pub const PIPE_QUERY_PIPELINE_STATISTICS: u32 = 10; +pub const PIPE_QUERY_OCCLUSION_PREDICATE_CONSERVATIVE: u32 = 11; +pub const PIPE_QUERY_SO_OVERFLOW_ANY_PREDICATE: u32 = 12; +pub const PIPE_QUERY_TYPES: u32 = 13; +pub const PIPE_QUERY_DRIVER_SPECIFIC: u32 = 256; +pub const PIPE_RENDER_COND_WAIT: u32 = 0; +pub const PIPE_RENDER_COND_NO_WAIT: u32 = 1; +pub const PIPE_RENDER_COND_BY_REGION_WAIT: u32 = 2; +pub const PIPE_RENDER_COND_BY_REGION_NO_WAIT: u32 = 3; +pub const PIPE_SPRITE_COORD_UPPER_LEFT: u32 = 0; +pub const PIPE_SPRITE_COORD_LOWER_LEFT: u32 = 1; +pub const PIPE_SWIZZLE_RED: u32 = 0; +pub const PIPE_SWIZZLE_GREEN: u32 = 1; +pub const PIPE_SWIZZLE_BLUE: u32 = 2; +pub const PIPE_SWIZZLE_ALPHA: u32 = 3; +pub const PIPE_SWIZZLE_ZERO: u32 = 4; +pub const PIPE_SWIZZLE_ONE: u32 = 5; +pub const PIPE_TIMEOUT_INFINITE: i32 = -1; +pub const PIPE_QUIRK_TEXTURE_BORDER_COLOR_SWIZZLE_NV50: u32 = 1; +pub const PIPE_QUIRK_TEXTURE_BORDER_COLOR_SWIZZLE_R600: u32 = 2; +pub type boolean = ::std::os::raw::c_uchar; +pub const PIPE_OK: pipe_error = 0; +/// < Generic error +pub const PIPE_ERROR: pipe_error = -1; +pub const PIPE_ERROR_BAD_INPUT: pipe_error = -2; +pub const PIPE_ERROR_OUT_OF_MEMORY: pipe_error = -3; +pub const PIPE_ERROR_RETRY: pipe_error = -4; +/// Gallium error codes. /// /// - A zero value always means success. /// - A negative value always means failure. -/// - The meaning of a positive value is function dependent. - pub type pipe_error = i32 ; pub const PIPE_BUFFER : pipe_texture_target = 0 ; pub const PIPE_TEXTURE_1D : pipe_texture_target = 1 ; pub const PIPE_TEXTURE_2D : pipe_texture_target = 2 ; pub const PIPE_TEXTURE_3D : pipe_texture_target = 3 ; pub const PIPE_TEXTURE_CUBE : pipe_texture_target = 4 ; pub const PIPE_TEXTURE_RECT : pipe_texture_target = 5 ; pub const PIPE_TEXTURE_1D_ARRAY : pipe_texture_target = 6 ; pub const PIPE_TEXTURE_2D_ARRAY : pipe_texture_target = 7 ; pub const PIPE_TEXTURE_CUBE_ARRAY : pipe_texture_target = 8 ; pub const PIPE_MAX_TEXTURE_TYPES : pipe_texture_target = 9 ; - /// Texture types. -/// See the documentation for info on PIPE_TEXTURE_RECT vs PIPE_TEXTURE_2D - pub type pipe_texture_target = u32 ; - /// Resource contents read back (or accessed directly) at transfer -/// create time. - pub const PIPE_TRANSFER_READ : pipe_transfer_usage = 1 ; - /// Resource contents will be written back at transfer_unmap -/// time (or modified as a result of being accessed directly). - pub const PIPE_TRANSFER_WRITE : pipe_transfer_usage = 2 ; - /// Read/modify/write - pub const PIPE_TRANSFER_READ_WRITE : pipe_transfer_usage = 3 ; - /// The transfer should map the texture storage directly. The driver may +/// - The meaning of a positive value is function dependent. +pub type pipe_error = i32; +pub const PIPE_BUFFER: pipe_texture_target = 0; +pub const PIPE_TEXTURE_1D: pipe_texture_target = 1; +pub const PIPE_TEXTURE_2D: pipe_texture_target = 2; +pub const PIPE_TEXTURE_3D: pipe_texture_target = 3; +pub const PIPE_TEXTURE_CUBE: pipe_texture_target = 4; +pub const PIPE_TEXTURE_RECT: pipe_texture_target = 5; +pub const PIPE_TEXTURE_1D_ARRAY: pipe_texture_target = 6; +pub const PIPE_TEXTURE_2D_ARRAY: pipe_texture_target = 7; +pub const PIPE_TEXTURE_CUBE_ARRAY: pipe_texture_target = 8; +pub const PIPE_MAX_TEXTURE_TYPES: pipe_texture_target = 9; +/// Texture types. +/// See the documentation for info on PIPE_TEXTURE_RECT vs PIPE_TEXTURE_2D +pub type pipe_texture_target = u32; +/// Resource contents read back (or accessed directly) at transfer +/// create time. +pub const PIPE_TRANSFER_READ: pipe_transfer_usage = 1; +/// Resource contents will be written back at transfer_unmap +/// time (or modified as a result of being accessed directly). +pub const PIPE_TRANSFER_WRITE: pipe_transfer_usage = 2; +/// Read/modify/write +pub const PIPE_TRANSFER_READ_WRITE: pipe_transfer_usage = 3; +/// The transfer should map the texture storage directly. The driver may /// return NULL if that isn't possible, and the state tracker needs to cope /// with that and use an alternative path without this flag. /// /// E.g. the state tracker could have a simpler path which maps textures and /// does read/modify/write cycles on them directly, and a more complicated -/// path which uses minimal read and write transfers. - pub const PIPE_TRANSFER_MAP_DIRECTLY : pipe_transfer_usage = 4 ; - /// Discards the memory within the mapped region. +/// path which uses minimal read and write transfers. +pub const PIPE_TRANSFER_MAP_DIRECTLY: pipe_transfer_usage = 4; +/// Discards the memory within the mapped region. /// /// It should not be used with PIPE_TRANSFER_READ. /// /// See also: -/// - OpenGL's ARB_map_buffer_range extension, MAP_INVALIDATE_RANGE_BIT flag. - pub const PIPE_TRANSFER_DISCARD_RANGE : pipe_transfer_usage = 256 ; - /// Fail if the resource cannot be mapped immediately. +/// - OpenGL's ARB_map_buffer_range extension, MAP_INVALIDATE_RANGE_BIT flag. +pub const PIPE_TRANSFER_DISCARD_RANGE: pipe_transfer_usage = 256; +/// Fail if the resource cannot be mapped immediately. /// /// See also: /// - Direct3D's D3DLOCK_DONOTWAIT flag. /// - Mesa3D's MESA_MAP_NOWAIT_BIT flag. -/// - WDDM's D3DDDICB_LOCKFLAGS.DonotWait flag. - pub const PIPE_TRANSFER_DONTBLOCK : pipe_transfer_usage = 512 ; - /// Do not attempt to synchronize pending operations on the resource when mapping. +/// - WDDM's D3DDDICB_LOCKFLAGS.DonotWait flag. +pub const PIPE_TRANSFER_DONTBLOCK: pipe_transfer_usage = 512; +/// Do not attempt to synchronize pending operations on the resource when mapping. /// /// It should not be used with PIPE_TRANSFER_READ. /// /// See also: /// - OpenGL's ARB_map_buffer_range extension, MAP_UNSYNCHRONIZED_BIT flag. /// - Direct3D's D3DLOCK_NOOVERWRITE flag. -/// - WDDM's D3DDDICB_LOCKFLAGS.IgnoreSync flag. - pub const PIPE_TRANSFER_UNSYNCHRONIZED : pipe_transfer_usage = 1024 ; - /// Written ranges will be notified later with +/// - WDDM's D3DDDICB_LOCKFLAGS.IgnoreSync flag. +pub const PIPE_TRANSFER_UNSYNCHRONIZED: pipe_transfer_usage = 1024; +/// Written ranges will be notified later with /// pipe_context::transfer_flush_region. /// /// It should not be used with PIPE_TRANSFER_READ. /// /// See also: /// - pipe_context::transfer_flush_region -/// - OpenGL's ARB_map_buffer_range extension, MAP_FLUSH_EXPLICIT_BIT flag. - pub const PIPE_TRANSFER_FLUSH_EXPLICIT : pipe_transfer_usage = 2048 ; - /// Discards all memory backing the resource. +/// - OpenGL's ARB_map_buffer_range extension, MAP_FLUSH_EXPLICIT_BIT flag. +pub const PIPE_TRANSFER_FLUSH_EXPLICIT: pipe_transfer_usage = 2048; +/// Discards all memory backing the resource. /// /// It should not be used with PIPE_TRANSFER_READ. /// @@ -70,218 +278,329 @@ pub const _POSIX_PIPE_BUF : u32 = 512 ; pub const PIPE_BUF : u32 = 4096 ; pub co /// - Direct3D's D3DLOCK_DISCARD flag. /// - WDDM's D3DDDICB_LOCKFLAGS.Discard flag. /// - D3D10 DDI's D3D10_DDI_MAP_WRITE_DISCARD flag -/// - D3D10's D3D10_MAP_WRITE_DISCARD flag. - pub const PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE : pipe_transfer_usage = 4096 ; - /// Allows the resource to be used for rendering while mapped. +/// - D3D10's D3D10_MAP_WRITE_DISCARD flag. +pub const PIPE_TRANSFER_DISCARD_WHOLE_RESOURCE: pipe_transfer_usage = 4096; +/// Allows the resource to be used for rendering while mapped. /// /// PIPE_RESOURCE_FLAG_MAP_PERSISTENT must be set when creating /// the resource. /// /// If COHERENT is not set, memory_barrier(PIPE_BARRIER_MAPPED_BUFFER) -/// must be called to ensure the device can see what the CPU has written. - pub const PIPE_TRANSFER_PERSISTENT : pipe_transfer_usage = 8192 ; - /// If PERSISTENT is set, this ensures any writes done by the device are +/// must be called to ensure the device can see what the CPU has written. +pub const PIPE_TRANSFER_PERSISTENT: pipe_transfer_usage = 8192; +/// If PERSISTENT is set, this ensures any writes done by the device are /// immediately visible to the CPU and vice versa. /// /// PIPE_RESOURCE_FLAG_MAP_COHERENT must be set when creating -/// the resource. - pub const PIPE_TRANSFER_COHERENT : pipe_transfer_usage = 16384 ; - /// Transfer object usage flags - pub type pipe_transfer_usage = u32 ; pub const PIPE_FLUSH_END_OF_FRAME : pipe_flush_flags = 1 ; - /// Flags for the flush function. - pub type pipe_flush_flags = u32 ; pub const PIPE_CAP_NPOT_TEXTURES : pipe_cap = 1 ; pub const PIPE_CAP_TWO_SIDED_STENCIL : pipe_cap = 2 ; pub const PIPE_CAP_MAX_DUAL_SOURCE_RENDER_TARGETS : pipe_cap = 4 ; pub const PIPE_CAP_ANISOTROPIC_FILTER : pipe_cap = 5 ; pub const PIPE_CAP_POINT_SPRITE : pipe_cap = 6 ; pub const PIPE_CAP_MAX_RENDER_TARGETS : pipe_cap = 7 ; pub const PIPE_CAP_OCCLUSION_QUERY : pipe_cap = 8 ; pub const PIPE_CAP_QUERY_TIME_ELAPSED : pipe_cap = 9 ; pub const PIPE_CAP_TEXTURE_SHADOW_MAP : pipe_cap = 10 ; pub const PIPE_CAP_TEXTURE_SWIZZLE : pipe_cap = 11 ; pub const PIPE_CAP_MAX_TEXTURE_2D_LEVELS : pipe_cap = 12 ; pub const PIPE_CAP_MAX_TEXTURE_3D_LEVELS : pipe_cap = 13 ; pub const PIPE_CAP_MAX_TEXTURE_CUBE_LEVELS : pipe_cap = 14 ; pub const PIPE_CAP_TEXTURE_MIRROR_CLAMP : pipe_cap = 25 ; pub const PIPE_CAP_BLEND_EQUATION_SEPARATE : pipe_cap = 28 ; pub const PIPE_CAP_SM3 : pipe_cap = 29 ; pub const PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS : pipe_cap = 30 ; pub const PIPE_CAP_PRIMITIVE_RESTART : pipe_cap = 31 ; - /// blend enables and write masks per rendertarget - pub const PIPE_CAP_INDEP_BLEND_ENABLE : pipe_cap = 33 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_INDEP_BLEND_FUNC : pipe_cap = 34 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS : pipe_cap = 36 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT : pipe_cap = 37 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT : pipe_cap = 38 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER : pipe_cap = 39 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER : pipe_cap = 40 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_DEPTH_CLIP_DISABLE : pipe_cap = 41 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_SHADER_STENCIL_EXPORT : pipe_cap = 42 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_INSTANCEID : pipe_cap = 43 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEX_ELEMENT_INSTANCE_DIVISOR : pipe_cap = 44 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_FRAGMENT_COLOR_CLAMPED : pipe_cap = 45 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MIXED_COLORBUFFER_FORMATS : pipe_cap = 46 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_SEAMLESS_CUBE_MAP : pipe_cap = 47 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_SEAMLESS_CUBE_MAP_PER_TEXTURE : pipe_cap = 48 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MIN_TEXEL_OFFSET : pipe_cap = 50 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_TEXEL_OFFSET : pipe_cap = 51 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_CONDITIONAL_RENDER : pipe_cap = 52 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_BARRIER : pipe_cap = 53 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_STREAM_OUTPUT_SEPARATE_COMPONENTS : pipe_cap = 55 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_STREAM_OUTPUT_INTERLEAVED_COMPONENTS : pipe_cap = 56 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_STREAM_OUTPUT_PAUSE_RESUME : pipe_cap = 57 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_CAN_COMPACT_CONSTANTS : pipe_cap = 59 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEX_COLOR_UNCLAMPED : pipe_cap = 60 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEX_COLOR_CLAMPED : pipe_cap = 61 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_GLSL_FEATURE_LEVEL : pipe_cap = 62 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION : pipe_cap = 63 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_USER_VERTEX_BUFFERS : pipe_cap = 64 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEX_BUFFER_OFFSET_4BYTE_ALIGNED_ONLY : pipe_cap = 65 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEX_BUFFER_STRIDE_4BYTE_ALIGNED_ONLY : pipe_cap = 66 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEX_ELEMENT_SRC_OFFSET_4BYTE_ALIGNED_ONLY : pipe_cap = 67 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_COMPUTE : pipe_cap = 68 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_USER_INDEX_BUFFERS : pipe_cap = 69 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_USER_CONSTANT_BUFFERS : pipe_cap = 70 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_CONSTANT_BUFFER_OFFSET_ALIGNMENT : pipe_cap = 71 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_START_INSTANCE : pipe_cap = 72 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_QUERY_TIMESTAMP : pipe_cap = 73 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_MULTISAMPLE : pipe_cap = 74 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MIN_MAP_BUFFER_ALIGNMENT : pipe_cap = 75 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_CUBE_MAP_ARRAY : pipe_cap = 76 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_BUFFER_OBJECTS : pipe_cap = 77 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_BUFFER_OFFSET_ALIGNMENT : pipe_cap = 78 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_TEXCOORD : pipe_cap = 79 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_PREFER_BLIT_BASED_TEXTURE_TRANSFER : pipe_cap = 80 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_QUERY_PIPELINE_STATISTICS : pipe_cap = 81 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_BORDER_COLOR_QUIRK : pipe_cap = 82 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_TEXTURE_BUFFER_SIZE : pipe_cap = 83 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_VIEWPORTS : pipe_cap = 84 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_ENDIANNESS : pipe_cap = 85 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MIXED_FRAMEBUFFER_SIZES : pipe_cap = 86 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_VS_LAYER_VIEWPORT : pipe_cap = 87 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_GEOMETRY_OUTPUT_VERTICES : pipe_cap = 88 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS : pipe_cap = 89 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_TEXTURE_GATHER_COMPONENTS : pipe_cap = 90 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_GATHER_SM5 : pipe_cap = 91 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_BUFFER_MAP_PERSISTENT_COHERENT : pipe_cap = 92 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_FAKE_SW_MSAA : pipe_cap = 93 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_QUERY_LOD : pipe_cap = 94 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MIN_TEXTURE_GATHER_OFFSET : pipe_cap = 95 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_TEXTURE_GATHER_OFFSET : pipe_cap = 96 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_SAMPLE_SHADING : pipe_cap = 97 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TEXTURE_GATHER_OFFSETS : pipe_cap = 98 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_VS_WINDOW_SPACE_POSITION : pipe_cap = 99 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_VERTEX_STREAMS : pipe_cap = 100 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_DRAW_INDIRECT : pipe_cap = 101 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_TGSI_FS_FINE_DERIVATIVE : pipe_cap = 102 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VENDOR_ID : pipe_cap = 103 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_DEVICE_ID : pipe_cap = 104 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_ACCELERATED : pipe_cap = 105 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VIDEO_MEMORY : pipe_cap = 106 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_UMA : pipe_cap = 107 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_CONDITIONAL_RENDER_INVERTED : pipe_cap = 108 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_MAX_VERTEX_ATTRIB_STRIDE : pipe_cap = 109 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_SAMPLER_VIEW_TARGET : pipe_cap = 110 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_CLIP_HALFZ : pipe_cap = 111 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_VERTEXID_NOBASE : pipe_cap = 112 ; - /// different blend funcs per rendertarget - pub const PIPE_CAP_POLYGON_OFFSET_CLAMP : pipe_cap = 113 ; - /// Implementation capabilities/limits which are queried through -/// pipe_screen::get_param() - pub type pipe_cap = u32 ; pub const PIPE_ENDIAN_LITTLE : pipe_endian = 0 ; pub const PIPE_ENDIAN_BIG : pipe_endian = 1 ; pub const PIPE_ENDIAN_NATIVE : pipe_endian = 0 ; pub type pipe_endian = u32 ; pub const PIPE_CAPF_MAX_LINE_WIDTH : pipe_capf = 0 ; pub const PIPE_CAPF_MAX_LINE_WIDTH_AA : pipe_capf = 1 ; pub const PIPE_CAPF_MAX_POINT_WIDTH : pipe_capf = 2 ; pub const PIPE_CAPF_MAX_POINT_WIDTH_AA : pipe_capf = 3 ; pub const PIPE_CAPF_MAX_TEXTURE_ANISOTROPY : pipe_capf = 4 ; pub const PIPE_CAPF_MAX_TEXTURE_LOD_BIAS : pipe_capf = 5 ; pub const PIPE_CAPF_GUARD_BAND_LEFT : pipe_capf = 6 ; pub const PIPE_CAPF_GUARD_BAND_TOP : pipe_capf = 7 ; pub const PIPE_CAPF_GUARD_BAND_RIGHT : pipe_capf = 8 ; pub const PIPE_CAPF_GUARD_BAND_BOTTOM : pipe_capf = 9 ; - /// Implementation limits which are queried through -/// pipe_screen::get_paramf() - pub type pipe_capf = u32 ; pub const PIPE_SHADER_CAP_MAX_INSTRUCTIONS : pipe_shader_cap = 0 ; pub const PIPE_SHADER_CAP_MAX_ALU_INSTRUCTIONS : pipe_shader_cap = 1 ; pub const PIPE_SHADER_CAP_MAX_TEX_INSTRUCTIONS : pipe_shader_cap = 2 ; pub const PIPE_SHADER_CAP_MAX_TEX_INDIRECTIONS : pipe_shader_cap = 3 ; pub const PIPE_SHADER_CAP_MAX_CONTROL_FLOW_DEPTH : pipe_shader_cap = 4 ; pub const PIPE_SHADER_CAP_MAX_INPUTS : pipe_shader_cap = 5 ; pub const PIPE_SHADER_CAP_MAX_OUTPUTS : pipe_shader_cap = 6 ; pub const PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE : pipe_shader_cap = 7 ; pub const PIPE_SHADER_CAP_MAX_CONST_BUFFERS : pipe_shader_cap = 8 ; pub const PIPE_SHADER_CAP_MAX_TEMPS : pipe_shader_cap = 9 ; pub const PIPE_SHADER_CAP_MAX_PREDS : pipe_shader_cap = 10 ; pub const PIPE_SHADER_CAP_TGSI_CONT_SUPPORTED : pipe_shader_cap = 11 ; pub const PIPE_SHADER_CAP_INDIRECT_INPUT_ADDR : pipe_shader_cap = 12 ; pub const PIPE_SHADER_CAP_INDIRECT_OUTPUT_ADDR : pipe_shader_cap = 13 ; pub const PIPE_SHADER_CAP_INDIRECT_TEMP_ADDR : pipe_shader_cap = 14 ; pub const PIPE_SHADER_CAP_INDIRECT_CONST_ADDR : pipe_shader_cap = 15 ; pub const PIPE_SHADER_CAP_SUBROUTINES : pipe_shader_cap = 16 ; pub const PIPE_SHADER_CAP_INTEGERS : pipe_shader_cap = 17 ; pub const PIPE_SHADER_CAP_MAX_TEXTURE_SAMPLERS : pipe_shader_cap = 18 ; pub const PIPE_SHADER_CAP_PREFERRED_IR : pipe_shader_cap = 19 ; pub const PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED : pipe_shader_cap = 20 ; pub const PIPE_SHADER_CAP_MAX_SAMPLER_VIEWS : pipe_shader_cap = 21 ; pub const PIPE_SHADER_CAP_DOUBLES : pipe_shader_cap = 22 ; pub type pipe_shader_cap = u32 ; pub const PIPE_SHADER_IR_TGSI : pipe_shader_ir = 0 ; pub const PIPE_SHADER_IR_LLVM : pipe_shader_ir = 1 ; pub const PIPE_SHADER_IR_NATIVE : pipe_shader_ir = 2 ; - /// Shader intermediate representation. - pub type pipe_shader_ir = u32 ; pub const PIPE_COMPUTE_CAP_IR_TARGET : pipe_compute_cap = 0 ; pub const PIPE_COMPUTE_CAP_GRID_DIMENSION : pipe_compute_cap = 1 ; pub const PIPE_COMPUTE_CAP_MAX_GRID_SIZE : pipe_compute_cap = 2 ; pub const PIPE_COMPUTE_CAP_MAX_BLOCK_SIZE : pipe_compute_cap = 3 ; pub const PIPE_COMPUTE_CAP_MAX_THREADS_PER_BLOCK : pipe_compute_cap = 4 ; pub const PIPE_COMPUTE_CAP_MAX_GLOBAL_SIZE : pipe_compute_cap = 5 ; pub const PIPE_COMPUTE_CAP_MAX_LOCAL_SIZE : pipe_compute_cap = 6 ; pub const PIPE_COMPUTE_CAP_MAX_PRIVATE_SIZE : pipe_compute_cap = 7 ; pub const PIPE_COMPUTE_CAP_MAX_INPUT_SIZE : pipe_compute_cap = 8 ; pub const PIPE_COMPUTE_CAP_MAX_MEM_ALLOC_SIZE : pipe_compute_cap = 9 ; pub const PIPE_COMPUTE_CAP_MAX_CLOCK_FREQUENCY : pipe_compute_cap = 10 ; pub const PIPE_COMPUTE_CAP_MAX_COMPUTE_UNITS : pipe_compute_cap = 11 ; pub const PIPE_COMPUTE_CAP_IMAGES_SUPPORTED : pipe_compute_cap = 12 ; - /// Compute-specific implementation capability. They can be queried -/// using pipe_screen::get_compute_param. - pub type pipe_compute_cap = u32 ; - /// Query result for PIPE_QUERY_SO_STATISTICS. - # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct pipe_query_data_so_statistics { pub num_primitives_written : u64 , pub primitives_storage_needed : u64 , } - /// Query result for PIPE_QUERY_TIMESTAMP_DISJOINT. - # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct pipe_query_data_timestamp_disjoint { pub frequency : u64 , pub disjoint : boolean , } - /// Query result for PIPE_QUERY_PIPELINE_STATISTICS. - # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct pipe_query_data_pipeline_statistics { - /// < Num vertices read by the vertex fetcher. - pub ia_vertices : u64 , - /// < Num primitives read by the vertex fetcher. - pub ia_primitives : u64 , - /// < Num vertex shader invocations. - pub vs_invocations : u64 , - /// < Num geometry shader invocations. - pub gs_invocations : u64 , - /// < Num primitives output by a geometry shader. - pub gs_primitives : u64 , - /// < Num primitives sent to the rasterizer. - pub c_invocations : u64 , - /// < Num primitives that were rendered. - pub c_primitives : u64 , - /// < Num pixel shader invocations. - pub ps_invocations : u64 , - /// < Num hull shader invocations. - pub hs_invocations : u64 , - /// < Num domain shader invocations. - pub ds_invocations : u64 , - /// < Num compute shader invocations. - pub cs_invocations : u64 , } - /// Query result (returned by pipe_context::get_query_result). - # [ repr ( C ) ] # [ derive ( Copy , Clone ) ] pub union pipe_query_result { pub b : boolean , pub u64 : u64 , pub so_statistics : pipe_query_data_so_statistics , pub timestamp_disjoint : pipe_query_data_timestamp_disjoint , pub pipeline_statistics : pipe_query_data_pipeline_statistics , _bindgen_union_align : [ u64 ; 11usize ] , } # [ repr ( C ) ] # [ derive ( Copy , Clone ) ] pub union pipe_color_union { pub f : [ f32 ; 4usize ] , pub i : [ :: std :: os :: raw :: c_int ; 4usize ] , pub ui : [ :: std :: os :: raw :: c_uint ; 4usize ] , _bindgen_union_align : [ u32 ; 4usize ] , } # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct pipe_driver_query_info { pub name : * const :: std :: os :: raw :: c_char , pub query_type : :: std :: os :: raw :: c_uint , pub max_value : u64 , pub uses_byte_units : boolean , } \ No newline at end of file +/// the resource. +pub const PIPE_TRANSFER_COHERENT: pipe_transfer_usage = 16384; +/// Transfer object usage flags +pub type pipe_transfer_usage = u32; +pub const PIPE_FLUSH_END_OF_FRAME: pipe_flush_flags = 1; +/// Flags for the flush function. +pub type pipe_flush_flags = u32; +pub const PIPE_CAP_NPOT_TEXTURES: pipe_cap = 1; +pub const PIPE_CAP_TWO_SIDED_STENCIL: pipe_cap = 2; +pub const PIPE_CAP_MAX_DUAL_SOURCE_RENDER_TARGETS: pipe_cap = 4; +pub const PIPE_CAP_ANISOTROPIC_FILTER: pipe_cap = 5; +pub const PIPE_CAP_POINT_SPRITE: pipe_cap = 6; +pub const PIPE_CAP_MAX_RENDER_TARGETS: pipe_cap = 7; +pub const PIPE_CAP_OCCLUSION_QUERY: pipe_cap = 8; +pub const PIPE_CAP_QUERY_TIME_ELAPSED: pipe_cap = 9; +pub const PIPE_CAP_TEXTURE_SHADOW_MAP: pipe_cap = 10; +pub const PIPE_CAP_TEXTURE_SWIZZLE: pipe_cap = 11; +pub const PIPE_CAP_MAX_TEXTURE_2D_LEVELS: pipe_cap = 12; +pub const PIPE_CAP_MAX_TEXTURE_3D_LEVELS: pipe_cap = 13; +pub const PIPE_CAP_MAX_TEXTURE_CUBE_LEVELS: pipe_cap = 14; +pub const PIPE_CAP_TEXTURE_MIRROR_CLAMP: pipe_cap = 25; +pub const PIPE_CAP_BLEND_EQUATION_SEPARATE: pipe_cap = 28; +pub const PIPE_CAP_SM3: pipe_cap = 29; +pub const PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS: pipe_cap = 30; +pub const PIPE_CAP_PRIMITIVE_RESTART: pipe_cap = 31; +/// blend enables and write masks per rendertarget +pub const PIPE_CAP_INDEP_BLEND_ENABLE: pipe_cap = 33; +/// different blend funcs per rendertarget +pub const PIPE_CAP_INDEP_BLEND_FUNC: pipe_cap = 34; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS: pipe_cap = 36; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_FS_COORD_ORIGIN_UPPER_LEFT: pipe_cap = 37; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_FS_COORD_ORIGIN_LOWER_LEFT: pipe_cap = 38; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_HALF_INTEGER: pipe_cap = 39; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_FS_COORD_PIXEL_CENTER_INTEGER: pipe_cap = 40; +/// different blend funcs per rendertarget +pub const PIPE_CAP_DEPTH_CLIP_DISABLE: pipe_cap = 41; +/// different blend funcs per rendertarget +pub const PIPE_CAP_SHADER_STENCIL_EXPORT: pipe_cap = 42; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_INSTANCEID: pipe_cap = 43; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEX_ELEMENT_INSTANCE_DIVISOR: pipe_cap = 44; +/// different blend funcs per rendertarget +pub const PIPE_CAP_FRAGMENT_COLOR_CLAMPED: pipe_cap = 45; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MIXED_COLORBUFFER_FORMATS: pipe_cap = 46; +/// different blend funcs per rendertarget +pub const PIPE_CAP_SEAMLESS_CUBE_MAP: pipe_cap = 47; +/// different blend funcs per rendertarget +pub const PIPE_CAP_SEAMLESS_CUBE_MAP_PER_TEXTURE: pipe_cap = 48; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MIN_TEXEL_OFFSET: pipe_cap = 50; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_TEXEL_OFFSET: pipe_cap = 51; +/// different blend funcs per rendertarget +pub const PIPE_CAP_CONDITIONAL_RENDER: pipe_cap = 52; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_BARRIER: pipe_cap = 53; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_STREAM_OUTPUT_SEPARATE_COMPONENTS: pipe_cap = 55; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_STREAM_OUTPUT_INTERLEAVED_COMPONENTS: pipe_cap = 56; +/// different blend funcs per rendertarget +pub const PIPE_CAP_STREAM_OUTPUT_PAUSE_RESUME: pipe_cap = 57; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_CAN_COMPACT_CONSTANTS: pipe_cap = 59; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEX_COLOR_UNCLAMPED: pipe_cap = 60; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEX_COLOR_CLAMPED: pipe_cap = 61; +/// different blend funcs per rendertarget +pub const PIPE_CAP_GLSL_FEATURE_LEVEL: pipe_cap = 62; +/// different blend funcs per rendertarget +pub const PIPE_CAP_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION: pipe_cap = 63; +/// different blend funcs per rendertarget +pub const PIPE_CAP_USER_VERTEX_BUFFERS: pipe_cap = 64; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEX_BUFFER_OFFSET_4BYTE_ALIGNED_ONLY: pipe_cap = 65; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEX_BUFFER_STRIDE_4BYTE_ALIGNED_ONLY: pipe_cap = 66; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEX_ELEMENT_SRC_OFFSET_4BYTE_ALIGNED_ONLY: pipe_cap = 67; +/// different blend funcs per rendertarget +pub const PIPE_CAP_COMPUTE: pipe_cap = 68; +/// different blend funcs per rendertarget +pub const PIPE_CAP_USER_INDEX_BUFFERS: pipe_cap = 69; +/// different blend funcs per rendertarget +pub const PIPE_CAP_USER_CONSTANT_BUFFERS: pipe_cap = 70; +/// different blend funcs per rendertarget +pub const PIPE_CAP_CONSTANT_BUFFER_OFFSET_ALIGNMENT: pipe_cap = 71; +/// different blend funcs per rendertarget +pub const PIPE_CAP_START_INSTANCE: pipe_cap = 72; +/// different blend funcs per rendertarget +pub const PIPE_CAP_QUERY_TIMESTAMP: pipe_cap = 73; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_MULTISAMPLE: pipe_cap = 74; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MIN_MAP_BUFFER_ALIGNMENT: pipe_cap = 75; +/// different blend funcs per rendertarget +pub const PIPE_CAP_CUBE_MAP_ARRAY: pipe_cap = 76; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_BUFFER_OBJECTS: pipe_cap = 77; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_BUFFER_OFFSET_ALIGNMENT: pipe_cap = 78; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_TEXCOORD: pipe_cap = 79; +/// different blend funcs per rendertarget +pub const PIPE_CAP_PREFER_BLIT_BASED_TEXTURE_TRANSFER: pipe_cap = 80; +/// different blend funcs per rendertarget +pub const PIPE_CAP_QUERY_PIPELINE_STATISTICS: pipe_cap = 81; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_BORDER_COLOR_QUIRK: pipe_cap = 82; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_TEXTURE_BUFFER_SIZE: pipe_cap = 83; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_VIEWPORTS: pipe_cap = 84; +/// different blend funcs per rendertarget +pub const PIPE_CAP_ENDIANNESS: pipe_cap = 85; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MIXED_FRAMEBUFFER_SIZES: pipe_cap = 86; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_VS_LAYER_VIEWPORT: pipe_cap = 87; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_GEOMETRY_OUTPUT_VERTICES: pipe_cap = 88; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS: pipe_cap = 89; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_TEXTURE_GATHER_COMPONENTS: pipe_cap = 90; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_GATHER_SM5: pipe_cap = 91; +/// different blend funcs per rendertarget +pub const PIPE_CAP_BUFFER_MAP_PERSISTENT_COHERENT: pipe_cap = 92; +/// different blend funcs per rendertarget +pub const PIPE_CAP_FAKE_SW_MSAA: pipe_cap = 93; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_QUERY_LOD: pipe_cap = 94; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MIN_TEXTURE_GATHER_OFFSET: pipe_cap = 95; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_TEXTURE_GATHER_OFFSET: pipe_cap = 96; +/// different blend funcs per rendertarget +pub const PIPE_CAP_SAMPLE_SHADING: pipe_cap = 97; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TEXTURE_GATHER_OFFSETS: pipe_cap = 98; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_VS_WINDOW_SPACE_POSITION: pipe_cap = 99; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_VERTEX_STREAMS: pipe_cap = 100; +/// different blend funcs per rendertarget +pub const PIPE_CAP_DRAW_INDIRECT: pipe_cap = 101; +/// different blend funcs per rendertarget +pub const PIPE_CAP_TGSI_FS_FINE_DERIVATIVE: pipe_cap = 102; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VENDOR_ID: pipe_cap = 103; +/// different blend funcs per rendertarget +pub const PIPE_CAP_DEVICE_ID: pipe_cap = 104; +/// different blend funcs per rendertarget +pub const PIPE_CAP_ACCELERATED: pipe_cap = 105; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VIDEO_MEMORY: pipe_cap = 106; +/// different blend funcs per rendertarget +pub const PIPE_CAP_UMA: pipe_cap = 107; +/// different blend funcs per rendertarget +pub const PIPE_CAP_CONDITIONAL_RENDER_INVERTED: pipe_cap = 108; +/// different blend funcs per rendertarget +pub const PIPE_CAP_MAX_VERTEX_ATTRIB_STRIDE: pipe_cap = 109; +/// different blend funcs per rendertarget +pub const PIPE_CAP_SAMPLER_VIEW_TARGET: pipe_cap = 110; +/// different blend funcs per rendertarget +pub const PIPE_CAP_CLIP_HALFZ: pipe_cap = 111; +/// different blend funcs per rendertarget +pub const PIPE_CAP_VERTEXID_NOBASE: pipe_cap = 112; +/// different blend funcs per rendertarget +pub const PIPE_CAP_POLYGON_OFFSET_CLAMP: pipe_cap = 113; +/// Implementation capabilities/limits which are queried through +/// pipe_screen::get_param() +pub type pipe_cap = u32; +pub const PIPE_ENDIAN_LITTLE: pipe_endian = 0; +pub const PIPE_ENDIAN_BIG: pipe_endian = 1; +pub const PIPE_ENDIAN_NATIVE: pipe_endian = 0; +pub type pipe_endian = u32; +pub const PIPE_CAPF_MAX_LINE_WIDTH: pipe_capf = 0; +pub const PIPE_CAPF_MAX_LINE_WIDTH_AA: pipe_capf = 1; +pub const PIPE_CAPF_MAX_POINT_WIDTH: pipe_capf = 2; +pub const PIPE_CAPF_MAX_POINT_WIDTH_AA: pipe_capf = 3; +pub const PIPE_CAPF_MAX_TEXTURE_ANISOTROPY: pipe_capf = 4; +pub const PIPE_CAPF_MAX_TEXTURE_LOD_BIAS: pipe_capf = 5; +pub const PIPE_CAPF_GUARD_BAND_LEFT: pipe_capf = 6; +pub const PIPE_CAPF_GUARD_BAND_TOP: pipe_capf = 7; +pub const PIPE_CAPF_GUARD_BAND_RIGHT: pipe_capf = 8; +pub const PIPE_CAPF_GUARD_BAND_BOTTOM: pipe_capf = 9; +/// Implementation limits which are queried through +/// pipe_screen::get_paramf() +pub type pipe_capf = u32; +pub const PIPE_SHADER_CAP_MAX_INSTRUCTIONS: pipe_shader_cap = 0; +pub const PIPE_SHADER_CAP_MAX_ALU_INSTRUCTIONS: pipe_shader_cap = 1; +pub const PIPE_SHADER_CAP_MAX_TEX_INSTRUCTIONS: pipe_shader_cap = 2; +pub const PIPE_SHADER_CAP_MAX_TEX_INDIRECTIONS: pipe_shader_cap = 3; +pub const PIPE_SHADER_CAP_MAX_CONTROL_FLOW_DEPTH: pipe_shader_cap = 4; +pub const PIPE_SHADER_CAP_MAX_INPUTS: pipe_shader_cap = 5; +pub const PIPE_SHADER_CAP_MAX_OUTPUTS: pipe_shader_cap = 6; +pub const PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE: pipe_shader_cap = 7; +pub const PIPE_SHADER_CAP_MAX_CONST_BUFFERS: pipe_shader_cap = 8; +pub const PIPE_SHADER_CAP_MAX_TEMPS: pipe_shader_cap = 9; +pub const PIPE_SHADER_CAP_MAX_PREDS: pipe_shader_cap = 10; +pub const PIPE_SHADER_CAP_TGSI_CONT_SUPPORTED: pipe_shader_cap = 11; +pub const PIPE_SHADER_CAP_INDIRECT_INPUT_ADDR: pipe_shader_cap = 12; +pub const PIPE_SHADER_CAP_INDIRECT_OUTPUT_ADDR: pipe_shader_cap = 13; +pub const PIPE_SHADER_CAP_INDIRECT_TEMP_ADDR: pipe_shader_cap = 14; +pub const PIPE_SHADER_CAP_INDIRECT_CONST_ADDR: pipe_shader_cap = 15; +pub const PIPE_SHADER_CAP_SUBROUTINES: pipe_shader_cap = 16; +pub const PIPE_SHADER_CAP_INTEGERS: pipe_shader_cap = 17; +pub const PIPE_SHADER_CAP_MAX_TEXTURE_SAMPLERS: pipe_shader_cap = 18; +pub const PIPE_SHADER_CAP_PREFERRED_IR: pipe_shader_cap = 19; +pub const PIPE_SHADER_CAP_TGSI_SQRT_SUPPORTED: pipe_shader_cap = 20; +pub const PIPE_SHADER_CAP_MAX_SAMPLER_VIEWS: pipe_shader_cap = 21; +pub const PIPE_SHADER_CAP_DOUBLES: pipe_shader_cap = 22; +pub type pipe_shader_cap = u32; +pub const PIPE_SHADER_IR_TGSI: pipe_shader_ir = 0; +pub const PIPE_SHADER_IR_LLVM: pipe_shader_ir = 1; +pub const PIPE_SHADER_IR_NATIVE: pipe_shader_ir = 2; +/// Shader intermediate representation. +pub type pipe_shader_ir = u32; +pub const PIPE_COMPUTE_CAP_IR_TARGET: pipe_compute_cap = 0; +pub const PIPE_COMPUTE_CAP_GRID_DIMENSION: pipe_compute_cap = 1; +pub const PIPE_COMPUTE_CAP_MAX_GRID_SIZE: pipe_compute_cap = 2; +pub const PIPE_COMPUTE_CAP_MAX_BLOCK_SIZE: pipe_compute_cap = 3; +pub const PIPE_COMPUTE_CAP_MAX_THREADS_PER_BLOCK: pipe_compute_cap = 4; +pub const PIPE_COMPUTE_CAP_MAX_GLOBAL_SIZE: pipe_compute_cap = 5; +pub const PIPE_COMPUTE_CAP_MAX_LOCAL_SIZE: pipe_compute_cap = 6; +pub const PIPE_COMPUTE_CAP_MAX_PRIVATE_SIZE: pipe_compute_cap = 7; +pub const PIPE_COMPUTE_CAP_MAX_INPUT_SIZE: pipe_compute_cap = 8; +pub const PIPE_COMPUTE_CAP_MAX_MEM_ALLOC_SIZE: pipe_compute_cap = 9; +pub const PIPE_COMPUTE_CAP_MAX_CLOCK_FREQUENCY: pipe_compute_cap = 10; +pub const PIPE_COMPUTE_CAP_MAX_COMPUTE_UNITS: pipe_compute_cap = 11; +pub const PIPE_COMPUTE_CAP_IMAGES_SUPPORTED: pipe_compute_cap = 12; +/// Compute-specific implementation capability. They can be queried +/// using pipe_screen::get_compute_param. +pub type pipe_compute_cap = u32; +/// Query result for PIPE_QUERY_SO_STATISTICS. +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct pipe_query_data_so_statistics { + pub num_primitives_written: u64, + pub primitives_storage_needed: u64, +} +/// Query result for PIPE_QUERY_TIMESTAMP_DISJOINT. +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct pipe_query_data_timestamp_disjoint { + pub frequency: u64, + pub disjoint: boolean, +} +/// Query result for PIPE_QUERY_PIPELINE_STATISTICS. +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct pipe_query_data_pipeline_statistics { + /// < Num vertices read by the vertex fetcher. + pub ia_vertices: u64, + /// < Num primitives read by the vertex fetcher. + pub ia_primitives: u64, + /// < Num vertex shader invocations. + pub vs_invocations: u64, + /// < Num geometry shader invocations. + pub gs_invocations: u64, + /// < Num primitives output by a geometry shader. + pub gs_primitives: u64, + /// < Num primitives sent to the rasterizer. + pub c_invocations: u64, + /// < Num primitives that were rendered. + pub c_primitives: u64, + /// < Num pixel shader invocations. + pub ps_invocations: u64, + /// < Num hull shader invocations. + pub hs_invocations: u64, + /// < Num domain shader invocations. + pub ds_invocations: u64, + /// < Num compute shader invocations. + pub cs_invocations: u64, +} +/// Query result (returned by pipe_context::get_query_result). +#[repr(C)] +#[derive(Copy, Clone)] +pub union pipe_query_result { + pub b: boolean, + pub u64: u64, + pub so_statistics: pipe_query_data_so_statistics, + pub timestamp_disjoint: pipe_query_data_timestamp_disjoint, + pub pipeline_statistics: pipe_query_data_pipeline_statistics, + _bindgen_union_align: [u64; 11usize], +} +#[repr(C)] +#[derive(Copy, Clone)] +pub union pipe_color_union { + pub f: [f32; 4usize], + pub i: [::std::os::raw::c_int; 4usize], + pub ui: [::std::os::raw::c_uint; 4usize], + _bindgen_union_align: [u32; 4usize], +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct pipe_driver_query_info { + pub name: *const ::std::os::raw::c_char, + pub query_type: ::std::os::raw::c_uint, + pub max_value: u64, + pub uses_byte_units: boolean, +} diff --git a/gpu_renderer/src/generated/p_format.rs b/gpu_renderer/src/generated/p_format.rs index 13f3d0b..ee86907 100644 --- a/gpu_renderer/src/generated/p_format.rs +++ b/gpu_renderer/src/generated/p_format.rs @@ -1,19 +1,318 @@ /* automatically generated by rust-bindgen */ -pub const PIPE_FORMAT_NONE : pipe_format = 0 ; pub const PIPE_FORMAT_B8G8R8A8_UNORM : pipe_format = 1 ; pub const PIPE_FORMAT_B8G8R8X8_UNORM : pipe_format = 2 ; pub const PIPE_FORMAT_A8R8G8B8_UNORM : pipe_format = 3 ; pub const PIPE_FORMAT_X8R8G8B8_UNORM : pipe_format = 4 ; pub const PIPE_FORMAT_B5G5R5A1_UNORM : pipe_format = 5 ; pub const PIPE_FORMAT_B4G4R4A4_UNORM : pipe_format = 6 ; pub const PIPE_FORMAT_B5G6R5_UNORM : pipe_format = 7 ; pub const PIPE_FORMAT_R10G10B10A2_UNORM : pipe_format = 8 ; - /// < ubyte luminance - pub const PIPE_FORMAT_L8_UNORM : pipe_format = 9 ; - /// < ubyte alpha - pub const PIPE_FORMAT_A8_UNORM : pipe_format = 10 ; - /// < ubyte intensity - pub const PIPE_FORMAT_I8_UNORM : pipe_format = 11 ; - /// < ubyte alpha, luminance - pub const PIPE_FORMAT_L8A8_UNORM : pipe_format = 12 ; - /// < ushort luminance - pub const PIPE_FORMAT_L16_UNORM : pipe_format = 13 ; pub const PIPE_FORMAT_UYVY : pipe_format = 14 ; pub const PIPE_FORMAT_YUYV : pipe_format = 15 ; pub const PIPE_FORMAT_Z16_UNORM : pipe_format = 16 ; pub const PIPE_FORMAT_Z32_UNORM : pipe_format = 17 ; pub const PIPE_FORMAT_Z32_FLOAT : pipe_format = 18 ; pub const PIPE_FORMAT_Z24_UNORM_S8_UINT : pipe_format = 19 ; pub const PIPE_FORMAT_S8_UINT_Z24_UNORM : pipe_format = 20 ; pub const PIPE_FORMAT_Z24X8_UNORM : pipe_format = 21 ; pub const PIPE_FORMAT_X8Z24_UNORM : pipe_format = 22 ; - /// < ubyte stencil - pub const PIPE_FORMAT_S8_UINT : pipe_format = 23 ; pub const PIPE_FORMAT_R64_FLOAT : pipe_format = 24 ; pub const PIPE_FORMAT_R64G64_FLOAT : pipe_format = 25 ; pub const PIPE_FORMAT_R64G64B64_FLOAT : pipe_format = 26 ; pub const PIPE_FORMAT_R64G64B64A64_FLOAT : pipe_format = 27 ; pub const PIPE_FORMAT_R32_FLOAT : pipe_format = 28 ; pub const PIPE_FORMAT_R32G32_FLOAT : pipe_format = 29 ; pub const PIPE_FORMAT_R32G32B32_FLOAT : pipe_format = 30 ; pub const PIPE_FORMAT_R32G32B32A32_FLOAT : pipe_format = 31 ; pub const PIPE_FORMAT_R32_UNORM : pipe_format = 32 ; pub const PIPE_FORMAT_R32G32_UNORM : pipe_format = 33 ; pub const PIPE_FORMAT_R32G32B32_UNORM : pipe_format = 34 ; pub const PIPE_FORMAT_R32G32B32A32_UNORM : pipe_format = 35 ; pub const PIPE_FORMAT_R32_USCALED : pipe_format = 36 ; pub const PIPE_FORMAT_R32G32_USCALED : pipe_format = 37 ; pub const PIPE_FORMAT_R32G32B32_USCALED : pipe_format = 38 ; pub const PIPE_FORMAT_R32G32B32A32_USCALED : pipe_format = 39 ; pub const PIPE_FORMAT_R32_SNORM : pipe_format = 40 ; pub const PIPE_FORMAT_R32G32_SNORM : pipe_format = 41 ; pub const PIPE_FORMAT_R32G32B32_SNORM : pipe_format = 42 ; pub const PIPE_FORMAT_R32G32B32A32_SNORM : pipe_format = 43 ; pub const PIPE_FORMAT_R32_SSCALED : pipe_format = 44 ; pub const PIPE_FORMAT_R32G32_SSCALED : pipe_format = 45 ; pub const PIPE_FORMAT_R32G32B32_SSCALED : pipe_format = 46 ; pub const PIPE_FORMAT_R32G32B32A32_SSCALED : pipe_format = 47 ; pub const PIPE_FORMAT_R16_UNORM : pipe_format = 48 ; pub const PIPE_FORMAT_R16G16_UNORM : pipe_format = 49 ; pub const PIPE_FORMAT_R16G16B16_UNORM : pipe_format = 50 ; pub const PIPE_FORMAT_R16G16B16A16_UNORM : pipe_format = 51 ; pub const PIPE_FORMAT_R16_USCALED : pipe_format = 52 ; pub const PIPE_FORMAT_R16G16_USCALED : pipe_format = 53 ; pub const PIPE_FORMAT_R16G16B16_USCALED : pipe_format = 54 ; pub const PIPE_FORMAT_R16G16B16A16_USCALED : pipe_format = 55 ; pub const PIPE_FORMAT_R16_SNORM : pipe_format = 56 ; pub const PIPE_FORMAT_R16G16_SNORM : pipe_format = 57 ; pub const PIPE_FORMAT_R16G16B16_SNORM : pipe_format = 58 ; pub const PIPE_FORMAT_R16G16B16A16_SNORM : pipe_format = 59 ; pub const PIPE_FORMAT_R16_SSCALED : pipe_format = 60 ; pub const PIPE_FORMAT_R16G16_SSCALED : pipe_format = 61 ; pub const PIPE_FORMAT_R16G16B16_SSCALED : pipe_format = 62 ; pub const PIPE_FORMAT_R16G16B16A16_SSCALED : pipe_format = 63 ; pub const PIPE_FORMAT_R8_UNORM : pipe_format = 64 ; pub const PIPE_FORMAT_R8G8_UNORM : pipe_format = 65 ; pub const PIPE_FORMAT_R8G8B8_UNORM : pipe_format = 66 ; pub const PIPE_FORMAT_R8G8B8A8_UNORM : pipe_format = 67 ; pub const PIPE_FORMAT_X8B8G8R8_UNORM : pipe_format = 68 ; pub const PIPE_FORMAT_R8_USCALED : pipe_format = 69 ; pub const PIPE_FORMAT_R8G8_USCALED : pipe_format = 70 ; pub const PIPE_FORMAT_R8G8B8_USCALED : pipe_format = 71 ; pub const PIPE_FORMAT_R8G8B8A8_USCALED : pipe_format = 72 ; pub const PIPE_FORMAT_R8_SNORM : pipe_format = 74 ; pub const PIPE_FORMAT_R8G8_SNORM : pipe_format = 75 ; pub const PIPE_FORMAT_R8G8B8_SNORM : pipe_format = 76 ; pub const PIPE_FORMAT_R8G8B8A8_SNORM : pipe_format = 77 ; pub const PIPE_FORMAT_R8_SSCALED : pipe_format = 82 ; pub const PIPE_FORMAT_R8G8_SSCALED : pipe_format = 83 ; pub const PIPE_FORMAT_R8G8B8_SSCALED : pipe_format = 84 ; pub const PIPE_FORMAT_R8G8B8A8_SSCALED : pipe_format = 85 ; pub const PIPE_FORMAT_R32_FIXED : pipe_format = 87 ; pub const PIPE_FORMAT_R32G32_FIXED : pipe_format = 88 ; pub const PIPE_FORMAT_R32G32B32_FIXED : pipe_format = 89 ; pub const PIPE_FORMAT_R32G32B32A32_FIXED : pipe_format = 90 ; pub const PIPE_FORMAT_R16_FLOAT : pipe_format = 91 ; pub const PIPE_FORMAT_R16G16_FLOAT : pipe_format = 92 ; pub const PIPE_FORMAT_R16G16B16_FLOAT : pipe_format = 93 ; pub const PIPE_FORMAT_R16G16B16A16_FLOAT : pipe_format = 94 ; pub const PIPE_FORMAT_L8_SRGB : pipe_format = 95 ; pub const PIPE_FORMAT_L8A8_SRGB : pipe_format = 96 ; pub const PIPE_FORMAT_R8G8B8_SRGB : pipe_format = 97 ; pub const PIPE_FORMAT_A8B8G8R8_SRGB : pipe_format = 98 ; pub const PIPE_FORMAT_X8B8G8R8_SRGB : pipe_format = 99 ; pub const PIPE_FORMAT_B8G8R8A8_SRGB : pipe_format = 100 ; pub const PIPE_FORMAT_B8G8R8X8_SRGB : pipe_format = 101 ; pub const PIPE_FORMAT_A8R8G8B8_SRGB : pipe_format = 102 ; pub const PIPE_FORMAT_X8R8G8B8_SRGB : pipe_format = 103 ; pub const PIPE_FORMAT_R8G8B8A8_SRGB : pipe_format = 104 ; pub const PIPE_FORMAT_DXT1_RGB : pipe_format = 105 ; pub const PIPE_FORMAT_DXT1_RGBA : pipe_format = 106 ; pub const PIPE_FORMAT_DXT3_RGBA : pipe_format = 107 ; pub const PIPE_FORMAT_DXT5_RGBA : pipe_format = 108 ; pub const PIPE_FORMAT_DXT1_SRGB : pipe_format = 109 ; pub const PIPE_FORMAT_DXT1_SRGBA : pipe_format = 110 ; pub const PIPE_FORMAT_DXT3_SRGBA : pipe_format = 111 ; pub const PIPE_FORMAT_DXT5_SRGBA : pipe_format = 112 ; pub const PIPE_FORMAT_RGTC1_UNORM : pipe_format = 113 ; pub const PIPE_FORMAT_RGTC1_SNORM : pipe_format = 114 ; pub const PIPE_FORMAT_RGTC2_UNORM : pipe_format = 115 ; pub const PIPE_FORMAT_RGTC2_SNORM : pipe_format = 116 ; pub const PIPE_FORMAT_R8G8_B8G8_UNORM : pipe_format = 117 ; pub const PIPE_FORMAT_G8R8_G8B8_UNORM : pipe_format = 118 ; pub const PIPE_FORMAT_R8SG8SB8UX8U_NORM : pipe_format = 119 ; pub const PIPE_FORMAT_R5SG5SB6U_NORM : pipe_format = 120 ; pub const PIPE_FORMAT_A8B8G8R8_UNORM : pipe_format = 121 ; pub const PIPE_FORMAT_B5G5R5X1_UNORM : pipe_format = 122 ; pub const PIPE_FORMAT_R10G10B10A2_USCALED : pipe_format = 123 ; pub const PIPE_FORMAT_R11G11B10_FLOAT : pipe_format = 124 ; pub const PIPE_FORMAT_R9G9B9E5_FLOAT : pipe_format = 125 ; pub const PIPE_FORMAT_Z32_FLOAT_S8X24_UINT : pipe_format = 126 ; pub const PIPE_FORMAT_R1_UNORM : pipe_format = 127 ; pub const PIPE_FORMAT_R10G10B10X2_USCALED : pipe_format = 128 ; pub const PIPE_FORMAT_R10G10B10X2_SNORM : pipe_format = 129 ; pub const PIPE_FORMAT_L4A4_UNORM : pipe_format = 130 ; pub const PIPE_FORMAT_B10G10R10A2_UNORM : pipe_format = 131 ; pub const PIPE_FORMAT_R10SG10SB10SA2U_NORM : pipe_format = 132 ; pub const PIPE_FORMAT_R8G8Bx_SNORM : pipe_format = 133 ; pub const PIPE_FORMAT_R8G8B8X8_UNORM : pipe_format = 134 ; pub const PIPE_FORMAT_B4G4R4X4_UNORM : pipe_format = 135 ; pub const PIPE_FORMAT_X24S8_UINT : pipe_format = 136 ; pub const PIPE_FORMAT_S8X24_UINT : pipe_format = 137 ; pub const PIPE_FORMAT_X32_S8X24_UINT : pipe_format = 138 ; pub const PIPE_FORMAT_B2G3R3_UNORM : pipe_format = 139 ; pub const PIPE_FORMAT_L16A16_UNORM : pipe_format = 140 ; pub const PIPE_FORMAT_A16_UNORM : pipe_format = 141 ; pub const PIPE_FORMAT_I16_UNORM : pipe_format = 142 ; pub const PIPE_FORMAT_LATC1_UNORM : pipe_format = 143 ; pub const PIPE_FORMAT_LATC1_SNORM : pipe_format = 144 ; pub const PIPE_FORMAT_LATC2_UNORM : pipe_format = 145 ; pub const PIPE_FORMAT_LATC2_SNORM : pipe_format = 146 ; pub const PIPE_FORMAT_A8_SNORM : pipe_format = 147 ; pub const PIPE_FORMAT_L8_SNORM : pipe_format = 148 ; pub const PIPE_FORMAT_L8A8_SNORM : pipe_format = 149 ; pub const PIPE_FORMAT_I8_SNORM : pipe_format = 150 ; pub const PIPE_FORMAT_A16_SNORM : pipe_format = 151 ; pub const PIPE_FORMAT_L16_SNORM : pipe_format = 152 ; pub const PIPE_FORMAT_L16A16_SNORM : pipe_format = 153 ; pub const PIPE_FORMAT_I16_SNORM : pipe_format = 154 ; pub const PIPE_FORMAT_A16_FLOAT : pipe_format = 155 ; pub const PIPE_FORMAT_L16_FLOAT : pipe_format = 156 ; pub const PIPE_FORMAT_L16A16_FLOAT : pipe_format = 157 ; pub const PIPE_FORMAT_I16_FLOAT : pipe_format = 158 ; pub const PIPE_FORMAT_A32_FLOAT : pipe_format = 159 ; pub const PIPE_FORMAT_L32_FLOAT : pipe_format = 160 ; pub const PIPE_FORMAT_L32A32_FLOAT : pipe_format = 161 ; pub const PIPE_FORMAT_I32_FLOAT : pipe_format = 162 ; pub const PIPE_FORMAT_YV12 : pipe_format = 163 ; pub const PIPE_FORMAT_YV16 : pipe_format = 164 ; - /// < aka I420 - pub const PIPE_FORMAT_IYUV : pipe_format = 165 ; pub const PIPE_FORMAT_NV12 : pipe_format = 166 ; pub const PIPE_FORMAT_NV21 : pipe_format = 167 ; pub const PIPE_FORMAT_A4R4_UNORM : pipe_format = 168 ; pub const PIPE_FORMAT_R4A4_UNORM : pipe_format = 169 ; pub const PIPE_FORMAT_R8A8_UNORM : pipe_format = 170 ; pub const PIPE_FORMAT_A8R8_UNORM : pipe_format = 171 ; pub const PIPE_FORMAT_R10G10B10A2_SSCALED : pipe_format = 172 ; pub const PIPE_FORMAT_R10G10B10A2_SNORM : pipe_format = 173 ; pub const PIPE_FORMAT_B10G10R10A2_USCALED : pipe_format = 174 ; pub const PIPE_FORMAT_B10G10R10A2_SSCALED : pipe_format = 175 ; pub const PIPE_FORMAT_B10G10R10A2_SNORM : pipe_format = 176 ; pub const PIPE_FORMAT_R8_UINT : pipe_format = 177 ; pub const PIPE_FORMAT_R8G8_UINT : pipe_format = 178 ; pub const PIPE_FORMAT_R8G8B8_UINT : pipe_format = 179 ; pub const PIPE_FORMAT_R8G8B8A8_UINT : pipe_format = 180 ; pub const PIPE_FORMAT_R8_SINT : pipe_format = 181 ; pub const PIPE_FORMAT_R8G8_SINT : pipe_format = 182 ; pub const PIPE_FORMAT_R8G8B8_SINT : pipe_format = 183 ; pub const PIPE_FORMAT_R8G8B8A8_SINT : pipe_format = 184 ; pub const PIPE_FORMAT_R16_UINT : pipe_format = 185 ; pub const PIPE_FORMAT_R16G16_UINT : pipe_format = 186 ; pub const PIPE_FORMAT_R16G16B16_UINT : pipe_format = 187 ; pub const PIPE_FORMAT_R16G16B16A16_UINT : pipe_format = 188 ; pub const PIPE_FORMAT_R16_SINT : pipe_format = 189 ; pub const PIPE_FORMAT_R16G16_SINT : pipe_format = 190 ; pub const PIPE_FORMAT_R16G16B16_SINT : pipe_format = 191 ; pub const PIPE_FORMAT_R16G16B16A16_SINT : pipe_format = 192 ; pub const PIPE_FORMAT_R32_UINT : pipe_format = 193 ; pub const PIPE_FORMAT_R32G32_UINT : pipe_format = 194 ; pub const PIPE_FORMAT_R32G32B32_UINT : pipe_format = 195 ; pub const PIPE_FORMAT_R32G32B32A32_UINT : pipe_format = 196 ; pub const PIPE_FORMAT_R32_SINT : pipe_format = 197 ; pub const PIPE_FORMAT_R32G32_SINT : pipe_format = 198 ; pub const PIPE_FORMAT_R32G32B32_SINT : pipe_format = 199 ; pub const PIPE_FORMAT_R32G32B32A32_SINT : pipe_format = 200 ; pub const PIPE_FORMAT_A8_UINT : pipe_format = 201 ; pub const PIPE_FORMAT_I8_UINT : pipe_format = 202 ; pub const PIPE_FORMAT_L8_UINT : pipe_format = 203 ; pub const PIPE_FORMAT_L8A8_UINT : pipe_format = 204 ; pub const PIPE_FORMAT_A8_SINT : pipe_format = 205 ; pub const PIPE_FORMAT_I8_SINT : pipe_format = 206 ; pub const PIPE_FORMAT_L8_SINT : pipe_format = 207 ; pub const PIPE_FORMAT_L8A8_SINT : pipe_format = 208 ; pub const PIPE_FORMAT_A16_UINT : pipe_format = 209 ; pub const PIPE_FORMAT_I16_UINT : pipe_format = 210 ; pub const PIPE_FORMAT_L16_UINT : pipe_format = 211 ; pub const PIPE_FORMAT_L16A16_UINT : pipe_format = 212 ; pub const PIPE_FORMAT_A16_SINT : pipe_format = 213 ; pub const PIPE_FORMAT_I16_SINT : pipe_format = 214 ; pub const PIPE_FORMAT_L16_SINT : pipe_format = 215 ; pub const PIPE_FORMAT_L16A16_SINT : pipe_format = 216 ; pub const PIPE_FORMAT_A32_UINT : pipe_format = 217 ; pub const PIPE_FORMAT_I32_UINT : pipe_format = 218 ; pub const PIPE_FORMAT_L32_UINT : pipe_format = 219 ; pub const PIPE_FORMAT_L32A32_UINT : pipe_format = 220 ; pub const PIPE_FORMAT_A32_SINT : pipe_format = 221 ; pub const PIPE_FORMAT_I32_SINT : pipe_format = 222 ; pub const PIPE_FORMAT_L32_SINT : pipe_format = 223 ; pub const PIPE_FORMAT_L32A32_SINT : pipe_format = 224 ; pub const PIPE_FORMAT_B10G10R10A2_UINT : pipe_format = 225 ; pub const PIPE_FORMAT_ETC1_RGB8 : pipe_format = 226 ; pub const PIPE_FORMAT_R8G8_R8B8_UNORM : pipe_format = 227 ; pub const PIPE_FORMAT_G8R8_B8R8_UNORM : pipe_format = 228 ; pub const PIPE_FORMAT_R8G8B8X8_SNORM : pipe_format = 229 ; pub const PIPE_FORMAT_R8G8B8X8_SRGB : pipe_format = 230 ; pub const PIPE_FORMAT_R8G8B8X8_UINT : pipe_format = 231 ; pub const PIPE_FORMAT_R8G8B8X8_SINT : pipe_format = 232 ; pub const PIPE_FORMAT_B10G10R10X2_UNORM : pipe_format = 233 ; pub const PIPE_FORMAT_R16G16B16X16_UNORM : pipe_format = 234 ; pub const PIPE_FORMAT_R16G16B16X16_SNORM : pipe_format = 235 ; pub const PIPE_FORMAT_R16G16B16X16_FLOAT : pipe_format = 236 ; pub const PIPE_FORMAT_R16G16B16X16_UINT : pipe_format = 237 ; pub const PIPE_FORMAT_R16G16B16X16_SINT : pipe_format = 238 ; pub const PIPE_FORMAT_R32G32B32X32_FLOAT : pipe_format = 239 ; pub const PIPE_FORMAT_R32G32B32X32_UINT : pipe_format = 240 ; pub const PIPE_FORMAT_R32G32B32X32_SINT : pipe_format = 241 ; pub const PIPE_FORMAT_R8A8_SNORM : pipe_format = 242 ; pub const PIPE_FORMAT_R16A16_UNORM : pipe_format = 243 ; pub const PIPE_FORMAT_R16A16_SNORM : pipe_format = 244 ; pub const PIPE_FORMAT_R16A16_FLOAT : pipe_format = 245 ; pub const PIPE_FORMAT_R32A32_FLOAT : pipe_format = 246 ; pub const PIPE_FORMAT_R8A8_UINT : pipe_format = 247 ; pub const PIPE_FORMAT_R8A8_SINT : pipe_format = 248 ; pub const PIPE_FORMAT_R16A16_UINT : pipe_format = 249 ; pub const PIPE_FORMAT_R16A16_SINT : pipe_format = 250 ; pub const PIPE_FORMAT_R32A32_UINT : pipe_format = 251 ; pub const PIPE_FORMAT_R32A32_SINT : pipe_format = 252 ; pub const PIPE_FORMAT_R10G10B10A2_UINT : pipe_format = 253 ; pub const PIPE_FORMAT_B5G6R5_SRGB : pipe_format = 254 ; pub const PIPE_FORMAT_BPTC_RGBA_UNORM : pipe_format = 255 ; pub const PIPE_FORMAT_BPTC_SRGBA : pipe_format = 256 ; pub const PIPE_FORMAT_BPTC_RGB_FLOAT : pipe_format = 257 ; pub const PIPE_FORMAT_BPTC_RGB_UFLOAT : pipe_format = 258 ; pub const PIPE_FORMAT_A8L8_UNORM : pipe_format = 259 ; pub const PIPE_FORMAT_A8L8_SNORM : pipe_format = 260 ; pub const PIPE_FORMAT_A8L8_SRGB : pipe_format = 261 ; pub const PIPE_FORMAT_A16L16_UNORM : pipe_format = 262 ; pub const PIPE_FORMAT_G8R8_UNORM : pipe_format = 263 ; pub const PIPE_FORMAT_G8R8_SNORM : pipe_format = 264 ; pub const PIPE_FORMAT_G16R16_UNORM : pipe_format = 265 ; pub const PIPE_FORMAT_G16R16_SNORM : pipe_format = 266 ; pub const PIPE_FORMAT_A8B8G8R8_SNORM : pipe_format = 267 ; pub const PIPE_FORMAT_X8B8G8R8_SNORM : pipe_format = 268 ; pub const PIPE_FORMAT_ETC2_RGB8 : pipe_format = 269 ; pub const PIPE_FORMAT_ETC2_SRGB8 : pipe_format = 270 ; pub const PIPE_FORMAT_ETC2_RGB8A1 : pipe_format = 271 ; pub const PIPE_FORMAT_ETC2_SRGB8A1 : pipe_format = 272 ; pub const PIPE_FORMAT_ETC2_RGBA8 : pipe_format = 273 ; pub const PIPE_FORMAT_ETC2_SRGBA8 : pipe_format = 274 ; pub const PIPE_FORMAT_ETC2_R11_UNORM : pipe_format = 275 ; pub const PIPE_FORMAT_ETC2_R11_SNORM : pipe_format = 276 ; pub const PIPE_FORMAT_ETC2_RG11_UNORM : pipe_format = 277 ; pub const PIPE_FORMAT_ETC2_RG11_SNORM : pipe_format = 278 ; pub const PIPE_FORMAT_ASTC_4x4 : pipe_format = 279 ; pub const PIPE_FORMAT_ASTC_5x4 : pipe_format = 280 ; pub const PIPE_FORMAT_ASTC_5x5 : pipe_format = 281 ; pub const PIPE_FORMAT_ASTC_6x5 : pipe_format = 282 ; pub const PIPE_FORMAT_ASTC_6x6 : pipe_format = 283 ; pub const PIPE_FORMAT_ASTC_8x5 : pipe_format = 284 ; pub const PIPE_FORMAT_ASTC_8x6 : pipe_format = 285 ; pub const PIPE_FORMAT_ASTC_8x8 : pipe_format = 286 ; pub const PIPE_FORMAT_ASTC_10x5 : pipe_format = 287 ; pub const PIPE_FORMAT_ASTC_10x6 : pipe_format = 288 ; pub const PIPE_FORMAT_ASTC_10x8 : pipe_format = 289 ; pub const PIPE_FORMAT_ASTC_10x10 : pipe_format = 290 ; pub const PIPE_FORMAT_ASTC_12x10 : pipe_format = 291 ; pub const PIPE_FORMAT_ASTC_12x12 : pipe_format = 292 ; pub const PIPE_FORMAT_ASTC_4x4_SRGB : pipe_format = 293 ; pub const PIPE_FORMAT_ASTC_5x4_SRGB : pipe_format = 294 ; pub const PIPE_FORMAT_ASTC_5x5_SRGB : pipe_format = 295 ; pub const PIPE_FORMAT_ASTC_6x5_SRGB : pipe_format = 296 ; pub const PIPE_FORMAT_ASTC_6x6_SRGB : pipe_format = 297 ; pub const PIPE_FORMAT_ASTC_8x5_SRGB : pipe_format = 298 ; pub const PIPE_FORMAT_ASTC_8x6_SRGB : pipe_format = 299 ; pub const PIPE_FORMAT_ASTC_8x8_SRGB : pipe_format = 300 ; pub const PIPE_FORMAT_ASTC_10x5_SRGB : pipe_format = 301 ; pub const PIPE_FORMAT_ASTC_10x6_SRGB : pipe_format = 302 ; pub const PIPE_FORMAT_ASTC_10x8_SRGB : pipe_format = 303 ; pub const PIPE_FORMAT_ASTC_10x10_SRGB : pipe_format = 304 ; pub const PIPE_FORMAT_ASTC_12x10_SRGB : pipe_format = 305 ; pub const PIPE_FORMAT_ASTC_12x12_SRGB : pipe_format = 306 ; pub const PIPE_FORMAT_P016 : pipe_format = 307 ; pub const PIPE_FORMAT_R10G10B10X2_UNORM : pipe_format = 308 ; pub const PIPE_FORMAT_A1B5G5R5_UNORM : pipe_format = 309 ; pub const PIPE_FORMAT_X1B5G5R5_UNORM : pipe_format = 310 ; pub const PIPE_FORMAT_A4B4G4R4_UNORM : pipe_format = 311 ; pub const PIPE_FORMAT_COUNT : pipe_format = 312 ; - /// Formats for textures, surfaces and vertex data - pub type pipe_format = u32 ; \ No newline at end of file +pub const PIPE_FORMAT_NONE: pipe_format = 0; +pub const PIPE_FORMAT_B8G8R8A8_UNORM: pipe_format = 1; +pub const PIPE_FORMAT_B8G8R8X8_UNORM: pipe_format = 2; +pub const PIPE_FORMAT_A8R8G8B8_UNORM: pipe_format = 3; +pub const PIPE_FORMAT_X8R8G8B8_UNORM: pipe_format = 4; +pub const PIPE_FORMAT_B5G5R5A1_UNORM: pipe_format = 5; +pub const PIPE_FORMAT_B4G4R4A4_UNORM: pipe_format = 6; +pub const PIPE_FORMAT_B5G6R5_UNORM: pipe_format = 7; +pub const PIPE_FORMAT_R10G10B10A2_UNORM: pipe_format = 8; +/// < ubyte luminance +pub const PIPE_FORMAT_L8_UNORM: pipe_format = 9; +/// < ubyte alpha +pub const PIPE_FORMAT_A8_UNORM: pipe_format = 10; +/// < ubyte intensity +pub const PIPE_FORMAT_I8_UNORM: pipe_format = 11; +/// < ubyte alpha, luminance +pub const PIPE_FORMAT_L8A8_UNORM: pipe_format = 12; +/// < ushort luminance +pub const PIPE_FORMAT_L16_UNORM: pipe_format = 13; +pub const PIPE_FORMAT_UYVY: pipe_format = 14; +pub const PIPE_FORMAT_YUYV: pipe_format = 15; +pub const PIPE_FORMAT_Z16_UNORM: pipe_format = 16; +pub const PIPE_FORMAT_Z32_UNORM: pipe_format = 17; +pub const PIPE_FORMAT_Z32_FLOAT: pipe_format = 18; +pub const PIPE_FORMAT_Z24_UNORM_S8_UINT: pipe_format = 19; +pub const PIPE_FORMAT_S8_UINT_Z24_UNORM: pipe_format = 20; +pub const PIPE_FORMAT_Z24X8_UNORM: pipe_format = 21; +pub const PIPE_FORMAT_X8Z24_UNORM: pipe_format = 22; +/// < ubyte stencil +pub const PIPE_FORMAT_S8_UINT: pipe_format = 23; +pub const PIPE_FORMAT_R64_FLOAT: pipe_format = 24; +pub const PIPE_FORMAT_R64G64_FLOAT: pipe_format = 25; +pub const PIPE_FORMAT_R64G64B64_FLOAT: pipe_format = 26; +pub const PIPE_FORMAT_R64G64B64A64_FLOAT: pipe_format = 27; +pub const PIPE_FORMAT_R32_FLOAT: pipe_format = 28; +pub const PIPE_FORMAT_R32G32_FLOAT: pipe_format = 29; +pub const PIPE_FORMAT_R32G32B32_FLOAT: pipe_format = 30; +pub const PIPE_FORMAT_R32G32B32A32_FLOAT: pipe_format = 31; +pub const PIPE_FORMAT_R32_UNORM: pipe_format = 32; +pub const PIPE_FORMAT_R32G32_UNORM: pipe_format = 33; +pub const PIPE_FORMAT_R32G32B32_UNORM: pipe_format = 34; +pub const PIPE_FORMAT_R32G32B32A32_UNORM: pipe_format = 35; +pub const PIPE_FORMAT_R32_USCALED: pipe_format = 36; +pub const PIPE_FORMAT_R32G32_USCALED: pipe_format = 37; +pub const PIPE_FORMAT_R32G32B32_USCALED: pipe_format = 38; +pub const PIPE_FORMAT_R32G32B32A32_USCALED: pipe_format = 39; +pub const PIPE_FORMAT_R32_SNORM: pipe_format = 40; +pub const PIPE_FORMAT_R32G32_SNORM: pipe_format = 41; +pub const PIPE_FORMAT_R32G32B32_SNORM: pipe_format = 42; +pub const PIPE_FORMAT_R32G32B32A32_SNORM: pipe_format = 43; +pub const PIPE_FORMAT_R32_SSCALED: pipe_format = 44; +pub const PIPE_FORMAT_R32G32_SSCALED: pipe_format = 45; +pub const PIPE_FORMAT_R32G32B32_SSCALED: pipe_format = 46; +pub const PIPE_FORMAT_R32G32B32A32_SSCALED: pipe_format = 47; +pub const PIPE_FORMAT_R16_UNORM: pipe_format = 48; +pub const PIPE_FORMAT_R16G16_UNORM: pipe_format = 49; +pub const PIPE_FORMAT_R16G16B16_UNORM: pipe_format = 50; +pub const PIPE_FORMAT_R16G16B16A16_UNORM: pipe_format = 51; +pub const PIPE_FORMAT_R16_USCALED: pipe_format = 52; +pub const PIPE_FORMAT_R16G16_USCALED: pipe_format = 53; +pub const PIPE_FORMAT_R16G16B16_USCALED: pipe_format = 54; +pub const PIPE_FORMAT_R16G16B16A16_USCALED: pipe_format = 55; +pub const PIPE_FORMAT_R16_SNORM: pipe_format = 56; +pub const PIPE_FORMAT_R16G16_SNORM: pipe_format = 57; +pub const PIPE_FORMAT_R16G16B16_SNORM: pipe_format = 58; +pub const PIPE_FORMAT_R16G16B16A16_SNORM: pipe_format = 59; +pub const PIPE_FORMAT_R16_SSCALED: pipe_format = 60; +pub const PIPE_FORMAT_R16G16_SSCALED: pipe_format = 61; +pub const PIPE_FORMAT_R16G16B16_SSCALED: pipe_format = 62; +pub const PIPE_FORMAT_R16G16B16A16_SSCALED: pipe_format = 63; +pub const PIPE_FORMAT_R8_UNORM: pipe_format = 64; +pub const PIPE_FORMAT_R8G8_UNORM: pipe_format = 65; +pub const PIPE_FORMAT_R8G8B8_UNORM: pipe_format = 66; +pub const PIPE_FORMAT_R8G8B8A8_UNORM: pipe_format = 67; +pub const PIPE_FORMAT_X8B8G8R8_UNORM: pipe_format = 68; +pub const PIPE_FORMAT_R8_USCALED: pipe_format = 69; +pub const PIPE_FORMAT_R8G8_USCALED: pipe_format = 70; +pub const PIPE_FORMAT_R8G8B8_USCALED: pipe_format = 71; +pub const PIPE_FORMAT_R8G8B8A8_USCALED: pipe_format = 72; +pub const PIPE_FORMAT_R8_SNORM: pipe_format = 74; +pub const PIPE_FORMAT_R8G8_SNORM: pipe_format = 75; +pub const PIPE_FORMAT_R8G8B8_SNORM: pipe_format = 76; +pub const PIPE_FORMAT_R8G8B8A8_SNORM: pipe_format = 77; +pub const PIPE_FORMAT_R8_SSCALED: pipe_format = 82; +pub const PIPE_FORMAT_R8G8_SSCALED: pipe_format = 83; +pub const PIPE_FORMAT_R8G8B8_SSCALED: pipe_format = 84; +pub const PIPE_FORMAT_R8G8B8A8_SSCALED: pipe_format = 85; +pub const PIPE_FORMAT_R32_FIXED: pipe_format = 87; +pub const PIPE_FORMAT_R32G32_FIXED: pipe_format = 88; +pub const PIPE_FORMAT_R32G32B32_FIXED: pipe_format = 89; +pub const PIPE_FORMAT_R32G32B32A32_FIXED: pipe_format = 90; +pub const PIPE_FORMAT_R16_FLOAT: pipe_format = 91; +pub const PIPE_FORMAT_R16G16_FLOAT: pipe_format = 92; +pub const PIPE_FORMAT_R16G16B16_FLOAT: pipe_format = 93; +pub const PIPE_FORMAT_R16G16B16A16_FLOAT: pipe_format = 94; +pub const PIPE_FORMAT_L8_SRGB: pipe_format = 95; +pub const PIPE_FORMAT_L8A8_SRGB: pipe_format = 96; +pub const PIPE_FORMAT_R8G8B8_SRGB: pipe_format = 97; +pub const PIPE_FORMAT_A8B8G8R8_SRGB: pipe_format = 98; +pub const PIPE_FORMAT_X8B8G8R8_SRGB: pipe_format = 99; +pub const PIPE_FORMAT_B8G8R8A8_SRGB: pipe_format = 100; +pub const PIPE_FORMAT_B8G8R8X8_SRGB: pipe_format = 101; +pub const PIPE_FORMAT_A8R8G8B8_SRGB: pipe_format = 102; +pub const PIPE_FORMAT_X8R8G8B8_SRGB: pipe_format = 103; +pub const PIPE_FORMAT_R8G8B8A8_SRGB: pipe_format = 104; +pub const PIPE_FORMAT_DXT1_RGB: pipe_format = 105; +pub const PIPE_FORMAT_DXT1_RGBA: pipe_format = 106; +pub const PIPE_FORMAT_DXT3_RGBA: pipe_format = 107; +pub const PIPE_FORMAT_DXT5_RGBA: pipe_format = 108; +pub const PIPE_FORMAT_DXT1_SRGB: pipe_format = 109; +pub const PIPE_FORMAT_DXT1_SRGBA: pipe_format = 110; +pub const PIPE_FORMAT_DXT3_SRGBA: pipe_format = 111; +pub const PIPE_FORMAT_DXT5_SRGBA: pipe_format = 112; +pub const PIPE_FORMAT_RGTC1_UNORM: pipe_format = 113; +pub const PIPE_FORMAT_RGTC1_SNORM: pipe_format = 114; +pub const PIPE_FORMAT_RGTC2_UNORM: pipe_format = 115; +pub const PIPE_FORMAT_RGTC2_SNORM: pipe_format = 116; +pub const PIPE_FORMAT_R8G8_B8G8_UNORM: pipe_format = 117; +pub const PIPE_FORMAT_G8R8_G8B8_UNORM: pipe_format = 118; +pub const PIPE_FORMAT_R8SG8SB8UX8U_NORM: pipe_format = 119; +pub const PIPE_FORMAT_R5SG5SB6U_NORM: pipe_format = 120; +pub const PIPE_FORMAT_A8B8G8R8_UNORM: pipe_format = 121; +pub const PIPE_FORMAT_B5G5R5X1_UNORM: pipe_format = 122; +pub const PIPE_FORMAT_R10G10B10A2_USCALED: pipe_format = 123; +pub const PIPE_FORMAT_R11G11B10_FLOAT: pipe_format = 124; +pub const PIPE_FORMAT_R9G9B9E5_FLOAT: pipe_format = 125; +pub const PIPE_FORMAT_Z32_FLOAT_S8X24_UINT: pipe_format = 126; +pub const PIPE_FORMAT_R1_UNORM: pipe_format = 127; +pub const PIPE_FORMAT_R10G10B10X2_USCALED: pipe_format = 128; +pub const PIPE_FORMAT_R10G10B10X2_SNORM: pipe_format = 129; +pub const PIPE_FORMAT_L4A4_UNORM: pipe_format = 130; +pub const PIPE_FORMAT_B10G10R10A2_UNORM: pipe_format = 131; +pub const PIPE_FORMAT_R10SG10SB10SA2U_NORM: pipe_format = 132; +pub const PIPE_FORMAT_R8G8Bx_SNORM: pipe_format = 133; +pub const PIPE_FORMAT_R8G8B8X8_UNORM: pipe_format = 134; +pub const PIPE_FORMAT_B4G4R4X4_UNORM: pipe_format = 135; +pub const PIPE_FORMAT_X24S8_UINT: pipe_format = 136; +pub const PIPE_FORMAT_S8X24_UINT: pipe_format = 137; +pub const PIPE_FORMAT_X32_S8X24_UINT: pipe_format = 138; +pub const PIPE_FORMAT_B2G3R3_UNORM: pipe_format = 139; +pub const PIPE_FORMAT_L16A16_UNORM: pipe_format = 140; +pub const PIPE_FORMAT_A16_UNORM: pipe_format = 141; +pub const PIPE_FORMAT_I16_UNORM: pipe_format = 142; +pub const PIPE_FORMAT_LATC1_UNORM: pipe_format = 143; +pub const PIPE_FORMAT_LATC1_SNORM: pipe_format = 144; +pub const PIPE_FORMAT_LATC2_UNORM: pipe_format = 145; +pub const PIPE_FORMAT_LATC2_SNORM: pipe_format = 146; +pub const PIPE_FORMAT_A8_SNORM: pipe_format = 147; +pub const PIPE_FORMAT_L8_SNORM: pipe_format = 148; +pub const PIPE_FORMAT_L8A8_SNORM: pipe_format = 149; +pub const PIPE_FORMAT_I8_SNORM: pipe_format = 150; +pub const PIPE_FORMAT_A16_SNORM: pipe_format = 151; +pub const PIPE_FORMAT_L16_SNORM: pipe_format = 152; +pub const PIPE_FORMAT_L16A16_SNORM: pipe_format = 153; +pub const PIPE_FORMAT_I16_SNORM: pipe_format = 154; +pub const PIPE_FORMAT_A16_FLOAT: pipe_format = 155; +pub const PIPE_FORMAT_L16_FLOAT: pipe_format = 156; +pub const PIPE_FORMAT_L16A16_FLOAT: pipe_format = 157; +pub const PIPE_FORMAT_I16_FLOAT: pipe_format = 158; +pub const PIPE_FORMAT_A32_FLOAT: pipe_format = 159; +pub const PIPE_FORMAT_L32_FLOAT: pipe_format = 160; +pub const PIPE_FORMAT_L32A32_FLOAT: pipe_format = 161; +pub const PIPE_FORMAT_I32_FLOAT: pipe_format = 162; +pub const PIPE_FORMAT_YV12: pipe_format = 163; +pub const PIPE_FORMAT_YV16: pipe_format = 164; +/// < aka I420 +pub const PIPE_FORMAT_IYUV: pipe_format = 165; +pub const PIPE_FORMAT_NV12: pipe_format = 166; +pub const PIPE_FORMAT_NV21: pipe_format = 167; +pub const PIPE_FORMAT_A4R4_UNORM: pipe_format = 168; +pub const PIPE_FORMAT_R4A4_UNORM: pipe_format = 169; +pub const PIPE_FORMAT_R8A8_UNORM: pipe_format = 170; +pub const PIPE_FORMAT_A8R8_UNORM: pipe_format = 171; +pub const PIPE_FORMAT_R10G10B10A2_SSCALED: pipe_format = 172; +pub const PIPE_FORMAT_R10G10B10A2_SNORM: pipe_format = 173; +pub const PIPE_FORMAT_B10G10R10A2_USCALED: pipe_format = 174; +pub const PIPE_FORMAT_B10G10R10A2_SSCALED: pipe_format = 175; +pub const PIPE_FORMAT_B10G10R10A2_SNORM: pipe_format = 176; +pub const PIPE_FORMAT_R8_UINT: pipe_format = 177; +pub const PIPE_FORMAT_R8G8_UINT: pipe_format = 178; +pub const PIPE_FORMAT_R8G8B8_UINT: pipe_format = 179; +pub const PIPE_FORMAT_R8G8B8A8_UINT: pipe_format = 180; +pub const PIPE_FORMAT_R8_SINT: pipe_format = 181; +pub const PIPE_FORMAT_R8G8_SINT: pipe_format = 182; +pub const PIPE_FORMAT_R8G8B8_SINT: pipe_format = 183; +pub const PIPE_FORMAT_R8G8B8A8_SINT: pipe_format = 184; +pub const PIPE_FORMAT_R16_UINT: pipe_format = 185; +pub const PIPE_FORMAT_R16G16_UINT: pipe_format = 186; +pub const PIPE_FORMAT_R16G16B16_UINT: pipe_format = 187; +pub const PIPE_FORMAT_R16G16B16A16_UINT: pipe_format = 188; +pub const PIPE_FORMAT_R16_SINT: pipe_format = 189; +pub const PIPE_FORMAT_R16G16_SINT: pipe_format = 190; +pub const PIPE_FORMAT_R16G16B16_SINT: pipe_format = 191; +pub const PIPE_FORMAT_R16G16B16A16_SINT: pipe_format = 192; +pub const PIPE_FORMAT_R32_UINT: pipe_format = 193; +pub const PIPE_FORMAT_R32G32_UINT: pipe_format = 194; +pub const PIPE_FORMAT_R32G32B32_UINT: pipe_format = 195; +pub const PIPE_FORMAT_R32G32B32A32_UINT: pipe_format = 196; +pub const PIPE_FORMAT_R32_SINT: pipe_format = 197; +pub const PIPE_FORMAT_R32G32_SINT: pipe_format = 198; +pub const PIPE_FORMAT_R32G32B32_SINT: pipe_format = 199; +pub const PIPE_FORMAT_R32G32B32A32_SINT: pipe_format = 200; +pub const PIPE_FORMAT_A8_UINT: pipe_format = 201; +pub const PIPE_FORMAT_I8_UINT: pipe_format = 202; +pub const PIPE_FORMAT_L8_UINT: pipe_format = 203; +pub const PIPE_FORMAT_L8A8_UINT: pipe_format = 204; +pub const PIPE_FORMAT_A8_SINT: pipe_format = 205; +pub const PIPE_FORMAT_I8_SINT: pipe_format = 206; +pub const PIPE_FORMAT_L8_SINT: pipe_format = 207; +pub const PIPE_FORMAT_L8A8_SINT: pipe_format = 208; +pub const PIPE_FORMAT_A16_UINT: pipe_format = 209; +pub const PIPE_FORMAT_I16_UINT: pipe_format = 210; +pub const PIPE_FORMAT_L16_UINT: pipe_format = 211; +pub const PIPE_FORMAT_L16A16_UINT: pipe_format = 212; +pub const PIPE_FORMAT_A16_SINT: pipe_format = 213; +pub const PIPE_FORMAT_I16_SINT: pipe_format = 214; +pub const PIPE_FORMAT_L16_SINT: pipe_format = 215; +pub const PIPE_FORMAT_L16A16_SINT: pipe_format = 216; +pub const PIPE_FORMAT_A32_UINT: pipe_format = 217; +pub const PIPE_FORMAT_I32_UINT: pipe_format = 218; +pub const PIPE_FORMAT_L32_UINT: pipe_format = 219; +pub const PIPE_FORMAT_L32A32_UINT: pipe_format = 220; +pub const PIPE_FORMAT_A32_SINT: pipe_format = 221; +pub const PIPE_FORMAT_I32_SINT: pipe_format = 222; +pub const PIPE_FORMAT_L32_SINT: pipe_format = 223; +pub const PIPE_FORMAT_L32A32_SINT: pipe_format = 224; +pub const PIPE_FORMAT_B10G10R10A2_UINT: pipe_format = 225; +pub const PIPE_FORMAT_ETC1_RGB8: pipe_format = 226; +pub const PIPE_FORMAT_R8G8_R8B8_UNORM: pipe_format = 227; +pub const PIPE_FORMAT_G8R8_B8R8_UNORM: pipe_format = 228; +pub const PIPE_FORMAT_R8G8B8X8_SNORM: pipe_format = 229; +pub const PIPE_FORMAT_R8G8B8X8_SRGB: pipe_format = 230; +pub const PIPE_FORMAT_R8G8B8X8_UINT: pipe_format = 231; +pub const PIPE_FORMAT_R8G8B8X8_SINT: pipe_format = 232; +pub const PIPE_FORMAT_B10G10R10X2_UNORM: pipe_format = 233; +pub const PIPE_FORMAT_R16G16B16X16_UNORM: pipe_format = 234; +pub const PIPE_FORMAT_R16G16B16X16_SNORM: pipe_format = 235; +pub const PIPE_FORMAT_R16G16B16X16_FLOAT: pipe_format = 236; +pub const PIPE_FORMAT_R16G16B16X16_UINT: pipe_format = 237; +pub const PIPE_FORMAT_R16G16B16X16_SINT: pipe_format = 238; +pub const PIPE_FORMAT_R32G32B32X32_FLOAT: pipe_format = 239; +pub const PIPE_FORMAT_R32G32B32X32_UINT: pipe_format = 240; +pub const PIPE_FORMAT_R32G32B32X32_SINT: pipe_format = 241; +pub const PIPE_FORMAT_R8A8_SNORM: pipe_format = 242; +pub const PIPE_FORMAT_R16A16_UNORM: pipe_format = 243; +pub const PIPE_FORMAT_R16A16_SNORM: pipe_format = 244; +pub const PIPE_FORMAT_R16A16_FLOAT: pipe_format = 245; +pub const PIPE_FORMAT_R32A32_FLOAT: pipe_format = 246; +pub const PIPE_FORMAT_R8A8_UINT: pipe_format = 247; +pub const PIPE_FORMAT_R8A8_SINT: pipe_format = 248; +pub const PIPE_FORMAT_R16A16_UINT: pipe_format = 249; +pub const PIPE_FORMAT_R16A16_SINT: pipe_format = 250; +pub const PIPE_FORMAT_R32A32_UINT: pipe_format = 251; +pub const PIPE_FORMAT_R32A32_SINT: pipe_format = 252; +pub const PIPE_FORMAT_R10G10B10A2_UINT: pipe_format = 253; +pub const PIPE_FORMAT_B5G6R5_SRGB: pipe_format = 254; +pub const PIPE_FORMAT_BPTC_RGBA_UNORM: pipe_format = 255; +pub const PIPE_FORMAT_BPTC_SRGBA: pipe_format = 256; +pub const PIPE_FORMAT_BPTC_RGB_FLOAT: pipe_format = 257; +pub const PIPE_FORMAT_BPTC_RGB_UFLOAT: pipe_format = 258; +pub const PIPE_FORMAT_A8L8_UNORM: pipe_format = 259; +pub const PIPE_FORMAT_A8L8_SNORM: pipe_format = 260; +pub const PIPE_FORMAT_A8L8_SRGB: pipe_format = 261; +pub const PIPE_FORMAT_A16L16_UNORM: pipe_format = 262; +pub const PIPE_FORMAT_G8R8_UNORM: pipe_format = 263; +pub const PIPE_FORMAT_G8R8_SNORM: pipe_format = 264; +pub const PIPE_FORMAT_G16R16_UNORM: pipe_format = 265; +pub const PIPE_FORMAT_G16R16_SNORM: pipe_format = 266; +pub const PIPE_FORMAT_A8B8G8R8_SNORM: pipe_format = 267; +pub const PIPE_FORMAT_X8B8G8R8_SNORM: pipe_format = 268; +pub const PIPE_FORMAT_ETC2_RGB8: pipe_format = 269; +pub const PIPE_FORMAT_ETC2_SRGB8: pipe_format = 270; +pub const PIPE_FORMAT_ETC2_RGB8A1: pipe_format = 271; +pub const PIPE_FORMAT_ETC2_SRGB8A1: pipe_format = 272; +pub const PIPE_FORMAT_ETC2_RGBA8: pipe_format = 273; +pub const PIPE_FORMAT_ETC2_SRGBA8: pipe_format = 274; +pub const PIPE_FORMAT_ETC2_R11_UNORM: pipe_format = 275; +pub const PIPE_FORMAT_ETC2_R11_SNORM: pipe_format = 276; +pub const PIPE_FORMAT_ETC2_RG11_UNORM: pipe_format = 277; +pub const PIPE_FORMAT_ETC2_RG11_SNORM: pipe_format = 278; +pub const PIPE_FORMAT_ASTC_4x4: pipe_format = 279; +pub const PIPE_FORMAT_ASTC_5x4: pipe_format = 280; +pub const PIPE_FORMAT_ASTC_5x5: pipe_format = 281; +pub const PIPE_FORMAT_ASTC_6x5: pipe_format = 282; +pub const PIPE_FORMAT_ASTC_6x6: pipe_format = 283; +pub const PIPE_FORMAT_ASTC_8x5: pipe_format = 284; +pub const PIPE_FORMAT_ASTC_8x6: pipe_format = 285; +pub const PIPE_FORMAT_ASTC_8x8: pipe_format = 286; +pub const PIPE_FORMAT_ASTC_10x5: pipe_format = 287; +pub const PIPE_FORMAT_ASTC_10x6: pipe_format = 288; +pub const PIPE_FORMAT_ASTC_10x8: pipe_format = 289; +pub const PIPE_FORMAT_ASTC_10x10: pipe_format = 290; +pub const PIPE_FORMAT_ASTC_12x10: pipe_format = 291; +pub const PIPE_FORMAT_ASTC_12x12: pipe_format = 292; +pub const PIPE_FORMAT_ASTC_4x4_SRGB: pipe_format = 293; +pub const PIPE_FORMAT_ASTC_5x4_SRGB: pipe_format = 294; +pub const PIPE_FORMAT_ASTC_5x5_SRGB: pipe_format = 295; +pub const PIPE_FORMAT_ASTC_6x5_SRGB: pipe_format = 296; +pub const PIPE_FORMAT_ASTC_6x6_SRGB: pipe_format = 297; +pub const PIPE_FORMAT_ASTC_8x5_SRGB: pipe_format = 298; +pub const PIPE_FORMAT_ASTC_8x6_SRGB: pipe_format = 299; +pub const PIPE_FORMAT_ASTC_8x8_SRGB: pipe_format = 300; +pub const PIPE_FORMAT_ASTC_10x5_SRGB: pipe_format = 301; +pub const PIPE_FORMAT_ASTC_10x6_SRGB: pipe_format = 302; +pub const PIPE_FORMAT_ASTC_10x8_SRGB: pipe_format = 303; +pub const PIPE_FORMAT_ASTC_10x10_SRGB: pipe_format = 304; +pub const PIPE_FORMAT_ASTC_12x10_SRGB: pipe_format = 305; +pub const PIPE_FORMAT_ASTC_12x12_SRGB: pipe_format = 306; +pub const PIPE_FORMAT_P016: pipe_format = 307; +pub const PIPE_FORMAT_R10G10B10X2_UNORM: pipe_format = 308; +pub const PIPE_FORMAT_A1B5G5R5_UNORM: pipe_format = 309; +pub const PIPE_FORMAT_X1B5G5R5_UNORM: pipe_format = 310; +pub const PIPE_FORMAT_A4B4G4R4_UNORM: pipe_format = 311; +pub const PIPE_FORMAT_COUNT: pipe_format = 312; +/// Formats for textures, surfaces and vertex data +pub type pipe_format = u32; diff --git a/gpu_renderer/src/generated/virgl_protocol.rs b/gpu_renderer/src/generated/virgl_protocol.rs index c9d0746..7e06f93 100644 --- a/gpu_renderer/src/generated/virgl_protocol.rs +++ b/gpu_renderer/src/generated/virgl_protocol.rs @@ -1,3 +1,254 @@ /* automatically generated by rust-bindgen */ -pub const VIRGL_QUERY_STATE_NEW : u32 = 0 ; pub const VIRGL_QUERY_STATE_DONE : u32 = 1 ; pub const VIRGL_QUERY_STATE_WAIT_HOST : u32 = 2 ; pub const VIRGL_MAX_COLOR_BUFS : u32 = 8 ; pub const VIRGL_MAX_CLIP_PLANES : u32 = 8 ; pub const VIRGL_OBJ_CREATE_HEADER : u32 = 0 ; pub const VIRGL_OBJ_CREATE_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_BIND_HEADER : u32 = 0 ; pub const VIRGL_OBJ_BIND_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_DESTROY_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_BLEND_SIZE : u32 = 11 ; pub const VIRGL_OBJ_BLEND_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_BLEND_S0 : u32 = 2 ; pub const VIRGL_OBJ_BLEND_S1 : u32 = 3 ; pub const VIRGL_OBJ_DSA_SIZE : u32 = 5 ; pub const VIRGL_OBJ_DSA_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_DSA_S0 : u32 = 2 ; pub const VIRGL_OBJ_DSA_S1 : u32 = 3 ; pub const VIRGL_OBJ_DSA_S2 : u32 = 4 ; pub const VIRGL_OBJ_DSA_ALPHA_REF : u32 = 5 ; pub const VIRGL_OBJ_RS_SIZE : u32 = 9 ; pub const VIRGL_OBJ_RS_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_RS_S0 : u32 = 2 ; pub const VIRGL_OBJ_RS_POINT_SIZE : u32 = 3 ; pub const VIRGL_OBJ_RS_SPRITE_COORD_ENABLE : u32 = 4 ; pub const VIRGL_OBJ_RS_S3 : u32 = 5 ; pub const VIRGL_OBJ_RS_LINE_WIDTH : u32 = 6 ; pub const VIRGL_OBJ_RS_OFFSET_UNITS : u32 = 7 ; pub const VIRGL_OBJ_RS_OFFSET_SCALE : u32 = 8 ; pub const VIRGL_OBJ_RS_OFFSET_CLAMP : u32 = 9 ; pub const VIRGL_OBJ_CLEAR_SIZE : u32 = 8 ; pub const VIRGL_OBJ_CLEAR_BUFFERS : u32 = 1 ; pub const VIRGL_OBJ_CLEAR_COLOR_0 : u32 = 2 ; pub const VIRGL_OBJ_CLEAR_COLOR_1 : u32 = 3 ; pub const VIRGL_OBJ_CLEAR_COLOR_2 : u32 = 4 ; pub const VIRGL_OBJ_CLEAR_COLOR_3 : u32 = 5 ; pub const VIRGL_OBJ_CLEAR_DEPTH_0 : u32 = 6 ; pub const VIRGL_OBJ_CLEAR_DEPTH_1 : u32 = 7 ; pub const VIRGL_OBJ_CLEAR_STENCIL : u32 = 8 ; pub const VIRGL_OBJ_SHADER_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_SHADER_TYPE : u32 = 2 ; pub const VIRGL_OBJ_SHADER_OFFSET : u32 = 3 ; pub const VIRGL_OBJ_SHADER_OFFSET_CONT : u32 = 2147483648 ; pub const VIRGL_OBJ_SHADER_NUM_TOKENS : u32 = 4 ; pub const VIRGL_OBJ_SHADER_SO_NUM_OUTPUTS : u32 = 5 ; pub const VIRGL_SET_VIEWPORT_START_SLOT : u32 = 1 ; pub const VIRGL_SET_FRAMEBUFFER_STATE_NR_CBUFS : u32 = 1 ; pub const VIRGL_SET_FRAMEBUFFER_STATE_NR_ZSURF_HANDLE : u32 = 2 ; pub const VIRGL_OBJ_VERTEX_ELEMENTS_HANDLE : u32 = 1 ; pub const VIRGL_SET_INDEX_BUFFER_HANDLE : u32 = 1 ; pub const VIRGL_SET_INDEX_BUFFER_INDEX_SIZE : u32 = 2 ; pub const VIRGL_SET_INDEX_BUFFER_OFFSET : u32 = 3 ; pub const VIRGL_SET_CONSTANT_BUFFER_SHADER_TYPE : u32 = 1 ; pub const VIRGL_SET_CONSTANT_BUFFER_INDEX : u32 = 2 ; pub const VIRGL_SET_CONSTANT_BUFFER_DATA_START : u32 = 3 ; pub const VIRGL_SET_UNIFORM_BUFFER_SIZE : u32 = 5 ; pub const VIRGL_SET_UNIFORM_BUFFER_SHADER_TYPE : u32 = 1 ; pub const VIRGL_SET_UNIFORM_BUFFER_INDEX : u32 = 2 ; pub const VIRGL_SET_UNIFORM_BUFFER_OFFSET : u32 = 3 ; pub const VIRGL_SET_UNIFORM_BUFFER_LENGTH : u32 = 4 ; pub const VIRGL_SET_UNIFORM_BUFFER_RES_HANDLE : u32 = 5 ; pub const VIRGL_DRAW_VBO_SIZE : u32 = 12 ; pub const VIRGL_DRAW_VBO_SIZE_TESS : u32 = 14 ; pub const VIRGL_DRAW_VBO_SIZE_INDIRECT : u32 = 20 ; pub const VIRGL_DRAW_VBO_START : u32 = 1 ; pub const VIRGL_DRAW_VBO_COUNT : u32 = 2 ; pub const VIRGL_DRAW_VBO_MODE : u32 = 3 ; pub const VIRGL_DRAW_VBO_INDEXED : u32 = 4 ; pub const VIRGL_DRAW_VBO_INSTANCE_COUNT : u32 = 5 ; pub const VIRGL_DRAW_VBO_INDEX_BIAS : u32 = 6 ; pub const VIRGL_DRAW_VBO_START_INSTANCE : u32 = 7 ; pub const VIRGL_DRAW_VBO_PRIMITIVE_RESTART : u32 = 8 ; pub const VIRGL_DRAW_VBO_RESTART_INDEX : u32 = 9 ; pub const VIRGL_DRAW_VBO_MIN_INDEX : u32 = 10 ; pub const VIRGL_DRAW_VBO_MAX_INDEX : u32 = 11 ; pub const VIRGL_DRAW_VBO_COUNT_FROM_SO : u32 = 12 ; pub const VIRGL_DRAW_VBO_VERTICES_PER_PATCH : u32 = 13 ; pub const VIRGL_DRAW_VBO_DRAWID : u32 = 14 ; pub const VIRGL_DRAW_VBO_INDIRECT_HANDLE : u32 = 15 ; pub const VIRGL_DRAW_VBO_INDIRECT_OFFSET : u32 = 16 ; pub const VIRGL_DRAW_VBO_INDIRECT_STRIDE : u32 = 17 ; pub const VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT : u32 = 18 ; pub const VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT_OFFSET : u32 = 19 ; pub const VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT_HANDLE : u32 = 20 ; pub const VIRGL_OBJ_SURFACE_SIZE : u32 = 5 ; pub const VIRGL_OBJ_SURFACE_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_SURFACE_RES_HANDLE : u32 = 2 ; pub const VIRGL_OBJ_SURFACE_FORMAT : u32 = 3 ; pub const VIRGL_OBJ_SURFACE_BUFFER_FIRST_ELEMENT : u32 = 4 ; pub const VIRGL_OBJ_SURFACE_BUFFER_LAST_ELEMENT : u32 = 5 ; pub const VIRGL_OBJ_SURFACE_TEXTURE_LEVEL : u32 = 4 ; pub const VIRGL_OBJ_SURFACE_TEXTURE_LAYERS : u32 = 5 ; pub const VIRGL_OBJ_STREAMOUT_SIZE : u32 = 4 ; pub const VIRGL_OBJ_STREAMOUT_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_STREAMOUT_RES_HANDLE : u32 = 2 ; pub const VIRGL_OBJ_STREAMOUT_BUFFER_OFFSET : u32 = 3 ; pub const VIRGL_OBJ_STREAMOUT_BUFFER_SIZE : u32 = 4 ; pub const VIRGL_OBJ_SAMPLER_STATE_SIZE : u32 = 9 ; pub const VIRGL_OBJ_SAMPLER_STATE_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_SAMPLER_STATE_S0 : u32 = 2 ; pub const VIRGL_OBJ_SAMPLER_STATE_LOD_BIAS : u32 = 3 ; pub const VIRGL_OBJ_SAMPLER_STATE_MIN_LOD : u32 = 4 ; pub const VIRGL_OBJ_SAMPLER_STATE_MAX_LOD : u32 = 5 ; pub const VIRGL_OBJ_SAMPLER_VIEW_SIZE : u32 = 6 ; pub const VIRGL_OBJ_SAMPLER_VIEW_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_SAMPLER_VIEW_RES_HANDLE : u32 = 2 ; pub const VIRGL_OBJ_SAMPLER_VIEW_FORMAT : u32 = 3 ; pub const VIRGL_OBJ_SAMPLER_VIEW_BUFFER_FIRST_ELEMENT : u32 = 4 ; pub const VIRGL_OBJ_SAMPLER_VIEW_BUFFER_LAST_ELEMENT : u32 = 5 ; pub const VIRGL_OBJ_SAMPLER_VIEW_TEXTURE_LAYER : u32 = 4 ; pub const VIRGL_OBJ_SAMPLER_VIEW_TEXTURE_LEVEL : u32 = 5 ; pub const VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE : u32 = 6 ; pub const VIRGL_SET_SAMPLER_VIEWS_SHADER_TYPE : u32 = 1 ; pub const VIRGL_SET_SAMPLER_VIEWS_START_SLOT : u32 = 2 ; pub const VIRGL_SET_SAMPLER_VIEWS_V0_HANDLE : u32 = 3 ; pub const VIRGL_BIND_SAMPLER_STATES_SHADER_TYPE : u32 = 1 ; pub const VIRGL_BIND_SAMPLER_STATES_START_SLOT : u32 = 2 ; pub const VIRGL_BIND_SAMPLER_STATES_S0_HANDLE : u32 = 3 ; pub const VIRGL_SET_STENCIL_REF_SIZE : u32 = 1 ; pub const VIRGL_SET_STENCIL_REF : u32 = 1 ; pub const VIRGL_SET_BLEND_COLOR_SIZE : u32 = 4 ; pub const VIRGL_SET_SCISSOR_START_SLOT : u32 = 1 ; pub const VIRGL_CMD_RESOURCE_COPY_REGION_SIZE : u32 = 13 ; pub const VIRGL_CMD_RCR_DST_RES_HANDLE : u32 = 1 ; pub const VIRGL_CMD_RCR_DST_LEVEL : u32 = 2 ; pub const VIRGL_CMD_RCR_DST_X : u32 = 3 ; pub const VIRGL_CMD_RCR_DST_Y : u32 = 4 ; pub const VIRGL_CMD_RCR_DST_Z : u32 = 5 ; pub const VIRGL_CMD_RCR_SRC_RES_HANDLE : u32 = 6 ; pub const VIRGL_CMD_RCR_SRC_LEVEL : u32 = 7 ; pub const VIRGL_CMD_RCR_SRC_X : u32 = 8 ; pub const VIRGL_CMD_RCR_SRC_Y : u32 = 9 ; pub const VIRGL_CMD_RCR_SRC_Z : u32 = 10 ; pub const VIRGL_CMD_RCR_SRC_W : u32 = 11 ; pub const VIRGL_CMD_RCR_SRC_H : u32 = 12 ; pub const VIRGL_CMD_RCR_SRC_D : u32 = 13 ; pub const VIRGL_CMD_BLIT_SIZE : u32 = 21 ; pub const VIRGL_CMD_BLIT_S0 : u32 = 1 ; pub const VIRGL_CMD_BLIT_SCISSOR_MINX_MINY : u32 = 2 ; pub const VIRGL_CMD_BLIT_SCISSOR_MAXX_MAXY : u32 = 3 ; pub const VIRGL_CMD_BLIT_DST_RES_HANDLE : u32 = 4 ; pub const VIRGL_CMD_BLIT_DST_LEVEL : u32 = 5 ; pub const VIRGL_CMD_BLIT_DST_FORMAT : u32 = 6 ; pub const VIRGL_CMD_BLIT_DST_X : u32 = 7 ; pub const VIRGL_CMD_BLIT_DST_Y : u32 = 8 ; pub const VIRGL_CMD_BLIT_DST_Z : u32 = 9 ; pub const VIRGL_CMD_BLIT_DST_W : u32 = 10 ; pub const VIRGL_CMD_BLIT_DST_H : u32 = 11 ; pub const VIRGL_CMD_BLIT_DST_D : u32 = 12 ; pub const VIRGL_CMD_BLIT_SRC_RES_HANDLE : u32 = 13 ; pub const VIRGL_CMD_BLIT_SRC_LEVEL : u32 = 14 ; pub const VIRGL_CMD_BLIT_SRC_FORMAT : u32 = 15 ; pub const VIRGL_CMD_BLIT_SRC_X : u32 = 16 ; pub const VIRGL_CMD_BLIT_SRC_Y : u32 = 17 ; pub const VIRGL_CMD_BLIT_SRC_Z : u32 = 18 ; pub const VIRGL_CMD_BLIT_SRC_W : u32 = 19 ; pub const VIRGL_CMD_BLIT_SRC_H : u32 = 20 ; pub const VIRGL_CMD_BLIT_SRC_D : u32 = 21 ; pub const VIRGL_OBJ_QUERY_SIZE : u32 = 4 ; pub const VIRGL_OBJ_QUERY_HANDLE : u32 = 1 ; pub const VIRGL_OBJ_QUERY_TYPE_INDEX : u32 = 2 ; pub const VIRGL_OBJ_QUERY_OFFSET : u32 = 3 ; pub const VIRGL_OBJ_QUERY_RES_HANDLE : u32 = 4 ; pub const VIRGL_QUERY_BEGIN_HANDLE : u32 = 1 ; pub const VIRGL_QUERY_END_HANDLE : u32 = 1 ; pub const VIRGL_QUERY_RESULT_HANDLE : u32 = 1 ; pub const VIRGL_QUERY_RESULT_WAIT : u32 = 2 ; pub const VIRGL_RENDER_CONDITION_SIZE : u32 = 3 ; pub const VIRGL_RENDER_CONDITION_HANDLE : u32 = 1 ; pub const VIRGL_RENDER_CONDITION_CONDITION : u32 = 2 ; pub const VIRGL_RENDER_CONDITION_MODE : u32 = 3 ; pub const VIRGL_RESOURCE_IW_RES_HANDLE : u32 = 1 ; pub const VIRGL_RESOURCE_IW_LEVEL : u32 = 2 ; pub const VIRGL_RESOURCE_IW_USAGE : u32 = 3 ; pub const VIRGL_RESOURCE_IW_STRIDE : u32 = 4 ; pub const VIRGL_RESOURCE_IW_LAYER_STRIDE : u32 = 5 ; pub const VIRGL_RESOURCE_IW_X : u32 = 6 ; pub const VIRGL_RESOURCE_IW_Y : u32 = 7 ; pub const VIRGL_RESOURCE_IW_Z : u32 = 8 ; pub const VIRGL_RESOURCE_IW_W : u32 = 9 ; pub const VIRGL_RESOURCE_IW_H : u32 = 10 ; pub const VIRGL_RESOURCE_IW_D : u32 = 11 ; pub const VIRGL_RESOURCE_IW_DATA_START : u32 = 12 ; pub const VIRGL_SET_STREAMOUT_TARGETS_APPEND_BITMASK : u32 = 1 ; pub const VIRGL_SET_STREAMOUT_TARGETS_H0 : u32 = 2 ; pub const VIRGL_SET_SAMPLE_MASK_SIZE : u32 = 1 ; pub const VIRGL_SET_SAMPLE_MASK_MASK : u32 = 1 ; pub const VIRGL_SET_CLIP_STATE_SIZE : u32 = 32 ; pub const VIRGL_SET_CLIP_STATE_C0 : u32 = 1 ; pub const VIRGL_POLYGON_STIPPLE_SIZE : u32 = 32 ; pub const VIRGL_POLYGON_STIPPLE_P0 : u32 = 1 ; pub const VIRGL_BIND_SHADER_SIZE : u32 = 2 ; pub const VIRGL_BIND_SHADER_HANDLE : u32 = 1 ; pub const VIRGL_BIND_SHADER_TYPE : u32 = 2 ; pub const VIRGL_TESS_STATE_SIZE : u32 = 6 ; pub const VIRGL_SET_MIN_SAMPLES_SIZE : u32 = 1 ; pub const VIRGL_SET_MIN_SAMPLES_MASK : u32 = 1 ; # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct virgl_host_query_state { pub query_state : u32 , pub result_size : u32 , pub result : u64 , } pub const VIRGL_OBJECT_NULL : virgl_object_type = 0 ; pub const VIRGL_OBJECT_BLEND : virgl_object_type = 1 ; pub const VIRGL_OBJECT_RASTERIZER : virgl_object_type = 2 ; pub const VIRGL_OBJECT_DSA : virgl_object_type = 3 ; pub const VIRGL_OBJECT_SHADER : virgl_object_type = 4 ; pub const VIRGL_OBJECT_VERTEX_ELEMENTS : virgl_object_type = 5 ; pub const VIRGL_OBJECT_SAMPLER_VIEW : virgl_object_type = 6 ; pub const VIRGL_OBJECT_SAMPLER_STATE : virgl_object_type = 7 ; pub const VIRGL_OBJECT_SURFACE : virgl_object_type = 8 ; pub const VIRGL_OBJECT_QUERY : virgl_object_type = 9 ; pub const VIRGL_OBJECT_STREAMOUT_TARGET : virgl_object_type = 10 ; pub const VIRGL_MAX_OBJECTS : virgl_object_type = 11 ; pub type virgl_object_type = u32 ; pub const VIRGL_CCMD_NOP : virgl_context_cmd = 0 ; pub const VIRGL_CCMD_CREATE_OBJECT : virgl_context_cmd = 1 ; pub const VIRGL_CCMD_BIND_OBJECT : virgl_context_cmd = 2 ; pub const VIRGL_CCMD_DESTROY_OBJECT : virgl_context_cmd = 3 ; pub const VIRGL_CCMD_SET_VIEWPORT_STATE : virgl_context_cmd = 4 ; pub const VIRGL_CCMD_SET_FRAMEBUFFER_STATE : virgl_context_cmd = 5 ; pub const VIRGL_CCMD_SET_VERTEX_BUFFERS : virgl_context_cmd = 6 ; pub const VIRGL_CCMD_CLEAR : virgl_context_cmd = 7 ; pub const VIRGL_CCMD_DRAW_VBO : virgl_context_cmd = 8 ; pub const VIRGL_CCMD_RESOURCE_INLINE_WRITE : virgl_context_cmd = 9 ; pub const VIRGL_CCMD_SET_SAMPLER_VIEWS : virgl_context_cmd = 10 ; pub const VIRGL_CCMD_SET_INDEX_BUFFER : virgl_context_cmd = 11 ; pub const VIRGL_CCMD_SET_CONSTANT_BUFFER : virgl_context_cmd = 12 ; pub const VIRGL_CCMD_SET_STENCIL_REF : virgl_context_cmd = 13 ; pub const VIRGL_CCMD_SET_BLEND_COLOR : virgl_context_cmd = 14 ; pub const VIRGL_CCMD_SET_SCISSOR_STATE : virgl_context_cmd = 15 ; pub const VIRGL_CCMD_BLIT : virgl_context_cmd = 16 ; pub const VIRGL_CCMD_RESOURCE_COPY_REGION : virgl_context_cmd = 17 ; pub const VIRGL_CCMD_BIND_SAMPLER_STATES : virgl_context_cmd = 18 ; pub const VIRGL_CCMD_BEGIN_QUERY : virgl_context_cmd = 19 ; pub const VIRGL_CCMD_END_QUERY : virgl_context_cmd = 20 ; pub const VIRGL_CCMD_GET_QUERY_RESULT : virgl_context_cmd = 21 ; pub const VIRGL_CCMD_SET_POLYGON_STIPPLE : virgl_context_cmd = 22 ; pub const VIRGL_CCMD_SET_CLIP_STATE : virgl_context_cmd = 23 ; pub const VIRGL_CCMD_SET_SAMPLE_MASK : virgl_context_cmd = 24 ; pub const VIRGL_CCMD_SET_STREAMOUT_TARGETS : virgl_context_cmd = 25 ; pub const VIRGL_CCMD_SET_RENDER_CONDITION : virgl_context_cmd = 26 ; pub const VIRGL_CCMD_SET_UNIFORM_BUFFER : virgl_context_cmd = 27 ; pub const VIRGL_CCMD_SET_SUB_CTX : virgl_context_cmd = 28 ; pub const VIRGL_CCMD_CREATE_SUB_CTX : virgl_context_cmd = 29 ; pub const VIRGL_CCMD_DESTROY_SUB_CTX : virgl_context_cmd = 30 ; pub const VIRGL_CCMD_BIND_SHADER : virgl_context_cmd = 31 ; pub const VIRGL_CCMD_SET_TESS_STATE : virgl_context_cmd = 32 ; pub const VIRGL_CCMD_SET_MIN_SAMPLES : virgl_context_cmd = 33 ; pub type virgl_context_cmd = u32 ; \ No newline at end of file +pub const VIRGL_QUERY_STATE_NEW: u32 = 0; +pub const VIRGL_QUERY_STATE_DONE: u32 = 1; +pub const VIRGL_QUERY_STATE_WAIT_HOST: u32 = 2; +pub const VIRGL_MAX_COLOR_BUFS: u32 = 8; +pub const VIRGL_MAX_CLIP_PLANES: u32 = 8; +pub const VIRGL_OBJ_CREATE_HEADER: u32 = 0; +pub const VIRGL_OBJ_CREATE_HANDLE: u32 = 1; +pub const VIRGL_OBJ_BIND_HEADER: u32 = 0; +pub const VIRGL_OBJ_BIND_HANDLE: u32 = 1; +pub const VIRGL_OBJ_DESTROY_HANDLE: u32 = 1; +pub const VIRGL_OBJ_BLEND_SIZE: u32 = 11; +pub const VIRGL_OBJ_BLEND_HANDLE: u32 = 1; +pub const VIRGL_OBJ_BLEND_S0: u32 = 2; +pub const VIRGL_OBJ_BLEND_S1: u32 = 3; +pub const VIRGL_OBJ_DSA_SIZE: u32 = 5; +pub const VIRGL_OBJ_DSA_HANDLE: u32 = 1; +pub const VIRGL_OBJ_DSA_S0: u32 = 2; +pub const VIRGL_OBJ_DSA_S1: u32 = 3; +pub const VIRGL_OBJ_DSA_S2: u32 = 4; +pub const VIRGL_OBJ_DSA_ALPHA_REF: u32 = 5; +pub const VIRGL_OBJ_RS_SIZE: u32 = 9; +pub const VIRGL_OBJ_RS_HANDLE: u32 = 1; +pub const VIRGL_OBJ_RS_S0: u32 = 2; +pub const VIRGL_OBJ_RS_POINT_SIZE: u32 = 3; +pub const VIRGL_OBJ_RS_SPRITE_COORD_ENABLE: u32 = 4; +pub const VIRGL_OBJ_RS_S3: u32 = 5; +pub const VIRGL_OBJ_RS_LINE_WIDTH: u32 = 6; +pub const VIRGL_OBJ_RS_OFFSET_UNITS: u32 = 7; +pub const VIRGL_OBJ_RS_OFFSET_SCALE: u32 = 8; +pub const VIRGL_OBJ_RS_OFFSET_CLAMP: u32 = 9; +pub const VIRGL_OBJ_CLEAR_SIZE: u32 = 8; +pub const VIRGL_OBJ_CLEAR_BUFFERS: u32 = 1; +pub const VIRGL_OBJ_CLEAR_COLOR_0: u32 = 2; +pub const VIRGL_OBJ_CLEAR_COLOR_1: u32 = 3; +pub const VIRGL_OBJ_CLEAR_COLOR_2: u32 = 4; +pub const VIRGL_OBJ_CLEAR_COLOR_3: u32 = 5; +pub const VIRGL_OBJ_CLEAR_DEPTH_0: u32 = 6; +pub const VIRGL_OBJ_CLEAR_DEPTH_1: u32 = 7; +pub const VIRGL_OBJ_CLEAR_STENCIL: u32 = 8; +pub const VIRGL_OBJ_SHADER_HANDLE: u32 = 1; +pub const VIRGL_OBJ_SHADER_TYPE: u32 = 2; +pub const VIRGL_OBJ_SHADER_OFFSET: u32 = 3; +pub const VIRGL_OBJ_SHADER_OFFSET_CONT: u32 = 2147483648; +pub const VIRGL_OBJ_SHADER_NUM_TOKENS: u32 = 4; +pub const VIRGL_OBJ_SHADER_SO_NUM_OUTPUTS: u32 = 5; +pub const VIRGL_SET_VIEWPORT_START_SLOT: u32 = 1; +pub const VIRGL_SET_FRAMEBUFFER_STATE_NR_CBUFS: u32 = 1; +pub const VIRGL_SET_FRAMEBUFFER_STATE_NR_ZSURF_HANDLE: u32 = 2; +pub const VIRGL_OBJ_VERTEX_ELEMENTS_HANDLE: u32 = 1; +pub const VIRGL_SET_INDEX_BUFFER_HANDLE: u32 = 1; +pub const VIRGL_SET_INDEX_BUFFER_INDEX_SIZE: u32 = 2; +pub const VIRGL_SET_INDEX_BUFFER_OFFSET: u32 = 3; +pub const VIRGL_SET_CONSTANT_BUFFER_SHADER_TYPE: u32 = 1; +pub const VIRGL_SET_CONSTANT_BUFFER_INDEX: u32 = 2; +pub const VIRGL_SET_CONSTANT_BUFFER_DATA_START: u32 = 3; +pub const VIRGL_SET_UNIFORM_BUFFER_SIZE: u32 = 5; +pub const VIRGL_SET_UNIFORM_BUFFER_SHADER_TYPE: u32 = 1; +pub const VIRGL_SET_UNIFORM_BUFFER_INDEX: u32 = 2; +pub const VIRGL_SET_UNIFORM_BUFFER_OFFSET: u32 = 3; +pub const VIRGL_SET_UNIFORM_BUFFER_LENGTH: u32 = 4; +pub const VIRGL_SET_UNIFORM_BUFFER_RES_HANDLE: u32 = 5; +pub const VIRGL_DRAW_VBO_SIZE: u32 = 12; +pub const VIRGL_DRAW_VBO_SIZE_TESS: u32 = 14; +pub const VIRGL_DRAW_VBO_SIZE_INDIRECT: u32 = 20; +pub const VIRGL_DRAW_VBO_START: u32 = 1; +pub const VIRGL_DRAW_VBO_COUNT: u32 = 2; +pub const VIRGL_DRAW_VBO_MODE: u32 = 3; +pub const VIRGL_DRAW_VBO_INDEXED: u32 = 4; +pub const VIRGL_DRAW_VBO_INSTANCE_COUNT: u32 = 5; +pub const VIRGL_DRAW_VBO_INDEX_BIAS: u32 = 6; +pub const VIRGL_DRAW_VBO_START_INSTANCE: u32 = 7; +pub const VIRGL_DRAW_VBO_PRIMITIVE_RESTART: u32 = 8; +pub const VIRGL_DRAW_VBO_RESTART_INDEX: u32 = 9; +pub const VIRGL_DRAW_VBO_MIN_INDEX: u32 = 10; +pub const VIRGL_DRAW_VBO_MAX_INDEX: u32 = 11; +pub const VIRGL_DRAW_VBO_COUNT_FROM_SO: u32 = 12; +pub const VIRGL_DRAW_VBO_VERTICES_PER_PATCH: u32 = 13; +pub const VIRGL_DRAW_VBO_DRAWID: u32 = 14; +pub const VIRGL_DRAW_VBO_INDIRECT_HANDLE: u32 = 15; +pub const VIRGL_DRAW_VBO_INDIRECT_OFFSET: u32 = 16; +pub const VIRGL_DRAW_VBO_INDIRECT_STRIDE: u32 = 17; +pub const VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT: u32 = 18; +pub const VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT_OFFSET: u32 = 19; +pub const VIRGL_DRAW_VBO_INDIRECT_DRAW_COUNT_HANDLE: u32 = 20; +pub const VIRGL_OBJ_SURFACE_SIZE: u32 = 5; +pub const VIRGL_OBJ_SURFACE_HANDLE: u32 = 1; +pub const VIRGL_OBJ_SURFACE_RES_HANDLE: u32 = 2; +pub const VIRGL_OBJ_SURFACE_FORMAT: u32 = 3; +pub const VIRGL_OBJ_SURFACE_BUFFER_FIRST_ELEMENT: u32 = 4; +pub const VIRGL_OBJ_SURFACE_BUFFER_LAST_ELEMENT: u32 = 5; +pub const VIRGL_OBJ_SURFACE_TEXTURE_LEVEL: u32 = 4; +pub const VIRGL_OBJ_SURFACE_TEXTURE_LAYERS: u32 = 5; +pub const VIRGL_OBJ_STREAMOUT_SIZE: u32 = 4; +pub const VIRGL_OBJ_STREAMOUT_HANDLE: u32 = 1; +pub const VIRGL_OBJ_STREAMOUT_RES_HANDLE: u32 = 2; +pub const VIRGL_OBJ_STREAMOUT_BUFFER_OFFSET: u32 = 3; +pub const VIRGL_OBJ_STREAMOUT_BUFFER_SIZE: u32 = 4; +pub const VIRGL_OBJ_SAMPLER_STATE_SIZE: u32 = 9; +pub const VIRGL_OBJ_SAMPLER_STATE_HANDLE: u32 = 1; +pub const VIRGL_OBJ_SAMPLER_STATE_S0: u32 = 2; +pub const VIRGL_OBJ_SAMPLER_STATE_LOD_BIAS: u32 = 3; +pub const VIRGL_OBJ_SAMPLER_STATE_MIN_LOD: u32 = 4; +pub const VIRGL_OBJ_SAMPLER_STATE_MAX_LOD: u32 = 5; +pub const VIRGL_OBJ_SAMPLER_VIEW_SIZE: u32 = 6; +pub const VIRGL_OBJ_SAMPLER_VIEW_HANDLE: u32 = 1; +pub const VIRGL_OBJ_SAMPLER_VIEW_RES_HANDLE: u32 = 2; +pub const VIRGL_OBJ_SAMPLER_VIEW_FORMAT: u32 = 3; +pub const VIRGL_OBJ_SAMPLER_VIEW_BUFFER_FIRST_ELEMENT: u32 = 4; +pub const VIRGL_OBJ_SAMPLER_VIEW_BUFFER_LAST_ELEMENT: u32 = 5; +pub const VIRGL_OBJ_SAMPLER_VIEW_TEXTURE_LAYER: u32 = 4; +pub const VIRGL_OBJ_SAMPLER_VIEW_TEXTURE_LEVEL: u32 = 5; +pub const VIRGL_OBJ_SAMPLER_VIEW_SWIZZLE: u32 = 6; +pub const VIRGL_SET_SAMPLER_VIEWS_SHADER_TYPE: u32 = 1; +pub const VIRGL_SET_SAMPLER_VIEWS_START_SLOT: u32 = 2; +pub const VIRGL_SET_SAMPLER_VIEWS_V0_HANDLE: u32 = 3; +pub const VIRGL_BIND_SAMPLER_STATES_SHADER_TYPE: u32 = 1; +pub const VIRGL_BIND_SAMPLER_STATES_START_SLOT: u32 = 2; +pub const VIRGL_BIND_SAMPLER_STATES_S0_HANDLE: u32 = 3; +pub const VIRGL_SET_STENCIL_REF_SIZE: u32 = 1; +pub const VIRGL_SET_STENCIL_REF: u32 = 1; +pub const VIRGL_SET_BLEND_COLOR_SIZE: u32 = 4; +pub const VIRGL_SET_SCISSOR_START_SLOT: u32 = 1; +pub const VIRGL_CMD_RESOURCE_COPY_REGION_SIZE: u32 = 13; +pub const VIRGL_CMD_RCR_DST_RES_HANDLE: u32 = 1; +pub const VIRGL_CMD_RCR_DST_LEVEL: u32 = 2; +pub const VIRGL_CMD_RCR_DST_X: u32 = 3; +pub const VIRGL_CMD_RCR_DST_Y: u32 = 4; +pub const VIRGL_CMD_RCR_DST_Z: u32 = 5; +pub const VIRGL_CMD_RCR_SRC_RES_HANDLE: u32 = 6; +pub const VIRGL_CMD_RCR_SRC_LEVEL: u32 = 7; +pub const VIRGL_CMD_RCR_SRC_X: u32 = 8; +pub const VIRGL_CMD_RCR_SRC_Y: u32 = 9; +pub const VIRGL_CMD_RCR_SRC_Z: u32 = 10; +pub const VIRGL_CMD_RCR_SRC_W: u32 = 11; +pub const VIRGL_CMD_RCR_SRC_H: u32 = 12; +pub const VIRGL_CMD_RCR_SRC_D: u32 = 13; +pub const VIRGL_CMD_BLIT_SIZE: u32 = 21; +pub const VIRGL_CMD_BLIT_S0: u32 = 1; +pub const VIRGL_CMD_BLIT_SCISSOR_MINX_MINY: u32 = 2; +pub const VIRGL_CMD_BLIT_SCISSOR_MAXX_MAXY: u32 = 3; +pub const VIRGL_CMD_BLIT_DST_RES_HANDLE: u32 = 4; +pub const VIRGL_CMD_BLIT_DST_LEVEL: u32 = 5; +pub const VIRGL_CMD_BLIT_DST_FORMAT: u32 = 6; +pub const VIRGL_CMD_BLIT_DST_X: u32 = 7; +pub const VIRGL_CMD_BLIT_DST_Y: u32 = 8; +pub const VIRGL_CMD_BLIT_DST_Z: u32 = 9; +pub const VIRGL_CMD_BLIT_DST_W: u32 = 10; +pub const VIRGL_CMD_BLIT_DST_H: u32 = 11; +pub const VIRGL_CMD_BLIT_DST_D: u32 = 12; +pub const VIRGL_CMD_BLIT_SRC_RES_HANDLE: u32 = 13; +pub const VIRGL_CMD_BLIT_SRC_LEVEL: u32 = 14; +pub const VIRGL_CMD_BLIT_SRC_FORMAT: u32 = 15; +pub const VIRGL_CMD_BLIT_SRC_X: u32 = 16; +pub const VIRGL_CMD_BLIT_SRC_Y: u32 = 17; +pub const VIRGL_CMD_BLIT_SRC_Z: u32 = 18; +pub const VIRGL_CMD_BLIT_SRC_W: u32 = 19; +pub const VIRGL_CMD_BLIT_SRC_H: u32 = 20; +pub const VIRGL_CMD_BLIT_SRC_D: u32 = 21; +pub const VIRGL_OBJ_QUERY_SIZE: u32 = 4; +pub const VIRGL_OBJ_QUERY_HANDLE: u32 = 1; +pub const VIRGL_OBJ_QUERY_TYPE_INDEX: u32 = 2; +pub const VIRGL_OBJ_QUERY_OFFSET: u32 = 3; +pub const VIRGL_OBJ_QUERY_RES_HANDLE: u32 = 4; +pub const VIRGL_QUERY_BEGIN_HANDLE: u32 = 1; +pub const VIRGL_QUERY_END_HANDLE: u32 = 1; +pub const VIRGL_QUERY_RESULT_HANDLE: u32 = 1; +pub const VIRGL_QUERY_RESULT_WAIT: u32 = 2; +pub const VIRGL_RENDER_CONDITION_SIZE: u32 = 3; +pub const VIRGL_RENDER_CONDITION_HANDLE: u32 = 1; +pub const VIRGL_RENDER_CONDITION_CONDITION: u32 = 2; +pub const VIRGL_RENDER_CONDITION_MODE: u32 = 3; +pub const VIRGL_RESOURCE_IW_RES_HANDLE: u32 = 1; +pub const VIRGL_RESOURCE_IW_LEVEL: u32 = 2; +pub const VIRGL_RESOURCE_IW_USAGE: u32 = 3; +pub const VIRGL_RESOURCE_IW_STRIDE: u32 = 4; +pub const VIRGL_RESOURCE_IW_LAYER_STRIDE: u32 = 5; +pub const VIRGL_RESOURCE_IW_X: u32 = 6; +pub const VIRGL_RESOURCE_IW_Y: u32 = 7; +pub const VIRGL_RESOURCE_IW_Z: u32 = 8; +pub const VIRGL_RESOURCE_IW_W: u32 = 9; +pub const VIRGL_RESOURCE_IW_H: u32 = 10; +pub const VIRGL_RESOURCE_IW_D: u32 = 11; +pub const VIRGL_RESOURCE_IW_DATA_START: u32 = 12; +pub const VIRGL_SET_STREAMOUT_TARGETS_APPEND_BITMASK: u32 = 1; +pub const VIRGL_SET_STREAMOUT_TARGETS_H0: u32 = 2; +pub const VIRGL_SET_SAMPLE_MASK_SIZE: u32 = 1; +pub const VIRGL_SET_SAMPLE_MASK_MASK: u32 = 1; +pub const VIRGL_SET_CLIP_STATE_SIZE: u32 = 32; +pub const VIRGL_SET_CLIP_STATE_C0: u32 = 1; +pub const VIRGL_POLYGON_STIPPLE_SIZE: u32 = 32; +pub const VIRGL_POLYGON_STIPPLE_P0: u32 = 1; +pub const VIRGL_BIND_SHADER_SIZE: u32 = 2; +pub const VIRGL_BIND_SHADER_HANDLE: u32 = 1; +pub const VIRGL_BIND_SHADER_TYPE: u32 = 2; +pub const VIRGL_TESS_STATE_SIZE: u32 = 6; +pub const VIRGL_SET_MIN_SAMPLES_SIZE: u32 = 1; +pub const VIRGL_SET_MIN_SAMPLES_MASK: u32 = 1; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct virgl_host_query_state { + pub query_state: u32, + pub result_size: u32, + pub result: u64, +} +pub const VIRGL_OBJECT_NULL: virgl_object_type = 0; +pub const VIRGL_OBJECT_BLEND: virgl_object_type = 1; +pub const VIRGL_OBJECT_RASTERIZER: virgl_object_type = 2; +pub const VIRGL_OBJECT_DSA: virgl_object_type = 3; +pub const VIRGL_OBJECT_SHADER: virgl_object_type = 4; +pub const VIRGL_OBJECT_VERTEX_ELEMENTS: virgl_object_type = 5; +pub const VIRGL_OBJECT_SAMPLER_VIEW: virgl_object_type = 6; +pub const VIRGL_OBJECT_SAMPLER_STATE: virgl_object_type = 7; +pub const VIRGL_OBJECT_SURFACE: virgl_object_type = 8; +pub const VIRGL_OBJECT_QUERY: virgl_object_type = 9; +pub const VIRGL_OBJECT_STREAMOUT_TARGET: virgl_object_type = 10; +pub const VIRGL_MAX_OBJECTS: virgl_object_type = 11; +pub type virgl_object_type = u32; +pub const VIRGL_CCMD_NOP: virgl_context_cmd = 0; +pub const VIRGL_CCMD_CREATE_OBJECT: virgl_context_cmd = 1; +pub const VIRGL_CCMD_BIND_OBJECT: virgl_context_cmd = 2; +pub const VIRGL_CCMD_DESTROY_OBJECT: virgl_context_cmd = 3; +pub const VIRGL_CCMD_SET_VIEWPORT_STATE: virgl_context_cmd = 4; +pub const VIRGL_CCMD_SET_FRAMEBUFFER_STATE: virgl_context_cmd = 5; +pub const VIRGL_CCMD_SET_VERTEX_BUFFERS: virgl_context_cmd = 6; +pub const VIRGL_CCMD_CLEAR: virgl_context_cmd = 7; +pub const VIRGL_CCMD_DRAW_VBO: virgl_context_cmd = 8; +pub const VIRGL_CCMD_RESOURCE_INLINE_WRITE: virgl_context_cmd = 9; +pub const VIRGL_CCMD_SET_SAMPLER_VIEWS: virgl_context_cmd = 10; +pub const VIRGL_CCMD_SET_INDEX_BUFFER: virgl_context_cmd = 11; +pub const VIRGL_CCMD_SET_CONSTANT_BUFFER: virgl_context_cmd = 12; +pub const VIRGL_CCMD_SET_STENCIL_REF: virgl_context_cmd = 13; +pub const VIRGL_CCMD_SET_BLEND_COLOR: virgl_context_cmd = 14; +pub const VIRGL_CCMD_SET_SCISSOR_STATE: virgl_context_cmd = 15; +pub const VIRGL_CCMD_BLIT: virgl_context_cmd = 16; +pub const VIRGL_CCMD_RESOURCE_COPY_REGION: virgl_context_cmd = 17; +pub const VIRGL_CCMD_BIND_SAMPLER_STATES: virgl_context_cmd = 18; +pub const VIRGL_CCMD_BEGIN_QUERY: virgl_context_cmd = 19; +pub const VIRGL_CCMD_END_QUERY: virgl_context_cmd = 20; +pub const VIRGL_CCMD_GET_QUERY_RESULT: virgl_context_cmd = 21; +pub const VIRGL_CCMD_SET_POLYGON_STIPPLE: virgl_context_cmd = 22; +pub const VIRGL_CCMD_SET_CLIP_STATE: virgl_context_cmd = 23; +pub const VIRGL_CCMD_SET_SAMPLE_MASK: virgl_context_cmd = 24; +pub const VIRGL_CCMD_SET_STREAMOUT_TARGETS: virgl_context_cmd = 25; +pub const VIRGL_CCMD_SET_RENDER_CONDITION: virgl_context_cmd = 26; +pub const VIRGL_CCMD_SET_UNIFORM_BUFFER: virgl_context_cmd = 27; +pub const VIRGL_CCMD_SET_SUB_CTX: virgl_context_cmd = 28; +pub const VIRGL_CCMD_CREATE_SUB_CTX: virgl_context_cmd = 29; +pub const VIRGL_CCMD_DESTROY_SUB_CTX: virgl_context_cmd = 30; +pub const VIRGL_CCMD_BIND_SHADER: virgl_context_cmd = 31; +pub const VIRGL_CCMD_SET_TESS_STATE: virgl_context_cmd = 32; +pub const VIRGL_CCMD_SET_MIN_SAMPLES: virgl_context_cmd = 33; +pub type virgl_context_cmd = u32; diff --git a/gpu_renderer/src/generated/virglrenderer.rs b/gpu_renderer/src/generated/virglrenderer.rs index 542c413..df45c1e 100644 --- a/gpu_renderer/src/generated/virglrenderer.rs +++ b/gpu_renderer/src/generated/virglrenderer.rs @@ -1,5 +1,238 @@ /* automatically generated by rust-bindgen */ -#[link(name = "virglrenderer")] extern {} +#[link(name = "virglrenderer")] +extern "C" {} -# [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct virgl_box { _unused : [ u8 ; 0 ] , } # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct iovec { _unused : [ u8 ; 0 ] , } pub type virgl_renderer_gl_context = * mut :: std :: os :: raw :: c_void ; # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct virgl_renderer_gl_ctx_param { pub version : :: std :: os :: raw :: c_int , pub shared : bool , pub major_ver : :: std :: os :: raw :: c_int , pub minor_ver : :: std :: os :: raw :: c_int , } # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct virgl_renderer_callbacks { pub version : :: std :: os :: raw :: c_int , pub write_fence : :: std :: option :: Option < unsafe extern "C" fn ( cookie : * mut :: std :: os :: raw :: c_void , fence : u32 ) > , pub create_gl_context : :: std :: option :: Option < unsafe extern "C" fn ( cookie : * mut :: std :: os :: raw :: c_void , scanout_idx : :: std :: os :: raw :: c_int , param : * mut virgl_renderer_gl_ctx_param ) -> virgl_renderer_gl_context > , pub destroy_gl_context : :: std :: option :: Option < unsafe extern "C" fn ( cookie : * mut :: std :: os :: raw :: c_void , ctx : virgl_renderer_gl_context ) > , pub make_current : :: std :: option :: Option < unsafe extern "C" fn ( cookie : * mut :: std :: os :: raw :: c_void , scanout_idx : :: std :: os :: raw :: c_int , ctx : virgl_renderer_gl_context ) -> :: std :: os :: raw :: c_int > , pub get_drm_fd : :: std :: option :: Option < unsafe extern "C" fn ( cookie : * mut :: std :: os :: raw :: c_void ) -> :: std :: os :: raw :: c_int > , } extern "C" { pub fn virgl_renderer_init ( cookie : * mut :: std :: os :: raw :: c_void , flags : :: std :: os :: raw :: c_int , cb : * mut virgl_renderer_callbacks ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_poll ( ) ; } extern "C" { pub fn virgl_renderer_get_cursor_data ( resource_id : u32 , width : * mut u32 , height : * mut u32 ) -> * mut :: std :: os :: raw :: c_void ; } extern "C" { pub fn virgl_renderer_get_rect ( resource_id : :: std :: os :: raw :: c_int , iov : * mut iovec , num_iovs : :: std :: os :: raw :: c_uint , offset : u32 , x : :: std :: os :: raw :: c_int , y : :: std :: os :: raw :: c_int , width : :: std :: os :: raw :: c_int , height : :: std :: os :: raw :: c_int ) ; } extern "C" { pub fn virgl_renderer_get_fd_for_texture ( tex_id : u32 , fd : * mut :: std :: os :: raw :: c_int ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_get_fd_for_texture2 ( tex_id : u32 , fd : * mut :: std :: os :: raw :: c_int , stride : * mut :: std :: os :: raw :: c_int , offset : * mut :: std :: os :: raw :: c_int ) -> :: std :: os :: raw :: c_int ; } # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct virgl_renderer_resource_create_args { pub handle : u32 , pub target : u32 , pub format : u32 , pub bind : u32 , pub width : u32 , pub height : u32 , pub depth : u32 , pub array_size : u32 , pub last_level : u32 , pub nr_samples : u32 , pub flags : u32 , } extern "C" { pub fn virgl_renderer_resource_create ( args : * mut virgl_renderer_resource_create_args , iov : * mut iovec , num_iovs : u32 ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_resource_import_eglimage ( args : * mut virgl_renderer_resource_create_args , image : * mut :: std :: os :: raw :: c_void ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_resource_unref ( res_handle : u32 ) ; } extern "C" { pub fn virgl_renderer_context_create ( handle : u32 , nlen : u32 , name : * const :: std :: os :: raw :: c_char ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_context_destroy ( handle : u32 ) ; } extern "C" { pub fn virgl_renderer_submit_cmd ( buffer : * mut :: std :: os :: raw :: c_void , ctx_id : :: std :: os :: raw :: c_int , ndw : :: std :: os :: raw :: c_int ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_transfer_read_iov ( handle : u32 , ctx_id : u32 , level : u32 , stride : u32 , layer_stride : u32 , box_ : * mut virgl_box , offset : u64 , iov : * mut iovec , iovec_cnt : :: std :: os :: raw :: c_int ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_transfer_write_iov ( handle : u32 , ctx_id : u32 , level : :: std :: os :: raw :: c_int , stride : u32 , layer_stride : u32 , box_ : * mut virgl_box , offset : u64 , iovec : * mut iovec , iovec_cnt : :: std :: os :: raw :: c_uint ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_get_cap_set ( set : u32 , max_ver : * mut u32 , max_size : * mut u32 ) ; } extern "C" { pub fn virgl_renderer_fill_caps ( set : u32 , version : u32 , caps : * mut :: std :: os :: raw :: c_void ) ; } extern "C" { pub fn virgl_renderer_resource_attach_iov ( res_handle : :: std :: os :: raw :: c_int , iov : * mut iovec , num_iovs : :: std :: os :: raw :: c_int ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_resource_detach_iov ( res_handle : :: std :: os :: raw :: c_int , iov : * mut * mut iovec , num_iovs : * mut :: std :: os :: raw :: c_int ) ; } extern "C" { pub fn virgl_renderer_create_fence ( client_fence_id : :: std :: os :: raw :: c_int , ctx_id : u32 ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_force_ctx_0 ( ) ; } extern "C" { pub fn virgl_renderer_ctx_attach_resource ( ctx_id : :: std :: os :: raw :: c_int , res_handle : :: std :: os :: raw :: c_int ) ; } extern "C" { pub fn virgl_renderer_ctx_detach_resource ( ctx_id : :: std :: os :: raw :: c_int , res_handle : :: std :: os :: raw :: c_int ) ; } # [ repr ( C ) ] # [ derive ( Debug , Copy , Clone ) ] pub struct virgl_renderer_resource_info { pub handle : u32 , pub virgl_format : u32 , pub width : u32 , pub height : u32 , pub depth : u32 , pub flags : u32 , pub tex_id : u32 , pub stride : u32 , pub drm_fourcc : :: std :: os :: raw :: c_int , } extern "C" { pub fn virgl_renderer_resource_get_info ( res_handle : :: std :: os :: raw :: c_int , info : * mut virgl_renderer_resource_info ) -> :: std :: os :: raw :: c_int ; } extern "C" { pub fn virgl_renderer_cleanup ( cookie : * mut :: std :: os :: raw :: c_void ) ; } extern "C" { pub fn virgl_renderer_reset ( ) ; } extern "C" { pub fn virgl_renderer_get_poll_fd ( ) -> :: std :: os :: raw :: c_int ; } \ No newline at end of file +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct virgl_box { + _unused: [u8; 0], +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct iovec { + _unused: [u8; 0], +} +pub type virgl_renderer_gl_context = *mut ::std::os::raw::c_void; +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct virgl_renderer_gl_ctx_param { + pub version: ::std::os::raw::c_int, + pub shared: bool, + pub major_ver: ::std::os::raw::c_int, + pub minor_ver: ::std::os::raw::c_int, +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct virgl_renderer_callbacks { + pub version: ::std::os::raw::c_int, + pub write_fence: ::std::option::Option< + unsafe extern "C" fn(cookie: *mut ::std::os::raw::c_void, fence: u32), + >, + pub create_gl_context: ::std::option::Option< + unsafe extern "C" fn( + cookie: *mut ::std::os::raw::c_void, + scanout_idx: ::std::os::raw::c_int, + param: *mut virgl_renderer_gl_ctx_param, + ) -> virgl_renderer_gl_context, + >, + pub destroy_gl_context: ::std::option::Option< + unsafe extern "C" fn(cookie: *mut ::std::os::raw::c_void, ctx: virgl_renderer_gl_context), + >, + pub make_current: ::std::option::Option< + unsafe extern "C" fn( + cookie: *mut ::std::os::raw::c_void, + scanout_idx: ::std::os::raw::c_int, + ctx: virgl_renderer_gl_context, + ) -> ::std::os::raw::c_int, + >, + pub get_drm_fd: ::std::option::Option< + unsafe extern "C" fn(cookie: *mut ::std::os::raw::c_void) -> ::std::os::raw::c_int, + >, +} +extern "C" { + pub fn virgl_renderer_init( + cookie: *mut ::std::os::raw::c_void, + flags: ::std::os::raw::c_int, + cb: *mut virgl_renderer_callbacks, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_poll(); +} +extern "C" { + pub fn virgl_renderer_get_cursor_data( + resource_id: u32, + width: *mut u32, + height: *mut u32, + ) -> *mut ::std::os::raw::c_void; +} +extern "C" { + pub fn virgl_renderer_get_rect( + resource_id: ::std::os::raw::c_int, + iov: *mut iovec, + num_iovs: ::std::os::raw::c_uint, + offset: u32, + x: ::std::os::raw::c_int, + y: ::std::os::raw::c_int, + width: ::std::os::raw::c_int, + height: ::std::os::raw::c_int, + ); +} +extern "C" { + pub fn virgl_renderer_get_fd_for_texture( + tex_id: u32, + fd: *mut ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_get_fd_for_texture2( + tex_id: u32, + fd: *mut ::std::os::raw::c_int, + stride: *mut ::std::os::raw::c_int, + offset: *mut ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct virgl_renderer_resource_create_args { + pub handle: u32, + pub target: u32, + pub format: u32, + pub bind: u32, + pub width: u32, + pub height: u32, + pub depth: u32, + pub array_size: u32, + pub last_level: u32, + pub nr_samples: u32, + pub flags: u32, +} +extern "C" { + pub fn virgl_renderer_resource_create( + args: *mut virgl_renderer_resource_create_args, + iov: *mut iovec, + num_iovs: u32, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_resource_import_eglimage( + args: *mut virgl_renderer_resource_create_args, + image: *mut ::std::os::raw::c_void, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_resource_unref(res_handle: u32); +} +extern "C" { + pub fn virgl_renderer_context_create( + handle: u32, + nlen: u32, + name: *const ::std::os::raw::c_char, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_context_destroy(handle: u32); +} +extern "C" { + pub fn virgl_renderer_submit_cmd( + buffer: *mut ::std::os::raw::c_void, + ctx_id: ::std::os::raw::c_int, + ndw: ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_transfer_read_iov( + handle: u32, + ctx_id: u32, + level: u32, + stride: u32, + layer_stride: u32, + box_: *mut virgl_box, + offset: u64, + iov: *mut iovec, + iovec_cnt: ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_transfer_write_iov( + handle: u32, + ctx_id: u32, + level: ::std::os::raw::c_int, + stride: u32, + layer_stride: u32, + box_: *mut virgl_box, + offset: u64, + iovec: *mut iovec, + iovec_cnt: ::std::os::raw::c_uint, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_get_cap_set(set: u32, max_ver: *mut u32, max_size: *mut u32); +} +extern "C" { + pub fn virgl_renderer_fill_caps(set: u32, version: u32, caps: *mut ::std::os::raw::c_void); +} +extern "C" { + pub fn virgl_renderer_resource_attach_iov( + res_handle: ::std::os::raw::c_int, + iov: *mut iovec, + num_iovs: ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_resource_detach_iov( + res_handle: ::std::os::raw::c_int, + iov: *mut *mut iovec, + num_iovs: *mut ::std::os::raw::c_int, + ); +} +extern "C" { + pub fn virgl_renderer_create_fence( + client_fence_id: ::std::os::raw::c_int, + ctx_id: u32, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_force_ctx_0(); +} +extern "C" { + pub fn virgl_renderer_ctx_attach_resource( + ctx_id: ::std::os::raw::c_int, + res_handle: ::std::os::raw::c_int, + ); +} +extern "C" { + pub fn virgl_renderer_ctx_detach_resource( + ctx_id: ::std::os::raw::c_int, + res_handle: ::std::os::raw::c_int, + ); +} +#[repr(C)] +#[derive(Debug, Copy, Clone)] +pub struct virgl_renderer_resource_info { + pub handle: u32, + pub virgl_format: u32, + pub width: u32, + pub height: u32, + pub depth: u32, + pub flags: u32, + pub tex_id: u32, + pub stride: u32, + pub drm_fourcc: ::std::os::raw::c_int, +} +extern "C" { + pub fn virgl_renderer_resource_get_info( + res_handle: ::std::os::raw::c_int, + info: *mut virgl_renderer_resource_info, + ) -> ::std::os::raw::c_int; +} +extern "C" { + pub fn virgl_renderer_cleanup(cookie: *mut ::std::os::raw::c_void); +} +extern "C" { + pub fn virgl_renderer_reset(); +} +extern "C" { + pub fn virgl_renderer_get_poll_fd() -> ::std::os::raw::c_int; +} diff --git a/gpu_renderer/src/lib.rs b/gpu_renderer/src/lib.rs index 09d5949..6864fe9 100644 --- a/gpu_renderer/src/lib.rs +++ b/gpu_renderer/src/lib.rs @@ -8,9 +8,9 @@ extern crate data_model; extern crate libc; extern crate sys_util; +mod command_buffer; mod generated; mod pipe_format_fourcc; -mod command_buffer; use std::cell::RefCell; use std::ffi::CStr; @@ -19,7 +19,7 @@ use std::fs::File; use std::marker::PhantomData; use std::mem::{size_of, transmute, uninitialized}; use std::ops::Deref; -use std::os::raw::{c_void, c_int, c_uint, c_char}; +use std::os::raw::{c_char, c_int, c_uint, c_void}; use std::os::unix::io::{FromRawFd, RawFd}; use std::ptr::{null, null_mut}; use std::rc::Rc; @@ -29,20 +29,21 @@ use std::sync::atomic::{AtomicBool, Ordering, ATOMIC_BOOL_INIT}; use data_model::{VolatileMemory, VolatileSlice}; use sys_util::{GuestAddress, GuestMemory}; -use generated::virglrenderer::*; -pub use generated::virglrenderer::{virgl_renderer_resource_create_args, - virgl_renderer_resource_info}; -use generated::epoxy_egl::{EGL_CONTEXT_CLIENT_VERSION, EGL_SURFACE_TYPE, EGL_OPENGL_ES_API, - EGL_NONE, EGL_GL_TEXTURE_2D_KHR, EGL_WIDTH, EGL_HEIGHT, - EGL_LINUX_DRM_FOURCC_EXT, EGL_DMA_BUF_PLANE0_FD_EXT, - EGL_DMA_BUF_PLANE0_OFFSET_EXT, EGL_DMA_BUF_PLANE0_PITCH_EXT, - EGL_LINUX_DMA_BUF_EXT, EGLDEBUGPROCKHR, EGLAttrib, - EGLuint64KHR, EGLNativeDisplayType, EGLConfig, EGLContext, EGLDisplay, - EGLSurface, EGLClientBuffer, EGLBoolean, EGLint, EGLenum, EGLImageKHR}; -use generated::p_defines::{PIPE_TEXTURE_1D, PIPE_TEXTURE_2D, PIPE_BIND_SAMPLER_VIEW}; +pub use command_buffer::CommandBufferBuilder; +use generated::epoxy_egl::{ + EGLAttrib, EGLBoolean, EGLClientBuffer, EGLConfig, EGLContext, EGLDisplay, EGLImageKHR, + EGLNativeDisplayType, EGLSurface, EGLenum, EGLint, EGLuint64KHR, EGLDEBUGPROCKHR, + EGL_CONTEXT_CLIENT_VERSION, EGL_DMA_BUF_PLANE0_FD_EXT, EGL_DMA_BUF_PLANE0_OFFSET_EXT, + EGL_DMA_BUF_PLANE0_PITCH_EXT, EGL_GL_TEXTURE_2D_KHR, EGL_HEIGHT, EGL_LINUX_DMA_BUF_EXT, + EGL_LINUX_DRM_FOURCC_EXT, EGL_NONE, EGL_OPENGL_ES_API, EGL_SURFACE_TYPE, EGL_WIDTH, +}; +use generated::p_defines::{PIPE_BIND_SAMPLER_VIEW, PIPE_TEXTURE_1D, PIPE_TEXTURE_2D}; use generated::p_format::PIPE_FORMAT_B8G8R8X8_UNORM; +use generated::virglrenderer::*; +pub use generated::virglrenderer::{ + virgl_renderer_resource_create_args, virgl_renderer_resource_info, +}; pub use pipe_format_fourcc::pipe_format_fourcc as format_fourcc; -pub use command_buffer::CommandBufferBuilder; /// Arguments used in `Renderer::create_resource`.. pub type ResourceCreateArgs = virgl_renderer_resource_create_args; @@ -163,8 +164,7 @@ struct VirglCookie { fence_state: Rc<RefCell<FenceState>>, } -extern "C" fn write_fence(cookie: *mut c_void, - fence: u32) { +extern "C" fn write_fence(cookie: *mut c_void, fence: u32) { assert!(!cookie.is_null()); let cookie = unsafe { &*(cookie as *mut VirglCookie) }; @@ -173,10 +173,11 @@ extern "C" fn write_fence(cookie: *mut c_void, fence_state.write(fence); } -unsafe extern "C" fn create_gl_context(cookie: *mut c_void, - scanout_idx: c_int, - param: *mut virgl_renderer_gl_ctx_param) - -> virgl_renderer_gl_context { +unsafe extern "C" fn create_gl_context( + cookie: *mut c_void, + scanout_idx: c_int, + param: *mut virgl_renderer_gl_ctx_param, +) -> virgl_renderer_gl_context { let _ = scanout_idx; let cookie = &*(cookie as *mut VirglCookie); @@ -186,16 +187,19 @@ unsafe extern "C" fn create_gl_context(cookie: *mut c_void, null_mut() }; let context_attribs = [EGL_CONTEXT_CLIENT_VERSION as i32, 3, EGL_NONE as i32]; - (cookie.egl_funcs.CreateContext)(cookie.display, - cookie.egl_config, - shared, - context_attribs.as_ptr()) + (cookie.egl_funcs.CreateContext)( + cookie.display, + cookie.egl_config, + shared, + context_attribs.as_ptr(), + ) } -unsafe extern "C" fn make_current(cookie: *mut c_void, - scanout_idx: c_int, - ctx: virgl_renderer_gl_context) - -> c_int { +unsafe extern "C" fn make_current( + cookie: *mut c_void, + scanout_idx: c_int, + ctx: virgl_renderer_gl_context, +) -> c_int { let _ = scanout_idx; let cookie = &*(cookie as *mut VirglCookie); @@ -207,22 +211,23 @@ unsafe extern "C" fn destroy_gl_context(cookie: *mut c_void, ctx: virgl_renderer (cookie.egl_funcs.DestroyContext)(cookie.display, ctx); } -const VIRGL_RENDERER_CALLBACKS: &virgl_renderer_callbacks = - &virgl_renderer_callbacks { - version: 1, - write_fence: Some(write_fence), - create_gl_context: Some(create_gl_context), - destroy_gl_context: Some(destroy_gl_context), - make_current: Some(make_current), - get_drm_fd: None, - }; - -unsafe extern "C" fn error_callback(error: c_uint, - command: *const c_char, - _: c_int, - _: *mut c_void, - _: *mut c_void, - message: *const c_char) { +const VIRGL_RENDERER_CALLBACKS: &virgl_renderer_callbacks = &virgl_renderer_callbacks { + version: 1, + write_fence: Some(write_fence), + create_gl_context: Some(create_gl_context), + destroy_gl_context: Some(destroy_gl_context), + make_current: Some(make_current), + get_drm_fd: None, +}; + +unsafe extern "C" fn error_callback( + error: c_uint, + command: *const c_char, + _: c_int, + _: *mut c_void, + _: *mut c_void, + message: *const c_char, +) { eprint!("EGL ERROR {}: {:?}", error, CStr::from_ptr(command)); if !message.is_null() { eprint!(": {:?}", CStr::from_ptr(message)); @@ -233,49 +238,52 @@ unsafe extern "C" fn error_callback(error: c_uint, #[allow(non_snake_case)] struct EGLFunctionsInner { BindAPI: unsafe extern "C" fn(api: EGLenum) -> EGLBoolean, - ChooseConfig: unsafe extern "C" fn(dpy: EGLDisplay, - attrib_list: *const EGLint, - configs: *mut EGLConfig, - config_size: EGLint, - num_config: *mut EGLint) - -> EGLBoolean, - CreateContext: unsafe extern "C" fn(dpy: EGLDisplay, - config: EGLConfig, - share_context: EGLContext, - attrib_list: *const EGLint) - -> EGLContext, - CreateImageKHR: unsafe extern "C" fn(dpy: EGLDisplay, - ctx: EGLContext, - target: EGLenum, - buffer: EGLClientBuffer, - attrib_list: *const EGLint) - -> EGLImageKHR, + ChooseConfig: unsafe extern "C" fn( + dpy: EGLDisplay, + attrib_list: *const EGLint, + configs: *mut EGLConfig, + config_size: EGLint, + num_config: *mut EGLint, + ) -> EGLBoolean, + CreateContext: unsafe extern "C" fn( + dpy: EGLDisplay, + config: EGLConfig, + share_context: EGLContext, + attrib_list: *const EGLint, + ) -> EGLContext, + CreateImageKHR: unsafe extern "C" fn( + dpy: EGLDisplay, + ctx: EGLContext, + target: EGLenum, + buffer: EGLClientBuffer, + attrib_list: *const EGLint, + ) -> EGLImageKHR, DebugMessageControlKHR: unsafe extern "C" fn(callback: EGLDEBUGPROCKHR, attrib_list: *const EGLAttrib) -> EGLint, DestroyContext: unsafe extern "C" fn(dpy: EGLDisplay, ctx: EGLContext) -> EGLBoolean, DestroyImageKHR: unsafe extern "C" fn(dpy: EGLDisplay, image: EGLImageKHR) -> EGLBoolean, - ExportDRMImageMESA: unsafe extern "C" fn(dpy: EGLDisplay, - image: EGLImageKHR, - fds: *mut ::std::os::raw::c_int, - strides: *mut EGLint, - offsets: *mut EGLint) - -> EGLBoolean, - ExportDMABUFImageQueryMESA: unsafe extern "C" fn(dpy: EGLDisplay, - image: EGLImageKHR, - fourcc: *mut ::std::os::raw::c_int, - num_planes: *mut ::std::os::raw::c_int, - modifiers: *mut EGLuint64KHR) - -> EGLBoolean, + ExportDRMImageMESA: unsafe extern "C" fn( + dpy: EGLDisplay, + image: EGLImageKHR, + fds: *mut ::std::os::raw::c_int, + strides: *mut EGLint, + offsets: *mut EGLint, + ) -> EGLBoolean, + ExportDMABUFImageQueryMESA: unsafe extern "C" fn( + dpy: EGLDisplay, + image: EGLImageKHR, + fourcc: *mut ::std::os::raw::c_int, + num_planes: *mut ::std::os::raw::c_int, + modifiers: *mut EGLuint64KHR, + ) -> EGLBoolean, GetCurrentContext: unsafe extern "C" fn() -> EGLContext, GetCurrentDisplay: unsafe extern "C" fn() -> EGLDisplay, GetDisplay: unsafe extern "C" fn(display_id: EGLNativeDisplayType) -> EGLDisplay, Initialize: unsafe extern "C" fn(dpy: EGLDisplay, major: *mut EGLint, minor: *mut EGLint) -> EGLBoolean, - MakeCurrent: unsafe extern "C" fn(dpy: EGLDisplay, - draw: EGLSurface, - read: EGLSurface, - ctx: EGLContext) - -> EGLBoolean, + MakeCurrent: + unsafe extern "C" fn(dpy: EGLDisplay, draw: EGLSurface, read: EGLSurface, ctx: EGLContext) + -> EGLBoolean, no_sync_send: PhantomData<*mut ()>, } @@ -284,32 +292,45 @@ struct EGLFunctions(Rc<EGLFunctionsInner>); impl EGLFunctions { fn new() -> Result<EGLFunctions> { - use generated::epoxy_egl::{epoxy_eglBindAPI, epoxy_eglChooseConfig, - epoxy_eglCreateContext, epoxy_eglCreateImageKHR, - epoxy_eglDebugMessageControlKHR, epoxy_eglDestroyContext, - epoxy_eglDestroyImageKHR, epoxy_eglExportDRMImageMESA, - epoxy_eglExportDMABUFImageQueryMESA, - epoxy_eglGetCurrentContext, epoxy_eglGetCurrentDisplay, - epoxy_eglGetDisplay, epoxy_eglInitialize, epoxy_eglMakeCurrent}; + use generated::epoxy_egl::{ + epoxy_eglBindAPI, epoxy_eglChooseConfig, epoxy_eglCreateContext, + epoxy_eglCreateImageKHR, epoxy_eglDebugMessageControlKHR, epoxy_eglDestroyContext, + epoxy_eglDestroyImageKHR, epoxy_eglExportDMABUFImageQueryMESA, + epoxy_eglExportDRMImageMESA, epoxy_eglGetCurrentContext, epoxy_eglGetCurrentDisplay, + epoxy_eglGetDisplay, epoxy_eglInitialize, epoxy_eglMakeCurrent, + }; // This is unsafe because it is reading mutable static variables exported by epoxy. These // variables are initialized during the binary's init and never modified again, so it should // be safe to read them now. unsafe { Ok(EGLFunctions(Rc::new(EGLFunctionsInner { BindAPI: epoxy_eglBindAPI.ok_or(Error::MissingEGLFunction("eglBindAPI"))?, - ChooseConfig: epoxy_eglChooseConfig.ok_or(Error::MissingEGLFunction("eglChooseConfig"))?, - CreateContext: epoxy_eglCreateContext.ok_or(Error::MissingEGLFunction("eglCreateContext"))?, - CreateImageKHR: epoxy_eglCreateImageKHR.ok_or(Error::MissingEGLFunction("eglCreateImageKHR"))?, - DebugMessageControlKHR: epoxy_eglDebugMessageControlKHR.ok_or(Error::MissingEGLFunction("eglDebugMessageControlKHR"))?, - DestroyContext: epoxy_eglDestroyContext.ok_or(Error::MissingEGLFunction("eglDestroyContext"))?, - DestroyImageKHR: epoxy_eglDestroyImageKHR.ok_or(Error::MissingEGLFunction("eglDestroyImageKHR"))?, - ExportDRMImageMESA: epoxy_eglExportDRMImageMESA.ok_or(Error::MissingEGLFunction("eglExportDRMImageMESA"))?, - ExportDMABUFImageQueryMESA: epoxy_eglExportDMABUFImageQueryMESA.ok_or(Error::MissingEGLFunction("eglExportDMABUFImageQueryMESA"))?, - GetCurrentContext: epoxy_eglGetCurrentContext.ok_or(Error::MissingEGLFunction("eglGetCurrentContext"))?, - GetCurrentDisplay: epoxy_eglGetCurrentDisplay.ok_or(Error::MissingEGLFunction("eglGetCurrentDisplay"))?, - GetDisplay: epoxy_eglGetDisplay.ok_or(Error::MissingEGLFunction("eglGetDisplay"))?, - Initialize: epoxy_eglInitialize.ok_or(Error::MissingEGLFunction("eglInitialize"))?, - MakeCurrent: epoxy_eglMakeCurrent.ok_or(Error::MissingEGLFunction("eglMakeCurrent"))?, + ChooseConfig: epoxy_eglChooseConfig + .ok_or(Error::MissingEGLFunction("eglChooseConfig"))?, + CreateContext: epoxy_eglCreateContext + .ok_or(Error::MissingEGLFunction("eglCreateContext"))?, + CreateImageKHR: epoxy_eglCreateImageKHR + .ok_or(Error::MissingEGLFunction("eglCreateImageKHR"))?, + DebugMessageControlKHR: epoxy_eglDebugMessageControlKHR + .ok_or(Error::MissingEGLFunction("eglDebugMessageControlKHR"))?, + DestroyContext: epoxy_eglDestroyContext + .ok_or(Error::MissingEGLFunction("eglDestroyContext"))?, + DestroyImageKHR: epoxy_eglDestroyImageKHR + .ok_or(Error::MissingEGLFunction("eglDestroyImageKHR"))?, + ExportDRMImageMESA: epoxy_eglExportDRMImageMESA + .ok_or(Error::MissingEGLFunction("eglExportDRMImageMESA"))?, + ExportDMABUFImageQueryMESA: epoxy_eglExportDMABUFImageQueryMESA + .ok_or(Error::MissingEGLFunction("eglExportDMABUFImageQueryMESA"))?, + GetCurrentContext: epoxy_eglGetCurrentContext + .ok_or(Error::MissingEGLFunction("eglGetCurrentContext"))?, + GetCurrentDisplay: epoxy_eglGetCurrentDisplay + .ok_or(Error::MissingEGLFunction("eglGetCurrentDisplay"))?, + GetDisplay: epoxy_eglGetDisplay + .ok_or(Error::MissingEGLFunction("eglGetDisplay"))?, + Initialize: epoxy_eglInitialize + .ok_or(Error::MissingEGLFunction("eglInitialize"))?, + MakeCurrent: epoxy_eglMakeCurrent + .ok_or(Error::MissingEGLFunction("eglMakeCurrent"))?, no_sync_send: PhantomData, }))) } @@ -371,11 +392,13 @@ impl Renderer { // Safe because only a valid, initialized display is used, along with validly sized // pointers to stack variables. let ret = unsafe { - (egl_funcs.ChooseConfig)(display, - config_attribs.as_ptr(), - &mut egl_config, - 1, - &mut num_configs /* unused but can't be null */) + (egl_funcs.ChooseConfig)( + display, + config_attribs.as_ptr(), + &mut egl_config, + 1, + &mut num_configs, /* unused but can't be null */ + ) }; if ret == 0 { return Err(Error::EGLChooseConfig); @@ -389,11 +412,11 @@ impl Renderer { let fence_state = Rc::new(RefCell::new(FenceState { latest_fence: 0 })); let cookie: *mut VirglCookie = Box::into_raw(Box::new(VirglCookie { - display, - egl_config, - egl_funcs: egl_funcs.clone(), - fence_state: Rc::clone(&fence_state), - })); + display, + egl_config, + egl_funcs: egl_funcs.clone(), + fence_state: Rc::clone(&fence_state), + })); // Safe because EGL was properly initialized before here.. let ret = unsafe { (egl_funcs.BindAPI)(EGL_OPENGL_ES_API) }; @@ -420,18 +443,20 @@ impl Renderer { // Safe because a valid cookie and set of callbacks is used and the result is checked for // error. let ret = unsafe { - virgl_renderer_init(cookie as *mut c_void, - 0, - transmute(VIRGL_RENDERER_CALLBACKS)) + virgl_renderer_init( + cookie as *mut c_void, + 0, + transmute(VIRGL_RENDERER_CALLBACKS), + ) }; ret_to_res(ret)?; Ok(Renderer { - no_sync_send: PhantomData, - egl_funcs, - display, - fence_state - }) + no_sync_send: PhantomData, + egl_funcs, + display, + fence_state, + }) } /// Gets the version and size for the given capability set ID. @@ -464,112 +489,122 @@ impl Renderer { // Safe because virglrenderer is initialized by now and the context name is statically // allocated. The return value is checked before returning a new context. let ret = unsafe { - virgl_renderer_context_create(id, - CONTEXT_NAME.len() as u32, - CONTEXT_NAME.as_ptr() as *const c_char) + virgl_renderer_context_create( + id, + CONTEXT_NAME.len() as u32, + CONTEXT_NAME.as_ptr() as *const c_char, + ) }; ret_to_res(ret)?; Ok(Context { - id, - no_sync_send: PhantomData, - }) + id, + no_sync_send: PhantomData, + }) } /// Creates a resource with the given arguments. - pub fn create_resource(&self, - mut args: virgl_renderer_resource_create_args) - -> Result<Resource> { + pub fn create_resource( + &self, + mut args: virgl_renderer_resource_create_args, + ) -> Result<Resource> { // Safe because virglrenderer is initialized by now, and the return value is checked before // returning a new resource. The backing buffers are not supplied with this call. let ret = unsafe { virgl_renderer_resource_create(&mut args, null_mut(), 0) }; ret_to_res(ret)?; Ok(Resource { - id: args.handle, - backing_iovecs: Vec::new(), - backing_mem: None, - egl_funcs: self.egl_funcs.clone(), - no_sync_send: PhantomData, - }) + id: args.handle, + backing_iovecs: Vec::new(), + backing_mem: None, + egl_funcs: self.egl_funcs.clone(), + no_sync_send: PhantomData, + }) } /// Imports a resource from an EGLImage. - pub fn import_resource(&self, - mut args: virgl_renderer_resource_create_args, - image: &Image) - -> Result<Resource> { + pub fn import_resource( + &self, + mut args: virgl_renderer_resource_create_args, + image: &Image, + ) -> Result<Resource> { let ret = unsafe { virgl_renderer_resource_import_eglimage(&mut args, image.image) }; ret_to_res(ret)?; Ok(Resource { - id: args.handle, - backing_iovecs: Vec::new(), - backing_mem: None, - egl_funcs: self.egl_funcs.clone(), - no_sync_send: PhantomData, - }) + id: args.handle, + backing_iovecs: Vec::new(), + backing_mem: None, + egl_funcs: self.egl_funcs.clone(), + no_sync_send: PhantomData, + }) } /// Helper that creates a simple 1 dimensional resource with basic metadata. pub fn create_tex_1d(&self, id: u32, width: u32) -> Result<Resource> { self.create_resource(virgl_renderer_resource_create_args { - handle: id, - target: PIPE_TEXTURE_1D, - format: PIPE_FORMAT_B8G8R8X8_UNORM, - width, - height: 1, - depth: 1, - array_size: 1, - last_level: 0, - nr_samples: 0, - bind: PIPE_BIND_SAMPLER_VIEW, - flags: 0, - }) + handle: id, + target: PIPE_TEXTURE_1D, + format: PIPE_FORMAT_B8G8R8X8_UNORM, + width, + height: 1, + depth: 1, + array_size: 1, + last_level: 0, + nr_samples: 0, + bind: PIPE_BIND_SAMPLER_VIEW, + flags: 0, + }) } /// Helper that creates a simple 2 dimensional resource with basic metadata. pub fn create_tex_2d(&self, id: u32, width: u32, height: u32) -> Result<Resource> { self.create_resource(virgl_renderer_resource_create_args { - handle: id, - target: PIPE_TEXTURE_2D, - format: PIPE_FORMAT_B8G8R8X8_UNORM, - width, - height, - depth: 1, - array_size: 1, - last_level: 0, - nr_samples: 0, - bind: PIPE_BIND_SAMPLER_VIEW, - flags: 0, - }) + handle: id, + target: PIPE_TEXTURE_2D, + format: PIPE_FORMAT_B8G8R8X8_UNORM, + width, + height, + depth: 1, + array_size: 1, + last_level: 0, + nr_samples: 0, + bind: PIPE_BIND_SAMPLER_VIEW, + flags: 0, + }) } /// Creates an EGLImage from a DMA buffer. - pub fn image_from_dmabuf(&self, - fourcc: u32, - width: u32, - height: u32, - fd: RawFd, - offset: u32, - stride: u32) -> Result<Image> { - let mut attrs = [EGL_WIDTH as EGLint, - width as EGLint, - EGL_HEIGHT as EGLint, - height as EGLint, - EGL_LINUX_DRM_FOURCC_EXT as EGLint, - fourcc as EGLint, - EGL_DMA_BUF_PLANE0_FD_EXT as EGLint, - fd as EGLint, - EGL_DMA_BUF_PLANE0_OFFSET_EXT as EGLint, - offset as EGLint, - EGL_DMA_BUF_PLANE0_PITCH_EXT as EGLint, - stride as EGLint, - EGL_NONE as EGLint]; + pub fn image_from_dmabuf( + &self, + fourcc: u32, + width: u32, + height: u32, + fd: RawFd, + offset: u32, + stride: u32, + ) -> Result<Image> { + let mut attrs = [ + EGL_WIDTH as EGLint, + width as EGLint, + EGL_HEIGHT as EGLint, + height as EGLint, + EGL_LINUX_DRM_FOURCC_EXT as EGLint, + fourcc as EGLint, + EGL_DMA_BUF_PLANE0_FD_EXT as EGLint, + fd as EGLint, + EGL_DMA_BUF_PLANE0_OFFSET_EXT as EGLint, + offset as EGLint, + EGL_DMA_BUF_PLANE0_PITCH_EXT as EGLint, + stride as EGLint, + EGL_NONE as EGLint, + ]; let image = unsafe { - (self.egl_funcs.CreateImageKHR)(self.display, - 0 as EGLContext, - EGL_LINUX_DMA_BUF_EXT, - null_mut() as EGLClientBuffer, - attrs.as_mut_ptr()) + (self.egl_funcs.CreateImageKHR)( + self.display, + 0 as EGLContext, + EGL_LINUX_DMA_BUF_EXT, + null_mut() as EGLClientBuffer, + attrs.as_mut_ptr(), + ) }; if image.is_null() { @@ -579,7 +614,7 @@ impl Renderer { Ok(Image { egl_funcs: self.egl_funcs.clone(), egl_dpy: self.display, - image + image, }) } @@ -589,9 +624,7 @@ impl Renderer { } pub fn create_fence(&mut self, fence_id: u32, ctx_id: u32) -> Result<()> { - let ret = unsafe { - virgl_renderer_create_fence(fence_id as i32, ctx_id) - }; + let ret = unsafe { virgl_renderer_create_fence(fence_id as i32, ctx_id) }; ret_to_res(ret) } @@ -734,11 +767,13 @@ impl Resource { // Safe because a valid display, context, and texture ID are given. The attribute list is // not needed. The result is checked to ensure the returned image is valid. let image = unsafe { - (self.egl_funcs.CreateImageKHR)(egl_dpy, - egl_ctx, - EGL_GL_TEXTURE_2D_KHR, - res_info.tex_id as EGLClientBuffer, - null()) + (self.egl_funcs.CreateImageKHR)( + egl_dpy, + egl_ctx, + EGL_GL_TEXTURE_2D_KHR, + res_info.tex_id as EGLClientBuffer, + null(), + ) }; if image.is_null() { @@ -748,16 +783,20 @@ impl Resource { // Safe because the display and image are valid and each function call is checked for // success. The returned image parameters are stored in stack variables of the correct type. let export_success = unsafe { - (self.egl_funcs.ExportDMABUFImageQueryMESA)(egl_dpy, - image, - &mut fourcc, - null_mut(), - &mut modifiers) != 0 && - (self.egl_funcs.ExportDRMImageMESA)(egl_dpy, - image, - &mut fd, - &mut stride, - &mut offset) != 0 + (self.egl_funcs.ExportDMABUFImageQueryMESA)( + egl_dpy, + image, + &mut fourcc, + null_mut(), + &mut modifiers, + ) != 0 + && (self.egl_funcs.ExportDRMImageMESA)( + egl_dpy, + image, + &mut fd, + &mut stride, + &mut offset, + ) != 0 }; // Safe because we checked that the image was valid and nobody else owns it. The image does @@ -774,24 +813,26 @@ impl Resource { // owned by us. let dmabuf = unsafe { File::from_raw_fd(fd) }; Ok(ExportedResource { - dmabuf, - width: res_info.width, - height: res_info.height, - fourcc: fourcc as u32, - modifiers: modifiers, - stride: stride as u32, - offset: offset as u32, - }) + dmabuf, + width: res_info.width, + height: res_info.height, + fourcc: fourcc as u32, + modifiers, + stride: stride as u32, + offset: offset as u32, + }) } /// Attaches a scatter-gather mapping of guest memory to this resource which used for transfers. - pub fn attach_backing(&mut self, - iovecs: &[(GuestAddress, usize)], - mem: &GuestMemory) - -> Result<()> { + pub fn attach_backing( + &mut self, + iovecs: &[(GuestAddress, usize)], + mem: &GuestMemory, + ) -> Result<()> { if iovecs - .iter() - .any(|&(addr, len)| mem.get_slice(addr.offset(), len as u64).is_err()) { + .iter() + .any(|&(addr, len)| mem.get_slice(addr.offset(), len as u64).is_err()) + { return Err(Error::InvalidIovec); } self.detach_backing(); @@ -799,17 +840,18 @@ impl Resource { for &(addr, len) in iovecs.iter() { // Unwrap will not panic because we already checked the slices. let slice = mem.get_slice(addr.offset(), len as u64).unwrap(); - self.backing_iovecs - .push(VirglVec { - base: slice.as_ptr() as *mut c_void, - len, - }); + self.backing_iovecs.push(VirglVec { + base: slice.as_ptr() as *mut c_void, + len, + }); } // Safe because the backing is into guest memory that we store a reference count for. let ret = unsafe { - virgl_renderer_resource_attach_iov(self.id as i32, - self.backing_iovecs.as_mut_ptr() as *mut iovec, - self.backing_iovecs.len() as i32) + virgl_renderer_resource_attach_iov( + self.id as i32, + self.backing_iovecs.as_mut_ptr() as *mut iovec, + self.backing_iovecs.len() as i32, + ) }; let res = ret_to_res(ret); if res.is_err() { @@ -833,63 +875,70 @@ impl Resource { } /// Performs a transfer to the given resource from its backing in guest memory. - pub fn transfer_write(&self, - ctx: Option<&Context>, - level: u32, - stride: u32, - layer_stride: u32, - mut transfer_box: Box3, - offset: u64) - -> Result<()> { + pub fn transfer_write( + &self, + ctx: Option<&Context>, + level: u32, + stride: u32, + layer_stride: u32, + mut transfer_box: Box3, + offset: u64, + ) -> Result<()> { // Safe because only stack variables of the appropriate type are used. let ret = unsafe { - virgl_renderer_transfer_write_iov(self.id, - ctx.map(Context::id).unwrap_or(0), - level as i32, - stride, - layer_stride, - &mut transfer_box as *mut Box3 as *mut virgl_box, - offset, - null_mut(), - 0) + virgl_renderer_transfer_write_iov( + self.id, + ctx.map(Context::id).unwrap_or(0), + level as i32, + stride, + layer_stride, + &mut transfer_box as *mut Box3 as *mut virgl_box, + offset, + null_mut(), + 0, + ) }; ret_to_res(ret) } /// Performs a transfer from the given resource to its backing in guest memory. - pub fn transfer_read(&self, - ctx: Option<&Context>, - level: u32, - stride: u32, - layer_stride: u32, - mut transfer_box: Box3, - offset: u64) - -> Result<()> { + pub fn transfer_read( + &self, + ctx: Option<&Context>, + level: u32, + stride: u32, + layer_stride: u32, + mut transfer_box: Box3, + offset: u64, + ) -> Result<()> { // Safe because only stack variables of the appropriate type are used. let ret = unsafe { - virgl_renderer_transfer_read_iov(self.id, - ctx.map(Context::id).unwrap_or(0), - level, - stride, - layer_stride, - &mut transfer_box as *mut Box3 as *mut virgl_box, - offset, - null_mut(), - 0) + virgl_renderer_transfer_read_iov( + self.id, + ctx.map(Context::id).unwrap_or(0), + level, + stride, + layer_stride, + &mut transfer_box as *mut Box3 as *mut virgl_box, + offset, + null_mut(), + 0, + ) }; ret_to_res(ret) } /// Performs a transfer from the given resource to the provided `buf` - pub fn transfer_read_buf(&self, - ctx: Option<&Context>, - level: u32, - stride: u32, - layer_stride: u32, - mut transfer_box: Box3, - offset: u64, - buf: &mut [u8]) - -> Result<()> { + pub fn transfer_read_buf( + &self, + ctx: Option<&Context>, + level: u32, + stride: u32, + layer_stride: u32, + mut transfer_box: Box3, + offset: u64, + buf: &mut [u8], + ) -> Result<()> { let mut iov = VirglVec { base: buf.as_mut_ptr() as *mut c_void, len: buf.len(), @@ -897,29 +946,32 @@ impl Resource { // Safe because only stack variables of the appropriate type are used, along with a properly // sized buffer. let ret = unsafe { - virgl_renderer_transfer_read_iov(self.id, - ctx.map(Context::id).unwrap_or(0), - level, - stride, - layer_stride, - &mut transfer_box as *mut Box3 as *mut virgl_box, - offset, - &mut iov as *mut VirglVec as *mut iovec, - 1) + virgl_renderer_transfer_read_iov( + self.id, + ctx.map(Context::id).unwrap_or(0), + level, + stride, + layer_stride, + &mut transfer_box as *mut Box3 as *mut virgl_box, + offset, + &mut iov as *mut VirglVec as *mut iovec, + 1, + ) }; ret_to_res(ret) } /// Reads from this resource to a volatile slice of memory. - pub fn read_to_volatile(&self, - ctx: Option<&Context>, - level: u32, - stride: u32, - layer_stride: u32, - mut transfer_box: Box3, - offset: u64, - buf: VolatileSlice) - -> Result<()> { + pub fn read_to_volatile( + &self, + ctx: Option<&Context>, + level: u32, + stride: u32, + layer_stride: u32, + mut transfer_box: Box3, + offset: u64, + buf: VolatileSlice, + ) -> Result<()> { let mut iov = VirglVec { base: buf.as_ptr() as *mut c_void, len: buf.size() as usize, @@ -927,15 +979,17 @@ impl Resource { // Safe because only stack variables of the appropriate type are used, along with a properly // sized buffer. let ret = unsafe { - virgl_renderer_transfer_read_iov(self.id, - ctx.map(Context::id).unwrap_or(0), - level, - stride, - layer_stride, - &mut transfer_box as *mut Box3 as *mut virgl_box, - offset, - &mut iov as *mut VirglVec as *mut iovec, - 1) + virgl_renderer_transfer_read_iov( + self.id, + ctx.map(Context::id).unwrap_or(0), + level, + stride, + layer_stride, + &mut transfer_box as *mut Box3 as *mut virgl_box, + offset, + &mut iov as *mut VirglVec as *mut iovec, + 1, + ) }; ret_to_res(ret) } @@ -961,9 +1015,7 @@ mod tests { // Make sure a simple buffer clear works by using a command stream. fn simple_clear() { let render = Renderer::init().expect("failed to initialize virglrenderer"); - let mut ctx = render - .create_context(1) - .expect("failed to create context"); + let mut ctx = render.create_context(1).expect("failed to create context"); // Create a 50x50 texture with id=2. let resource = render @@ -983,14 +1035,15 @@ mod tests { // Read the result of the rendering into a buffer. let mut pix_buf = [0; 50 * 50 * 4]; resource - .transfer_read_buf(Some(&ctx), - 0, - 50, - 0, - Box3::new_2d(0, 5, 0, 1), - 0, - &mut pix_buf[..]) - .expect("failed to read back resource data"); + .transfer_read_buf( + Some(&ctx), + 0, + 50, + 0, + Box3::new_2d(0, 5, 0, 1), + 0, + &mut pix_buf[..], + ).expect("failed to read back resource data"); // Check that the pixels are the color we cleared to. The red and blue channels are switched // because the surface was created with the BGR format, but the colors are RGB order in the diff --git a/gpu_renderer/src/pipe_format_fourcc.rs b/gpu_renderer/src/pipe_format_fourcc.rs index 7693973..828f372 100644 --- a/gpu_renderer/src/pipe_format_fourcc.rs +++ b/gpu_renderer/src/pipe_format_fourcc.rs @@ -5,9 +5,9 @@ use generated::p_format; macro_rules! fourcc { - ($a:expr, $b:expr, $c:expr, $d:expr) => ( + ($a:expr, $b:expr, $c:expr, $d:expr) => { Some($a as u32 | ($b as u32) << 8 | ($c as u32) << 16 | ($d as u32) << 24) - ) + }; } /// Gets the fourcc that corresponds to the given pipe format, or `None` if the format is diff --git a/io_jail/src/lib.rs b/io_jail/src/lib.rs index e711b30..773a3e9 100644 --- a/io_jail/src/lib.rs +++ b/io_jail/src/lib.rs @@ -11,8 +11,8 @@ extern crate libc; mod libminijail; use libc::pid_t; -use std::fmt; use std::ffi::CString; +use std::fmt; use std::fs; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; @@ -74,16 +74,14 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { &Error::BindMount { - ref src, - ref dst, - errno, - } => { - write!(f, - "failed to accept bind mount {:?} -> {:?}: {}", - src, - dst, - errno) - } + ref src, + ref dst, + errno, + } => write!( + f, + "failed to accept bind mount {:?} -> {:?}: {}", + src, dst, errno + ), &Error::Mount { errno, ref src, @@ -91,29 +89,24 @@ impl fmt::Display for Error { ref fstype, flags, ref data, - } => { - write!(f, - "failed to accept mount {:?} -> {:?} of type {:?} with flags 0x{:x} \ - and data {:?}: {}", - src, - dest, - fstype, - flags, - data, - errno) - } - &Error::CheckingMultiThreaded(ref e) => { - write!(f, "Failed to count the number of threads from /proc/self/tasks {}", e) - }, + } => write!( + f, + "failed to accept mount {:?} -> {:?} of type {:?} with flags 0x{:x} \ + and data {:?}: {}", + src, dest, fstype, flags, data, errno + ), + &Error::CheckingMultiThreaded(ref e) => write!( + f, + "Failed to count the number of threads from /proc/self/tasks {}", + e + ), &Error::CreatingMinijail => { write!(f, "minjail_new failed due to an allocation failure") } - &Error::ForkingMinijail(ref e) => { - write!(f, "minijail_fork failed with error {}", e) - }, + &Error::ForkingMinijail(ref e) => write!(f, "minijail_fork failed with error {}", e), &Error::ForkingWhileMultiThreaded => { write!(f, "Attempt to call fork() while multithreaded") - }, + } &Error::SeccompPath(ref p) => write!(f, "missing seccomp policy path: {:?}", p), &Error::StrToCString(ref s) => { write!(f, "failed to convert string into CString: {:?}", s) @@ -121,16 +114,16 @@ impl fmt::Display for Error { &Error::PathToCString(ref s) => { write!(f, "failed to convert path into CString: {:?}", s) } - &Error::DupDevNull(errno) => { - write!(f, - "failed to call dup2 to set stdin, stdout, or stderr to /dev/null: {}", - errno) - } - &Error::OpenDevNull(ref e) => { - write!(f, - "fail to open /dev/null for setting FDs 0, 1, or 2: {}", - e) - } + &Error::DupDevNull(errno) => write!( + f, + "failed to call dup2 to set stdin, stdout, or stderr to /dev/null: {}", + errno + ), + &Error::OpenDevNull(ref e) => write!( + f, + "fail to open /dev/null for setting FDs 0, 1, or 2: {}", + e + ), &Error::SetAltSyscallTable { ref name, errno } => { write!(f, "failed to set alt-syscall table {:?}: {}", name, errno) } @@ -149,15 +142,13 @@ impl fmt::Display for Error { } &Error::PreservingFd(ref e) => { write!(f, "fork failed in minijail_preserve_fd with error {}", e) - }, + } } } } - pub type Result<T> = std::result::Result<T, Error>; - /// Configuration to jail a process based on wrapping libminijail. /// /// Intentionally leave out everything related to `minijail_run`. Forking is @@ -223,117 +214,180 @@ impl Minijail { // `struct Minijail` so it is guaranteed to be valid pub fn change_uid(&mut self, uid: libc::uid_t) { - unsafe { libminijail::minijail_change_uid(self.jail, uid); } + unsafe { + libminijail::minijail_change_uid(self.jail, uid); + } } pub fn change_gid(&mut self, gid: libc::gid_t) { - unsafe { libminijail::minijail_change_gid(self.jail, gid); } + unsafe { + libminijail::minijail_change_gid(self.jail, gid); + } } pub fn set_supplementary_gids(&mut self, ids: &[libc::gid_t]) { - unsafe { libminijail::minijail_set_supplementary_gids(self.jail, ids.len(), ids.as_ptr()); } + unsafe { + libminijail::minijail_set_supplementary_gids(self.jail, ids.len(), ids.as_ptr()); + } } pub fn keep_supplementary_gids(&mut self) { - unsafe { libminijail::minijail_keep_supplementary_gids(self.jail); } + unsafe { + libminijail::minijail_keep_supplementary_gids(self.jail); + } } pub fn use_seccomp(&mut self) { - unsafe { libminijail::minijail_use_seccomp(self.jail); } + unsafe { + libminijail::minijail_use_seccomp(self.jail); + } } pub fn no_new_privs(&mut self) { - unsafe { libminijail::minijail_no_new_privs(self.jail); } + unsafe { + libminijail::minijail_no_new_privs(self.jail); + } } pub fn use_seccomp_filter(&mut self) { - unsafe { libminijail::minijail_use_seccomp_filter(self.jail); } + unsafe { + libminijail::minijail_use_seccomp_filter(self.jail); + } } pub fn set_seccomp_filter_tsync(&mut self) { - unsafe { libminijail::minijail_set_seccomp_filter_tsync(self.jail); } + unsafe { + libminijail::minijail_set_seccomp_filter_tsync(self.jail); + } } pub fn parse_seccomp_filters(&mut self, path: &Path) -> Result<()> { if !path.is_file() { return Err(Error::SeccompPath(path.to_owned())); } - let pathstring = path.as_os_str().to_str().ok_or(Error::PathToCString(path.to_owned()))?; - let filename = CString::new(pathstring).map_err(|_| Error::PathToCString(path.to_owned()))?; + let pathstring = path + .as_os_str() + .to_str() + .ok_or(Error::PathToCString(path.to_owned()))?; + let filename = + CString::new(pathstring).map_err(|_| Error::PathToCString(path.to_owned()))?; unsafe { libminijail::minijail_parse_seccomp_filters(self.jail, filename.as_ptr()); } Ok(()) } pub fn log_seccomp_filter_failures(&mut self) { - unsafe { libminijail::minijail_log_seccomp_filter_failures(self.jail); } + unsafe { + libminijail::minijail_log_seccomp_filter_failures(self.jail); + } } pub fn use_caps(&mut self, capmask: u64) { - unsafe { libminijail::minijail_use_caps(self.jail, capmask); } + unsafe { + libminijail::minijail_use_caps(self.jail, capmask); + } } pub fn capbset_drop(&mut self, capmask: u64) { - unsafe { libminijail::minijail_capbset_drop(self.jail, capmask); } + unsafe { + libminijail::minijail_capbset_drop(self.jail, capmask); + } } pub fn set_ambient_caps(&mut self) { - unsafe { libminijail::minijail_set_ambient_caps(self.jail); } + unsafe { + libminijail::minijail_set_ambient_caps(self.jail); + } } pub fn reset_signal_mask(&mut self) { - unsafe { libminijail::minijail_reset_signal_mask(self.jail); } + unsafe { + libminijail::minijail_reset_signal_mask(self.jail); + } } pub fn run_as_init(&mut self) { - unsafe { libminijail::minijail_run_as_init(self.jail); } + unsafe { + libminijail::minijail_run_as_init(self.jail); + } } pub fn namespace_pids(&mut self) { - unsafe { libminijail::minijail_namespace_pids(self.jail); } + unsafe { + libminijail::minijail_namespace_pids(self.jail); + } } pub fn namespace_user(&mut self) { - unsafe { libminijail::minijail_namespace_user(self.jail); } + unsafe { + libminijail::minijail_namespace_user(self.jail); + } } pub fn namespace_user_disable_setgroups(&mut self) { - unsafe { libminijail::minijail_namespace_user_disable_setgroups(self.jail); } + unsafe { + libminijail::minijail_namespace_user_disable_setgroups(self.jail); + } } pub fn namespace_vfs(&mut self) { - unsafe { libminijail::minijail_namespace_vfs(self.jail); } + unsafe { + libminijail::minijail_namespace_vfs(self.jail); + } } pub fn new_session_keyring(&mut self) { - unsafe { libminijail::minijail_new_session_keyring(self.jail); } + unsafe { + libminijail::minijail_new_session_keyring(self.jail); + } } pub fn skip_remount_private(&mut self) { - unsafe { libminijail::minijail_skip_remount_private(self.jail); } + unsafe { + libminijail::minijail_skip_remount_private(self.jail); + } } pub fn namespace_ipc(&mut self) { - unsafe { libminijail::minijail_namespace_ipc(self.jail); } + unsafe { + libminijail::minijail_namespace_ipc(self.jail); + } } pub fn namespace_net(&mut self) { - unsafe { libminijail::minijail_namespace_net(self.jail); } + unsafe { + libminijail::minijail_namespace_net(self.jail); + } } pub fn namespace_cgroups(&mut self) { - unsafe { libminijail::minijail_namespace_cgroups(self.jail); } + unsafe { + libminijail::minijail_namespace_cgroups(self.jail); + } } pub fn remount_proc_readonly(&mut self) { - unsafe { libminijail::minijail_remount_proc_readonly(self.jail); } + unsafe { + libminijail::minijail_remount_proc_readonly(self.jail); + } } pub fn uidmap(&mut self, uid_map: &str) -> Result<()> { - let map_cstring = CString::new(uid_map) - .map_err(|_| Error::StrToCString(uid_map.to_owned()))?; - unsafe { libminijail::minijail_uidmap(self.jail, map_cstring.as_ptr()); } + let map_cstring = + CString::new(uid_map).map_err(|_| Error::StrToCString(uid_map.to_owned()))?; + unsafe { + libminijail::minijail_uidmap(self.jail, map_cstring.as_ptr()); + } Ok(()) } pub fn gidmap(&mut self, gid_map: &str) -> Result<()> { - let map_cstring = CString::new(gid_map) - .map_err(|_| Error::StrToCString(gid_map.to_owned()))?; - unsafe { libminijail::minijail_gidmap(self.jail, map_cstring.as_ptr()); } + let map_cstring = + CString::new(gid_map).map_err(|_| Error::StrToCString(gid_map.to_owned()))?; + unsafe { + libminijail::minijail_gidmap(self.jail, map_cstring.as_ptr()); + } Ok(()) } pub fn inherit_usergroups(&mut self) { - unsafe { libminijail::minijail_inherit_usergroups(self.jail); } + unsafe { + libminijail::minijail_inherit_usergroups(self.jail); + } } pub fn use_alt_syscall(&mut self, table_name: &str) -> Result<()> { - let table_name_string = CString::new(table_name) - .map_err(|_| Error::StrToCString(table_name.to_owned()))?; - let ret = unsafe { - libminijail::minijail_use_alt_syscall(self.jail, table_name_string.as_ptr()) - }; + let table_name_string = + CString::new(table_name).map_err(|_| Error::StrToCString(table_name.to_owned()))?; + let ret = + unsafe { libminijail::minijail_use_alt_syscall(self.jail, table_name_string.as_ptr()) }; if ret < 0 { - return Err(Error::SetAltSyscallTable { errno: ret, name: table_name.to_owned() }); + return Err(Error::SetAltSyscallTable { + errno: ret, + name: table_name.to_owned(), + }); } Ok(()) } pub fn enter_chroot(&mut self, dir: &Path) -> Result<()> { - let pathstring = dir.as_os_str().to_str().ok_or(Error::PathToCString(dir.to_owned()))?; + let pathstring = dir + .as_os_str() + .to_str() + .ok_or(Error::PathToCString(dir.to_owned()))?; let dirname = CString::new(pathstring).map_err(|_| Error::PathToCString(dir.to_owned()))?; let ret = unsafe { libminijail::minijail_enter_chroot(self.jail, dirname.as_ptr()) }; if ret < 0 { @@ -342,7 +396,10 @@ impl Minijail { Ok(()) } pub fn enter_pivot_root(&mut self, dir: &Path) -> Result<()> { - let pathstring = dir.as_os_str().to_str().ok_or(Error::PathToCString(dir.to_owned()))?; + let pathstring = dir + .as_os_str() + .to_str() + .ok_or(Error::PathToCString(dir.to_owned()))?; let dirname = CString::new(pathstring).map_err(|_| Error::PathToCString(dir.to_owned()))?; let ret = unsafe { libminijail::minijail_enter_pivot_root(self.jail, dirname.as_ptr()) }; if ret < 0 { @@ -353,29 +410,37 @@ impl Minijail { pub fn mount(&mut self, src: &Path, dest: &Path, fstype: &str, flags: usize) -> Result<()> { self.mount_with_data(src, dest, fstype, flags, "") } - pub fn mount_with_data(&mut self, src: &Path, dest: &Path, fstype: &str, - flags: usize, data: &str) -> Result<()> { - let src_os = src.as_os_str() + pub fn mount_with_data( + &mut self, + src: &Path, + dest: &Path, + fstype: &str, + flags: usize, + data: &str, + ) -> Result<()> { + let src_os = src + .as_os_str() .to_str() .ok_or(Error::PathToCString(src.to_owned()))?; - let src_path = CString::new(src_os) - .map_err(|_| Error::StrToCString(src_os.to_owned()))?; - let dest_os = dest.as_os_str() + let src_path = CString::new(src_os).map_err(|_| Error::StrToCString(src_os.to_owned()))?; + let dest_os = dest + .as_os_str() .to_str() .ok_or(Error::PathToCString(dest.to_owned()))?; - let dest_path = CString::new(dest_os) - .map_err(|_| Error::StrToCString(dest_os.to_owned()))?; - let fstype_string = CString::new(fstype) - .map_err(|_| Error::StrToCString(fstype.to_owned()))?; - let data_string = CString::new(data) - .map_err(|_| Error::StrToCString(data.to_owned()))?; + let dest_path = + CString::new(dest_os).map_err(|_| Error::StrToCString(dest_os.to_owned()))?; + let fstype_string = + CString::new(fstype).map_err(|_| Error::StrToCString(fstype.to_owned()))?; + let data_string = CString::new(data).map_err(|_| Error::StrToCString(data.to_owned()))?; let ret = unsafe { - libminijail::minijail_mount_with_data(self.jail, - src_path.as_ptr(), - dest_path.as_ptr(), - fstype_string.as_ptr(), - flags as _, - data_string.as_ptr()) + libminijail::minijail_mount_with_data( + self.jail, + src_path.as_ptr(), + dest_path.as_ptr(), + fstype_string.as_ptr(), + flags as _, + data_string.as_ptr(), + ) }; if ret < 0 { return Err(Error::Mount { @@ -383,41 +448,48 @@ impl Minijail { src: src.to_owned(), dest: dest.to_owned(), fstype: fstype.to_owned(), - flags: flags, + flags, data: data.to_owned(), }); } Ok(()) } pub fn mount_tmp(&mut self) { - unsafe { libminijail::minijail_mount_tmp(self.jail); } + unsafe { + libminijail::minijail_mount_tmp(self.jail); + } } pub fn mount_tmp_size(&mut self, size: usize) { - unsafe { libminijail::minijail_mount_tmp_size(self.jail, size); } + unsafe { + libminijail::minijail_mount_tmp_size(self.jail, size); + } } pub fn mount_bind(&mut self, src: &Path, dest: &Path, writable: bool) -> Result<()> { - let src_os = src.as_os_str() + let src_os = src + .as_os_str() .to_str() .ok_or(Error::PathToCString(src.to_owned()))?; - let src_path = CString::new(src_os) - .map_err(|_| Error::StrToCString(src_os.to_owned()))?; - let dest_os = dest.as_os_str() + let src_path = CString::new(src_os).map_err(|_| Error::StrToCString(src_os.to_owned()))?; + let dest_os = dest + .as_os_str() .to_str() .ok_or(Error::PathToCString(dest.to_owned()))?; - let dest_path = CString::new(dest_os) - .map_err(|_| Error::StrToCString(dest_os.to_owned()))?; + let dest_path = + CString::new(dest_os).map_err(|_| Error::StrToCString(dest_os.to_owned()))?; let ret = unsafe { - libminijail::minijail_bind(self.jail, - src_path.as_ptr(), - dest_path.as_ptr(), - writable as _) + libminijail::minijail_bind( + self.jail, + src_path.as_ptr(), + dest_path.as_ptr(), + writable as _, + ) }; if ret < 0 { return Err(Error::BindMount { - errno: ret, - src: src.to_owned(), - dst: dest.to_owned(), - }); + errno: ret, + src: src.to_owned(), + dst: dest.to_owned(), + }); } Ok(()) } @@ -427,18 +499,15 @@ impl Minijail { /// inheritable_fds list. This function may abort in the child on error because a partially /// entered jail isn't recoverable. pub fn run(&self, cmd: &Path, inheritable_fds: &[RawFd], args: &[&str]) -> Result<pid_t> { - let cmd_os = cmd.to_str() - .ok_or(Error::PathToCString(cmd.to_owned()))?; - let cmd_cstr = CString::new(cmd_os) - .map_err(|_| Error::StrToCString(cmd_os.to_owned()))?; + let cmd_os = cmd.to_str().ok_or(Error::PathToCString(cmd.to_owned()))?; + let cmd_cstr = CString::new(cmd_os).map_err(|_| Error::StrToCString(cmd_os.to_owned()))?; // Converts each incoming `args` string to a `CString`, and then puts each `CString` pointer // into a null terminated array, suitable for use as an argv parameter to `execve`. let mut args_cstr = Vec::with_capacity(args.len()); let mut args_array = Vec::with_capacity(args.len()); for &arg in args { - let arg_cstr = CString::new(arg) - .map_err(|_| Error::StrToCString(arg.to_owned()))?; + let arg_cstr = CString::new(arg).map_err(|_| Error::StrToCString(arg.to_owned()))?; args_array.push(arg_cstr.as_ptr()); args_cstr.push(arg_cstr); } @@ -475,13 +544,15 @@ impl Minijail { let mut pid = 0; let ret = unsafe { - libminijail::minijail_run_pid_pipes(self.jail, - cmd_cstr.as_ptr(), - args_array.as_ptr(), - &mut pid, - null_mut(), - null_mut(), - null_mut()) + libminijail::minijail_run_pid_pipes( + self.jail, + cmd_cstr.as_ptr(), + args_array.as_ptr(), + &mut pid, + null_mut(), + null_mut(), + null_mut(), + ) }; if ret < 0 { return Err(Error::ForkingMinijail(ret)); @@ -523,9 +594,8 @@ impl Minijail { // These will only be closed when this process exits. for io_fd in &[libc::STDIN_FILENO, libc::STDOUT_FILENO, libc::STDERR_FILENO] { if inheritable_fds.is_none() || !inheritable_fds.unwrap().contains(io_fd) { - let ret = libminijail::minijail_preserve_fd(self.jail, - dev_null.as_raw_fd(), - *io_fd); + let ret = + libminijail::minijail_preserve_fd(self.jail, dev_null.as_raw_fd(), *io_fd); if ret < 0 { return Err(Error::PreservingFd(ret)); } @@ -589,7 +659,8 @@ mod tests { fn seccomp_no_new_privs() { let mut j = Minijail::new().unwrap(); j.no_new_privs(); - j.parse_seccomp_filters(Path::new("src/test_filter.policy")).unwrap(); + j.parse_seccomp_filters(Path::new("src/test_filter.policy")) + .unwrap(); j.use_seccomp_filter(); unsafe { j.fork(None).unwrap(); @@ -599,7 +670,8 @@ mod tests { #[test] // Test that open FDs get closed and that FDs in the inherit list are left open. fn close_fds() { - unsafe { // Using libc to open/close FDs for testing. + unsafe { + // Using libc to open/close FDs for testing. const FILE_PATH: &[u8] = b"/dev/null\0"; let j = Minijail::new().unwrap(); let first = libc::open(FILE_PATH.as_ptr() as *const i8, libc::O_RDONLY); diff --git a/io_jail/src/libminijail.rs b/io_jail/src/libminijail.rs index a8d250d..8762721 100644 --- a/io_jail/src/libminijail.rs +++ b/io_jail/src/libminijail.rs @@ -17,16 +17,10 @@ extern "C" { pub fn minijail_new() -> *mut minijail; pub fn minijail_change_uid(j: *mut minijail, uid: uid_t); pub fn minijail_change_gid(j: *mut minijail, gid: gid_t); - pub fn minijail_set_supplementary_gids(j: *mut minijail, - size: usize, - list: *const gid_t); + pub fn minijail_set_supplementary_gids(j: *mut minijail, size: usize, list: *const gid_t); pub fn minijail_keep_supplementary_gids(j: *mut minijail); - pub fn minijail_change_user(j: *mut minijail, - user: *const c_char) - -> c_int; - pub fn minijail_change_group(j: *mut minijail, - group: *const c_char) - -> c_int; + pub fn minijail_change_user(j: *mut minijail, user: *const c_char) -> c_int; + pub fn minijail_change_group(j: *mut minijail, group: *const c_char) -> c_int; pub fn minijail_use_seccomp(j: *mut minijail); pub fn minijail_no_new_privs(j: *mut minijail); pub fn minijail_use_seccomp_filter(j: *mut minijail); @@ -50,93 +44,83 @@ extern "C" { pub fn minijail_namespace_pids(j: *mut minijail); pub fn minijail_namespace_user(j: *mut minijail); pub fn minijail_namespace_user_disable_setgroups(j: *mut minijail); - pub fn minijail_uidmap(j: *mut minijail, - uidmap: *const c_char) - -> c_int; - pub fn minijail_gidmap(j: *mut minijail, - gidmap: *const c_char) - -> c_int; + pub fn minijail_uidmap(j: *mut minijail, uidmap: *const c_char) -> c_int; + pub fn minijail_gidmap(j: *mut minijail, gidmap: *const c_char) -> c_int; pub fn minijail_remount_proc_readonly(j: *mut minijail); pub fn minijail_run_as_init(j: *mut minijail); - pub fn minijail_write_pid_file(j: *mut minijail, - path: *const c_char) - -> c_int; + pub fn minijail_write_pid_file(j: *mut minijail, path: *const c_char) -> c_int; pub fn minijail_inherit_usergroups(j: *mut minijail); - pub fn minijail_use_alt_syscall(j: *mut minijail, - table: *const c_char) - -> c_int; - pub fn minijail_add_to_cgroup(j: *mut minijail, - path: *const c_char) - -> c_int; - pub fn minijail_enter_chroot(j: *mut minijail, - dir: *const c_char) - -> c_int; - pub fn minijail_enter_pivot_root(j: *mut minijail, - dir: *const c_char) - -> c_int; + pub fn minijail_use_alt_syscall(j: *mut minijail, table: *const c_char) -> c_int; + pub fn minijail_add_to_cgroup(j: *mut minijail, path: *const c_char) -> c_int; + pub fn minijail_enter_chroot(j: *mut minijail, dir: *const c_char) -> c_int; + pub fn minijail_enter_pivot_root(j: *mut minijail, dir: *const c_char) -> c_int; pub fn minijail_fork(j: *mut minijail) -> pid_t; - pub fn minijail_get_original_path(j: *mut minijail, - chroot_path: *const c_char) - -> *mut c_char; + pub fn minijail_get_original_path(j: *mut minijail, chroot_path: *const c_char) -> *mut c_char; pub fn minijail_mount_tmp(j: *mut minijail); pub fn minijail_mount_tmp_size(j: *mut minijail, size: usize); - pub fn minijail_mount_with_data(j: *mut minijail, - src: *const c_char, - dest: *const c_char, - type_: *const c_char, - flags: c_ulong, - data: *const c_char) - -> c_int; - pub fn minijail_mount(j: *mut minijail, - src: *const c_char, - dest: *const c_char, - type_: *const c_char, - flags: c_ulong) - -> c_int; - pub fn minijail_bind(j: *mut minijail, - src: *const c_char, - dest: *const c_char, - writeable: c_int) - -> c_int; - pub fn minijail_preserve_fd(j: *mut minijail, - parent_fd: c_int, - child_fd: c_int) - -> c_int; + pub fn minijail_mount_with_data( + j: *mut minijail, + src: *const c_char, + dest: *const c_char, + type_: *const c_char, + flags: c_ulong, + data: *const c_char, + ) -> c_int; + pub fn minijail_mount( + j: *mut minijail, + src: *const c_char, + dest: *const c_char, + type_: *const c_char, + flags: c_ulong, + ) -> c_int; + pub fn minijail_bind( + j: *mut minijail, + src: *const c_char, + dest: *const c_char, + writeable: c_int, + ) -> c_int; + pub fn minijail_preserve_fd(j: *mut minijail, parent_fd: c_int, child_fd: c_int) -> c_int; pub fn minijail_enter(j: *const minijail); - pub fn minijail_run(j: *mut minijail, - filename: *const c_char, - argv: *const *const c_char) - -> c_int; - pub fn minijail_run_no_preload(j: *mut minijail, - filename: *const c_char, - argv: *const *const c_char) - -> c_int; - pub fn minijail_run_pid(j: *mut minijail, - filename: *const c_char, - argv: *const *const c_char, - pchild_pid: *mut pid_t) - -> c_int; - pub fn minijail_run_pipe(j: *mut minijail, - filename: *const c_char, - argv: *const *const c_char, - pstdin_fd: *mut c_int) - -> c_int; - pub fn minijail_run_pid_pipes(j: *mut minijail, - filename: *const c_char, - argv: *const *const c_char, - pchild_pid: *mut pid_t, - pstdin_fd: *mut c_int, - pstdout_fd: *mut c_int, - pstderr_fd: *mut c_int) - -> c_int; - pub fn minijail_run_pid_pipes_no_preload(j: *mut minijail, - filename: *const c_char, - argv: *const *const c_char, - pchild_pid: *mut pid_t, - pstdin_fd: *mut c_int, - pstdout_fd: *mut c_int, - pstderr_fd: *mut c_int) - -> c_int; + pub fn minijail_run( + j: *mut minijail, + filename: *const c_char, + argv: *const *const c_char, + ) -> c_int; + pub fn minijail_run_no_preload( + j: *mut minijail, + filename: *const c_char, + argv: *const *const c_char, + ) -> c_int; + pub fn minijail_run_pid( + j: *mut minijail, + filename: *const c_char, + argv: *const *const c_char, + pchild_pid: *mut pid_t, + ) -> c_int; + pub fn minijail_run_pipe( + j: *mut minijail, + filename: *const c_char, + argv: *const *const c_char, + pstdin_fd: *mut c_int, + ) -> c_int; + pub fn minijail_run_pid_pipes( + j: *mut minijail, + filename: *const c_char, + argv: *const *const c_char, + pchild_pid: *mut pid_t, + pstdin_fd: *mut c_int, + pstdout_fd: *mut c_int, + pstderr_fd: *mut c_int, + ) -> c_int; + pub fn minijail_run_pid_pipes_no_preload( + j: *mut minijail, + filename: *const c_char, + argv: *const *const c_char, + pchild_pid: *mut pid_t, + pstdin_fd: *mut c_int, + pstdout_fd: *mut c_int, + pstderr_fd: *mut c_int, + ) -> c_int; pub fn minijail_kill(j: *mut minijail) -> c_int; pub fn minijail_wait(j: *mut minijail) -> c_int; pub fn minijail_destroy(j: *mut minijail); diff --git a/kernel_cmdline/src/kernel_cmdline.rs b/kernel_cmdline/src/kernel_cmdline.rs index db6dffa..1e1870e 100644 --- a/kernel_cmdline/src/kernel_cmdline.rs +++ b/kernel_cmdline/src/kernel_cmdline.rs @@ -4,8 +4,8 @@ //! Helper for creating valid kernel command line strings. -use std::result; use std::fmt; +use std::result; /// The error type for command line building operations. #[derive(PartialEq, Debug)] @@ -22,14 +22,16 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, - "{}", - match *self { - Error::InvalidAscii => "string contains non-printable ASCII character", - Error::HasSpace => "string contains a space", - Error::HasEquals => "string contains an equals sign", - Error::TooLarge => "inserting string would make command line too long", - }) + write!( + f, + "{}", + match *self { + Error::InvalidAscii => "string contains non-printable ASCII character", + Error::HasSpace => "string contains a space", + Error::HasEquals => "string contains an equals sign", + Error::TooLarge => "inserting string would make command line too long", + } + ) } } @@ -77,7 +79,7 @@ impl Cmdline { assert_ne!(capacity, 0); Cmdline { line: String::new(), - capacity: capacity, + capacity, } } diff --git a/kernel_loader/src/elf.rs b/kernel_loader/src/elf.rs index e689b87..05d4777 100644 --- a/kernel_loader/src/elf.rs +++ b/kernel_loader/src/elf.rs @@ -265,18 +265,26 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>(), - 128usize, - concat!("Size of: ", stringify!(__kernel_fd_set))); - assert_eq!(::std::mem::align_of::<__kernel_fd_set>(), - 8usize, - concat!("Alignment of ", stringify!(__kernel_fd_set))); - assert_eq!(unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(__kernel_fd_set), - "::", - stringify!(fds_bits))); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { fn clone(&self) -> Self { @@ -312,18 +320,26 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>(), - 8usize, - concat!("Size of: ", stringify!(__kernel_fsid_t))); - assert_eq!(::std::mem::align_of::<__kernel_fsid_t>(), - 4usize, - concat!("Alignment of ", stringify!(__kernel_fsid_t))); - assert_eq!(unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(__kernel_fsid_t), - "::", - stringify!(val))); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { fn clone(&self) -> Self { @@ -375,24 +391,36 @@ pub struct dynamic__bindgen_ty_1 { } #[test] fn bindgen_test_layout_dynamic__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<dynamic__bindgen_ty_1>(), - 4usize, - concat!("Size of: ", stringify!(dynamic__bindgen_ty_1))); - assert_eq!(::std::mem::align_of::<dynamic__bindgen_ty_1>(), - 4usize, - concat!("Alignment of ", stringify!(dynamic__bindgen_ty_1))); - assert_eq!(unsafe { &(*(0 as *const dynamic__bindgen_ty_1)).d_val as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(dynamic__bindgen_ty_1), - "::", - stringify!(d_val))); - assert_eq!(unsafe { &(*(0 as *const dynamic__bindgen_ty_1)).d_ptr as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(dynamic__bindgen_ty_1), - "::", - stringify!(d_ptr))); + assert_eq!( + ::std::mem::size_of::<dynamic__bindgen_ty_1>(), + 4usize, + concat!("Size of: ", stringify!(dynamic__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<dynamic__bindgen_ty_1>(), + 4usize, + concat!("Alignment of ", stringify!(dynamic__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const dynamic__bindgen_ty_1)).d_val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(dynamic__bindgen_ty_1), + "::", + stringify!(d_val) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const dynamic__bindgen_ty_1)).d_ptr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(dynamic__bindgen_ty_1), + "::", + stringify!(d_ptr) + ) + ); } impl Clone for dynamic__bindgen_ty_1 { fn clone(&self) -> Self { @@ -401,24 +429,36 @@ impl Clone for dynamic__bindgen_ty_1 { } #[test] fn bindgen_test_layout_dynamic() { - assert_eq!(::std::mem::size_of::<dynamic>(), - 8usize, - concat!("Size of: ", stringify!(dynamic))); - assert_eq!(::std::mem::align_of::<dynamic>(), - 4usize, - concat!("Alignment of ", stringify!(dynamic))); - assert_eq!(unsafe { &(*(0 as *const dynamic)).d_tag as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(dynamic), - "::", - stringify!(d_tag))); - assert_eq!(unsafe { &(*(0 as *const dynamic)).d_un as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(dynamic), - "::", - stringify!(d_un))); + assert_eq!( + ::std::mem::size_of::<dynamic>(), + 8usize, + concat!("Size of: ", stringify!(dynamic)) + ); + assert_eq!( + ::std::mem::align_of::<dynamic>(), + 4usize, + concat!("Alignment of ", stringify!(dynamic)) + ); + assert_eq!( + unsafe { &(*(0 as *const dynamic)).d_tag as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(dynamic), + "::", + stringify!(d_tag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const dynamic)).d_un as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(dynamic), + "::", + stringify!(d_un) + ) + ); } impl Clone for dynamic { fn clone(&self) -> Self { @@ -441,24 +481,36 @@ pub struct Elf64_Dyn__bindgen_ty_1 { } #[test] fn bindgen_test_layout_Elf64_Dyn__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<Elf64_Dyn__bindgen_ty_1>(), - 8usize, - concat!("Size of: ", stringify!(Elf64_Dyn__bindgen_ty_1))); - assert_eq!(::std::mem::align_of::<Elf64_Dyn__bindgen_ty_1>(), - 8usize, - concat!("Alignment of ", stringify!(Elf64_Dyn__bindgen_ty_1))); - assert_eq!(unsafe { &(*(0 as *const Elf64_Dyn__bindgen_ty_1)).d_val as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(Elf64_Dyn__bindgen_ty_1), - "::", - stringify!(d_val))); - assert_eq!(unsafe { &(*(0 as *const Elf64_Dyn__bindgen_ty_1)).d_ptr as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(Elf64_Dyn__bindgen_ty_1), - "::", - stringify!(d_ptr))); + assert_eq!( + ::std::mem::size_of::<Elf64_Dyn__bindgen_ty_1>(), + 8usize, + concat!("Size of: ", stringify!(Elf64_Dyn__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<Elf64_Dyn__bindgen_ty_1>(), + 8usize, + concat!("Alignment of ", stringify!(Elf64_Dyn__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const Elf64_Dyn__bindgen_ty_1)).d_val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(Elf64_Dyn__bindgen_ty_1), + "::", + stringify!(d_val) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const Elf64_Dyn__bindgen_ty_1)).d_ptr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(Elf64_Dyn__bindgen_ty_1), + "::", + stringify!(d_ptr) + ) + ); } impl Clone for Elf64_Dyn__bindgen_ty_1 { fn clone(&self) -> Self { @@ -467,24 +519,36 @@ impl Clone for Elf64_Dyn__bindgen_ty_1 { } #[test] fn bindgen_test_layout_Elf64_Dyn() { - assert_eq!(::std::mem::size_of::<Elf64_Dyn>(), - 16usize, - concat!("Size of: ", stringify!(Elf64_Dyn))); - assert_eq!(::std::mem::align_of::<Elf64_Dyn>(), - 8usize, - concat!("Alignment of ", stringify!(Elf64_Dyn))); - assert_eq!(unsafe { &(*(0 as *const Elf64_Dyn)).d_tag as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(Elf64_Dyn), - "::", - stringify!(d_tag))); - assert_eq!(unsafe { &(*(0 as *const Elf64_Dyn)).d_un as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(Elf64_Dyn), - "::", - stringify!(d_un))); + assert_eq!( + ::std::mem::size_of::<Elf64_Dyn>(), + 16usize, + concat!("Size of: ", stringify!(Elf64_Dyn)) + ); + assert_eq!( + ::std::mem::align_of::<Elf64_Dyn>(), + 8usize, + concat!("Alignment of ", stringify!(Elf64_Dyn)) + ); + assert_eq!( + unsafe { &(*(0 as *const Elf64_Dyn)).d_tag as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(Elf64_Dyn), + "::", + stringify!(d_tag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const Elf64_Dyn)).d_un as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(Elf64_Dyn), + "::", + stringify!(d_un) + ) + ); } impl Clone for Elf64_Dyn { fn clone(&self) -> Self { @@ -499,24 +563,36 @@ pub struct elf32_rel { } #[test] fn bindgen_test_layout_elf32_rel() { - assert_eq!(::std::mem::size_of::<elf32_rel>(), - 8usize, - concat!("Size of: ", stringify!(elf32_rel))); - assert_eq!(::std::mem::align_of::<elf32_rel>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_rel))); - assert_eq!(unsafe { &(*(0 as *const elf32_rel)).r_offset as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_rel), - "::", - stringify!(r_offset))); - assert_eq!(unsafe { &(*(0 as *const elf32_rel)).r_info as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf32_rel), - "::", - stringify!(r_info))); + assert_eq!( + ::std::mem::size_of::<elf32_rel>(), + 8usize, + concat!("Size of: ", stringify!(elf32_rel)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_rel>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_rel)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_rel)).r_offset as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_rel), + "::", + stringify!(r_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_rel)).r_info as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf32_rel), + "::", + stringify!(r_info) + ) + ); } impl Clone for elf32_rel { fn clone(&self) -> Self { @@ -532,24 +608,36 @@ pub struct elf64_rel { } #[test] fn bindgen_test_layout_elf64_rel() { - assert_eq!(::std::mem::size_of::<elf64_rel>(), - 16usize, - concat!("Size of: ", stringify!(elf64_rel))); - assert_eq!(::std::mem::align_of::<elf64_rel>(), - 8usize, - concat!("Alignment of ", stringify!(elf64_rel))); - assert_eq!(unsafe { &(*(0 as *const elf64_rel)).r_offset as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_rel), - "::", - stringify!(r_offset))); - assert_eq!(unsafe { &(*(0 as *const elf64_rel)).r_info as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf64_rel), - "::", - stringify!(r_info))); + assert_eq!( + ::std::mem::size_of::<elf64_rel>(), + 16usize, + concat!("Size of: ", stringify!(elf64_rel)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_rel>(), + 8usize, + concat!("Alignment of ", stringify!(elf64_rel)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_rel)).r_offset as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_rel), + "::", + stringify!(r_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_rel)).r_info as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf64_rel), + "::", + stringify!(r_info) + ) + ); } impl Clone for elf64_rel { fn clone(&self) -> Self { @@ -566,30 +654,46 @@ pub struct elf32_rela { } #[test] fn bindgen_test_layout_elf32_rela() { - assert_eq!(::std::mem::size_of::<elf32_rela>(), - 12usize, - concat!("Size of: ", stringify!(elf32_rela))); - assert_eq!(::std::mem::align_of::<elf32_rela>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_rela))); - assert_eq!(unsafe { &(*(0 as *const elf32_rela)).r_offset as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_rela), - "::", - stringify!(r_offset))); - assert_eq!(unsafe { &(*(0 as *const elf32_rela)).r_info as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf32_rela), - "::", - stringify!(r_info))); - assert_eq!(unsafe { &(*(0 as *const elf32_rela)).r_addend as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf32_rela), - "::", - stringify!(r_addend))); + assert_eq!( + ::std::mem::size_of::<elf32_rela>(), + 12usize, + concat!("Size of: ", stringify!(elf32_rela)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_rela>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_rela)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_rela)).r_offset as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_rela), + "::", + stringify!(r_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_rela)).r_info as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf32_rela), + "::", + stringify!(r_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_rela)).r_addend as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf32_rela), + "::", + stringify!(r_addend) + ) + ); } impl Clone for elf32_rela { fn clone(&self) -> Self { @@ -606,30 +710,46 @@ pub struct elf64_rela { } #[test] fn bindgen_test_layout_elf64_rela() { - assert_eq!(::std::mem::size_of::<elf64_rela>(), - 24usize, - concat!("Size of: ", stringify!(elf64_rela))); - assert_eq!(::std::mem::align_of::<elf64_rela>(), - 8usize, - concat!("Alignment of ", stringify!(elf64_rela))); - assert_eq!(unsafe { &(*(0 as *const elf64_rela)).r_offset as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_rela), - "::", - stringify!(r_offset))); - assert_eq!(unsafe { &(*(0 as *const elf64_rela)).r_info as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf64_rela), - "::", - stringify!(r_info))); - assert_eq!(unsafe { &(*(0 as *const elf64_rela)).r_addend as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf64_rela), - "::", - stringify!(r_addend))); + assert_eq!( + ::std::mem::size_of::<elf64_rela>(), + 24usize, + concat!("Size of: ", stringify!(elf64_rela)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_rela>(), + 8usize, + concat!("Alignment of ", stringify!(elf64_rela)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_rela)).r_offset as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_rela), + "::", + stringify!(r_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_rela)).r_info as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf64_rela), + "::", + stringify!(r_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_rela)).r_addend as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf64_rela), + "::", + stringify!(r_addend) + ) + ); } impl Clone for elf64_rela { fn clone(&self) -> Self { @@ -649,48 +769,76 @@ pub struct elf32_sym { } #[test] fn bindgen_test_layout_elf32_sym() { - assert_eq!(::std::mem::size_of::<elf32_sym>(), - 16usize, - concat!("Size of: ", stringify!(elf32_sym))); - assert_eq!(::std::mem::align_of::<elf32_sym>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_sym))); - assert_eq!(unsafe { &(*(0 as *const elf32_sym)).st_name as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_sym), - "::", - stringify!(st_name))); - assert_eq!(unsafe { &(*(0 as *const elf32_sym)).st_value as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf32_sym), - "::", - stringify!(st_value))); - assert_eq!(unsafe { &(*(0 as *const elf32_sym)).st_size as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf32_sym), - "::", - stringify!(st_size))); - assert_eq!(unsafe { &(*(0 as *const elf32_sym)).st_info as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(elf32_sym), - "::", - stringify!(st_info))); - assert_eq!(unsafe { &(*(0 as *const elf32_sym)).st_other as *const _ as usize }, - 13usize, - concat!("Alignment of field: ", - stringify!(elf32_sym), - "::", - stringify!(st_other))); - assert_eq!(unsafe { &(*(0 as *const elf32_sym)).st_shndx as *const _ as usize }, - 14usize, - concat!("Alignment of field: ", - stringify!(elf32_sym), - "::", - stringify!(st_shndx))); + assert_eq!( + ::std::mem::size_of::<elf32_sym>(), + 16usize, + concat!("Size of: ", stringify!(elf32_sym)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_sym>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_sym)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_sym)).st_name as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_sym), + "::", + stringify!(st_name) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_sym)).st_value as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf32_sym), + "::", + stringify!(st_value) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_sym)).st_size as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf32_sym), + "::", + stringify!(st_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_sym)).st_info as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(elf32_sym), + "::", + stringify!(st_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_sym)).st_other as *const _ as usize }, + 13usize, + concat!( + "Alignment of field: ", + stringify!(elf32_sym), + "::", + stringify!(st_other) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_sym)).st_shndx as *const _ as usize }, + 14usize, + concat!( + "Alignment of field: ", + stringify!(elf32_sym), + "::", + stringify!(st_shndx) + ) + ); } impl Clone for elf32_sym { fn clone(&self) -> Self { @@ -710,48 +858,76 @@ pub struct elf64_sym { } #[test] fn bindgen_test_layout_elf64_sym() { - assert_eq!(::std::mem::size_of::<elf64_sym>(), - 24usize, - concat!("Size of: ", stringify!(elf64_sym))); - assert_eq!(::std::mem::align_of::<elf64_sym>(), - 8usize, - concat!("Alignment of ", stringify!(elf64_sym))); - assert_eq!(unsafe { &(*(0 as *const elf64_sym)).st_name as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_sym), - "::", - stringify!(st_name))); - assert_eq!(unsafe { &(*(0 as *const elf64_sym)).st_info as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf64_sym), - "::", - stringify!(st_info))); - assert_eq!(unsafe { &(*(0 as *const elf64_sym)).st_other as *const _ as usize }, - 5usize, - concat!("Alignment of field: ", - stringify!(elf64_sym), - "::", - stringify!(st_other))); - assert_eq!(unsafe { &(*(0 as *const elf64_sym)).st_shndx as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(elf64_sym), - "::", - stringify!(st_shndx))); - assert_eq!(unsafe { &(*(0 as *const elf64_sym)).st_value as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf64_sym), - "::", - stringify!(st_value))); - assert_eq!(unsafe { &(*(0 as *const elf64_sym)).st_size as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf64_sym), - "::", - stringify!(st_size))); + assert_eq!( + ::std::mem::size_of::<elf64_sym>(), + 24usize, + concat!("Size of: ", stringify!(elf64_sym)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_sym>(), + 8usize, + concat!("Alignment of ", stringify!(elf64_sym)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_sym)).st_name as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_sym), + "::", + stringify!(st_name) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_sym)).st_info as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf64_sym), + "::", + stringify!(st_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_sym)).st_other as *const _ as usize }, + 5usize, + concat!( + "Alignment of field: ", + stringify!(elf64_sym), + "::", + stringify!(st_other) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_sym)).st_shndx as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(elf64_sym), + "::", + stringify!(st_shndx) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_sym)).st_value as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf64_sym), + "::", + stringify!(st_value) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_sym)).st_size as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf64_sym), + "::", + stringify!(st_size) + ) + ); } impl Clone for elf64_sym { fn clone(&self) -> Self { @@ -779,96 +955,156 @@ pub struct elf32_hdr { } #[test] fn bindgen_test_layout_elf32_hdr() { - assert_eq!(::std::mem::size_of::<elf32_hdr>(), - 52usize, - concat!("Size of: ", stringify!(elf32_hdr))); - assert_eq!(::std::mem::align_of::<elf32_hdr>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_hdr))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_ident as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_ident))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_type as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_type))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_machine as *const _ as usize }, - 18usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_machine))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_version as *const _ as usize }, - 20usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_version))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_entry as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_entry))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_phoff as *const _ as usize }, - 28usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_phoff))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_shoff as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_shoff))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_flags as *const _ as usize }, - 36usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_flags))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_ehsize as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_ehsize))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_phentsize as *const _ as usize }, - 42usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_phentsize))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_phnum as *const _ as usize }, - 44usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_phnum))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_shentsize as *const _ as usize }, - 46usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_shentsize))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_shnum as *const _ as usize }, - 48usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_shnum))); - assert_eq!(unsafe { &(*(0 as *const elf32_hdr)).e_shstrndx as *const _ as usize }, - 50usize, - concat!("Alignment of field: ", - stringify!(elf32_hdr), - "::", - stringify!(e_shstrndx))); + assert_eq!( + ::std::mem::size_of::<elf32_hdr>(), + 52usize, + concat!("Size of: ", stringify!(elf32_hdr)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_hdr>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_hdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_ident as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_ident) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_type as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_machine as *const _ as usize }, + 18usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_machine) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_version as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_entry as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_entry) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_phoff as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_phoff) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_shoff as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_shoff) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_flags as *const _ as usize }, + 36usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_ehsize as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_ehsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_phentsize as *const _ as usize }, + 42usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_phentsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_phnum as *const _ as usize }, + 44usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_phnum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_shentsize as *const _ as usize }, + 46usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_shentsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_shnum as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_shnum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_hdr)).e_shstrndx as *const _ as usize }, + 50usize, + concat!( + "Alignment of field: ", + stringify!(elf32_hdr), + "::", + stringify!(e_shstrndx) + ) + ); } impl Clone for elf32_hdr { fn clone(&self) -> Self { @@ -896,96 +1132,156 @@ pub struct elf64_hdr { } #[test] fn bindgen_test_layout_elf64_hdr() { - assert_eq!(::std::mem::size_of::<elf64_hdr>(), - 64usize, - concat!("Size of: ", stringify!(elf64_hdr))); - assert_eq!(::std::mem::align_of::<elf64_hdr>(), - 8usize, - concat!("Alignment of ", stringify!(elf64_hdr))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_ident as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_ident))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_type as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_type))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_machine as *const _ as usize }, - 18usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_machine))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_version as *const _ as usize }, - 20usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_version))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_entry as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_entry))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_phoff as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_phoff))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_shoff as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_shoff))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_flags as *const _ as usize }, - 48usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_flags))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_ehsize as *const _ as usize }, - 52usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_ehsize))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_phentsize as *const _ as usize }, - 54usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_phentsize))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_phnum as *const _ as usize }, - 56usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_phnum))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_shentsize as *const _ as usize }, - 58usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_shentsize))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_shnum as *const _ as usize }, - 60usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_shnum))); - assert_eq!(unsafe { &(*(0 as *const elf64_hdr)).e_shstrndx as *const _ as usize }, - 62usize, - concat!("Alignment of field: ", - stringify!(elf64_hdr), - "::", - stringify!(e_shstrndx))); + assert_eq!( + ::std::mem::size_of::<elf64_hdr>(), + 64usize, + concat!("Size of: ", stringify!(elf64_hdr)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_hdr>(), + 8usize, + concat!("Alignment of ", stringify!(elf64_hdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_ident as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_ident) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_type as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_machine as *const _ as usize }, + 18usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_machine) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_version as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_entry as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_entry) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_phoff as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_phoff) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_shoff as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_shoff) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_flags as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_ehsize as *const _ as usize }, + 52usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_ehsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_phentsize as *const _ as usize }, + 54usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_phentsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_phnum as *const _ as usize }, + 56usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_phnum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_shentsize as *const _ as usize }, + 58usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_shentsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_shnum as *const _ as usize }, + 60usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_shnum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_hdr)).e_shstrndx as *const _ as usize }, + 62usize, + concat!( + "Alignment of field: ", + stringify!(elf64_hdr), + "::", + stringify!(e_shstrndx) + ) + ); } impl Clone for elf64_hdr { fn clone(&self) -> Self { @@ -1007,60 +1303,96 @@ pub struct elf32_phdr { } #[test] fn bindgen_test_layout_elf32_phdr() { - assert_eq!(::std::mem::size_of::<elf32_phdr>(), - 32usize, - concat!("Size of: ", stringify!(elf32_phdr))); - assert_eq!(::std::mem::align_of::<elf32_phdr>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_phdr))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_type as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_type))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_offset as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_offset))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_vaddr as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_vaddr))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_paddr as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_paddr))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_filesz as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_filesz))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_memsz as *const _ as usize }, - 20usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_memsz))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_flags as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_flags))); - assert_eq!(unsafe { &(*(0 as *const elf32_phdr)).p_align as *const _ as usize }, - 28usize, - concat!("Alignment of field: ", - stringify!(elf32_phdr), - "::", - stringify!(p_align))); + assert_eq!( + ::std::mem::size_of::<elf32_phdr>(), + 32usize, + concat!("Size of: ", stringify!(elf32_phdr)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_phdr>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_phdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_type as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_offset as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_vaddr as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_vaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_paddr as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_paddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_filesz as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_filesz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_memsz as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_memsz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_flags as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_phdr)).p_align as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(elf32_phdr), + "::", + stringify!(p_align) + ) + ); } impl Clone for elf32_phdr { fn clone(&self) -> Self { @@ -1082,60 +1414,96 @@ pub struct elf64_phdr { } #[test] fn bindgen_test_layout_elf64_phdr() { - assert_eq!(::std::mem::size_of::<elf64_phdr>(), - 56usize, - concat!("Size of: ", stringify!(elf64_phdr))); - assert_eq!(::std::mem::align_of::<elf64_phdr>(), - 8usize, - concat!("Alignment of ", stringify!(elf64_phdr))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_type as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_type))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_flags as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_flags))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_offset as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_offset))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_vaddr as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_vaddr))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_paddr as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_paddr))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_filesz as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_filesz))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_memsz as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_memsz))); - assert_eq!(unsafe { &(*(0 as *const elf64_phdr)).p_align as *const _ as usize }, - 48usize, - concat!("Alignment of field: ", - stringify!(elf64_phdr), - "::", - stringify!(p_align))); + assert_eq!( + ::std::mem::size_of::<elf64_phdr>(), + 56usize, + concat!("Size of: ", stringify!(elf64_phdr)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_phdr>(), + 8usize, + concat!("Alignment of ", stringify!(elf64_phdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_type as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_flags as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_offset as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_vaddr as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_vaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_paddr as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_paddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_filesz as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_filesz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_memsz as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_memsz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_phdr)).p_align as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(elf64_phdr), + "::", + stringify!(p_align) + ) + ); } impl Clone for elf64_phdr { fn clone(&self) -> Self { @@ -1159,72 +1527,116 @@ pub struct elf32_shdr { } #[test] fn bindgen_test_layout_elf32_shdr() { - assert_eq!(::std::mem::size_of::<elf32_shdr>(), - 40usize, - concat!("Size of: ", stringify!(elf32_shdr))); - assert_eq!(::std::mem::align_of::<elf32_shdr>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_shdr))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_name as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_name))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_type as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_type))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_flags as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_flags))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_addr as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_addr))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_offset as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_offset))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_size as *const _ as usize }, - 20usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_size))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_link as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_link))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_info as *const _ as usize }, - 28usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_info))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_addralign as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_addralign))); - assert_eq!(unsafe { &(*(0 as *const elf32_shdr)).sh_entsize as *const _ as usize }, - 36usize, - concat!("Alignment of field: ", - stringify!(elf32_shdr), - "::", - stringify!(sh_entsize))); + assert_eq!( + ::std::mem::size_of::<elf32_shdr>(), + 40usize, + concat!("Size of: ", stringify!(elf32_shdr)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_shdr>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_shdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_name as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_name) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_type as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_flags as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_addr as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_offset as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_size as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_link as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_link) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_info as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_addralign as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_addralign) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_shdr)).sh_entsize as *const _ as usize }, + 36usize, + concat!( + "Alignment of field: ", + stringify!(elf32_shdr), + "::", + stringify!(sh_entsize) + ) + ); } impl Clone for elf32_shdr { fn clone(&self) -> Self { @@ -1248,72 +1660,116 @@ pub struct elf64_shdr { } #[test] fn bindgen_test_layout_elf64_shdr() { - assert_eq!(::std::mem::size_of::<elf64_shdr>(), - 64usize, - concat!("Size of: ", stringify!(elf64_shdr))); - assert_eq!(::std::mem::align_of::<elf64_shdr>(), - 8usize, - concat!("Alignment of ", stringify!(elf64_shdr))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_name as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_name))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_type as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_type))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_flags as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_flags))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_addr as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_addr))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_offset as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_offset))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_size as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_size))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_link as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_link))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_info as *const _ as usize }, - 44usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_info))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_addralign as *const _ as usize }, - 48usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_addralign))); - assert_eq!(unsafe { &(*(0 as *const elf64_shdr)).sh_entsize as *const _ as usize }, - 56usize, - concat!("Alignment of field: ", - stringify!(elf64_shdr), - "::", - stringify!(sh_entsize))); + assert_eq!( + ::std::mem::size_of::<elf64_shdr>(), + 64usize, + concat!("Size of: ", stringify!(elf64_shdr)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_shdr>(), + 8usize, + concat!("Alignment of ", stringify!(elf64_shdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_name as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_name) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_type as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_flags as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_addr as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_offset as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_size as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_link as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_link) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_info as *const _ as usize }, + 44usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_addralign as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_addralign) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_shdr)).sh_entsize as *const _ as usize }, + 56usize, + concat!( + "Alignment of field: ", + stringify!(elf64_shdr), + "::", + stringify!(sh_entsize) + ) + ); } impl Clone for elf64_shdr { fn clone(&self) -> Self { @@ -1330,30 +1786,46 @@ pub struct elf32_note { } #[test] fn bindgen_test_layout_elf32_note() { - assert_eq!(::std::mem::size_of::<elf32_note>(), - 12usize, - concat!("Size of: ", stringify!(elf32_note))); - assert_eq!(::std::mem::align_of::<elf32_note>(), - 4usize, - concat!("Alignment of ", stringify!(elf32_note))); - assert_eq!(unsafe { &(*(0 as *const elf32_note)).n_namesz as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf32_note), - "::", - stringify!(n_namesz))); - assert_eq!(unsafe { &(*(0 as *const elf32_note)).n_descsz as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf32_note), - "::", - stringify!(n_descsz))); - assert_eq!(unsafe { &(*(0 as *const elf32_note)).n_type as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf32_note), - "::", - stringify!(n_type))); + assert_eq!( + ::std::mem::size_of::<elf32_note>(), + 12usize, + concat!("Size of: ", stringify!(elf32_note)) + ); + assert_eq!( + ::std::mem::align_of::<elf32_note>(), + 4usize, + concat!("Alignment of ", stringify!(elf32_note)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_note)).n_namesz as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf32_note), + "::", + stringify!(n_namesz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_note)).n_descsz as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf32_note), + "::", + stringify!(n_descsz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf32_note)).n_type as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf32_note), + "::", + stringify!(n_type) + ) + ); } impl Clone for elf32_note { fn clone(&self) -> Self { @@ -1370,30 +1842,46 @@ pub struct elf64_note { } #[test] fn bindgen_test_layout_elf64_note() { - assert_eq!(::std::mem::size_of::<elf64_note>(), - 12usize, - concat!("Size of: ", stringify!(elf64_note))); - assert_eq!(::std::mem::align_of::<elf64_note>(), - 4usize, - concat!("Alignment of ", stringify!(elf64_note))); - assert_eq!(unsafe { &(*(0 as *const elf64_note)).n_namesz as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(elf64_note), - "::", - stringify!(n_namesz))); - assert_eq!(unsafe { &(*(0 as *const elf64_note)).n_descsz as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(elf64_note), - "::", - stringify!(n_descsz))); - assert_eq!(unsafe { &(*(0 as *const elf64_note)).n_type as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(elf64_note), - "::", - stringify!(n_type))); + assert_eq!( + ::std::mem::size_of::<elf64_note>(), + 12usize, + concat!("Size of: ", stringify!(elf64_note)) + ); + assert_eq!( + ::std::mem::align_of::<elf64_note>(), + 4usize, + concat!("Alignment of ", stringify!(elf64_note)) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_note)).n_namesz as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(elf64_note), + "::", + stringify!(n_namesz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_note)).n_descsz as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(elf64_note), + "::", + stringify!(n_descsz) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const elf64_note)).n_type as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(elf64_note), + "::", + stringify!(n_type) + ) + ); } impl Clone for elf64_note { fn clone(&self) -> Self { diff --git a/kernel_loader/src/lib.rs b/kernel_loader/src/lib.rs index 9d03df0..23405d9 100644 --- a/kernel_loader/src/lib.rs +++ b/kernel_loader/src/lib.rs @@ -4,11 +4,11 @@ extern crate sys_util; -use std::mem; -use std::ffi::CStr; -use std::io::{Read, Seek, SeekFrom}; use std::error::{self, Error as KernelLoaderError}; +use std::ffi::CStr; use std::fmt::{self, Display}; +use std::io::{Read, Seek, SeekFrom}; +use std::mem; use sys_util::{GuestAddress, GuestMemory}; @@ -39,32 +39,21 @@ pub type Result<T> = std::result::Result<T, Error>; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::BigEndianElfOnLittle => - "Trying to load big-endian binary on little-endian machine", - &Error::CommandLineCopy => - "Failed writing command line to guest memory", - &Error::CommandLineOverflow => - "Command line overflowed guest memory", - &Error::InvalidElfMagicNumber => - "Invalid Elf magic number", - &Error::InvalidProgramHeaderSize => - "Invalid program header size", - &Error::InvalidProgramHeaderOffset => - "Invalid program header offset", - &Error::InvalidProgramHeaderAddress => - "Invalid Program Header Address", - &Error::ReadElfHeader => - "Unable to read elf header", - &Error::ReadKernelImage => - "Unable to read kernel image", - &Error::ReadProgramHeader => - "Unable to read program header", - &Error::SeekKernelStart => - "Unable to seek to kernel start", - &Error::SeekElfStart => - "Unable to seek to elf start", - &Error::SeekProgramHeader => - "Unable to seek to program header", + &Error::BigEndianElfOnLittle => { + "Trying to load big-endian binary on little-endian machine" + } + &Error::CommandLineCopy => "Failed writing command line to guest memory", + &Error::CommandLineOverflow => "Command line overflowed guest memory", + &Error::InvalidElfMagicNumber => "Invalid Elf magic number", + &Error::InvalidProgramHeaderSize => "Invalid program header size", + &Error::InvalidProgramHeaderOffset => "Invalid program header offset", + &Error::InvalidProgramHeaderAddress => "Invalid Program Header Address", + &Error::ReadElfHeader => "Unable to read elf header", + &Error::ReadKernelImage => "Unable to read kernel image", + &Error::ReadProgramHeader => "Unable to read program header", + &Error::SeekKernelStart => "Unable to seek to kernel start", + &Error::SeekElfStart => "Unable to seek to elf start", + &Error::SeekProgramHeader => "Unable to seek to program header", } } } @@ -82,11 +71,17 @@ impl Display for Error { /// * `guest_mem` - The guest memory region the kernel is written to. /// * `kernel_start` - The offset into `guest_mem` at which to load the kernel. /// * `kernel_image` - Input vmlinux image. -pub fn load_kernel<F>(guest_mem: &GuestMemory, kernel_start: GuestAddress, kernel_image: &mut F) -> Result<()> - where F: Read + Seek +pub fn load_kernel<F>( + guest_mem: &GuestMemory, + kernel_start: GuestAddress, + kernel_image: &mut F, +) -> Result<()> +where + F: Read + Seek, { let mut ehdr: elf::Elf64_Ehdr = Default::default(); - kernel_image.seek(SeekFrom::Start(0)) + kernel_image + .seek(SeekFrom::Start(0)) .map_err(|_| Error::SeekElfStart)?; unsafe { // read_struct is safe when reading a POD struct. It can be used and dropped without issue. @@ -94,10 +89,11 @@ pub fn load_kernel<F>(guest_mem: &GuestMemory, kernel_start: GuestAddress, kerne } // Sanity checks - if ehdr.e_ident[elf::EI_MAG0 as usize] != elf::ELFMAG0 as u8 || - ehdr.e_ident[elf::EI_MAG1 as usize] != elf::ELFMAG1 || - ehdr.e_ident[elf::EI_MAG2 as usize] != elf::ELFMAG2 || - ehdr.e_ident[elf::EI_MAG3 as usize] != elf::ELFMAG3 { + if ehdr.e_ident[elf::EI_MAG0 as usize] != elf::ELFMAG0 as u8 + || ehdr.e_ident[elf::EI_MAG1 as usize] != elf::ELFMAG1 + || ehdr.e_ident[elf::EI_MAG2 as usize] != elf::ELFMAG2 + || ehdr.e_ident[elf::EI_MAG3 as usize] != elf::ELFMAG3 + { return Err(Error::InvalidElfMagicNumber); } if ehdr.e_ident[elf::EI_DATA as usize] != elf::ELFDATA2LSB as u8 { @@ -111,7 +107,8 @@ pub fn load_kernel<F>(guest_mem: &GuestMemory, kernel_start: GuestAddress, kerne return Err(Error::InvalidProgramHeaderOffset); } - kernel_image.seek(SeekFrom::Start(ehdr.e_phoff)) + kernel_image + .seek(SeekFrom::Start(ehdr.e_phoff)) .map_err(|_| Error::SeekProgramHeader)?; let phdrs: Vec<elf::Elf64_Phdr> = unsafe { // Reading the structs is safe for a slice of POD structs. @@ -125,12 +122,15 @@ pub fn load_kernel<F>(guest_mem: &GuestMemory, kernel_start: GuestAddress, kerne continue; } - kernel_image.seek(SeekFrom::Start(phdr.p_offset)) + kernel_image + .seek(SeekFrom::Start(phdr.p_offset)) .map_err(|_| Error::SeekKernelStart)?; - let mem_offset = kernel_start.checked_add(phdr.p_paddr) + let mem_offset = kernel_start + .checked_add(phdr.p_paddr) .ok_or(Error::InvalidProgramHeaderAddress)?; - guest_mem.read_to_memory(mem_offset, kernel_image, phdr.p_filesz as usize) + guest_mem + .read_to_memory(mem_offset, kernel_image, phdr.p_filesz as usize) .map_err(|_| Error::ReadKernelImage)?; } @@ -144,19 +144,25 @@ pub fn load_kernel<F>(guest_mem: &GuestMemory, kernel_start: GuestAddress, kerne /// * `guest_mem` - A u8 slice that will be partially overwritten by the command line. /// * `guest_addr` - The address in `guest_mem` at which to load the command line. /// * `cmdline` - The kernel command line. -pub fn load_cmdline(guest_mem: &GuestMemory, guest_addr: GuestAddress, cmdline: &CStr) -> Result<()> { +pub fn load_cmdline( + guest_mem: &GuestMemory, + guest_addr: GuestAddress, + cmdline: &CStr, +) -> Result<()> { let len = cmdline.to_bytes().len(); if len == 0 { return Ok(()); } - let end = guest_addr.checked_add(len as u64 + 1) + let end = guest_addr + .checked_add(len as u64 + 1) .ok_or(Error::CommandLineOverflow)?; // Extra for null termination. if end > guest_mem.end_addr() { return Err(Error::CommandLineOverflow)?; } - guest_mem.write_slice_at_addr(cmdline.to_bytes_with_nul(), guest_addr) + guest_mem + .write_slice_at_addr(cmdline.to_bytes_with_nul(), guest_addr) .map_err(|_| Error::CommandLineCopy)?; Ok(()) @@ -164,8 +170,8 @@ pub fn load_cmdline(guest_mem: &GuestMemory, guest_addr: GuestAddress, cmdline: #[cfg(test)] mod test { - use std::io::Cursor; use super::*; + use std::io::Cursor; use sys_util::{GuestAddress, GuestMemory}; const MEM_SIZE: u64 = 0x8000; @@ -178,20 +184,28 @@ mod test { fn cmdline_overflow() { let gm = create_guest_mem(); let cmdline_address = GuestAddress(MEM_SIZE - 5); - assert_eq!(Err(Error::CommandLineOverflow), - load_cmdline(&gm, - cmdline_address, - CStr::from_bytes_with_nul(b"12345\0").unwrap())); + assert_eq!( + Err(Error::CommandLineOverflow), + load_cmdline( + &gm, + cmdline_address, + CStr::from_bytes_with_nul(b"12345\0").unwrap() + ) + ); } #[test] fn cmdline_write_end() { let gm = create_guest_mem(); let mut cmdline_address = GuestAddress(45); - assert_eq!(Ok(()), - load_cmdline(&gm, - cmdline_address, - CStr::from_bytes_with_nul(b"1234\0").unwrap())); + assert_eq!( + Ok(()), + load_cmdline( + &gm, + cmdline_address, + CStr::from_bytes_with_nul(b"1234\0").unwrap() + ) + ); let val: u8 = gm.read_obj_from_addr(cmdline_address).unwrap(); assert_eq!(val, '1' as u8); cmdline_address = cmdline_address.unchecked_add(1); @@ -220,8 +234,10 @@ mod test { let gm = create_guest_mem(); let kernel_addr = GuestAddress(0x0); let image = make_elf_bin(); - assert_eq!(Ok(()), - load_kernel(&gm, kernel_addr, &mut Cursor::new(&image))); + assert_eq!( + Ok(()), + load_kernel(&gm, kernel_addr, &mut Cursor::new(&image)) + ); } #[test] @@ -230,8 +246,10 @@ mod test { let kernel_addr = GuestAddress(0x0); let mut bad_image = make_elf_bin(); bad_image[0x1] = 0x33; - assert_eq!(Err(Error::InvalidElfMagicNumber), - load_kernel(&gm, kernel_addr, &mut Cursor::new(&bad_image))); + assert_eq!( + Err(Error::InvalidElfMagicNumber), + load_kernel(&gm, kernel_addr, &mut Cursor::new(&bad_image)) + ); } #[test] @@ -241,8 +259,10 @@ mod test { let kernel_addr = GuestAddress(0x0); let mut bad_image = make_elf_bin(); bad_image[0x5] = 2; - assert_eq!(Err(Error::BigEndianElfOnLittle), - load_kernel(&gm, kernel_addr, &mut Cursor::new(&bad_image))); + assert_eq!( + Err(Error::BigEndianElfOnLittle), + load_kernel(&gm, kernel_addr, &mut Cursor::new(&bad_image)) + ); } #[test] @@ -252,7 +272,9 @@ mod test { let kernel_addr = GuestAddress(0x0); let mut bad_image = make_elf_bin(); bad_image[0x20] = 0x10; - assert_eq!(Err(Error::InvalidProgramHeaderOffset), - load_kernel(&gm, kernel_addr, &mut Cursor::new(&bad_image))); + assert_eq!( + Err(Error::InvalidProgramHeaderOffset), + load_kernel(&gm, kernel_addr, &mut Cursor::new(&bad_image)) + ); } } diff --git a/kvm/src/lib.rs b/kvm/src/lib.rs index 2017bb9..c9c5673 100644 --- a/kvm/src/lib.rs +++ b/kvm/src/lib.rs @@ -4,30 +4,32 @@ //! A safe wrapper around the kernel's KVM interface. -extern crate libc; extern crate kvm_sys; +extern crate libc; #[macro_use] extern crate sys_util; mod cap; -use std::fs::File; -use std::collections::{BinaryHeap, HashMap}; use std::collections::hash_map::Entry; +use std::collections::{BinaryHeap, HashMap}; +use std::fs::File; use std::mem::size_of; use std::os::raw::*; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; -use libc::{open, O_RDWR, O_CLOEXEC, EINVAL, ENOSPC, ENOENT}; use libc::sigset_t; +use libc::{open, EINVAL, ENOENT, ENOSPC, O_CLOEXEC, O_RDWR}; use kvm_sys::*; -use sys_util::{GuestAddress, GuestMemory, MemoryMapping, EventFd, - signal, Error, Result, pagesize}; #[allow(unused_imports)] -use sys_util::{ioctl, ioctl_with_val, ioctl_with_ref, ioctl_with_mut_ref, ioctl_with_ptr, - ioctl_with_mut_ptr}; +use sys_util::{ + ioctl, ioctl_with_mut_ptr, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref, ioctl_with_val, +}; +use sys_util::{ + pagesize, signal, Error, EventFd, GuestAddress, GuestMemory, MemoryMapping, Result, +}; pub use cap::*; @@ -35,32 +37,33 @@ fn errno_result<T>() -> Result<T> { Err(Error::last()) } -unsafe fn set_user_memory_region<F: AsRawFd>(fd: &F, - slot: u32, - read_only: bool, - log_dirty_pages: bool, - guest_addr: u64, - memory_size: u64, - userspace_addr: u64) - -> Result<()> { - let mut flags = if read_only { - KVM_MEM_READONLY - } else { - 0 - }; +unsafe fn set_user_memory_region<F: AsRawFd>( + fd: &F, + slot: u32, + read_only: bool, + log_dirty_pages: bool, + guest_addr: u64, + memory_size: u64, + userspace_addr: u64, +) -> Result<()> { + let mut flags = if read_only { KVM_MEM_READONLY } else { 0 }; if log_dirty_pages { flags |= KVM_MEM_LOG_DIRTY_PAGES; } let region = kvm_userspace_memory_region { - slot: slot, + slot, flags, guest_phys_addr: guest_addr, - memory_size: memory_size, - userspace_addr: userspace_addr, + memory_size, + userspace_addr, }; let ret = ioctl_with_ref(fd, KVM_SET_USER_MEMORY_REGION(), ®ion); - if ret == 0 { Ok(()) } else { errno_result() } + if ret == 0 { + Ok(()) + } else { + errno_result() + } } /// Helper function to determine the size in bytes of a dirty log bitmap for the given memory region @@ -93,7 +96,7 @@ impl Kvm { } // Safe because we verify that ret is valid and we own the fd. Ok(Kvm { - kvm: unsafe { File::from_raw_fd(ret) } + kvm: unsafe { File::from_raw_fd(ret) }, }) } @@ -127,7 +130,7 @@ impl Kvm { _ => { warn!("kernel returned invalid number of VCPUs"); 4 - }, + } } } @@ -168,8 +171,7 @@ impl Kvm { pub fn get_msr_index_list(&self) -> Result<Vec<u32>> { const MAX_KVM_MSR_ENTRIES: usize = 256; - let vec_size_bytes = size_of::<kvm_msr_list>() + - MAX_KVM_MSR_ENTRIES * size_of::<u32>(); + let vec_size_bytes = size_of::<kvm_msr_list>() + MAX_KVM_MSR_ENTRIES * size_of::<u32>(); let bytes: Vec<u8> = vec![0; vec_size_bytes]; let msr_list: &mut kvm_msr_list = unsafe { // We have ensured in new that there is enough space for the structure so this @@ -260,16 +262,21 @@ impl Vm { guest_mem.with_regions(|index, guest_addr, size, host_addr| { unsafe { // Safe because the guest regions are guaranteed not to overlap. - set_user_memory_region(&vm_file, index as u32, false, false, + set_user_memory_region( + &vm_file, + index as u32, + false, + false, guest_addr.offset() as u64, size as u64, - host_addr as u64) + host_addr as u64, + ) } })?; Ok(Vm { vm: vm_file, - guest_mem: guest_mem, + guest_mem, device_memory: HashMap::new(), mem_slot_gaps: BinaryHeap::new(), }) @@ -289,7 +296,6 @@ impl Vm { unsafe { ioctl_with_val(self, KVM_CHECK_EXTENSION(), c as c_ulong) == 1 } } - /// Inserts the given `MemoryMapping` into the VM's address space at `guest_addr`. /// /// The slot that was assigned the device memory mapping is returned on success. The slot can be @@ -304,12 +310,13 @@ impl Vm { /// /// If `log_dirty_pages` is true, the slot number can be used to retrieve the pages written to /// by the guest with `get_dirty_log`. - pub fn add_device_memory(&mut self, - guest_addr: GuestAddress, - mem: MemoryMapping, - read_only: bool, - log_dirty_pages: bool) - -> Result<u32> { + pub fn add_device_memory( + &mut self, + guest_addr: GuestAddress, + mem: MemoryMapping, + read_only: bool, + log_dirty_pages: bool, + ) -> Result<u32> { if guest_addr < self.guest_mem.end_addr() { return Err(Error::new(ENOSPC)); } @@ -329,10 +336,15 @@ impl Vm { // this. We take ownership of the memory mapping so that it won't be unmapped until the slot // is removed. unsafe { - set_user_memory_region(&self.vm, slot, read_only, log_dirty_pages, - guest_addr.offset() as u64, - mem.size() as u64, - mem.as_ptr() as u64)?; + set_user_memory_region( + &self.vm, + slot, + read_only, + log_dirty_pages, + guest_addr.offset() as u64, + mem.size() as u64, + mem.as_ptr() as u64, + )?; }; self.device_memory.insert(slot, mem); @@ -354,7 +366,7 @@ impl Vm { self.mem_slot_gaps.push(-(slot as i32)); Ok(entry.remove()) } - _ => Err(Error::new(ENOENT)) + _ => Err(Error::new(ENOENT)), } } @@ -380,7 +392,11 @@ impl Vm { // (because it's from a slice) and we checked that it will be large enough to hold // the entire log. let ret = unsafe { ioctl_with_ref(self, KVM_GET_DIRTY_LOG(), &dirty_log_kvm) }; - if ret == 0 { Ok(()) } else { errno_result() } + if ret == 0 { + Ok(()) + } else { + errno_result() + } } _ => Err(Error::new(ENOENT)), } @@ -400,9 +416,7 @@ impl Vm { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub fn set_tss_addr(&self, addr: GuestAddress) -> Result<()> { // Safe because we know that our file is a VM fd and we verify the return result. - let ret = unsafe { - ioctl_with_val(self, KVM_SET_TSS_ADDR(), addr.offset() as u64) - }; + let ret = unsafe { ioctl_with_val(self, KVM_SET_TSS_ADDR(), addr.offset() as u64) }; if ret == 0 { Ok(()) } else { @@ -416,9 +430,8 @@ impl Vm { #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub fn set_identity_map_addr(&self, addr: GuestAddress) -> Result<()> { // Safe because we know that our file is a VM fd and we verify the return result. - let ret = unsafe { - ioctl_with_ref(self, KVM_SET_IDENTITY_MAP_ADDR(), &(addr.offset() as u64)) - }; + let ret = + unsafe { ioctl_with_ref(self, KVM_SET_IDENTITY_MAP_ADDR(), &(addr.offset() as u64)) }; if ret == 0 { Ok(()) } else { @@ -429,7 +442,14 @@ impl Vm { /// Crates an in kernel interrupt controller. /// /// See the documentation on the KVM_CREATE_IRQCHIP ioctl. - #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] + #[cfg( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "arm", + target_arch = "aarch64" + ) + )] pub fn create_irq_chip(&self) -> Result<()> { // Safe because we know that our file is a VM fd and we verify the return result. let ret = unsafe { ioctl(self, KVM_CREATE_IRQCHIP()) }; @@ -481,7 +501,6 @@ impl Vm { } } - /// Retrieves the state of IOAPIC by issuing KVM_GET_IRQCHIP ioctl. /// /// Note that this call can only succeed after a call to `Vm::create_irq_chip`. @@ -524,7 +543,14 @@ impl Vm { } /// Sets the level on the given irq to 1 if `active` is true, and 0 otherwise. - #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] + #[cfg( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "arm", + target_arch = "aarch64" + ) + )] pub fn set_irq_line(&self, irq: u32, active: bool) -> Result<()> { let mut irq_level = kvm_irq_level::default(); irq_level.__bindgen_anon_1.irq = irq; @@ -595,19 +621,48 @@ impl Vm { /// /// In all cases where `evt` is signaled, the ordinary vmexit to userspace that would be /// triggered is prevented. - pub fn register_ioevent<T: Into<u64>>(&self, evt: &EventFd, addr: IoeventAddress, datamatch: T) -> Result<()> { - self.ioeventfd(evt, addr, datamatch.into(), std::mem::size_of::<T>() as u32, false) + pub fn register_ioevent<T: Into<u64>>( + &self, + evt: &EventFd, + addr: IoeventAddress, + datamatch: T, + ) -> Result<()> { + self.ioeventfd( + evt, + addr, + datamatch.into(), + std::mem::size_of::<T>() as u32, + false, + ) } /// Unregisters an event previously registered with `register_ioevent`. /// /// The `evt`, `addr`, and `datamatch` set must be the same as the ones passed into /// `register_ioevent`. - pub fn unregister_ioevent<T: Into<u64>>(&self, evt: &EventFd, addr: IoeventAddress, datamatch: T) -> Result<()> { - self.ioeventfd(evt, addr, datamatch.into(), std::mem::size_of::<T>() as u32, true) - } - - fn ioeventfd(&self, evt: &EventFd, addr: IoeventAddress, datamatch: u64, datamatch_len: u32, deassign: bool) -> Result<()> { + pub fn unregister_ioevent<T: Into<u64>>( + &self, + evt: &EventFd, + addr: IoeventAddress, + datamatch: T, + ) -> Result<()> { + self.ioeventfd( + evt, + addr, + datamatch.into(), + std::mem::size_of::<T>() as u32, + true, + ) + } + + fn ioeventfd( + &self, + evt: &EventFd, + addr: IoeventAddress, + datamatch: u64, + datamatch_len: u32, + deassign: bool, + ) -> Result<()> { let mut flags = 0; if deassign { flags |= 1 << kvm_ioeventfd_flag_nr_deassign; @@ -620,11 +675,14 @@ impl Vm { _ => {} }; let ioeventfd = kvm_ioeventfd { - datamatch: datamatch, + datamatch, len: datamatch_len, - addr: match addr { IoeventAddress::Pio(p) => p as u64, IoeventAddress::Mmio(m) => m }, + addr: match addr { + IoeventAddress::Pio(p) => p as u64, + IoeventAddress::Mmio(m) => m, + }, fd: evt.as_raw_fd(), - flags: flags, + flags, ..Default::default() }; // Safe because we know that our file is a VM fd, we know the kernel will only read the @@ -638,11 +696,18 @@ impl Vm { } /// Registers an event that will, when signalled, trigger the `gsi` irq. - #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] + #[cfg( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "arm", + target_arch = "aarch64" + ) + )] pub fn register_irqfd(&self, evt: &EventFd, gsi: u32) -> Result<()> { let irqfd = kvm_irqfd { fd: evt.as_raw_fd() as u32, - gsi: gsi, + gsi, ..Default::default() }; // Safe because we know that our file is a VM fd, we know the kernel will only read the @@ -657,23 +722,35 @@ impl Vm { /// Registers an event that will, when signalled, trigger the `gsi` irq, and `resample_evt` will /// get triggered when the irqchip is resampled. - #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] - pub fn register_irqfd_resample(&self, - evt: &EventFd, - resample_evt: &EventFd, - gsi: u32) - -> Result<()> { + #[cfg( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "arm", + target_arch = "aarch64" + ) + )] + pub fn register_irqfd_resample( + &self, + evt: &EventFd, + resample_evt: &EventFd, + gsi: u32, + ) -> Result<()> { let irqfd = kvm_irqfd { flags: KVM_IRQFD_FLAG_RESAMPLE, fd: evt.as_raw_fd() as u32, resamplefd: resample_evt.as_raw_fd() as u32, - gsi: gsi, + gsi, ..Default::default() }; // Safe because we know that our file is a VM fd, we know the kernel will only read the // correct amount of memory from our pointer, and we verify the return result. let ret = unsafe { ioctl_with_ref(self, KVM_IRQFD(), &irqfd) }; - if ret == 0 { Ok(()) } else { errno_result() } + if ret == 0 { + Ok(()) + } else { + errno_result() + } } /// Unregisters an event that was previously registered with @@ -681,11 +758,18 @@ impl Vm { /// /// The `evt` and `gsi` pair must be the same as the ones passed into /// `register_irqfd`/`register_irqfd_resample`. - #[cfg(any(target_arch = "x86", target_arch = "x86_64", target_arch = "arm", target_arch = "aarch64"))] + #[cfg( + any( + target_arch = "x86", + target_arch = "x86_64", + target_arch = "arm", + target_arch = "aarch64" + ) + )] pub fn unregister_irqfd(&self, evt: &EventFd, gsi: u32) -> Result<()> { let irqfd = kvm_irqfd { fd: evt.as_raw_fd() as u32, - gsi: gsi, + gsi, flags: KVM_IRQFD_FLAG_DEASSIGN, ..Default::default() }; @@ -703,8 +787,8 @@ impl Vm { /// `set_gsi_routing`. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub fn set_gsi_routing(&self, routes: &[IrqRoute]) -> Result<()> { - let vec_size_bytes = size_of::<kvm_irq_routing>() + - (routes.len() * size_of::<kvm_irq_routing_entry>()); + let vec_size_bytes = + size_of::<kvm_irq_routing>() + (routes.len() * size_of::<kvm_irq_routing_entry>()); let bytes: Vec<u8> = vec![0; vec_size_bytes]; let irq_routing: &mut kvm_irq_routing = unsafe { // We have ensured in new that there is enough space for the structure so this @@ -722,17 +806,14 @@ impl Vm { match route.source { IrqSource::Irqchip { chip, pin } => { irq_route.type_ = KVM_IRQ_ROUTING_IRQCHIP; - irq_route.u.irqchip = kvm_irq_routing_irqchip { - irqchip: chip, - pin, - } + irq_route.u.irqchip = kvm_irq_routing_irqchip { irqchip: chip, pin } } IrqSource::Msi { address, data } => { irq_route.type_ = KVM_IRQ_ROUTING_MSI; irq_route.u.msi = kvm_irq_routing_msi { address_lo: address as u32, address_hi: (address >> 32) as u32, - data: data, + data, ..Default::default() } } @@ -763,15 +844,12 @@ impl Vm { pub fn arm_preferred_target(&self, kvi: &mut kvm_vcpu_init) -> Result<()> { // The ioctl is safe because we allocated the struct and we know the // kernel will write exactly the size of the struct. - let ret = unsafe { - ioctl_with_mut_ref(self, KVM_ARM_PREFERRED_TARGET(), kvi) - }; + let ret = unsafe { ioctl_with_mut_ref(self, KVM_ARM_PREFERRED_TARGET(), kvi) }; if ret < 0 { return errno_result(); } Ok(()) } - } impl AsRawFd for Vm { @@ -840,20 +918,17 @@ impl Vcpu { // Safe because we know that vm a VM fd and we verify the return result. let vcpu_fd = unsafe { ioctl_with_val(vm, KVM_CREATE_VCPU(), id) }; if vcpu_fd < 0 { - return errno_result() + return errno_result(); } // Wrap the vcpu now in case the following ? returns early. This is safe because we verified // the value of the fd and we own the fd. let vcpu = unsafe { File::from_raw_fd(vcpu_fd) }; - let run_mmap = MemoryMapping::from_fd(&vcpu, run_mmap_size) - .map_err(|_| Error::new(ENOSPC))?; + let run_mmap = + MemoryMapping::from_fd(&vcpu, run_mmap_size).map_err(|_| Error::new(ENOSPC))?; - Ok(Vcpu { - vcpu: vcpu, - run_mmap: run_mmap - }) + Ok(Vcpu { vcpu, run_mmap }) } fn get_run(&self) -> &mut kvm_run { @@ -877,7 +952,7 @@ impl Vcpu { // Safe because the exit_reason (which comes from the kernel) told us which // union field to use. let io = unsafe { run.__bindgen_anon_1.io }; - let port = io.port; + let port = io.port; let data_size = io.count as usize * io.size as usize; // The data_offset is defined by the kernel to be some number of bytes into the // kvm_run stucture, which we have fully mmap'd. @@ -892,7 +967,7 @@ impl Vcpu { KVM_EXIT_IO_OUT => Ok(VcpuExit::IoOut(port, data_slice)), _ => Err(Error::new(EINVAL)), } - }, + } KVM_EXIT_MMIO => { // Safe because the exit_reason (which comes from the kernel) told us which // union field to use. @@ -905,36 +980,36 @@ impl Vcpu { } else { Ok(VcpuExit::MmioRead(addr, data_slice)) } - }, - KVM_EXIT_UNKNOWN => Ok(VcpuExit::Unknown), - KVM_EXIT_EXCEPTION => Ok(VcpuExit::Exception), - KVM_EXIT_HYPERCALL => Ok(VcpuExit::Hypercall), - KVM_EXIT_DEBUG => Ok(VcpuExit::Debug), - KVM_EXIT_HLT => Ok(VcpuExit::Hlt), + } + KVM_EXIT_UNKNOWN => Ok(VcpuExit::Unknown), + KVM_EXIT_EXCEPTION => Ok(VcpuExit::Exception), + KVM_EXIT_HYPERCALL => Ok(VcpuExit::Hypercall), + KVM_EXIT_DEBUG => Ok(VcpuExit::Debug), + KVM_EXIT_HLT => Ok(VcpuExit::Hlt), KVM_EXIT_IRQ_WINDOW_OPEN => Ok(VcpuExit::IrqWindowOpen), - KVM_EXIT_SHUTDOWN => Ok(VcpuExit::Shutdown), - KVM_EXIT_FAIL_ENTRY => Ok(VcpuExit::FailEntry), - KVM_EXIT_INTR => Ok(VcpuExit::Intr), - KVM_EXIT_SET_TPR => Ok(VcpuExit::SetTpr), - KVM_EXIT_TPR_ACCESS => Ok(VcpuExit::TprAccess), - KVM_EXIT_S390_SIEIC => Ok(VcpuExit::S390Sieic), - KVM_EXIT_S390_RESET => Ok(VcpuExit::S390Reset), - KVM_EXIT_DCR => Ok(VcpuExit::Dcr), - KVM_EXIT_NMI => Ok(VcpuExit::Nmi), - KVM_EXIT_INTERNAL_ERROR => Ok(VcpuExit::InternalError), - KVM_EXIT_OSI => Ok(VcpuExit::Osi), - KVM_EXIT_PAPR_HCALL => Ok(VcpuExit::PaprHcall), - KVM_EXIT_S390_UCONTROL => Ok(VcpuExit::S390Ucontrol), - KVM_EXIT_WATCHDOG => Ok(VcpuExit::Watchdog), - KVM_EXIT_S390_TSCH => Ok(VcpuExit::S390Tsch), - KVM_EXIT_EPR => Ok(VcpuExit::Epr), - KVM_EXIT_SYSTEM_EVENT => { + KVM_EXIT_SHUTDOWN => Ok(VcpuExit::Shutdown), + KVM_EXIT_FAIL_ENTRY => Ok(VcpuExit::FailEntry), + KVM_EXIT_INTR => Ok(VcpuExit::Intr), + KVM_EXIT_SET_TPR => Ok(VcpuExit::SetTpr), + KVM_EXIT_TPR_ACCESS => Ok(VcpuExit::TprAccess), + KVM_EXIT_S390_SIEIC => Ok(VcpuExit::S390Sieic), + KVM_EXIT_S390_RESET => Ok(VcpuExit::S390Reset), + KVM_EXIT_DCR => Ok(VcpuExit::Dcr), + KVM_EXIT_NMI => Ok(VcpuExit::Nmi), + KVM_EXIT_INTERNAL_ERROR => Ok(VcpuExit::InternalError), + KVM_EXIT_OSI => Ok(VcpuExit::Osi), + KVM_EXIT_PAPR_HCALL => Ok(VcpuExit::PaprHcall), + KVM_EXIT_S390_UCONTROL => Ok(VcpuExit::S390Ucontrol), + KVM_EXIT_WATCHDOG => Ok(VcpuExit::Watchdog), + KVM_EXIT_S390_TSCH => Ok(VcpuExit::S390Tsch), + KVM_EXIT_EPR => Ok(VcpuExit::Epr), + KVM_EXIT_SYSTEM_EVENT => { // Safe because we know the exit reason told us this union // field is valid let event_type = unsafe { run.__bindgen_anon_1.system_event.type_ }; let event_flags = unsafe { run.__bindgen_anon_1.system_event.flags }; Ok(VcpuExit::SystemEvent(event_type, event_flags)) - }, + } r => panic!("unknown kvm exit reason: {}", r), } } else { @@ -950,7 +1025,7 @@ impl Vcpu { let mut regs = unsafe { std::mem::zeroed() }; let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_REGS(), &mut regs) }; if ret != 0 { - return errno_result() + return errno_result(); } Ok(regs) } @@ -962,7 +1037,7 @@ impl Vcpu { // correct amount of memory from our pointer, and we verify the return result. let ret = unsafe { ioctl_with_ref(self, KVM_SET_REGS(), regs) }; if ret != 0 { - return errno_result() + return errno_result(); } Ok(()) } @@ -987,7 +1062,7 @@ impl Vcpu { // correct amount of memory from our pointer, and we verify the return result. let ret = unsafe { ioctl_with_ref(self, KVM_SET_SREGS(), sregs) }; if ret != 0 { - return errno_result() + return errno_result(); } Ok(()) } @@ -1077,8 +1152,8 @@ impl Vcpu { /// See the documentation for KVM_SET_MSRS. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub fn get_msrs(&self, msr_entries: &mut Vec<kvm_msr_entry>) -> Result<()> { - let vec_size_bytes = size_of::<kvm_msrs>() + - (msr_entries.len() * size_of::<kvm_msr_entry>()); + let vec_size_bytes = + size_of::<kvm_msrs>() + (msr_entries.len() * size_of::<kvm_msr_entry>()); let vec: Vec<u8> = vec![0; vec_size_bytes]; let msrs: &mut kvm_msrs = unsafe { // Converting the vector's memory to a struct is unsafe. Carefully using the read-only @@ -1119,7 +1194,8 @@ impl Vcpu { // Here we trust the kernel not to read past the end of the kvm_msrs struct. ioctl_with_ref(self, KVM_SET_MSRS(), msrs) }; - if ret < 0 { // KVM_SET_MSRS actually returns the number of msr entries written. + if ret < 0 { + // KVM_SET_MSRS actually returns the number of msr entries written. return errno_result(); } Ok(()) @@ -1221,8 +1297,7 @@ impl Vcpu { // will only write correct amount of memory to our pointer, and we // verify the return result. let mut events: kvm_vcpu_events = unsafe { std::mem::zeroed() }; - let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_VCPU_EVENTS(), - &mut events) }; + let ret = unsafe { ioctl_with_mut_ref(self, KVM_GET_VCPU_EVENTS(), &mut events) }; if ret < 0 { return errno_result(); } @@ -1291,8 +1366,10 @@ impl Vcpu { #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] pub fn set_one_reg(&self, reg_id: u64, data: u64) -> Result<()> { let data_ref = &data as *const u64; - let onereg = kvm_one_reg { id: reg_id, - addr: data_ref as u64}; + let onereg = kvm_one_reg { + id: reg_id, + addr: data_ref as u64, + }; // safe becuase we allocated the struct and we know the kernel will read // exactly the size of the struct let ret = unsafe { ioctl_with_ref(self, KVM_SET_ONE_REG(), &onereg) }; @@ -1326,7 +1403,7 @@ impl AsRawFd for Vcpu { /// Hides the zero length array behind a bounds check. #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] pub struct CpuId { - bytes: Vec<u8>, // Actually accessed as a kvm_cpuid2 struct. + bytes: Vec<u8>, // Actually accessed as a kvm_cpuid2 struct. allocated_len: usize, // Number of kvm_cpuid_entry2 structs at the end of kvm_cpuid2. } @@ -1335,8 +1412,7 @@ impl CpuId { pub fn new(array_len: usize) -> CpuId { use std::mem::size_of; - let vec_size_bytes = size_of::<kvm_cpuid2>() + - (array_len * size_of::<kvm_cpuid_entry2>()); + let vec_size_bytes = size_of::<kvm_cpuid2>() + (array_len * size_of::<kvm_cpuid_entry2>()); let bytes: Vec<u8> = vec![0; vec_size_bytes]; let kvm_cpuid: &mut kvm_cpuid2 = unsafe { // We have ensured in new that there is enough space for the structure so this @@ -1345,7 +1421,10 @@ impl CpuId { }; kvm_cpuid.nent = array_len as u32; - CpuId { bytes: bytes, allocated_len: array_len } + CpuId { + bytes, + allocated_len: array_len, + } } /// Get the entries slice so they can be modified before passing to the VCPU. @@ -1448,7 +1527,8 @@ mod tests { let mut vm = Vm::new(&kvm, gm).unwrap(); let mem_size = 0x1000; let mem = MemoryMapping::new(mem_size).unwrap(); - vm.add_device_memory(GuestAddress(0x1000), mem, false, false).unwrap(); + vm.add_device_memory(GuestAddress(0x1000), mem, false, false) + .unwrap(); } #[test] @@ -1458,7 +1538,8 @@ mod tests { let mut vm = Vm::new(&kvm, gm).unwrap(); let mem_size = 0x1000; let mem = MemoryMapping::new(mem_size).unwrap(); - vm.add_device_memory(GuestAddress(0x1000), mem, true, false).unwrap(); + vm.add_device_memory(GuestAddress(0x1000), mem, true, false) + .unwrap(); } #[test] @@ -1469,7 +1550,9 @@ mod tests { let mem_size = 0x1000; let mem = MemoryMapping::new(mem_size).unwrap(); let mem_ptr = mem.as_ptr(); - let slot = vm.add_device_memory(GuestAddress(0x1000), mem, false, false).unwrap(); + let slot = vm + .add_device_memory(GuestAddress(0x1000), mem, false, false) + .unwrap(); let mem = vm.remove_device_memory(slot).unwrap(); assert_eq!(mem.size(), mem_size); assert_eq!(mem.as_ptr(), mem_ptr); @@ -1483,14 +1566,17 @@ mod tests { assert!(vm.remove_device_memory(0).is_err()); } - #[test] + #[test] fn overlap_memory() { let kvm = Kvm::new().unwrap(); let gm = GuestMemory::new(&vec![(GuestAddress(0), 0x10000)]).unwrap(); let mut vm = Vm::new(&kvm, gm).unwrap(); let mem_size = 0x2000; let mem = MemoryMapping::new(mem_size).unwrap(); - assert!(vm.add_device_memory(GuestAddress(0x2000), mem, false, false).is_err()); + assert!( + vm.add_device_memory(GuestAddress(0x2000), mem, false, false) + .is_err() + ); } #[test] @@ -1543,12 +1629,18 @@ mod tests { let gm = GuestMemory::new(&vec![(GuestAddress(0), 0x10000)]).unwrap(); let vm = Vm::new(&kvm, gm).unwrap(); let evtfd = EventFd::new().unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xf4), NoDatamatch).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Mmio(0x1000), NoDatamatch).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc1), 0x7fu8).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc2), 0x1337u16).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc4), 0xdeadbeefu32).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc8), 0xdeadbeefdeadbeefu64).unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xf4), NoDatamatch) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Mmio(0x1000), NoDatamatch) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc1), 0x7fu8) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc2), 0x1337u16) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc4), 0xdeadbeefu32) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xc8), 0xdeadbeefdeadbeefu64) + .unwrap(); } #[test] @@ -1557,12 +1649,18 @@ mod tests { let gm = GuestMemory::new(&vec![(GuestAddress(0), 0x10000)]).unwrap(); let vm = Vm::new(&kvm, gm).unwrap(); let evtfd = EventFd::new().unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xf4), NoDatamatch).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Mmio(0x1000), NoDatamatch).unwrap(); - vm.register_ioevent(&evtfd, IoeventAddress::Mmio(0x1004), 0x7fu8).unwrap(); - vm.unregister_ioevent(&evtfd, IoeventAddress::Pio(0xf4), NoDatamatch).unwrap(); - vm.unregister_ioevent(&evtfd, IoeventAddress::Mmio(0x1000), NoDatamatch).unwrap(); - vm.unregister_ioevent(&evtfd, IoeventAddress::Mmio(0x1004), 0x7fu8).unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Pio(0xf4), NoDatamatch) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Mmio(0x1000), NoDatamatch) + .unwrap(); + vm.register_ioevent(&evtfd, IoeventAddress::Mmio(0x1004), 0x7fu8) + .unwrap(); + vm.unregister_ioevent(&evtfd, IoeventAddress::Pio(0xf4), NoDatamatch) + .unwrap(); + vm.unregister_ioevent(&evtfd, IoeventAddress::Mmio(0x1000), NoDatamatch) + .unwrap(); + vm.unregister_ioevent(&evtfd, IoeventAddress::Mmio(0x1004), 0x7fu8) + .unwrap(); } #[test] @@ -1605,7 +1703,8 @@ mod tests { vm.register_irqfd_resample(&evtfd1, &evtfd2, 4).unwrap(); vm.unregister_irqfd(&evtfd1, 4).unwrap(); // Ensures the ioctl is actually reading the resamplefd. - vm.register_irqfd_resample(&evtfd1, unsafe { &EventFd::from_raw_fd(-1) }, 4).unwrap_err(); + vm.register_irqfd_resample(&evtfd1, unsafe { &EventFd::from_raw_fd(-1) }, 4) + .unwrap_err(); } #[test] @@ -1696,9 +1795,15 @@ mod tests { let vcpu = Vcpu::new(0, &kvm, &vm).unwrap(); let mut msrs = vec![ // This one should succeed - kvm_msr_entry { index: 0x0000011e, ..Default::default() }, + kvm_msr_entry { + index: 0x0000011e, + ..Default::default() + }, // This one will fail to fetch - kvm_msr_entry { index: 0x000003f1, ..Default::default() }, + kvm_msr_entry { + index: 0x000003f1, + ..Default::default() + }, ]; vcpu.get_msrs(&mut msrs).unwrap(); assert_eq!(msrs.len(), 1); diff --git a/kvm/tests/dirty_log.rs b/kvm/tests/dirty_log.rs index 7226220..269e465 100644 --- a/kvm/tests/dirty_log.rs +++ b/kvm/tests/dirty_log.rs @@ -4,13 +4,13 @@ #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -extern crate sys_util; -extern crate kvm_sys; extern crate kvm; +extern crate kvm_sys; +extern crate sys_util; use kvm::*; use kvm_sys::kvm_regs; -use sys_util::{GuestAddress, GuestMemory, SharedMemory, MemoryMapping}; +use sys_util::{GuestAddress, GuestMemory, MemoryMapping, SharedMemory}; #[test] fn test_run() { @@ -25,8 +25,8 @@ fn test_run() { let mut mem = SharedMemory::new(None).expect("failed to create shared memory"); mem.set_size(mem_size) .expect("failed to set shared memory size"); - let mmap = MemoryMapping::from_fd(&mem, mem_size as usize) - .expect("failed to create memory mapping"); + let mmap = + MemoryMapping::from_fd(&mem, mem_size as usize).expect("failed to create memory mapping"); mmap.write_slice(&code[..], load_addr.offset() as usize) .expect("Writing code to memory failed."); @@ -46,13 +46,14 @@ fn test_run() { vcpu_regs.rsi = 0x8000; vcpu_regs.rbx = 0x12; vcpu.set_regs(&vcpu_regs).expect("set regs failed"); - let slot = vm.add_device_memory(GuestAddress(0), - MemoryMapping::from_fd(&mem, mem_size as usize) - .expect("failed to create memory mapping"), - false, - true) - .expect("failed to register memory"); - + let slot = vm + .add_device_memory( + GuestAddress(0), + MemoryMapping::from_fd(&mem, mem_size as usize) + .expect("failed to create memory mapping"), + false, + true, + ).expect("failed to register memory"); loop { match vcpu.run().expect("run failed") { @@ -66,6 +67,8 @@ fn test_run() { .expect("failed to get dirty log"); // Tests the 9th page was written to. assert_eq!(dirty_log[1], 0x1); - assert_eq!(mmap.read_obj::<u64>(vcpu_regs.rsi as usize).unwrap(), - vcpu_regs.rbx); + assert_eq!( + mmap.read_obj::<u64>(vcpu_regs.rsi as usize).unwrap(), + vcpu_regs.rbx + ); } diff --git a/kvm/tests/read_only_memory.rs b/kvm/tests/read_only_memory.rs index 50f76f0..68d0c45 100644 --- a/kvm/tests/read_only_memory.rs +++ b/kvm/tests/read_only_memory.rs @@ -4,13 +4,13 @@ #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -extern crate sys_util; -extern crate kvm_sys; extern crate kvm; +extern crate kvm_sys; +extern crate sys_util; use kvm::*; use kvm_sys::kvm_regs; -use sys_util::{GuestAddress, GuestMemory, SharedMemory, MemoryMapping}; +use sys_util::{GuestAddress, GuestMemory, MemoryMapping, SharedMemory}; #[test] fn test_run() { @@ -49,12 +49,12 @@ fn test_run() { vcpu_regs.rax = 0x66; vcpu_regs.rbx = 0; vcpu.set_regs(&vcpu_regs).expect("set regs failed"); - vm.add_device_memory(GuestAddress(0), - MemoryMapping::from_fd(&mem, mem_size as usize) - .expect("failed to create memory mapping"), + vm.add_device_memory( + GuestAddress(0), + MemoryMapping::from_fd(&mem, mem_size as usize).expect("failed to create memory mapping"), + false, false, - false) - .expect("failed to register memory"); + ).expect("failed to register memory"); // Give some read only memory for the test code to read from and force a vcpu exit when it reads // from it. @@ -66,12 +66,12 @@ fn test_run() { mmap_ro .write_obj(vcpu_regs.rax as u8, 0) .expect("failed writing data to ro memory"); - vm.add_device_memory(GuestAddress(vcpu_sregs.es.base), - MemoryMapping::from_fd(&mem_ro, 0x1000) - .expect("failed to create memory mapping"), + vm.add_device_memory( + GuestAddress(vcpu_sregs.es.base), + MemoryMapping::from_fd(&mem_ro, 0x1000).expect("failed to create memory mapping"), true, - false) - .expect("failed to register memory"); + false, + ).expect("failed to register memory"); // Ensure we get exactly 1 exit from attempting to write to read only memory. let mut exits = 0; @@ -91,8 +91,10 @@ fn test_run() { // Check that exactly 1 attempt to write to read only memory was made, and that the memory is // unchanged after that attempt. assert_eq!(exits, 1); - assert_eq!(mmap_ro - .read_obj::<u8>(0) - .expect("failed to read data from ro memory"), - vcpu_regs.rax as u8); + assert_eq!( + mmap_ro + .read_obj::<u8>(0) + .expect("failed to read data from ro memory"), + vcpu_regs.rax as u8 + ); } diff --git a/kvm/tests/real_run_adder.rs b/kvm/tests/real_run_adder.rs index 26b1add..e3ce7ac 100644 --- a/kvm/tests/real_run_adder.rs +++ b/kvm/tests/real_run_adder.rs @@ -4,9 +4,9 @@ #![cfg(any(target_arch = "x86", target_arch = "x86_64"))] -extern crate sys_util; -extern crate kvm_sys; extern crate kvm; +extern crate kvm_sys; +extern crate sys_util; use kvm::*; use kvm_sys::kvm_regs; @@ -17,13 +17,13 @@ fn test_run() { // This example based on https://lwn.net/Articles/658511/ let code = [ 0xba, 0xf8, 0x03, /* mov $0x3f8, %dx */ - 0x00, 0xd8, /* add %bl, %al */ - 0x04, '0' as u8, /* add $'0', %al */ - 0xee, /* out %al, (%dx) */ + 0x00, 0xd8, /* add %bl, %al */ + 0x04, '0' as u8, /* add $'0', %al */ + 0xee, /* out %al, (%dx) */ 0xb0, '\n' as u8, /* mov $'\n', %al */ - 0xee, /* out %al, (%dx) */ + 0xee, /* out %al, (%dx) */ 0x2e, 0xc6, 0x06, 0xf1, 0x10, 0x13, /* movb $0x13, %cs:0xf1 */ - 0xf4, /* hlt */ + 0xf4, /* hlt */ ]; let mem_size = 0x1000; @@ -58,16 +58,16 @@ fn test_run() { VcpuExit::IoOut(0x3f8, data) => { assert_eq!(data.len(), 1); out.push(data[0] as char); - }, + } VcpuExit::Hlt => break, r => panic!("unexpected exit reason: {:?}", r), } } assert_eq!(out, "9\n"); - let result: u8 = - vm.get_memory() - .read_obj_from_addr(load_addr.checked_add(0xf1).unwrap()) - .expect("Error reading the result."); + let result: u8 = vm + .get_memory() + .read_obj_from_addr(load_addr.checked_add(0xf1).unwrap()) + .expect("Error reading the result."); assert_eq!(result, 0x13); } diff --git a/kvm_sys/src/aarch64/bindings.rs b/kvm_sys/src/aarch64/bindings.rs index 4da2d9b..4fdbe27 100644 --- a/kvm_sys/src/aarch64/bindings.rs +++ b/kvm_sys/src/aarch64/bindings.rs @@ -1257,7 +1257,9 @@ fn bindgen_test_layout_kvm_memory_region() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_memory_region>())).guest_phys_addr as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_memory_region>())).guest_phys_addr as *const _ as usize + }, 8usize, concat!( "Offset of field: ", @@ -1299,7 +1301,9 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { concat!("Alignment of ", stringify!(kvm_userspace_memory_region)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_userspace_memory_region>())).slot as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).slot as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -1309,7 +1313,9 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_userspace_memory_region>())).flags as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).flags as *const _ as usize + }, 4usize, concat!( "Offset of field: ", @@ -1320,8 +1326,8 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_userspace_memory_region>())).guest_phys_addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).guest_phys_addr as *const _ + as usize }, 8usize, concat!( @@ -1345,8 +1351,8 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_userspace_memory_region>())).userspace_addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).userspace_addr as *const _ + as usize }, 24usize, concat!( @@ -1393,7 +1399,9 @@ fn bindgen_test_layout_kvm_irq_level__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_irq_level__bindgen_ty_1>())).status as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_irq_level__bindgen_ty_1>())).status as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -1682,7 +1690,7 @@ pub union kvm_run__bindgen_ty_1 { pub eoi: kvm_run__bindgen_ty_1__bindgen_ty_19, pub padding: [::std::os::raw::c_char; 256usize], _bindgen_union_align: [u64; 32usize], -} +} #[test] fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_1() { assert_eq!( @@ -1700,8 +1708,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_1>())) - .hardware_exit_reason as *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_1>())).hardware_exit_reason + as *const _ as usize }, 0usize, concat!( @@ -1769,8 +1777,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_3() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).exception as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).exception as *const _ + as usize }, 0usize, concat!( @@ -1782,8 +1790,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_3() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).error_code as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).error_code as *const _ + as usize }, 4usize, concat!( @@ -1820,8 +1828,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).direction as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).direction as *const _ + as usize }, 0usize, concat!( @@ -1833,8 +1841,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).size as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).size as *const _ + as usize }, 1usize, concat!( @@ -1846,8 +1854,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).port as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).port as *const _ + as usize }, 2usize, concat!( @@ -1859,8 +1867,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).count as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).count as *const _ + as usize }, 4usize, concat!( @@ -1872,8 +1880,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).data_offset as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).data_offset as *const _ + as usize }, 8usize, concat!( @@ -1906,8 +1914,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_5() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_5>())).arch as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_5>())).arch as *const _ + as usize }, 0usize, concat!( @@ -1943,8 +1951,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_6() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).phys_addr as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).phys_addr as *const _ + as usize }, 0usize, concat!( @@ -1956,8 +1964,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_6() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).data as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).data as *const _ + as usize }, 8usize, concat!( @@ -1981,8 +1989,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_6() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).is_write as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).is_write as *const _ + as usize }, 20usize, concat!( @@ -2031,8 +2039,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_7() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).args as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).args as *const _ + as usize }, 8usize, concat!( @@ -2056,8 +2064,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_7() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).longmode as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).longmode as *const _ + as usize }, 64usize, concat!( @@ -2116,8 +2124,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_8() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_8>())).is_write as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_8>())).is_write as *const _ + as usize }, 8usize, concat!( @@ -2164,8 +2172,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_9() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_9>())).icptcode as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_9>())).icptcode as *const _ + as usize }, 0usize, concat!( @@ -2226,8 +2234,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_10() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).trans_exc_code as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).trans_exc_code + as *const _ as usize }, 0usize, concat!( @@ -2239,8 +2247,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_10() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).pgm_code as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).pgm_code as *const _ + as usize }, 8usize, concat!( @@ -2278,8 +2286,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_11() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).dcrn as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).dcrn as *const _ + as usize }, 0usize, concat!( @@ -2291,8 +2299,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_11() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).data as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).data as *const _ + as usize }, 4usize, concat!( @@ -2304,8 +2312,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_11() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).is_write as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).is_write as *const _ + as usize }, 8usize, concat!( @@ -2343,8 +2351,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_12() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).suberror as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).suberror as *const _ + as usize }, 0usize, concat!( @@ -2356,8 +2364,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_12() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).ndata as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).ndata as *const _ + as usize }, 4usize, concat!( @@ -2369,8 +2377,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_12() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).data as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).data as *const _ + as usize }, 8usize, concat!( @@ -2406,8 +2414,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_13() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_13>())).gprs as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_13>())).gprs as *const _ + as usize }, 0usize, concat!( @@ -2457,8 +2465,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_14() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).ret as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).ret as *const _ + as usize }, 8usize, concat!( @@ -2470,8 +2478,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_14() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).args as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).args as *const _ + as usize }, 16usize, concat!( @@ -2512,8 +2520,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_id as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_id + as *const _ as usize }, 0usize, concat!( @@ -2525,8 +2533,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_nr as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_nr + as *const _ as usize }, 2usize, concat!( @@ -2538,8 +2546,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_parm as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_parm as *const _ + as usize }, 4usize, concat!( @@ -2551,8 +2559,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_word as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_word as *const _ + as usize }, 8usize, concat!( @@ -2564,8 +2572,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).ipb as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).ipb as *const _ + as usize }, 12usize, concat!( @@ -2577,8 +2585,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).dequeued as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).dequeued as *const _ + as usize }, 16usize, concat!( @@ -2614,8 +2622,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_16() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_16>())).epr as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_16>())).epr as *const _ + as usize }, 0usize, concat!( @@ -2652,8 +2660,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_17() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).type_ as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).type_ as *const _ + as usize }, 0usize, concat!( @@ -2665,8 +2673,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_17() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).flags as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).flags as *const _ + as usize }, 8usize, concat!( @@ -2707,8 +2715,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).addr as *const _ + as usize }, 0usize, concat!( @@ -2732,8 +2740,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).reserved as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).reserved as *const _ + as usize }, 9usize, concat!( @@ -2757,8 +2765,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel1 as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel1 as *const _ + as usize }, 11usize, concat!( @@ -2770,8 +2778,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel2 as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel2 as *const _ + as usize }, 12usize, concat!( @@ -2807,8 +2815,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_19() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_19>())).vector as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_19>())).vector as *const _ + as usize }, 0usize, concat!( @@ -2842,7 +2850,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).fail_entry as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).fail_entry as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -2902,7 +2912,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).tpr_access as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).tpr_access as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -2912,7 +2924,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_sieic as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_sieic as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -2934,7 +2948,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_ucontrol as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_ucontrol as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -2974,7 +2990,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).papr_hcall as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).papr_hcall as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -3004,7 +3022,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).system_event as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).system_event as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -3107,7 +3127,9 @@ fn bindgen_test_layout_kvm_run() { concat!("Alignment of ", stringify!(kvm_run)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run>())).request_interrupt_window as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run>())).request_interrupt_window as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -3422,7 +3444,9 @@ fn bindgen_test_layout_kvm_translation() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_translation>())).physical_address as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_translation>())).physical_address as *const _ as usize + }, 8usize, concat!( "Offset of field: ", @@ -3604,7 +3628,7 @@ pub struct kvm_dirty_log { #[repr(C)] #[derive(Copy, Clone)] pub union kvm_dirty_log__bindgen_ty_1 { - pub dirty_bitmap: *mut::std::os::raw::c_void, + pub dirty_bitmap: *mut ::std::os::raw::c_void, pub padding2: __u64, _bindgen_union_align: u64, } @@ -3622,8 +3646,8 @@ fn bindgen_test_layout_kvm_dirty_log__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_dirty_log__bindgen_ty_1>())).dirty_bitmap as *const _ as - usize + &(*(::std::ptr::null::<kvm_dirty_log__bindgen_ty_1>())).dirty_bitmap as *const _ + as usize }, 0usize, concat!( @@ -4063,7 +4087,9 @@ fn bindgen_test_layout_kvm_s390_pgm_info() { concat!("Alignment of ", stringify!(kvm_s390_pgm_info)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_pgm_info>())).trans_exc_code as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_pgm_info>())).trans_exc_code as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4339,8 +4365,8 @@ fn bindgen_test_layout_kvm_s390_mchk_info() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_s390_mchk_info>())).failing_storage_address as *const _ as - usize + &(*(::std::ptr::null::<kvm_s390_mchk_info>())).failing_storage_address as *const _ + as usize }, 16usize, concat!( @@ -4351,7 +4377,9 @@ fn bindgen_test_layout_kvm_s390_mchk_info() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_mchk_info>())).ext_damage_code as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_mchk_info>())).ext_damage_code as *const _ as usize + }, 24usize, concat!( "Offset of field: ", @@ -4445,7 +4473,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).emerg as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).emerg as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4455,7 +4485,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).extcall as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).extcall as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4465,7 +4497,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).prefix as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).prefix as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4495,7 +4529,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).reserved as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).reserved as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4894,7 +4930,9 @@ fn bindgen_test_layout_kvm_ppc_one_page_size() { concat!("Alignment of ", stringify!(kvm_ppc_one_page_size)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_ppc_one_page_size>())).page_shift as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_ppc_one_page_size>())).page_shift as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4946,7 +4984,9 @@ fn bindgen_test_layout_kvm_ppc_one_seg_page_size() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_ppc_one_seg_page_size>())).slb_enc as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_ppc_one_seg_page_size>())).slb_enc as *const _ as usize + }, 4usize, concat!( "Offset of field: ", @@ -5162,8 +5202,8 @@ fn bindgen_test_layout_kvm_irq_routing_s390_adapter() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_addr as *const _ + as usize }, 8usize, concat!( @@ -5187,8 +5227,8 @@ fn bindgen_test_layout_kvm_irq_routing_s390_adapter() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_offset as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_offset as *const _ + as usize }, 24usize, concat!( @@ -5246,8 +5286,8 @@ fn bindgen_test_layout_kvm_irq_routing_entry__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).irqchip as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).irqchip as *const _ + as usize }, 0usize, concat!( @@ -5271,8 +5311,8 @@ fn bindgen_test_layout_kvm_irq_routing_entry__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).adapter as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).adapter as *const _ + as usize }, 0usize, concat!( @@ -6038,8 +6078,8 @@ fn bindgen_test_layout_kvm_assigned_pci_dev__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_assigned_pci_dev__bindgen_ty_1>())).reserved as *const _ as - usize + &(*(::std::ptr::null::<kvm_assigned_pci_dev__bindgen_ty_1>())).reserved as *const _ + as usize }, 0usize, concat!( @@ -6183,7 +6223,9 @@ fn bindgen_test_layout_kvm_assigned_irq() { concat!("Alignment of ", stringify!(kvm_assigned_irq)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_assigned_irq>())).assigned_dev_id as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_assigned_irq>())).assigned_dev_id as *const _ as usize + }, 0usize, concat!( "Offset of field: ", diff --git a/kvm_sys/src/lib.rs b/kvm_sys/src/lib.rs index fc0705a..46d48b4 100644 --- a/kvm_sys/src/lib.rs +++ b/kvm_sys/src/lib.rs @@ -63,13 +63,18 @@ pub mod aarch64 { ioctl_io_nr!(KVM_GET_API_VERSION, KVMIO, 0x00); ioctl_io_nr!(KVM_CREATE_VM, KVMIO, 0x01); ioctl_io_nr!(KVM_CHECK_EXTENSION, KVMIO, 0x03); -ioctl_io_nr!(KVM_GET_VCPU_MMAP_SIZE, KVMIO, 0x04) /* in bytes */; +ioctl_io_nr!(KVM_GET_VCPU_MMAP_SIZE, KVMIO, 0x04); ioctl_iow_nr!(KVM_SET_MEMORY_REGION, KVMIO, 0x40, kvm_memory_region); ioctl_io_nr!(KVM_CREATE_VCPU, KVMIO, 0x41); ioctl_iow_nr!(KVM_GET_DIRTY_LOG, KVMIO, 0x42, kvm_dirty_log); ioctl_io_nr!(KVM_SET_NR_MMU_PAGES, KVMIO, 0x44); ioctl_io_nr!(KVM_GET_NR_MMU_PAGES, KVMIO, 0x45); -ioctl_iow_nr!(KVM_SET_USER_MEMORY_REGION,KVMIO, 0x46, kvm_userspace_memory_region); +ioctl_iow_nr!( + KVM_SET_USER_MEMORY_REGION, + KVMIO, + 0x46, + kvm_userspace_memory_region +); ioctl_io_nr!(KVM_SET_TSS_ADDR, KVMIO, 0x47); ioctl_iow_nr!(KVM_SET_IDENTITY_MAP_ADDR, KVMIO, 0x48, __u64); ioctl_io_nr!(KVM_CREATE_IRQCHIP, KVMIO, 0x60); @@ -78,14 +83,29 @@ ioctl_iowr_nr!(KVM_GET_IRQCHIP, KVMIO, 0x62, kvm_irqchip); ioctl_ior_nr!(KVM_SET_IRQCHIP, KVMIO, 0x63, kvm_irqchip); ioctl_io_nr!(KVM_CREATE_PIT, KVMIO, 0x64); ioctl_iowr_nr!(KVM_IRQ_LINE_STATUS, KVMIO, 0x67, kvm_irq_level); -ioctl_iow_nr!(KVM_REGISTER_COALESCED_MMIO, KVMIO, 0x67, kvm_coalesced_mmio_zone); -ioctl_iow_nr!(KVM_UNREGISTER_COALESCED_MMIO, KVMIO, 0x68, kvm_coalesced_mmio_zone); -ioctl_ior_nr!(KVM_ASSIGN_PCI_DEVICE, KVMIO, 0x69, kvm_assigned_pci_dev); +ioctl_iow_nr!( + KVM_REGISTER_COALESCED_MMIO, + KVMIO, + 0x67, + kvm_coalesced_mmio_zone +); +ioctl_iow_nr!( + KVM_UNREGISTER_COALESCED_MMIO, + KVMIO, + 0x68, + kvm_coalesced_mmio_zone +); +ioctl_ior_nr!(KVM_ASSIGN_PCI_DEVICE, KVMIO, 0x69, kvm_assigned_pci_dev); ioctl_iow_nr!(KVM_ASSIGN_DEV_IRQ, KVMIO, 0x70, kvm_assigned_irq); ioctl_io_nr!(KVM_REINJECT_CONTROL, KVMIO, 0x71); -ioctl_iow_nr!(KVM_DEASSIGN_PCI_DEVICE, KVMIO, 0x72, kvm_assigned_pci_dev); -ioctl_iow_nr!(KVM_ASSIGN_SET_MSIX_NR, KVMIO, 0x73, kvm_assigned_msix_nr); -ioctl_iow_nr!(KVM_ASSIGN_SET_MSIX_ENTRY, KVMIO, 0x74, kvm_assigned_msix_entry); +ioctl_iow_nr!(KVM_DEASSIGN_PCI_DEVICE, KVMIO, 0x72, kvm_assigned_pci_dev); +ioctl_iow_nr!(KVM_ASSIGN_SET_MSIX_NR, KVMIO, 0x73, kvm_assigned_msix_nr); +ioctl_iow_nr!( + KVM_ASSIGN_SET_MSIX_ENTRY, + KVMIO, + 0x74, + kvm_assigned_msix_entry +); ioctl_iow_nr!(KVM_DEASSIGN_DEV_IRQ, KVMIO, 0x75, kvm_assigned_irq); ioctl_iow_nr!(KVM_IRQFD, KVMIO, 0x76, kvm_irqfd); ioctl_iow_nr!(KVM_CREATE_PIT2, KVMIO, 0x77, kvm_pit_config); @@ -95,7 +115,7 @@ ioctl_iow_nr!(KVM_SET_CLOCK, KVMIO, 0x7b, kvm_clock_data); ioctl_ior_nr!(KVM_GET_CLOCK, KVMIO, 0x7c, kvm_clock_data); ioctl_io_nr!(KVM_SET_TSC_KHZ, KVMIO, 0xa2); ioctl_io_nr!(KVM_GET_TSC_KHZ, KVMIO, 0xa3); -ioctl_iow_nr!(KVM_ASSIGN_SET_INTX_MASK, KVMIO, 0xa4, kvm_assigned_pci_dev); +ioctl_iow_nr!(KVM_ASSIGN_SET_INTX_MASK, KVMIO, 0xa4, kvm_assigned_pci_dev); ioctl_iow_nr!(KVM_SIGNAL_MSI, KVMIO, 0xa5, kvm_msi); ioctl_iowr_nr!(KVM_CREATE_DEVICE, KVMIO, 0xe0, kvm_create_device); ioctl_iow_nr!(KVM_SET_DEVICE_ATTR, KVMIO, 0xe1, kvm_device_attr); diff --git a/kvm_sys/src/x86/bindings.rs b/kvm_sys/src/x86/bindings.rs index a0b5985..989e757 100644 --- a/kvm_sys/src/x86/bindings.rs +++ b/kvm_sys/src/x86/bindings.rs @@ -607,7 +607,9 @@ fn bindgen_test_layout_kvm_memory_alias() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_memory_alias>())).guest_phys_addr as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_memory_alias>())).guest_phys_addr as *const _ as usize + }, 8usize, concat!( "Offset of field: ", @@ -627,7 +629,9 @@ fn bindgen_test_layout_kvm_memory_alias() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_memory_alias>())).target_phys_addr as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_memory_alias>())).target_phys_addr as *const _ as usize + }, 24usize, concat!( "Offset of field: ", @@ -780,7 +784,9 @@ fn bindgen_test_layout_kvm_pic_state() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_pic_state>())).rotate_on_auto_eoi as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_pic_state>())).rotate_on_auto_eoi as *const _ as usize + }, 11usize, concat!( "Offset of field: ", @@ -877,8 +883,8 @@ fn bindgen_test_layout_kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1>())).vector as - *const _ as usize + &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1>())).vector + as *const _ as usize }, 0usize, concat!( @@ -890,8 +896,8 @@ fn bindgen_test_layout_kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1>())) - .reserved as *const _ as usize + &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1>())).reserved + as *const _ as usize }, 3usize, concat!( @@ -903,8 +909,8 @@ fn bindgen_test_layout_kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1>())).dest_id as - *const _ as usize + &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1__bindgen_ty_1>())).dest_id + as *const _ as usize }, 7usize, concat!( @@ -1065,7 +1071,9 @@ fn bindgen_test_layout_kvm_ioapic_state__bindgen_ty_1() { concat!("Alignment of ", stringify!(kvm_ioapic_state__bindgen_ty_1)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1>())).bits as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_ioapic_state__bindgen_ty_1>())).bits as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -2450,7 +2458,9 @@ fn bindgen_test_layout_kvm_pit_channel_state() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_pit_channel_state>())).latched_count as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_pit_channel_state>())).latched_count as *const _ as usize + }, 4usize, concat!( "Offset of field: ", @@ -2460,7 +2470,9 @@ fn bindgen_test_layout_kvm_pit_channel_state() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_pit_channel_state>())).count_latched as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_pit_channel_state>())).count_latched as *const _ as usize + }, 6usize, concat!( "Offset of field: ", @@ -2492,7 +2504,9 @@ fn bindgen_test_layout_kvm_pit_channel_state() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_pit_channel_state>())).read_state as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_pit_channel_state>())).read_state as *const _ as usize + }, 9usize, concat!( "Offset of field: ", @@ -2502,7 +2516,9 @@ fn bindgen_test_layout_kvm_pit_channel_state() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_pit_channel_state>())).write_state as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_pit_channel_state>())).write_state as *const _ as usize + }, 10usize, concat!( "Offset of field: ", @@ -2512,7 +2528,9 @@ fn bindgen_test_layout_kvm_pit_channel_state() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_pit_channel_state>())).write_latch as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_pit_channel_state>())).write_latch as *const _ as usize + }, 11usize, concat!( "Offset of field: ", @@ -2771,7 +2789,9 @@ fn bindgen_test_layout_kvm_reinject_control() { concat!("Alignment of ", stringify!(kvm_reinject_control)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_reinject_control>())).pit_reinject as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_reinject_control>())).pit_reinject as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -2836,7 +2856,9 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).nr as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).nr as *const _ as usize + }, 1usize, concat!( "Offset of field: ", @@ -2847,8 +2869,8 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).has_error_code as *const _ as - usize + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).has_error_code as *const _ + as usize }, 2usize, concat!( @@ -2859,7 +2881,9 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).pad as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).pad as *const _ as usize + }, 3usize, concat!( "Offset of field: ", @@ -2870,8 +2894,8 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).error_code as *const _ as - usize + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_1>())).error_code as *const _ + as usize }, 4usize, concat!( @@ -2915,7 +2939,9 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_2() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_2>())).nr as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_2>())).nr as *const _ as usize + }, 1usize, concat!( "Offset of field: ", @@ -2925,7 +2951,9 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_2() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_2>())).soft as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_2>())).soft as *const _ as usize + }, 2usize, concat!( "Offset of field: ", @@ -3004,7 +3032,9 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_3() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_3>())).pad as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_3>())).pad as *const _ as usize + }, 3usize, concat!( "Offset of field: ", @@ -3035,7 +3065,9 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_4() { concat!("Alignment of ", stringify!(kvm_vcpu_events__bindgen_ty_4)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_4>())).smm as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_4>())).smm as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -3058,8 +3090,8 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_4>())).smm_inside_nmi as *const _ as - usize + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_4>())).smm_inside_nmi as *const _ + as usize }, 2usize, concat!( @@ -3071,8 +3103,8 @@ fn bindgen_test_layout_kvm_vcpu_events__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_4>())).latched_init as *const _ as - usize + &(*(::std::ptr::null::<kvm_vcpu_events__bindgen_ty_4>())).latched_init as *const _ + as usize }, 3usize, concat!( @@ -3589,7 +3621,9 @@ fn bindgen_test_layout_kvm_memory_region() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_memory_region>())).guest_phys_addr as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_memory_region>())).guest_phys_addr as *const _ as usize + }, 8usize, concat!( "Offset of field: ", @@ -3631,7 +3665,9 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { concat!("Alignment of ", stringify!(kvm_userspace_memory_region)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_userspace_memory_region>())).slot as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).slot as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -3641,7 +3677,9 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_userspace_memory_region>())).flags as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).flags as *const _ as usize + }, 4usize, concat!( "Offset of field: ", @@ -3652,8 +3690,8 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_userspace_memory_region>())).guest_phys_addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).guest_phys_addr as *const _ + as usize }, 8usize, concat!( @@ -3677,8 +3715,8 @@ fn bindgen_test_layout_kvm_userspace_memory_region() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_userspace_memory_region>())).userspace_addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_userspace_memory_region>())).userspace_addr as *const _ + as usize }, 24usize, concat!( @@ -3725,7 +3763,9 @@ fn bindgen_test_layout_kvm_irq_level__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_irq_level__bindgen_ty_1>())).status as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_irq_level__bindgen_ty_1>())).status as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -3816,7 +3856,9 @@ fn bindgen_test_layout_kvm_irqchip__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_irqchip__bindgen_ty_1>())).ioapic as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_irqchip__bindgen_ty_1>())).ioapic as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -4036,7 +4078,7 @@ pub union kvm_run__bindgen_ty_1 { pub eoi: kvm_run__bindgen_ty_1__bindgen_ty_19, pub padding: [::std::os::raw::c_char; 256usize], _bindgen_union_align: [u64; 32usize], -} +} #[test] fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_1() { assert_eq!( @@ -4054,8 +4096,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_1>())) - .hardware_exit_reason as *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_1>())).hardware_exit_reason + as *const _ as usize }, 0usize, concat!( @@ -4123,8 +4165,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_3() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).exception as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).exception as *const _ + as usize }, 0usize, concat!( @@ -4136,8 +4178,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_3() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).error_code as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_3>())).error_code as *const _ + as usize }, 4usize, concat!( @@ -4174,8 +4216,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).direction as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).direction as *const _ + as usize }, 0usize, concat!( @@ -4187,8 +4229,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).size as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).size as *const _ + as usize }, 1usize, concat!( @@ -4200,8 +4242,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).port as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).port as *const _ + as usize }, 2usize, concat!( @@ -4213,8 +4255,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).count as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).count as *const _ + as usize }, 4usize, concat!( @@ -4226,8 +4268,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_4() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).data_offset as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_4>())).data_offset as *const _ + as usize }, 8usize, concat!( @@ -4260,8 +4302,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_5() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_5>())).arch as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_5>())).arch as *const _ + as usize }, 0usize, concat!( @@ -4297,8 +4339,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_6() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).phys_addr as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).phys_addr as *const _ + as usize }, 0usize, concat!( @@ -4310,8 +4352,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_6() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).data as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).data as *const _ + as usize }, 8usize, concat!( @@ -4335,8 +4377,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_6() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).is_write as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_6>())).is_write as *const _ + as usize }, 20usize, concat!( @@ -4385,8 +4427,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_7() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).args as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).args as *const _ + as usize }, 8usize, concat!( @@ -4410,8 +4452,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_7() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).longmode as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_7>())).longmode as *const _ + as usize }, 64usize, concat!( @@ -4470,8 +4512,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_8() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_8>())).is_write as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_8>())).is_write as *const _ + as usize }, 8usize, concat!( @@ -4518,8 +4560,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_9() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_9>())).icptcode as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_9>())).icptcode as *const _ + as usize }, 0usize, concat!( @@ -4580,8 +4622,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_10() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).trans_exc_code as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).trans_exc_code + as *const _ as usize }, 0usize, concat!( @@ -4593,8 +4635,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_10() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).pgm_code as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_10>())).pgm_code as *const _ + as usize }, 8usize, concat!( @@ -4632,8 +4674,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_11() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).dcrn as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).dcrn as *const _ + as usize }, 0usize, concat!( @@ -4645,8 +4687,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_11() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).data as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).data as *const _ + as usize }, 4usize, concat!( @@ -4658,8 +4700,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_11() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).is_write as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_11>())).is_write as *const _ + as usize }, 8usize, concat!( @@ -4697,8 +4739,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_12() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).suberror as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).suberror as *const _ + as usize }, 0usize, concat!( @@ -4710,8 +4752,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_12() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).ndata as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).ndata as *const _ + as usize }, 4usize, concat!( @@ -4723,8 +4765,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_12() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).data as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_12>())).data as *const _ + as usize }, 8usize, concat!( @@ -4760,8 +4802,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_13() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_13>())).gprs as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_13>())).gprs as *const _ + as usize }, 0usize, concat!( @@ -4811,8 +4853,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_14() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).ret as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).ret as *const _ + as usize }, 8usize, concat!( @@ -4824,8 +4866,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_14() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).args as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_14>())).args as *const _ + as usize }, 16usize, concat!( @@ -4866,8 +4908,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_id as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_id + as *const _ as usize }, 0usize, concat!( @@ -4879,8 +4921,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_nr as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).subchannel_nr + as *const _ as usize }, 2usize, concat!( @@ -4892,8 +4934,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_parm as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_parm as *const _ + as usize }, 4usize, concat!( @@ -4905,8 +4947,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_word as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).io_int_word as *const _ + as usize }, 8usize, concat!( @@ -4918,8 +4960,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).ipb as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).ipb as *const _ + as usize }, 12usize, concat!( @@ -4931,8 +4973,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_15() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).dequeued as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_15>())).dequeued as *const _ + as usize }, 16usize, concat!( @@ -4968,8 +5010,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_16() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_16>())).epr as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_16>())).epr as *const _ + as usize }, 0usize, concat!( @@ -5006,8 +5048,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_17() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).type_ as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).type_ as *const _ + as usize }, 0usize, concat!( @@ -5019,8 +5061,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_17() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).flags as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_17>())).flags as *const _ + as usize }, 8usize, concat!( @@ -5061,8 +5103,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).addr as *const _ + as usize }, 0usize, concat!( @@ -5086,8 +5128,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).reserved as - *const _ as usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).reserved as *const _ + as usize }, 9usize, concat!( @@ -5111,8 +5153,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel1 as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel1 as *const _ + as usize }, 11usize, concat!( @@ -5124,8 +5166,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_18() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel2 as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_18>())).sel2 as *const _ + as usize }, 12usize, concat!( @@ -5161,8 +5203,8 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1__bindgen_ty_19() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_19>())).vector as *const _ as - usize + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1__bindgen_ty_19>())).vector as *const _ + as usize }, 0usize, concat!( @@ -5197,7 +5239,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).fail_entry as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).fail_entry as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5257,7 +5301,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).tpr_access as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).tpr_access as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5267,7 +5313,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_sieic as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_sieic as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5289,7 +5337,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_ucontrol as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).s390_ucontrol as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5329,7 +5379,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).papr_hcall as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).papr_hcall as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5359,7 +5411,9 @@ fn bindgen_test_layout_kvm_run__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).system_event as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run__bindgen_ty_1>())).system_event as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5462,7 +5516,9 @@ fn bindgen_test_layout_kvm_run() { concat!("Alignment of ", stringify!(kvm_run)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_run>())).request_interrupt_window as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_run>())).request_interrupt_window as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -5777,7 +5833,9 @@ fn bindgen_test_layout_kvm_translation() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_translation>())).physical_address as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_translation>())).physical_address as *const _ as usize + }, 8usize, concat!( "Offset of field: ", @@ -5959,7 +6017,7 @@ pub struct kvm_dirty_log { #[repr(C)] #[derive(Copy, Clone)] pub union kvm_dirty_log__bindgen_ty_1 { - pub dirty_bitmap: *mut::std::os::raw::c_void, + pub dirty_bitmap: *mut ::std::os::raw::c_void, pub padding2: __u64, _bindgen_union_align: u64, } @@ -5977,8 +6035,8 @@ fn bindgen_test_layout_kvm_dirty_log__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_dirty_log__bindgen_ty_1>())).dirty_bitmap as *const _ as - usize + &(*(::std::ptr::null::<kvm_dirty_log__bindgen_ty_1>())).dirty_bitmap as *const _ + as usize }, 0usize, concat!( @@ -6418,7 +6476,9 @@ fn bindgen_test_layout_kvm_s390_pgm_info() { concat!("Alignment of ", stringify!(kvm_s390_pgm_info)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_pgm_info>())).trans_exc_code as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_pgm_info>())).trans_exc_code as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -6694,8 +6754,8 @@ fn bindgen_test_layout_kvm_s390_mchk_info() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_s390_mchk_info>())).failing_storage_address as *const _ as - usize + &(*(::std::ptr::null::<kvm_s390_mchk_info>())).failing_storage_address as *const _ + as usize }, 16usize, concat!( @@ -6706,7 +6766,9 @@ fn bindgen_test_layout_kvm_s390_mchk_info() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_mchk_info>())).ext_damage_code as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_mchk_info>())).ext_damage_code as *const _ as usize + }, 24usize, concat!( "Offset of field: ", @@ -6799,7 +6861,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).emerg as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).emerg as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -6809,7 +6873,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).extcall as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).extcall as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -6819,7 +6885,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).prefix as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).prefix as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -6849,7 +6917,9 @@ fn bindgen_test_layout_kvm_s390_irq__bindgen_ty_1() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).reserved as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_s390_irq__bindgen_ty_1>())).reserved as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -7248,7 +7318,9 @@ fn bindgen_test_layout_kvm_ppc_one_page_size() { concat!("Alignment of ", stringify!(kvm_ppc_one_page_size)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_ppc_one_page_size>())).page_shift as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_ppc_one_page_size>())).page_shift as *const _ as usize + }, 0usize, concat!( "Offset of field: ", @@ -7300,7 +7372,9 @@ fn bindgen_test_layout_kvm_ppc_one_seg_page_size() { ) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_ppc_one_seg_page_size>())).slb_enc as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_ppc_one_seg_page_size>())).slb_enc as *const _ as usize + }, 4usize, concat!( "Offset of field: ", @@ -7516,8 +7590,8 @@ fn bindgen_test_layout_kvm_irq_routing_s390_adapter() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_addr as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_addr as *const _ + as usize }, 8usize, concat!( @@ -7541,8 +7615,8 @@ fn bindgen_test_layout_kvm_irq_routing_s390_adapter() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_offset as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_s390_adapter>())).summary_offset as *const _ + as usize }, 24usize, concat!( @@ -7600,8 +7674,8 @@ fn bindgen_test_layout_kvm_irq_routing_entry__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).irqchip as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).irqchip as *const _ + as usize }, 0usize, concat!( @@ -7625,8 +7699,8 @@ fn bindgen_test_layout_kvm_irq_routing_entry__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).adapter as *const _ as - usize + &(*(::std::ptr::null::<kvm_irq_routing_entry__bindgen_ty_1>())).adapter as *const _ + as usize }, 0usize, concat!( @@ -8580,8 +8654,8 @@ fn bindgen_test_layout_kvm_assigned_pci_dev__bindgen_ty_1() { ); assert_eq!( unsafe { - &(*(::std::ptr::null::<kvm_assigned_pci_dev__bindgen_ty_1>())).reserved as *const _ as - usize + &(*(::std::ptr::null::<kvm_assigned_pci_dev__bindgen_ty_1>())).reserved as *const _ + as usize }, 0usize, concat!( @@ -8725,7 +8799,9 @@ fn bindgen_test_layout_kvm_assigned_irq() { concat!("Alignment of ", stringify!(kvm_assigned_irq)) ); assert_eq!( - unsafe { &(*(::std::ptr::null::<kvm_assigned_irq>())).assigned_dev_id as *const _ as usize }, + unsafe { + &(*(::std::ptr::null::<kvm_assigned_irq>())).assigned_dev_id as *const _ as usize + }, 0usize, concat!( "Offset of field: ", diff --git a/kvm_sys/tests/sanity.rs b/kvm_sys/tests/sanity.rs index f9d0144..2dd1326 100644 --- a/kvm_sys/tests/sanity.rs +++ b/kvm_sys/tests/sanity.rs @@ -5,7 +5,7 @@ extern crate kvm_sys; extern crate libc; -use libc::{ioctl, open, c_char, O_RDWR}; +use libc::{c_char, ioctl, open, O_RDWR}; use kvm_sys::*; diff --git a/net_sys/src/if_tun.rs b/net_sys/src/if_tun.rs index 857eaa7..b26ea06 100644 --- a/net_sys/src/if_tun.rs +++ b/net_sys/src/if_tun.rs @@ -3,13 +3,15 @@ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>); -impl <T> __IncompleteArrayField<T> { +impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData) } #[inline] - pub unsafe fn as_ptr(&self) -> *const T { ::std::mem::transmute(self) } + pub unsafe fn as_ptr(&self) -> *const T { + ::std::mem::transmute(self) + } #[inline] pub unsafe fn as_mut_ptr(&mut self) -> *mut T { ::std::mem::transmute(self) @@ -23,16 +25,18 @@ impl <T> __IncompleteArrayField<T> { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } -impl <T> ::std::fmt::Debug for __IncompleteArrayField<T> { +impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } -impl <T> ::std::clone::Clone for __IncompleteArrayField<T> { +impl<T> ::std::clone::Clone for __IncompleteArrayField<T> { #[inline] - fn clone(&self) -> Self { Self::new() } + fn clone(&self) -> Self { + Self::new() + } } -impl <T> ::std::marker::Copy for __IncompleteArrayField<T> { } +impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {} pub const __BITS_PER_LONG: ::std::os::raw::c_uint = 64; pub const __FD_SETSIZE: ::std::os::raw::c_uint = 1024; pub const ETH_ALEN: ::std::os::raw::c_uint = 6; @@ -222,18 +226,31 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>() , 128usize , concat ! - ( "Size of: " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (::std::mem::align_of::<__kernel_fd_set>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fd_set ) ) . fds_bits as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fd_set ) , - "::" , stringify ! ( fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_sighandler_t = ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int)>; @@ -264,18 +281,31 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (::std::mem::align_of::<__kernel_fsid_t>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fsid_t ) ) . val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fsid_t ) , - "::" , stringify ! ( val ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_off_t = __kernel_long_t; pub type __kernel_loff_t = ::std::os::raw::c_longlong; @@ -303,28 +333,51 @@ pub struct ethhdr { } #[test] fn bindgen_test_layout_ethhdr() { - assert_eq!(::std::mem::size_of::<ethhdr>() , 14usize , concat ! ( - "Size of: " , stringify ! ( ethhdr ) )); - assert_eq! (::std::mem::align_of::<ethhdr>() , 1usize , concat ! ( - "Alignment of " , stringify ! ( ethhdr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ethhdr ) ) . h_dest as * const _ as usize - } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ethhdr ) , "::" , - stringify ! ( h_dest ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ethhdr ) ) . h_source as * const _ as - usize } , 6usize , concat ! ( - "Alignment of field: " , stringify ! ( ethhdr ) , "::" , - stringify ! ( h_source ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ethhdr ) ) . h_proto as * const _ as - usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( ethhdr ) , "::" , - stringify ! ( h_proto ) )); + assert_eq!( + ::std::mem::size_of::<ethhdr>(), + 14usize, + concat!("Size of: ", stringify!(ethhdr)) + ); + assert_eq!( + ::std::mem::align_of::<ethhdr>(), + 1usize, + concat!("Alignment of ", stringify!(ethhdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const ethhdr)).h_dest as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ethhdr), + "::", + stringify!(h_dest) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ethhdr)).h_source as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(ethhdr), + "::", + stringify!(h_source) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ethhdr)).h_proto as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(ethhdr), + "::", + stringify!(h_proto) + ) + ); } impl Clone for ethhdr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -336,33 +389,61 @@ pub struct sock_filter { } #[test] fn bindgen_test_layout_sock_filter() { - assert_eq!(::std::mem::size_of::<sock_filter>() , 8usize , concat ! ( - "Size of: " , stringify ! ( sock_filter ) )); - assert_eq! (::std::mem::align_of::<sock_filter>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( sock_filter ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sock_filter ) ) . code as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( sock_filter ) , "::" , - stringify ! ( code ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sock_filter ) ) . jt as * const _ as - usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( sock_filter ) , "::" , - stringify ! ( jt ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sock_filter ) ) . jf as * const _ as - usize } , 3usize , concat ! ( - "Alignment of field: " , stringify ! ( sock_filter ) , "::" , - stringify ! ( jf ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sock_filter ) ) . k as * const _ as usize - } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( sock_filter ) , "::" , - stringify ! ( k ) )); + assert_eq!( + ::std::mem::size_of::<sock_filter>(), + 8usize, + concat!("Size of: ", stringify!(sock_filter)) + ); + assert_eq!( + ::std::mem::align_of::<sock_filter>(), + 4usize, + concat!("Alignment of ", stringify!(sock_filter)) + ); + assert_eq!( + unsafe { &(*(0 as *const sock_filter)).code as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sock_filter), + "::", + stringify!(code) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sock_filter)).jt as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(sock_filter), + "::", + stringify!(jt) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sock_filter)).jf as *const _ as usize }, + 3usize, + concat!( + "Alignment of field: ", + stringify!(sock_filter), + "::", + stringify!(jf) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sock_filter)).k as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(sock_filter), + "::", + stringify!(k) + ) + ); } impl Clone for sock_filter { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -372,26 +453,46 @@ pub struct sock_fprog { } #[test] fn bindgen_test_layout_sock_fprog() { - assert_eq!(::std::mem::size_of::<sock_fprog>() , 16usize , concat ! ( - "Size of: " , stringify ! ( sock_fprog ) )); - assert_eq! (::std::mem::align_of::<sock_fprog>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( sock_fprog ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sock_fprog ) ) . len as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( sock_fprog ) , "::" , - stringify ! ( len ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sock_fprog ) ) . filter as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( sock_fprog ) , "::" , - stringify ! ( filter ) )); + assert_eq!( + ::std::mem::size_of::<sock_fprog>(), + 16usize, + concat!("Size of: ", stringify!(sock_fprog)) + ); + assert_eq!( + ::std::mem::align_of::<sock_fprog>(), + 8usize, + concat!("Alignment of ", stringify!(sock_fprog)) + ); + assert_eq!( + unsafe { &(*(0 as *const sock_fprog)).len as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sock_fprog), + "::", + stringify!(len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sock_fprog)).filter as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(sock_fprog), + "::", + stringify!(filter) + ) + ); } impl Clone for sock_fprog { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for sock_fprog { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -401,23 +502,41 @@ pub struct tun_pi { } #[test] fn bindgen_test_layout_tun_pi() { - assert_eq!(::std::mem::size_of::<tun_pi>() , 4usize , concat ! ( - "Size of: " , stringify ! ( tun_pi ) )); - assert_eq! (::std::mem::align_of::<tun_pi>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( tun_pi ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const tun_pi ) ) . flags as * const _ as usize - } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( tun_pi ) , "::" , - stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const tun_pi ) ) . proto as * const _ as usize - } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( tun_pi ) , "::" , - stringify ! ( proto ) )); + assert_eq!( + ::std::mem::size_of::<tun_pi>(), + 4usize, + concat!("Size of: ", stringify!(tun_pi)) + ); + assert_eq!( + ::std::mem::align_of::<tun_pi>(), + 2usize, + concat!("Alignment of ", stringify!(tun_pi)) + ); + assert_eq!( + unsafe { &(*(0 as *const tun_pi)).flags as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(tun_pi), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const tun_pi)).proto as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(tun_pi), + "::", + stringify!(proto) + ) + ); } impl Clone for tun_pi { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -428,26 +547,49 @@ pub struct tun_filter { } #[test] fn bindgen_test_layout_tun_filter() { - assert_eq!(::std::mem::size_of::<tun_filter>() , 4usize , concat ! ( - "Size of: " , stringify ! ( tun_filter ) )); - assert_eq! (::std::mem::align_of::<tun_filter>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( tun_filter ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const tun_filter ) ) . flags as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( tun_filter ) , "::" , - stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const tun_filter ) ) . count as * const _ as - usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( tun_filter ) , "::" , - stringify ! ( count ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const tun_filter ) ) . addr as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( tun_filter ) , "::" , - stringify ! ( addr ) )); + assert_eq!( + ::std::mem::size_of::<tun_filter>(), + 4usize, + concat!("Size of: ", stringify!(tun_filter)) + ); + assert_eq!( + ::std::mem::align_of::<tun_filter>(), + 2usize, + concat!("Alignment of ", stringify!(tun_filter)) + ); + assert_eq!( + unsafe { &(*(0 as *const tun_filter)).flags as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(tun_filter), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const tun_filter)).count as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(tun_filter), + "::", + stringify!(count) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const tun_filter)).addr as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(tun_filter), + "::", + stringify!(addr) + ) + ); } impl Clone for tun_filter { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } diff --git a/net_sys/src/iff.rs b/net_sys/src/iff.rs index 21feced..57357ae 100644 --- a/net_sys/src/iff.rs +++ b/net_sys/src/iff.rs @@ -3,13 +3,15 @@ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>); -impl <T> __IncompleteArrayField<T> { +impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData) } #[inline] - pub unsafe fn as_ptr(&self) -> *const T { ::std::mem::transmute(self) } + pub unsafe fn as_ptr(&self) -> *const T { + ::std::mem::transmute(self) + } #[inline] pub unsafe fn as_mut_ptr(&mut self) -> *mut T { ::std::mem::transmute(self) @@ -23,36 +25,48 @@ impl <T> __IncompleteArrayField<T> { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } -impl <T> ::std::fmt::Debug for __IncompleteArrayField<T> { +impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } -impl <T> ::std::clone::Clone for __IncompleteArrayField<T> { +impl<T> ::std::clone::Clone for __IncompleteArrayField<T> { #[inline] - fn clone(&self) -> Self { Self::new() } + fn clone(&self) -> Self { + Self::new() + } } -impl <T> ::std::marker::Copy for __IncompleteArrayField<T> { } +impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {} #[repr(C)] pub struct __BindgenUnionField<T>(::std::marker::PhantomData<T>); -impl <T> __BindgenUnionField<T> { +impl<T> __BindgenUnionField<T> { #[inline] - pub fn new() -> Self { __BindgenUnionField(::std::marker::PhantomData) } + pub fn new() -> Self { + __BindgenUnionField(::std::marker::PhantomData) + } #[inline] - pub unsafe fn as_ref(&self) -> &T { ::std::mem::transmute(self) } + pub unsafe fn as_ref(&self) -> &T { + ::std::mem::transmute(self) + } #[inline] - pub unsafe fn as_mut(&mut self) -> &mut T { ::std::mem::transmute(self) } + pub unsafe fn as_mut(&mut self) -> &mut T { + ::std::mem::transmute(self) + } } -impl <T> ::std::default::Default for __BindgenUnionField<T> { +impl<T> ::std::default::Default for __BindgenUnionField<T> { #[inline] - fn default() -> Self { Self::new() } + fn default() -> Self { + Self::new() + } } -impl <T> ::std::clone::Clone for __BindgenUnionField<T> { +impl<T> ::std::clone::Clone for __BindgenUnionField<T> { #[inline] - fn clone(&self) -> Self { Self::new() } + fn clone(&self) -> Self { + Self::new() + } } -impl <T> ::std::marker::Copy for __BindgenUnionField<T> { } -impl <T> ::std::fmt::Debug for __BindgenUnionField<T> { +impl<T> ::std::marker::Copy for __BindgenUnionField<T> {} +impl<T> ::std::fmt::Debug for __BindgenUnionField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fmt.write_str("__BindgenUnionField") } @@ -379,18 +393,31 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>() , 128usize , concat ! - ( "Size of: " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (::std::mem::align_of::<__kernel_fd_set>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fd_set ) ) . fds_bits as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fd_set ) , - "::" , stringify ! ( fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_sighandler_t = ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int)>; @@ -421,18 +448,31 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (::std::mem::align_of::<__kernel_fsid_t>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fsid_t ) ) . val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fsid_t ) , - "::" , stringify ! ( val ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_off_t = __kernel_long_t; pub type __kernel_loff_t = ::std::os::raw::c_longlong; @@ -460,28 +500,41 @@ pub struct __kernel_sockaddr_storage { } #[test] fn bindgen_test_layout___kernel_sockaddr_storage() { - assert_eq!(::std::mem::size_of::<__kernel_sockaddr_storage>() , 128usize , - concat ! ( - "Size of: " , stringify ! ( __kernel_sockaddr_storage ) )); - assert_eq! (::std::mem::align_of::<__kernel_sockaddr_storage>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( __kernel_sockaddr_storage ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_sockaddr_storage ) ) . ss_family - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - __kernel_sockaddr_storage ) , "::" , stringify ! ( ss_family ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_sockaddr_storage ) ) . __data as - * const _ as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( - __kernel_sockaddr_storage ) , "::" , stringify ! ( __data ) - )); + assert_eq!( + ::std::mem::size_of::<__kernel_sockaddr_storage>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_sockaddr_storage)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_sockaddr_storage>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_sockaddr_storage)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_sockaddr_storage)).ss_family as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_sockaddr_storage), + "::", + stringify!(ss_family) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_sockaddr_storage)).__data as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_sockaddr_storage), + "::", + stringify!(__data) + ) + ); } impl Default for __kernel_sockaddr_storage { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } pub type __u_char = ::std::os::raw::c_uchar; pub type __u_short = ::std::os::raw::c_ushort; @@ -514,18 +567,31 @@ pub struct __fsid_t { } #[test] fn bindgen_test_layout___fsid_t() { - assert_eq!(::std::mem::size_of::<__fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __fsid_t ) )); - assert_eq! (::std::mem::align_of::<__fsid_t>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( __fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __fsid_t ) ) . __val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __fsid_t ) , "::" , - stringify ! ( __val ) )); + assert_eq!( + ::std::mem::size_of::<__fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __fsid_t)).__val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__fsid_t), + "::", + stringify!(__val) + ) + ); } impl Clone for __fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __clock_t = ::std::os::raw::c_long; pub type __rlim_t = ::std::os::raw::c_ulong; @@ -594,18 +660,31 @@ pub struct __sigset_t { } #[test] fn bindgen_test_layout___sigset_t() { - assert_eq!(::std::mem::size_of::<__sigset_t>() , 128usize , concat ! ( - "Size of: " , stringify ! ( __sigset_t ) )); - assert_eq! (::std::mem::align_of::<__sigset_t>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( __sigset_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __sigset_t ) ) . __val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __sigset_t ) , "::" , - stringify ! ( __val ) )); + assert_eq!( + ::std::mem::size_of::<__sigset_t>(), + 128usize, + concat!("Size of: ", stringify!(__sigset_t)) + ); + assert_eq!( + ::std::mem::align_of::<__sigset_t>(), + 8usize, + concat!("Alignment of ", stringify!(__sigset_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __sigset_t)).__val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__sigset_t), + "::", + stringify!(__val) + ) + ); } impl Clone for __sigset_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type sigset_t = __sigset_t; #[repr(C)] @@ -616,23 +695,41 @@ pub struct timespec { } #[test] fn bindgen_test_layout_timespec() { - assert_eq!(::std::mem::size_of::<timespec>() , 16usize , concat ! ( - "Size of: " , stringify ! ( timespec ) )); - assert_eq! (::std::mem::align_of::<timespec>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( timespec ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const timespec ) ) . tv_sec as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( timespec ) , "::" , - stringify ! ( tv_sec ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const timespec ) ) . tv_nsec as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( timespec ) , "::" , - stringify ! ( tv_nsec ) )); + assert_eq!( + ::std::mem::size_of::<timespec>(), + 16usize, + concat!("Size of: ", stringify!(timespec)) + ); + assert_eq!( + ::std::mem::align_of::<timespec>(), + 8usize, + concat!("Alignment of ", stringify!(timespec)) + ); + assert_eq!( + unsafe { &(*(0 as *const timespec)).tv_sec as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(timespec), + "::", + stringify!(tv_sec) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const timespec)).tv_nsec as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(timespec), + "::", + stringify!(tv_nsec) + ) + ); } impl Clone for timespec { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -642,23 +739,41 @@ pub struct timeval { } #[test] fn bindgen_test_layout_timeval() { - assert_eq!(::std::mem::size_of::<timeval>() , 16usize , concat ! ( - "Size of: " , stringify ! ( timeval ) )); - assert_eq! (::std::mem::align_of::<timeval>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( timeval ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const timeval ) ) . tv_sec as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( timeval ) , "::" , - stringify ! ( tv_sec ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const timeval ) ) . tv_usec as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( timeval ) , "::" , - stringify ! ( tv_usec ) )); + assert_eq!( + ::std::mem::size_of::<timeval>(), + 16usize, + concat!("Size of: ", stringify!(timeval)) + ); + assert_eq!( + ::std::mem::align_of::<timeval>(), + 8usize, + concat!("Alignment of ", stringify!(timeval)) + ); + assert_eq!( + unsafe { &(*(0 as *const timeval)).tv_sec as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(timeval), + "::", + stringify!(tv_sec) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const timeval)).tv_usec as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(timeval), + "::", + stringify!(tv_usec) + ) + ); } impl Clone for timeval { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type suseconds_t = __suseconds_t; pub type __fd_mask = ::std::os::raw::c_long; @@ -669,43 +784,63 @@ pub struct fd_set { } #[test] fn bindgen_test_layout_fd_set() { - assert_eq!(::std::mem::size_of::<fd_set>() , 128usize , concat ! ( - "Size of: " , stringify ! ( fd_set ) )); - assert_eq! (::std::mem::align_of::<fd_set>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fd_set ) ) . __fds_bits as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( fd_set ) , "::" , - stringify ! ( __fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<fd_set>(), + 128usize, + concat!("Size of: ", stringify!(fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const fd_set)).__fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(fd_set), + "::", + stringify!(__fds_bits) + ) + ); } impl Clone for fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type fd_mask = __fd_mask; extern "C" { - pub fn select(__nfds: ::std::os::raw::c_int, __readfds: *mut fd_set, - __writefds: *mut fd_set, __exceptfds: *mut fd_set, - __timeout: *mut timeval) -> ::std::os::raw::c_int; + pub fn select( + __nfds: ::std::os::raw::c_int, + __readfds: *mut fd_set, + __writefds: *mut fd_set, + __exceptfds: *mut fd_set, + __timeout: *mut timeval, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn pselect(__nfds: ::std::os::raw::c_int, __readfds: *mut fd_set, - __writefds: *mut fd_set, __exceptfds: *mut fd_set, - __timeout: *const timespec, __sigmask: *const __sigset_t) - -> ::std::os::raw::c_int; + pub fn pselect( + __nfds: ::std::os::raw::c_int, + __readfds: *mut fd_set, + __writefds: *mut fd_set, + __exceptfds: *mut fd_set, + __timeout: *const timespec, + __sigmask: *const __sigset_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn gnu_dev_major(__dev: ::std::os::raw::c_ulonglong) - -> ::std::os::raw::c_uint; + pub fn gnu_dev_major(__dev: ::std::os::raw::c_ulonglong) -> ::std::os::raw::c_uint; } extern "C" { - pub fn gnu_dev_minor(__dev: ::std::os::raw::c_ulonglong) - -> ::std::os::raw::c_uint; + pub fn gnu_dev_minor(__dev: ::std::os::raw::c_ulonglong) -> ::std::os::raw::c_uint; } extern "C" { - pub fn gnu_dev_makedev(__major: ::std::os::raw::c_uint, - __minor: ::std::os::raw::c_uint) - -> ::std::os::raw::c_ulonglong; + pub fn gnu_dev_makedev( + __major: ::std::os::raw::c_uint, + __minor: ::std::os::raw::c_uint, + ) -> ::std::os::raw::c_ulonglong; } pub type blksize_t = __blksize_t; pub type blkcnt_t = __blkcnt_t; @@ -721,23 +856,41 @@ pub struct pthread_attr_t { } #[test] fn bindgen_test_layout_pthread_attr_t() { - assert_eq!(::std::mem::size_of::<pthread_attr_t>() , 56usize , concat ! ( - "Size of: " , stringify ! ( pthread_attr_t ) )); - assert_eq! (::std::mem::align_of::<pthread_attr_t>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( pthread_attr_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_attr_t ) ) . __size as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_attr_t ) , "::" - , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_attr_t ) ) . __align as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_attr_t ) , "::" - , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_attr_t>(), + 56usize, + concat!("Size of: ", stringify!(pthread_attr_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_attr_t>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_attr_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_attr_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_attr_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_attr_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_attr_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_attr_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -747,28 +900,46 @@ pub struct __pthread_internal_list { } #[test] fn bindgen_test_layout___pthread_internal_list() { - assert_eq!(::std::mem::size_of::<__pthread_internal_list>() , 16usize , - concat ! ( - "Size of: " , stringify ! ( __pthread_internal_list ) )); - assert_eq! (::std::mem::align_of::<__pthread_internal_list>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( __pthread_internal_list ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __pthread_internal_list ) ) . __prev as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __pthread_internal_list - ) , "::" , stringify ! ( __prev ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __pthread_internal_list ) ) . __next as * - const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( __pthread_internal_list - ) , "::" , stringify ! ( __next ) )); + assert_eq!( + ::std::mem::size_of::<__pthread_internal_list>(), + 16usize, + concat!("Size of: ", stringify!(__pthread_internal_list)) + ); + assert_eq!( + ::std::mem::align_of::<__pthread_internal_list>(), + 8usize, + concat!("Alignment of ", stringify!(__pthread_internal_list)) + ); + assert_eq!( + unsafe { &(*(0 as *const __pthread_internal_list)).__prev as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__pthread_internal_list), + "::", + stringify!(__prev) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const __pthread_internal_list)).__next as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(__pthread_internal_list), + "::", + stringify!(__next) + ) + ); } impl Clone for __pthread_internal_list { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for __pthread_internal_list { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } pub type __pthread_list_t = __pthread_internal_list; #[repr(C)] @@ -793,93 +964,161 @@ pub struct pthread_mutex_t___pthread_mutex_s { } #[test] fn bindgen_test_layout_pthread_mutex_t___pthread_mutex_s() { - assert_eq!(::std::mem::size_of::<pthread_mutex_t___pthread_mutex_s>() , - 40usize , concat ! ( - "Size of: " , stringify ! ( pthread_mutex_t___pthread_mutex_s ) - )); - assert_eq! (::std::mem::align_of::<pthread_mutex_t___pthread_mutex_s>() , - 8usize , concat ! ( - "Alignment of " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __lock as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __lock ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __count as * const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __count ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __owner as * const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __owner ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __nusers as * const _ as usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __nusers ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __kind as * const _ as usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __kind ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __spins as * const _ as usize } , 20usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __spins ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __elision as * const _ as usize } , 22usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __elision ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t___pthread_mutex_s ) ) . - __list as * const _ as usize } , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_mutex_t___pthread_mutex_s ) , "::" , stringify ! ( - __list ) )); + assert_eq!( + ::std::mem::size_of::<pthread_mutex_t___pthread_mutex_s>(), + 40usize, + concat!("Size of: ", stringify!(pthread_mutex_t___pthread_mutex_s)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_mutex_t___pthread_mutex_s>(), + 8usize, + concat!( + "Alignment of ", + stringify!(pthread_mutex_t___pthread_mutex_s) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__lock as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__lock) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__count as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__count) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__owner as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__owner) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__nusers as *const _ as usize + }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__nusers) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__kind as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__kind) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__spins as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__spins) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__elision as *const _ as usize + }, + 22usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__elision) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t___pthread_mutex_s)).__list as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t___pthread_mutex_s), + "::", + stringify!(__list) + ) + ); } impl Clone for pthread_mutex_t___pthread_mutex_s { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for pthread_mutex_t___pthread_mutex_s { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[test] fn bindgen_test_layout_pthread_mutex_t() { - assert_eq!(::std::mem::size_of::<pthread_mutex_t>() , 40usize , concat ! ( - "Size of: " , stringify ! ( pthread_mutex_t ) )); - assert_eq! (::std::mem::align_of::<pthread_mutex_t>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( pthread_mutex_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t ) ) . __data as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_mutex_t ) , - "::" , stringify ! ( __data ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t ) ) . __size as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_mutex_t ) , - "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutex_t ) ) . __align as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_mutex_t ) , - "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_mutex_t>(), + 40usize, + concat!("Size of: ", stringify!(pthread_mutex_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_mutex_t>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_mutex_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t)).__data as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t), + "::", + stringify!(__data) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutex_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutex_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_mutex_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -890,24 +1129,41 @@ pub struct pthread_mutexattr_t { } #[test] fn bindgen_test_layout_pthread_mutexattr_t() { - assert_eq!(::std::mem::size_of::<pthread_mutexattr_t>() , 4usize , concat - ! ( "Size of: " , stringify ! ( pthread_mutexattr_t ) )); - assert_eq! (::std::mem::align_of::<pthread_mutexattr_t>() , 4usize , - concat ! ( - "Alignment of " , stringify ! ( pthread_mutexattr_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutexattr_t ) ) . __size as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_mutexattr_t ) , - "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_mutexattr_t ) ) . __align as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_mutexattr_t ) , - "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_mutexattr_t>(), + 4usize, + concat!("Size of: ", stringify!(pthread_mutexattr_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_mutexattr_t>(), + 4usize, + concat!("Alignment of ", stringify!(pthread_mutexattr_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutexattr_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutexattr_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_mutexattr_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_mutexattr_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_mutexattr_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -931,92 +1187,156 @@ pub struct pthread_cond_t__bindgen_ty_1 { } #[test] fn bindgen_test_layout_pthread_cond_t__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<pthread_cond_t__bindgen_ty_1>() , 48usize - , concat ! ( - "Size of: " , stringify ! ( pthread_cond_t__bindgen_ty_1 ) )); - assert_eq! (::std::mem::align_of::<pthread_cond_t__bindgen_ty_1>() , - 8usize , concat ! ( - "Alignment of " , stringify ! ( pthread_cond_t__bindgen_ty_1 ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . __lock - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( __lock ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __futex as * const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( __futex - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __total_seq as * const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( - __total_seq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __wakeup_seq as * const _ as usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( - __wakeup_seq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __woken_seq as * const _ as usize } , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( - __woken_seq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __mutex as * const _ as usize } , 32usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( __mutex - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __nwaiters as * const _ as usize } , 40usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( - __nwaiters ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t__bindgen_ty_1 ) ) . - __broadcast_seq as * const _ as usize } , 44usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_cond_t__bindgen_ty_1 ) , "::" , stringify ! ( - __broadcast_seq ) )); + assert_eq!( + ::std::mem::size_of::<pthread_cond_t__bindgen_ty_1>(), + 48usize, + concat!("Size of: ", stringify!(pthread_cond_t__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_cond_t__bindgen_ty_1>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_cond_t__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__lock as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__lock) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__futex as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__futex) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__total_seq as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__total_seq) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__wakeup_seq as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__wakeup_seq) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__woken_seq as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__woken_seq) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__mutex as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__mutex) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__nwaiters as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__nwaiters) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_cond_t__bindgen_ty_1)).__broadcast_seq as *const _ as usize + }, + 44usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t__bindgen_ty_1), + "::", + stringify!(__broadcast_seq) + ) + ); } impl Clone for pthread_cond_t__bindgen_ty_1 { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for pthread_cond_t__bindgen_ty_1 { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[test] fn bindgen_test_layout_pthread_cond_t() { - assert_eq!(::std::mem::size_of::<pthread_cond_t>() , 48usize , concat ! ( - "Size of: " , stringify ! ( pthread_cond_t ) )); - assert_eq! (::std::mem::align_of::<pthread_cond_t>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( pthread_cond_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t ) ) . __data as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_cond_t ) , "::" - , stringify ! ( __data ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t ) ) . __size as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_cond_t ) , "::" - , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_cond_t ) ) . __align as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_cond_t ) , "::" - , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_cond_t>(), + 48usize, + concat!("Size of: ", stringify!(pthread_cond_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_cond_t>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_cond_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t)).__data as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t), + "::", + stringify!(__data) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_cond_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_cond_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_cond_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1027,23 +1347,41 @@ pub struct pthread_condattr_t { } #[test] fn bindgen_test_layout_pthread_condattr_t() { - assert_eq!(::std::mem::size_of::<pthread_condattr_t>() , 4usize , concat ! - ( "Size of: " , stringify ! ( pthread_condattr_t ) )); - assert_eq! (::std::mem::align_of::<pthread_condattr_t>() , 4usize , concat - ! ( "Alignment of " , stringify ! ( pthread_condattr_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_condattr_t ) ) . __size as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_condattr_t ) , - "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_condattr_t ) ) . __align as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_condattr_t ) , - "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_condattr_t>(), + 4usize, + concat!("Size of: ", stringify!(pthread_condattr_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_condattr_t>(), + 4usize, + concat!("Alignment of ", stringify!(pthread_condattr_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_condattr_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_condattr_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_condattr_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_condattr_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_condattr_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type pthread_key_t = ::std::os::raw::c_uint; pub type pthread_once_t = ::std::os::raw::c_int; @@ -1073,116 +1411,203 @@ pub struct pthread_rwlock_t__bindgen_ty_1 { } #[test] fn bindgen_test_layout_pthread_rwlock_t__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<pthread_rwlock_t__bindgen_ty_1>() , - 56usize , concat ! ( - "Size of: " , stringify ! ( pthread_rwlock_t__bindgen_ty_1 ) - )); - assert_eq! (::std::mem::align_of::<pthread_rwlock_t__bindgen_ty_1>() , - 8usize , concat ! ( - "Alignment of " , stringify ! ( pthread_rwlock_t__bindgen_ty_1 - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __lock as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( __lock - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __nr_readers as * const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __nr_readers ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __readers_wakeup as * const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __readers_wakeup ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __writer_wakeup as * const _ as usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __writer_wakeup ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __nr_readers_queued as * const _ as usize } , 16usize , concat - ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __nr_readers_queued ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __nr_writers_queued as * const _ as usize } , 20usize , concat - ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __nr_writers_queued ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __writer as * const _ as usize } , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __writer ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __shared as * const _ as usize } , 28usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __shared ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __rwelision as * const _ as usize } , 32usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __rwelision ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __pad1 as * const _ as usize } , 33usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( __pad1 - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __pad2 as * const _ as usize } , 40usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( __pad2 - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t__bindgen_ty_1 ) ) . - __flags as * const _ as usize } , 48usize , concat ! ( - "Alignment of field: " , stringify ! ( - pthread_rwlock_t__bindgen_ty_1 ) , "::" , stringify ! ( - __flags ) )); + assert_eq!( + ::std::mem::size_of::<pthread_rwlock_t__bindgen_ty_1>(), + 56usize, + concat!("Size of: ", stringify!(pthread_rwlock_t__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_rwlock_t__bindgen_ty_1>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_rwlock_t__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__lock as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__lock) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__nr_readers as *const _ as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__nr_readers) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__readers_wakeup as *const _ as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__readers_wakeup) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__writer_wakeup as *const _ as usize + }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__writer_wakeup) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__nr_readers_queued as *const _ + as usize + }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__nr_readers_queued) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__nr_writers_queued as *const _ + as usize + }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__nr_writers_queued) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__writer as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__writer) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__shared as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__shared) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__rwelision as *const _ as usize + }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__rwelision) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__pad1 as *const _ as usize }, + 33usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__pad1) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__pad2 as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__pad2) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t__bindgen_ty_1)).__flags as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t__bindgen_ty_1), + "::", + stringify!(__flags) + ) + ); } impl Clone for pthread_rwlock_t__bindgen_ty_1 { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[test] fn bindgen_test_layout_pthread_rwlock_t() { - assert_eq!(::std::mem::size_of::<pthread_rwlock_t>() , 56usize , concat ! - ( "Size of: " , stringify ! ( pthread_rwlock_t ) )); - assert_eq! (::std::mem::align_of::<pthread_rwlock_t>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( pthread_rwlock_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t ) ) . __data as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_rwlock_t ) , - "::" , stringify ! ( __data ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t ) ) . __size as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_rwlock_t ) , - "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlock_t ) ) . __align as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_rwlock_t ) , - "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_rwlock_t>(), + 56usize, + concat!("Size of: ", stringify!(pthread_rwlock_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_rwlock_t>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_rwlock_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t)).__data as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t), + "::", + stringify!(__data) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlock_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlock_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_rwlock_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1193,24 +1618,41 @@ pub struct pthread_rwlockattr_t { } #[test] fn bindgen_test_layout_pthread_rwlockattr_t() { - assert_eq!(::std::mem::size_of::<pthread_rwlockattr_t>() , 8usize , concat - ! ( "Size of: " , stringify ! ( pthread_rwlockattr_t ) )); - assert_eq! (::std::mem::align_of::<pthread_rwlockattr_t>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( pthread_rwlockattr_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlockattr_t ) ) . __size as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_rwlockattr_t ) - , "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_rwlockattr_t ) ) . __align as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_rwlockattr_t ) - , "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_rwlockattr_t>(), + 8usize, + concat!("Size of: ", stringify!(pthread_rwlockattr_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_rwlockattr_t>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_rwlockattr_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlockattr_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlockattr_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_rwlockattr_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_rwlockattr_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_rwlockattr_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type pthread_spinlock_t = ::std::os::raw::c_int; #[repr(C)] @@ -1222,23 +1664,41 @@ pub struct pthread_barrier_t { } #[test] fn bindgen_test_layout_pthread_barrier_t() { - assert_eq!(::std::mem::size_of::<pthread_barrier_t>() , 32usize , concat ! - ( "Size of: " , stringify ! ( pthread_barrier_t ) )); - assert_eq! (::std::mem::align_of::<pthread_barrier_t>() , 8usize , concat - ! ( "Alignment of " , stringify ! ( pthread_barrier_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_barrier_t ) ) . __size as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_barrier_t ) , - "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_barrier_t ) ) . __align as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_barrier_t ) , - "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_barrier_t>(), + 32usize, + concat!("Size of: ", stringify!(pthread_barrier_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_barrier_t>(), + 8usize, + concat!("Alignment of ", stringify!(pthread_barrier_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_barrier_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_barrier_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_barrier_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_barrier_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_barrier_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1249,25 +1709,41 @@ pub struct pthread_barrierattr_t { } #[test] fn bindgen_test_layout_pthread_barrierattr_t() { - assert_eq!(::std::mem::size_of::<pthread_barrierattr_t>() , 4usize , - concat ! ( "Size of: " , stringify ! ( pthread_barrierattr_t ) - )); - assert_eq! (::std::mem::align_of::<pthread_barrierattr_t>() , 4usize , - concat ! ( - "Alignment of " , stringify ! ( pthread_barrierattr_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_barrierattr_t ) ) . __size as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_barrierattr_t ) - , "::" , stringify ! ( __size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const pthread_barrierattr_t ) ) . __align as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( pthread_barrierattr_t ) - , "::" , stringify ! ( __align ) )); + assert_eq!( + ::std::mem::size_of::<pthread_barrierattr_t>(), + 4usize, + concat!("Size of: ", stringify!(pthread_barrierattr_t)) + ); + assert_eq!( + ::std::mem::align_of::<pthread_barrierattr_t>(), + 4usize, + concat!("Alignment of ", stringify!(pthread_barrierattr_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_barrierattr_t)).__size as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_barrierattr_t), + "::", + stringify!(__size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const pthread_barrierattr_t)).__align as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(pthread_barrierattr_t), + "::", + stringify!(__align) + ) + ); } impl Clone for pthread_barrierattr_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -1277,43 +1753,76 @@ pub struct iovec { } #[test] fn bindgen_test_layout_iovec() { - assert_eq!(::std::mem::size_of::<iovec>() , 16usize , concat ! ( - "Size of: " , stringify ! ( iovec ) )); - assert_eq! (::std::mem::align_of::<iovec>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( iovec ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const iovec ) ) . iov_base as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( iovec ) , "::" , - stringify ! ( iov_base ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const iovec ) ) . iov_len as * const _ as usize - } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( iovec ) , "::" , - stringify ! ( iov_len ) )); + assert_eq!( + ::std::mem::size_of::<iovec>(), + 16usize, + concat!("Size of: ", stringify!(iovec)) + ); + assert_eq!( + ::std::mem::align_of::<iovec>(), + 8usize, + concat!("Alignment of ", stringify!(iovec)) + ); + assert_eq!( + unsafe { &(*(0 as *const iovec)).iov_base as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(iovec), + "::", + stringify!(iov_base) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const iovec)).iov_len as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(iovec), + "::", + stringify!(iov_len) + ) + ); } impl Clone for iovec { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for iovec { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } extern "C" { - pub fn readv(__fd: ::std::os::raw::c_int, __iovec: *const iovec, - __count: ::std::os::raw::c_int) -> isize; + pub fn readv( + __fd: ::std::os::raw::c_int, + __iovec: *const iovec, + __count: ::std::os::raw::c_int, + ) -> isize; } extern "C" { - pub fn writev(__fd: ::std::os::raw::c_int, __iovec: *const iovec, - __count: ::std::os::raw::c_int) -> isize; + pub fn writev( + __fd: ::std::os::raw::c_int, + __iovec: *const iovec, + __count: ::std::os::raw::c_int, + ) -> isize; } extern "C" { - pub fn preadv(__fd: ::std::os::raw::c_int, __iovec: *const iovec, - __count: ::std::os::raw::c_int, __offset: __off_t) -> isize; + pub fn preadv( + __fd: ::std::os::raw::c_int, + __iovec: *const iovec, + __count: ::std::os::raw::c_int, + __offset: __off_t, + ) -> isize; } extern "C" { - pub fn pwritev(__fd: ::std::os::raw::c_int, __iovec: *const iovec, - __count: ::std::os::raw::c_int, __offset: __off_t) - -> isize; + pub fn pwritev( + __fd: ::std::os::raw::c_int, + __iovec: *const iovec, + __count: ::std::os::raw::c_int, + __offset: __off_t, + ) -> isize; } pub type socklen_t = __socklen_t; pub const __socket_type_SOCK_STREAM: __socket_type = 1; @@ -1335,23 +1844,41 @@ pub struct sockaddr { } #[test] fn bindgen_test_layout_sockaddr() { - assert_eq!(::std::mem::size_of::<sockaddr>() , 16usize , concat ! ( - "Size of: " , stringify ! ( sockaddr ) )); - assert_eq! (::std::mem::align_of::<sockaddr>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( sockaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr ) ) . sa_family as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr ) , "::" , - stringify ! ( sa_family ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr ) ) . sa_data as * const _ as - usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr ) , "::" , - stringify ! ( sa_data ) )); + assert_eq!( + ::std::mem::size_of::<sockaddr>(), + 16usize, + concat!("Size of: ", stringify!(sockaddr)) + ); + assert_eq!( + ::std::mem::align_of::<sockaddr>(), + 2usize, + concat!("Alignment of ", stringify!(sockaddr)) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr)).sa_family as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr), + "::", + stringify!(sa_family) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr)).sa_data as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr), + "::", + stringify!(sa_data) + ) + ); } impl Clone for sockaddr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] pub struct sockaddr_storage { @@ -1361,28 +1888,51 @@ pub struct sockaddr_storage { } #[test] fn bindgen_test_layout_sockaddr_storage() { - assert_eq!(::std::mem::size_of::<sockaddr_storage>() , 128usize , concat ! - ( "Size of: " , stringify ! ( sockaddr_storage ) )); - assert_eq! (::std::mem::align_of::<sockaddr_storage>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( sockaddr_storage ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_storage ) ) . ss_family as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_storage ) , - "::" , stringify ! ( ss_family ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_storage ) ) . __ss_padding as * - const _ as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_storage ) , - "::" , stringify ! ( __ss_padding ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_storage ) ) . __ss_align as * - const _ as usize } , 120usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_storage ) , - "::" , stringify ! ( __ss_align ) )); + assert_eq!( + ::std::mem::size_of::<sockaddr_storage>(), + 128usize, + concat!("Size of: ", stringify!(sockaddr_storage)) + ); + assert_eq!( + ::std::mem::align_of::<sockaddr_storage>(), + 8usize, + concat!("Alignment of ", stringify!(sockaddr_storage)) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_storage)).ss_family as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_storage), + "::", + stringify!(ss_family) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_storage)).__ss_padding as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_storage), + "::", + stringify!(__ss_padding) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_storage)).__ss_align as *const _ as usize }, + 120usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_storage), + "::", + stringify!(__ss_align) + ) + ); } impl Default for sockaddr_storage { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } pub const MSG_OOB: _bindgen_ty_1 = 1; pub const MSG_PEEK: _bindgen_ty_1 = 2; @@ -1417,51 +1967,96 @@ pub struct msghdr { } #[test] fn bindgen_test_layout_msghdr() { - assert_eq!(::std::mem::size_of::<msghdr>() , 56usize , concat ! ( - "Size of: " , stringify ! ( msghdr ) )); - assert_eq! (::std::mem::align_of::<msghdr>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( msghdr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_name as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_name ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_namelen as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_namelen ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_iov as * const _ as - usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_iov ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_iovlen as * const _ as - usize } , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_iovlen ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_control as * const _ as - usize } , 32usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_control ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_controllen as * const _ - as usize } , 40usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_controllen ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const msghdr ) ) . msg_flags as * const _ as - usize } , 48usize , concat ! ( - "Alignment of field: " , stringify ! ( msghdr ) , "::" , - stringify ! ( msg_flags ) )); + assert_eq!( + ::std::mem::size_of::<msghdr>(), + 56usize, + concat!("Size of: ", stringify!(msghdr)) + ); + assert_eq!( + ::std::mem::align_of::<msghdr>(), + 8usize, + concat!("Alignment of ", stringify!(msghdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_name as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_name) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_namelen as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_namelen) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_iov as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_iov) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_iovlen as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_iovlen) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_control as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_control) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_controllen as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_controllen) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const msghdr)).msg_flags as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(msghdr), + "::", + stringify!(msg_flags) + ) + ); } impl Clone for msghdr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for msghdr { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1473,17 +2068,24 @@ pub struct cmsghdr { } #[test] fn bindgen_test_layout_cmsghdr() { - assert_eq!(::std::mem::size_of::<cmsghdr>() , 16usize , concat ! ( - "Size of: " , stringify ! ( cmsghdr ) )); - assert_eq! (::std::mem::align_of::<cmsghdr>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( cmsghdr ) )); + assert_eq!( + ::std::mem::size_of::<cmsghdr>(), + 16usize, + concat!("Size of: ", stringify!(cmsghdr)) + ); + assert_eq!( + ::std::mem::align_of::<cmsghdr>(), + 8usize, + concat!("Alignment of ", stringify!(cmsghdr)) + ); } impl Clone for cmsghdr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } extern "C" { - pub fn __cmsg_nxthdr(__mhdr: *mut msghdr, __cmsg: *mut cmsghdr) - -> *mut cmsghdr; + pub fn __cmsg_nxthdr(__mhdr: *mut msghdr, __cmsg: *mut cmsghdr) -> *mut cmsghdr; } pub const SCM_RIGHTS: _bindgen_ty_2 = 1; pub type _bindgen_ty_2 = ::std::os::raw::c_uint; @@ -1495,23 +2097,41 @@ pub struct linger { } #[test] fn bindgen_test_layout_linger() { - assert_eq!(::std::mem::size_of::<linger>() , 8usize , concat ! ( - "Size of: " , stringify ! ( linger ) )); - assert_eq! (::std::mem::align_of::<linger>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( linger ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const linger ) ) . l_onoff as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( linger ) , "::" , - stringify ! ( l_onoff ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const linger ) ) . l_linger as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( linger ) , "::" , - stringify ! ( l_linger ) )); + assert_eq!( + ::std::mem::size_of::<linger>(), + 8usize, + concat!("Size of: ", stringify!(linger)) + ); + assert_eq!( + ::std::mem::align_of::<linger>(), + 4usize, + concat!("Alignment of ", stringify!(linger)) + ); + assert_eq!( + unsafe { &(*(0 as *const linger)).l_onoff as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(linger), + "::", + stringify!(l_onoff) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const linger)).l_linger as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(linger), + "::", + stringify!(l_linger) + ) + ); } impl Clone for linger { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1521,118 +2141,182 @@ pub struct osockaddr { } #[test] fn bindgen_test_layout_osockaddr() { - assert_eq!(::std::mem::size_of::<osockaddr>() , 16usize , concat ! ( - "Size of: " , stringify ! ( osockaddr ) )); - assert_eq! (::std::mem::align_of::<osockaddr>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( osockaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const osockaddr ) ) . sa_family as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( osockaddr ) , "::" , - stringify ! ( sa_family ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const osockaddr ) ) . sa_data as * const _ as - usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( osockaddr ) , "::" , - stringify ! ( sa_data ) )); + assert_eq!( + ::std::mem::size_of::<osockaddr>(), + 16usize, + concat!("Size of: ", stringify!(osockaddr)) + ); + assert_eq!( + ::std::mem::align_of::<osockaddr>(), + 2usize, + concat!("Alignment of ", stringify!(osockaddr)) + ); + assert_eq!( + unsafe { &(*(0 as *const osockaddr)).sa_family as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(osockaddr), + "::", + stringify!(sa_family) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const osockaddr)).sa_data as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(osockaddr), + "::", + stringify!(sa_data) + ) + ); } impl Clone for osockaddr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub const SHUT_RD: _bindgen_ty_3 = 0; pub const SHUT_WR: _bindgen_ty_3 = 1; pub const SHUT_RDWR: _bindgen_ty_3 = 2; pub type _bindgen_ty_3 = ::std::os::raw::c_uint; extern "C" { - pub fn socket(__domain: ::std::os::raw::c_int, - __type: ::std::os::raw::c_int, - __protocol: ::std::os::raw::c_int) -> ::std::os::raw::c_int; + pub fn socket( + __domain: ::std::os::raw::c_int, + __type: ::std::os::raw::c_int, + __protocol: ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn socketpair(__domain: ::std::os::raw::c_int, - __type: ::std::os::raw::c_int, - __protocol: ::std::os::raw::c_int, - __fds: *mut ::std::os::raw::c_int) - -> ::std::os::raw::c_int; + pub fn socketpair( + __domain: ::std::os::raw::c_int, + __type: ::std::os::raw::c_int, + __protocol: ::std::os::raw::c_int, + __fds: *mut ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn bind(__fd: ::std::os::raw::c_int, __addr: *const sockaddr, - __len: socklen_t) -> ::std::os::raw::c_int; + pub fn bind( + __fd: ::std::os::raw::c_int, + __addr: *const sockaddr, + __len: socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn getsockname(__fd: ::std::os::raw::c_int, __addr: *mut sockaddr, - __len: *mut socklen_t) -> ::std::os::raw::c_int; + pub fn getsockname( + __fd: ::std::os::raw::c_int, + __addr: *mut sockaddr, + __len: *mut socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn connect(__fd: ::std::os::raw::c_int, __addr: *const sockaddr, - __len: socklen_t) -> ::std::os::raw::c_int; + pub fn connect( + __fd: ::std::os::raw::c_int, + __addr: *const sockaddr, + __len: socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn getpeername(__fd: ::std::os::raw::c_int, __addr: *mut sockaddr, - __len: *mut socklen_t) -> ::std::os::raw::c_int; + pub fn getpeername( + __fd: ::std::os::raw::c_int, + __addr: *mut sockaddr, + __len: *mut socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn send(__fd: ::std::os::raw::c_int, - __buf: *const ::std::os::raw::c_void, __n: usize, - __flags: ::std::os::raw::c_int) -> isize; + pub fn send( + __fd: ::std::os::raw::c_int, + __buf: *const ::std::os::raw::c_void, + __n: usize, + __flags: ::std::os::raw::c_int, + ) -> isize; } extern "C" { - pub fn recv(__fd: ::std::os::raw::c_int, - __buf: *mut ::std::os::raw::c_void, __n: usize, - __flags: ::std::os::raw::c_int) -> isize; + pub fn recv( + __fd: ::std::os::raw::c_int, + __buf: *mut ::std::os::raw::c_void, + __n: usize, + __flags: ::std::os::raw::c_int, + ) -> isize; } extern "C" { - pub fn sendto(__fd: ::std::os::raw::c_int, - __buf: *const ::std::os::raw::c_void, __n: usize, - __flags: ::std::os::raw::c_int, __addr: *const sockaddr, - __addr_len: socklen_t) -> isize; + pub fn sendto( + __fd: ::std::os::raw::c_int, + __buf: *const ::std::os::raw::c_void, + __n: usize, + __flags: ::std::os::raw::c_int, + __addr: *const sockaddr, + __addr_len: socklen_t, + ) -> isize; } extern "C" { - pub fn recvfrom(__fd: ::std::os::raw::c_int, - __buf: *mut ::std::os::raw::c_void, __n: usize, - __flags: ::std::os::raw::c_int, __addr: *mut sockaddr, - __addr_len: *mut socklen_t) -> isize; + pub fn recvfrom( + __fd: ::std::os::raw::c_int, + __buf: *mut ::std::os::raw::c_void, + __n: usize, + __flags: ::std::os::raw::c_int, + __addr: *mut sockaddr, + __addr_len: *mut socklen_t, + ) -> isize; } extern "C" { - pub fn sendmsg(__fd: ::std::os::raw::c_int, __message: *const msghdr, - __flags: ::std::os::raw::c_int) -> isize; + pub fn sendmsg( + __fd: ::std::os::raw::c_int, + __message: *const msghdr, + __flags: ::std::os::raw::c_int, + ) -> isize; } extern "C" { - pub fn recvmsg(__fd: ::std::os::raw::c_int, __message: *mut msghdr, - __flags: ::std::os::raw::c_int) -> isize; + pub fn recvmsg( + __fd: ::std::os::raw::c_int, + __message: *mut msghdr, + __flags: ::std::os::raw::c_int, + ) -> isize; } extern "C" { - pub fn getsockopt(__fd: ::std::os::raw::c_int, - __level: ::std::os::raw::c_int, - __optname: ::std::os::raw::c_int, - __optval: *mut ::std::os::raw::c_void, - __optlen: *mut socklen_t) -> ::std::os::raw::c_int; + pub fn getsockopt( + __fd: ::std::os::raw::c_int, + __level: ::std::os::raw::c_int, + __optname: ::std::os::raw::c_int, + __optval: *mut ::std::os::raw::c_void, + __optlen: *mut socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn setsockopt(__fd: ::std::os::raw::c_int, - __level: ::std::os::raw::c_int, - __optname: ::std::os::raw::c_int, - __optval: *const ::std::os::raw::c_void, - __optlen: socklen_t) -> ::std::os::raw::c_int; + pub fn setsockopt( + __fd: ::std::os::raw::c_int, + __level: ::std::os::raw::c_int, + __optname: ::std::os::raw::c_int, + __optval: *const ::std::os::raw::c_void, + __optlen: socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { pub fn listen(__fd: ::std::os::raw::c_int, __n: ::std::os::raw::c_int) - -> ::std::os::raw::c_int; + -> ::std::os::raw::c_int; } extern "C" { - pub fn accept(__fd: ::std::os::raw::c_int, __addr: *mut sockaddr, - __addr_len: *mut socklen_t) -> ::std::os::raw::c_int; + pub fn accept( + __fd: ::std::os::raw::c_int, + __addr: *mut sockaddr, + __addr_len: *mut socklen_t, + ) -> ::std::os::raw::c_int; } extern "C" { - pub fn shutdown(__fd: ::std::os::raw::c_int, __how: ::std::os::raw::c_int) - -> ::std::os::raw::c_int; + pub fn shutdown( + __fd: ::std::os::raw::c_int, + __how: ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; } extern "C" { pub fn sockatmark(__fd: ::std::os::raw::c_int) -> ::std::os::raw::c_int; } extern "C" { - pub fn isfdtype(__fd: ::std::os::raw::c_int, - __fdtype: ::std::os::raw::c_int) -> ::std::os::raw::c_int; + pub fn isfdtype( + __fd: ::std::os::raw::c_int, + __fdtype: ::std::os::raw::c_int, + ) -> ::std::os::raw::c_int; } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1643,30 +2327,51 @@ pub struct sync_serial_settings { } #[test] fn bindgen_test_layout_sync_serial_settings() { - assert_eq!(::std::mem::size_of::<sync_serial_settings>() , 12usize , - concat ! ( "Size of: " , stringify ! ( sync_serial_settings ) - )); - assert_eq! (::std::mem::align_of::<sync_serial_settings>() , 4usize , - concat ! ( - "Alignment of " , stringify ! ( sync_serial_settings ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sync_serial_settings ) ) . clock_rate as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( sync_serial_settings ) - , "::" , stringify ! ( clock_rate ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sync_serial_settings ) ) . clock_type as - * const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( sync_serial_settings ) - , "::" , stringify ! ( clock_type ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sync_serial_settings ) ) . loopback as * - const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( sync_serial_settings ) - , "::" , stringify ! ( loopback ) )); + assert_eq!( + ::std::mem::size_of::<sync_serial_settings>(), + 12usize, + concat!("Size of: ", stringify!(sync_serial_settings)) + ); + assert_eq!( + ::std::mem::align_of::<sync_serial_settings>(), + 4usize, + concat!("Alignment of ", stringify!(sync_serial_settings)) + ); + assert_eq!( + unsafe { &(*(0 as *const sync_serial_settings)).clock_rate as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sync_serial_settings), + "::", + stringify!(clock_rate) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sync_serial_settings)).clock_type as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(sync_serial_settings), + "::", + stringify!(clock_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sync_serial_settings)).loopback as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(sync_serial_settings), + "::", + stringify!(loopback) + ) + ); } impl Clone for sync_serial_settings { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1678,33 +2383,61 @@ pub struct te1_settings { } #[test] fn bindgen_test_layout_te1_settings() { - assert_eq!(::std::mem::size_of::<te1_settings>() , 16usize , concat ! ( - "Size of: " , stringify ! ( te1_settings ) )); - assert_eq! (::std::mem::align_of::<te1_settings>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( te1_settings ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const te1_settings ) ) . clock_rate as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( te1_settings ) , "::" , - stringify ! ( clock_rate ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const te1_settings ) ) . clock_type as * const - _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( te1_settings ) , "::" , - stringify ! ( clock_type ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const te1_settings ) ) . loopback as * const _ - as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( te1_settings ) , "::" , - stringify ! ( loopback ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const te1_settings ) ) . slot_map as * const _ - as usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( te1_settings ) , "::" , - stringify ! ( slot_map ) )); + assert_eq!( + ::std::mem::size_of::<te1_settings>(), + 16usize, + concat!("Size of: ", stringify!(te1_settings)) + ); + assert_eq!( + ::std::mem::align_of::<te1_settings>(), + 4usize, + concat!("Alignment of ", stringify!(te1_settings)) + ); + assert_eq!( + unsafe { &(*(0 as *const te1_settings)).clock_rate as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(te1_settings), + "::", + stringify!(clock_rate) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const te1_settings)).clock_type as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(te1_settings), + "::", + stringify!(clock_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const te1_settings)).loopback as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(te1_settings), + "::", + stringify!(loopback) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const te1_settings)).slot_map as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(te1_settings), + "::", + stringify!(slot_map) + ) + ); } impl Clone for te1_settings { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1714,23 +2447,41 @@ pub struct raw_hdlc_proto { } #[test] fn bindgen_test_layout_raw_hdlc_proto() { - assert_eq!(::std::mem::size_of::<raw_hdlc_proto>() , 4usize , concat ! ( - "Size of: " , stringify ! ( raw_hdlc_proto ) )); - assert_eq! (::std::mem::align_of::<raw_hdlc_proto>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( raw_hdlc_proto ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const raw_hdlc_proto ) ) . encoding as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( raw_hdlc_proto ) , "::" - , stringify ! ( encoding ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const raw_hdlc_proto ) ) . parity as * const _ - as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( raw_hdlc_proto ) , "::" - , stringify ! ( parity ) )); + assert_eq!( + ::std::mem::size_of::<raw_hdlc_proto>(), + 4usize, + concat!("Size of: ", stringify!(raw_hdlc_proto)) + ); + assert_eq!( + ::std::mem::align_of::<raw_hdlc_proto>(), + 2usize, + concat!("Alignment of ", stringify!(raw_hdlc_proto)) + ); + assert_eq!( + unsafe { &(*(0 as *const raw_hdlc_proto)).encoding as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(raw_hdlc_proto), + "::", + stringify!(encoding) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const raw_hdlc_proto)).parity as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(raw_hdlc_proto), + "::", + stringify!(parity) + ) + ); } impl Clone for raw_hdlc_proto { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1745,48 +2496,91 @@ pub struct fr_proto { } #[test] fn bindgen_test_layout_fr_proto() { - assert_eq!(::std::mem::size_of::<fr_proto>() , 24usize , concat ! ( - "Size of: " , stringify ! ( fr_proto ) )); - assert_eq! (::std::mem::align_of::<fr_proto>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( fr_proto ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . t391 as * const _ as usize - } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( t391 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . t392 as * const _ as usize - } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( t392 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . n391 as * const _ as usize - } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( n391 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . n392 as * const _ as usize - } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( n392 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . n393 as * const _ as usize - } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( n393 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . lmi as * const _ as usize - } , 20usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( lmi ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto ) ) . dce as * const _ as usize - } , 22usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto ) , "::" , - stringify ! ( dce ) )); + assert_eq!( + ::std::mem::size_of::<fr_proto>(), + 24usize, + concat!("Size of: ", stringify!(fr_proto)) + ); + assert_eq!( + ::std::mem::align_of::<fr_proto>(), + 4usize, + concat!("Alignment of ", stringify!(fr_proto)) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).t391 as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(t391) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).t392 as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(t392) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).n391 as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(n391) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).n392 as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(n392) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).n393 as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(n393) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).lmi as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(lmi) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto)).dce as *const _ as usize }, + 22usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto), + "::", + stringify!(dce) + ) + ); } impl Clone for fr_proto { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1795,18 +2589,31 @@ pub struct fr_proto_pvc { } #[test] fn bindgen_test_layout_fr_proto_pvc() { - assert_eq!(::std::mem::size_of::<fr_proto_pvc>() , 4usize , concat ! ( - "Size of: " , stringify ! ( fr_proto_pvc ) )); - assert_eq! (::std::mem::align_of::<fr_proto_pvc>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( fr_proto_pvc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto_pvc ) ) . dlci as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto_pvc ) , "::" , - stringify ! ( dlci ) )); + assert_eq!( + ::std::mem::size_of::<fr_proto_pvc>(), + 4usize, + concat!("Size of: ", stringify!(fr_proto_pvc)) + ); + assert_eq!( + ::std::mem::align_of::<fr_proto_pvc>(), + 4usize, + concat!("Alignment of ", stringify!(fr_proto_pvc)) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto_pvc)).dlci as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto_pvc), + "::", + stringify!(dlci) + ) + ); } impl Clone for fr_proto_pvc { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1816,23 +2623,41 @@ pub struct fr_proto_pvc_info { } #[test] fn bindgen_test_layout_fr_proto_pvc_info() { - assert_eq!(::std::mem::size_of::<fr_proto_pvc_info>() , 20usize , concat ! - ( "Size of: " , stringify ! ( fr_proto_pvc_info ) )); - assert_eq! (::std::mem::align_of::<fr_proto_pvc_info>() , 4usize , concat - ! ( "Alignment of " , stringify ! ( fr_proto_pvc_info ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto_pvc_info ) ) . dlci as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto_pvc_info ) , - "::" , stringify ! ( dlci ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const fr_proto_pvc_info ) ) . master as * const - _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( fr_proto_pvc_info ) , - "::" , stringify ! ( master ) )); + assert_eq!( + ::std::mem::size_of::<fr_proto_pvc_info>(), + 20usize, + concat!("Size of: ", stringify!(fr_proto_pvc_info)) + ); + assert_eq!( + ::std::mem::align_of::<fr_proto_pvc_info>(), + 4usize, + concat!("Alignment of ", stringify!(fr_proto_pvc_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto_pvc_info)).dlci as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto_pvc_info), + "::", + stringify!(dlci) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const fr_proto_pvc_info)).master as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(fr_proto_pvc_info), + "::", + stringify!(master) + ) + ); } impl Clone for fr_proto_pvc_info { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1842,23 +2667,41 @@ pub struct cisco_proto { } #[test] fn bindgen_test_layout_cisco_proto() { - assert_eq!(::std::mem::size_of::<cisco_proto>() , 8usize , concat ! ( - "Size of: " , stringify ! ( cisco_proto ) )); - assert_eq! (::std::mem::align_of::<cisco_proto>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( cisco_proto ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const cisco_proto ) ) . interval as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( cisco_proto ) , "::" , - stringify ! ( interval ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const cisco_proto ) ) . timeout as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( cisco_proto ) , "::" , - stringify ! ( timeout ) )); + assert_eq!( + ::std::mem::size_of::<cisco_proto>(), + 8usize, + concat!("Size of: ", stringify!(cisco_proto)) + ); + assert_eq!( + ::std::mem::align_of::<cisco_proto>(), + 4usize, + concat!("Alignment of ", stringify!(cisco_proto)) + ); + assert_eq!( + unsafe { &(*(0 as *const cisco_proto)).interval as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(cisco_proto), + "::", + stringify!(interval) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const cisco_proto)).timeout as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(cisco_proto), + "::", + stringify!(timeout) + ) + ); } impl Clone for cisco_proto { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub const net_device_flags_IFF_UP: net_device_flags = 1; pub const net_device_flags_IFF_BROADCAST: net_device_flags = 2; @@ -1940,43 +2783,81 @@ pub struct ifmap { } #[test] fn bindgen_test_layout_ifmap() { - assert_eq!(::std::mem::size_of::<ifmap>() , 24usize , concat ! ( - "Size of: " , stringify ! ( ifmap ) )); - assert_eq! (::std::mem::align_of::<ifmap>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( ifmap ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifmap ) ) . mem_start as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifmap ) , "::" , - stringify ! ( mem_start ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifmap ) ) . mem_end as * const _ as usize - } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( ifmap ) , "::" , - stringify ! ( mem_end ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifmap ) ) . base_addr as * const _ as - usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( ifmap ) , "::" , - stringify ! ( base_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifmap ) ) . irq as * const _ as usize } , - 18usize , concat ! ( - "Alignment of field: " , stringify ! ( ifmap ) , "::" , - stringify ! ( irq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifmap ) ) . dma as * const _ as usize } , - 19usize , concat ! ( - "Alignment of field: " , stringify ! ( ifmap ) , "::" , - stringify ! ( dma ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifmap ) ) . port as * const _ as usize } - , 20usize , concat ! ( - "Alignment of field: " , stringify ! ( ifmap ) , "::" , - stringify ! ( port ) )); + assert_eq!( + ::std::mem::size_of::<ifmap>(), + 24usize, + concat!("Size of: ", stringify!(ifmap)) + ); + assert_eq!( + ::std::mem::align_of::<ifmap>(), + 8usize, + concat!("Alignment of ", stringify!(ifmap)) + ); + assert_eq!( + unsafe { &(*(0 as *const ifmap)).mem_start as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifmap), + "::", + stringify!(mem_start) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifmap)).mem_end as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(ifmap), + "::", + stringify!(mem_end) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifmap)).base_addr as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(ifmap), + "::", + stringify!(base_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifmap)).irq as *const _ as usize }, + 18usize, + concat!( + "Alignment of field: ", + stringify!(ifmap), + "::", + stringify!(irq) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifmap)).dma as *const _ as usize }, + 19usize, + concat!( + "Alignment of field: ", + stringify!(ifmap), + "::", + stringify!(dma) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifmap)).port as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(ifmap), + "::", + stringify!(port) + ) + ); } impl Clone for ifmap { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -1999,79 +2880,139 @@ pub struct if_settings__bindgen_ty_1 { } #[test] fn bindgen_test_layout_if_settings__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<if_settings__bindgen_ty_1>() , 8usize , - concat ! ( - "Size of: " , stringify ! ( if_settings__bindgen_ty_1 ) )); - assert_eq! (::std::mem::align_of::<if_settings__bindgen_ty_1>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( if_settings__bindgen_ty_1 ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . raw_hdlc - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( raw_hdlc ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . cisco as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( cisco ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . fr as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( fr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . fr_pvc as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( fr_pvc ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . - fr_pvc_info as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( fr_pvc_info - ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . sync as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( sync ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings__bindgen_ty_1 ) ) . te1 as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - if_settings__bindgen_ty_1 ) , "::" , stringify ! ( te1 ) )); + assert_eq!( + ::std::mem::size_of::<if_settings__bindgen_ty_1>(), + 8usize, + concat!("Size of: ", stringify!(if_settings__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<if_settings__bindgen_ty_1>(), + 8usize, + concat!("Alignment of ", stringify!(if_settings__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).raw_hdlc as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(raw_hdlc) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).cisco as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(cisco) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).fr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(fr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).fr_pvc as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(fr_pvc) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).fr_pvc_info as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(fr_pvc_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).sync as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(sync) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings__bindgen_ty_1)).te1 as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings__bindgen_ty_1), + "::", + stringify!(te1) + ) + ); } impl Clone for if_settings__bindgen_ty_1 { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[test] fn bindgen_test_layout_if_settings() { - assert_eq!(::std::mem::size_of::<if_settings>() , 16usize , concat ! ( - "Size of: " , stringify ! ( if_settings ) )); - assert_eq! (::std::mem::align_of::<if_settings>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( if_settings ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings ) ) . type_ as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( if_settings ) , "::" , - stringify ! ( type_ ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings ) ) . size as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( if_settings ) , "::" , - stringify ! ( size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const if_settings ) ) . ifs_ifsu as * const _ - as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( if_settings ) , "::" , - stringify ! ( ifs_ifsu ) )); + assert_eq!( + ::std::mem::size_of::<if_settings>(), + 16usize, + concat!("Size of: ", stringify!(if_settings)) + ); + assert_eq!( + ::std::mem::align_of::<if_settings>(), + 8usize, + concat!("Alignment of ", stringify!(if_settings)) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings)).type_ as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(if_settings), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings)).size as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(if_settings), + "::", + stringify!(size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const if_settings)).ifs_ifsu as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(if_settings), + "::", + stringify!(ifs_ifsu) + ) + ); } impl Clone for if_settings { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -2087,19 +3028,31 @@ pub struct ifreq__bindgen_ty_1 { } #[test] fn bindgen_test_layout_ifreq__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<ifreq__bindgen_ty_1>() , 16usize , concat - ! ( "Size of: " , stringify ! ( ifreq__bindgen_ty_1 ) )); - assert_eq! (::std::mem::align_of::<ifreq__bindgen_ty_1>() , 1usize , - concat ! ( - "Alignment of " , stringify ! ( ifreq__bindgen_ty_1 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_1 ) ) . ifrn_name as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_1 ) , - "::" , stringify ! ( ifrn_name ) )); + assert_eq!( + ::std::mem::size_of::<ifreq__bindgen_ty_1>(), + 16usize, + concat!("Size of: ", stringify!(ifreq__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<ifreq__bindgen_ty_1>(), + 1usize, + concat!("Alignment of ", stringify!(ifreq__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_1)).ifrn_name as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_1), + "::", + stringify!(ifrn_name) + ) + ); } impl Clone for ifreq__bindgen_ty_1 { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -2121,97 +3074,187 @@ pub struct ifreq__bindgen_ty_2 { } #[test] fn bindgen_test_layout_ifreq__bindgen_ty_2() { - assert_eq!(::std::mem::size_of::<ifreq__bindgen_ty_2>() , 24usize , concat - ! ( "Size of: " , stringify ! ( ifreq__bindgen_ty_2 ) )); - assert_eq! (::std::mem::align_of::<ifreq__bindgen_ty_2>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( ifreq__bindgen_ty_2 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_addr as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_dstaddr as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_dstaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_broadaddr - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_broadaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_netmask as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_netmask ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_hwaddr as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_hwaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_flags as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_ivalue as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_ivalue ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_mtu as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_mtu ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_map as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_map ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_slave as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_slave ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_newname as - * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_newname ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_data as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_data ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq__bindgen_ty_2 ) ) . ifru_settings - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq__bindgen_ty_2 ) , - "::" , stringify ! ( ifru_settings ) )); + assert_eq!( + ::std::mem::size_of::<ifreq__bindgen_ty_2>(), + 24usize, + concat!("Size of: ", stringify!(ifreq__bindgen_ty_2)) + ); + assert_eq!( + ::std::mem::align_of::<ifreq__bindgen_ty_2>(), + 8usize, + concat!("Alignment of ", stringify!(ifreq__bindgen_ty_2)) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_addr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_dstaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_dstaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_broadaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_broadaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_netmask as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_netmask) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_hwaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_hwaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_flags as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_ivalue as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_ivalue) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_mtu as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_mtu) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_map as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_map) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_slave as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_slave) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_newname as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_newname) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_data as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_data) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq__bindgen_ty_2)).ifru_settings as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq__bindgen_ty_2), + "::", + stringify!(ifru_settings) + ) + ); } impl Clone for ifreq__bindgen_ty_2 { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[test] fn bindgen_test_layout_ifreq() { - assert_eq!(::std::mem::size_of::<ifreq>() , 40usize , concat ! ( - "Size of: " , stringify ! ( ifreq ) )); - assert_eq! (::std::mem::align_of::<ifreq>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( ifreq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq ) ) . ifr_ifrn as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq ) , "::" , - stringify ! ( ifr_ifrn ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ifreq ) ) . ifr_ifru as * const _ as - usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( ifreq ) , "::" , - stringify ! ( ifr_ifru ) )); + assert_eq!( + ::std::mem::size_of::<ifreq>(), + 40usize, + concat!("Size of: ", stringify!(ifreq)) + ); + assert_eq!( + ::std::mem::align_of::<ifreq>(), + 8usize, + concat!("Alignment of ", stringify!(ifreq)) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq)).ifr_ifrn as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ifreq), + "::", + stringify!(ifr_ifrn) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ifreq)).ifr_ifru as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(ifreq), + "::", + stringify!(ifr_ifru) + ) + ); } impl Clone for ifreq { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } diff --git a/net_sys/src/inn.rs b/net_sys/src/inn.rs index 0f84b16..ea279f0 100644 --- a/net_sys/src/inn.rs +++ b/net_sys/src/inn.rs @@ -109,18 +109,31 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>() , 128usize , concat ! - ( "Size of: " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (::std::mem::align_of::<__kernel_fd_set>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fd_set ) ) . fds_bits as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fd_set ) , - "::" , stringify ! ( fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_sighandler_t = ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int)>; @@ -151,18 +164,31 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (::std::mem::align_of::<__kernel_fsid_t>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fsid_t ) ) . val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fsid_t ) , - "::" , stringify ! ( val ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_off_t = __kernel_long_t; pub type __kernel_loff_t = ::std::os::raw::c_longlong; @@ -190,28 +216,41 @@ pub struct __kernel_sockaddr_storage { } #[test] fn bindgen_test_layout___kernel_sockaddr_storage() { - assert_eq!(::std::mem::size_of::<__kernel_sockaddr_storage>() , 128usize , - concat ! ( - "Size of: " , stringify ! ( __kernel_sockaddr_storage ) )); - assert_eq! (::std::mem::align_of::<__kernel_sockaddr_storage>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( __kernel_sockaddr_storage ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_sockaddr_storage ) ) . ss_family - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - __kernel_sockaddr_storage ) , "::" , stringify ! ( ss_family ) - )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_sockaddr_storage ) ) . __data as - * const _ as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( - __kernel_sockaddr_storage ) , "::" , stringify ! ( __data ) - )); + assert_eq!( + ::std::mem::size_of::<__kernel_sockaddr_storage>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_sockaddr_storage)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_sockaddr_storage>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_sockaddr_storage)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_sockaddr_storage)).ss_family as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_sockaddr_storage), + "::", + stringify!(ss_family) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_sockaddr_storage)).__data as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_sockaddr_storage), + "::", + stringify!(__data) + ) + ); } impl Default for __kernel_sockaddr_storage { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } pub const IPPROTO_IP: _bindgen_ty_1 = 0; pub const IPPROTO_ICMP: _bindgen_ty_1 = 1; @@ -247,18 +286,31 @@ pub struct in_addr { } #[test] fn bindgen_test_layout_in_addr() { - assert_eq!(::std::mem::size_of::<in_addr>() , 4usize , concat ! ( - "Size of: " , stringify ! ( in_addr ) )); - assert_eq! (::std::mem::align_of::<in_addr>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( in_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const in_addr ) ) . s_addr as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( in_addr ) , "::" , - stringify ! ( s_addr ) )); + assert_eq!( + ::std::mem::size_of::<in_addr>(), + 4usize, + concat!("Size of: ", stringify!(in_addr)) + ); + assert_eq!( + ::std::mem::align_of::<in_addr>(), + 4usize, + concat!("Alignment of ", stringify!(in_addr)) + ); + assert_eq!( + unsafe { &(*(0 as *const in_addr)).s_addr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(in_addr), + "::", + stringify!(s_addr) + ) + ); } impl Clone for in_addr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -268,23 +320,41 @@ pub struct ip_mreq { } #[test] fn bindgen_test_layout_ip_mreq() { - assert_eq!(::std::mem::size_of::<ip_mreq>() , 8usize , concat ! ( - "Size of: " , stringify ! ( ip_mreq ) )); - assert_eq! (::std::mem::align_of::<ip_mreq>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( ip_mreq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreq ) ) . imr_multiaddr as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreq ) , "::" , - stringify ! ( imr_multiaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreq ) ) . imr_interface as * const _ - as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreq ) , "::" , - stringify ! ( imr_interface ) )); + assert_eq!( + ::std::mem::size_of::<ip_mreq>(), + 8usize, + concat!("Size of: ", stringify!(ip_mreq)) + ); + assert_eq!( + ::std::mem::align_of::<ip_mreq>(), + 4usize, + concat!("Alignment of ", stringify!(ip_mreq)) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreq)).imr_multiaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreq), + "::", + stringify!(imr_multiaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreq)).imr_interface as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreq), + "::", + stringify!(imr_interface) + ) + ); } impl Clone for ip_mreq { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -295,28 +365,51 @@ pub struct ip_mreqn { } #[test] fn bindgen_test_layout_ip_mreqn() { - assert_eq!(::std::mem::size_of::<ip_mreqn>() , 12usize , concat ! ( - "Size of: " , stringify ! ( ip_mreqn ) )); - assert_eq! (::std::mem::align_of::<ip_mreqn>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( ip_mreqn ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreqn ) ) . imr_multiaddr as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreqn ) , "::" , - stringify ! ( imr_multiaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreqn ) ) . imr_address as * const _ - as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreqn ) , "::" , - stringify ! ( imr_address ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreqn ) ) . imr_ifindex as * const _ - as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreqn ) , "::" , - stringify ! ( imr_ifindex ) )); + assert_eq!( + ::std::mem::size_of::<ip_mreqn>(), + 12usize, + concat!("Size of: ", stringify!(ip_mreqn)) + ); + assert_eq!( + ::std::mem::align_of::<ip_mreqn>(), + 4usize, + concat!("Alignment of ", stringify!(ip_mreqn)) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreqn)).imr_multiaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreqn), + "::", + stringify!(imr_multiaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreqn)).imr_address as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreqn), + "::", + stringify!(imr_address) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreqn)).imr_ifindex as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreqn), + "::", + stringify!(imr_ifindex) + ) + ); } impl Clone for ip_mreqn { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -327,28 +420,51 @@ pub struct ip_mreq_source { } #[test] fn bindgen_test_layout_ip_mreq_source() { - assert_eq!(::std::mem::size_of::<ip_mreq_source>() , 12usize , concat ! ( - "Size of: " , stringify ! ( ip_mreq_source ) )); - assert_eq! (::std::mem::align_of::<ip_mreq_source>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( ip_mreq_source ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreq_source ) ) . imr_multiaddr as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreq_source ) , "::" - , stringify ! ( imr_multiaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreq_source ) ) . imr_interface as * - const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreq_source ) , "::" - , stringify ! ( imr_interface ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_mreq_source ) ) . imr_sourceaddr as * - const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_mreq_source ) , "::" - , stringify ! ( imr_sourceaddr ) )); + assert_eq!( + ::std::mem::size_of::<ip_mreq_source>(), + 12usize, + concat!("Size of: ", stringify!(ip_mreq_source)) + ); + assert_eq!( + ::std::mem::align_of::<ip_mreq_source>(), + 4usize, + concat!("Alignment of ", stringify!(ip_mreq_source)) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreq_source)).imr_multiaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreq_source), + "::", + stringify!(imr_multiaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreq_source)).imr_interface as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreq_source), + "::", + stringify!(imr_interface) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_mreq_source)).imr_sourceaddr as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(ip_mreq_source), + "::", + stringify!(imr_sourceaddr) + ) + ); } impl Clone for ip_mreq_source { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -361,38 +477,71 @@ pub struct ip_msfilter { } #[test] fn bindgen_test_layout_ip_msfilter() { - assert_eq!(::std::mem::size_of::<ip_msfilter>() , 20usize , concat ! ( - "Size of: " , stringify ! ( ip_msfilter ) )); - assert_eq! (::std::mem::align_of::<ip_msfilter>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( ip_msfilter ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_msfilter ) ) . imsf_multiaddr as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_msfilter ) , "::" , - stringify ! ( imsf_multiaddr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_msfilter ) ) . imsf_interface as * - const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_msfilter ) , "::" , - stringify ! ( imsf_interface ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_msfilter ) ) . imsf_fmode as * const _ - as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_msfilter ) , "::" , - stringify ! ( imsf_fmode ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_msfilter ) ) . imsf_numsrc as * const - _ as usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_msfilter ) , "::" , - stringify ! ( imsf_numsrc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ip_msfilter ) ) . imsf_slist as * const _ - as usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( ip_msfilter ) , "::" , - stringify ! ( imsf_slist ) )); + assert_eq!( + ::std::mem::size_of::<ip_msfilter>(), + 20usize, + concat!("Size of: ", stringify!(ip_msfilter)) + ); + assert_eq!( + ::std::mem::align_of::<ip_msfilter>(), + 4usize, + concat!("Alignment of ", stringify!(ip_msfilter)) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_msfilter)).imsf_multiaddr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ip_msfilter), + "::", + stringify!(imsf_multiaddr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_msfilter)).imsf_interface as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(ip_msfilter), + "::", + stringify!(imsf_interface) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_msfilter)).imsf_fmode as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(ip_msfilter), + "::", + stringify!(imsf_fmode) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_msfilter)).imsf_numsrc as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(ip_msfilter), + "::", + stringify!(imsf_numsrc) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ip_msfilter)).imsf_slist as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(ip_msfilter), + "::", + stringify!(imsf_slist) + ) + ); } impl Clone for ip_msfilter { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] pub struct group_req { @@ -401,23 +550,41 @@ pub struct group_req { } #[test] fn bindgen_test_layout_group_req() { - assert_eq!(::std::mem::size_of::<group_req>() , 136usize , concat ! ( - "Size of: " , stringify ! ( group_req ) )); - assert_eq! (::std::mem::align_of::<group_req>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( group_req ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_req ) ) . gr_interface as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( group_req ) , "::" , - stringify ! ( gr_interface ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_req ) ) . gr_group as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( group_req ) , "::" , - stringify ! ( gr_group ) )); + assert_eq!( + ::std::mem::size_of::<group_req>(), + 136usize, + concat!("Size of: ", stringify!(group_req)) + ); + assert_eq!( + ::std::mem::align_of::<group_req>(), + 8usize, + concat!("Alignment of ", stringify!(group_req)) + ); + assert_eq!( + unsafe { &(*(0 as *const group_req)).gr_interface as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(group_req), + "::", + stringify!(gr_interface) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_req)).gr_group as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(group_req), + "::", + stringify!(gr_group) + ) + ); } impl Default for group_req { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[repr(C)] pub struct group_source_req { @@ -427,28 +594,51 @@ pub struct group_source_req { } #[test] fn bindgen_test_layout_group_source_req() { - assert_eq!(::std::mem::size_of::<group_source_req>() , 264usize , concat ! - ( "Size of: " , stringify ! ( group_source_req ) )); - assert_eq! (::std::mem::align_of::<group_source_req>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( group_source_req ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_source_req ) ) . gsr_interface as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( group_source_req ) , - "::" , stringify ! ( gsr_interface ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_source_req ) ) . gsr_group as * - const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( group_source_req ) , - "::" , stringify ! ( gsr_group ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_source_req ) ) . gsr_source as * - const _ as usize } , 136usize , concat ! ( - "Alignment of field: " , stringify ! ( group_source_req ) , - "::" , stringify ! ( gsr_source ) )); + assert_eq!( + ::std::mem::size_of::<group_source_req>(), + 264usize, + concat!("Size of: ", stringify!(group_source_req)) + ); + assert_eq!( + ::std::mem::align_of::<group_source_req>(), + 8usize, + concat!("Alignment of ", stringify!(group_source_req)) + ); + assert_eq!( + unsafe { &(*(0 as *const group_source_req)).gsr_interface as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(group_source_req), + "::", + stringify!(gsr_interface) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_source_req)).gsr_group as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(group_source_req), + "::", + stringify!(gsr_group) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_source_req)).gsr_source as *const _ as usize }, + 136usize, + concat!( + "Alignment of field: ", + stringify!(group_source_req), + "::", + stringify!(gsr_source) + ) + ); } impl Default for group_source_req { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[repr(C)] pub struct group_filter { @@ -460,38 +650,71 @@ pub struct group_filter { } #[test] fn bindgen_test_layout_group_filter() { - assert_eq!(::std::mem::size_of::<group_filter>() , 272usize , concat ! ( - "Size of: " , stringify ! ( group_filter ) )); - assert_eq! (::std::mem::align_of::<group_filter>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( group_filter ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_filter ) ) . gf_interface as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( group_filter ) , "::" , - stringify ! ( gf_interface ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_filter ) ) . gf_group as * const _ - as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( group_filter ) , "::" , - stringify ! ( gf_group ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_filter ) ) . gf_fmode as * const _ - as usize } , 136usize , concat ! ( - "Alignment of field: " , stringify ! ( group_filter ) , "::" , - stringify ! ( gf_fmode ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_filter ) ) . gf_numsrc as * const _ - as usize } , 140usize , concat ! ( - "Alignment of field: " , stringify ! ( group_filter ) , "::" , - stringify ! ( gf_numsrc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const group_filter ) ) . gf_slist as * const _ - as usize } , 144usize , concat ! ( - "Alignment of field: " , stringify ! ( group_filter ) , "::" , - stringify ! ( gf_slist ) )); + assert_eq!( + ::std::mem::size_of::<group_filter>(), + 272usize, + concat!("Size of: ", stringify!(group_filter)) + ); + assert_eq!( + ::std::mem::align_of::<group_filter>(), + 8usize, + concat!("Alignment of ", stringify!(group_filter)) + ); + assert_eq!( + unsafe { &(*(0 as *const group_filter)).gf_interface as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(group_filter), + "::", + stringify!(gf_interface) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_filter)).gf_group as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(group_filter), + "::", + stringify!(gf_group) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_filter)).gf_fmode as *const _ as usize }, + 136usize, + concat!( + "Alignment of field: ", + stringify!(group_filter), + "::", + stringify!(gf_fmode) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_filter)).gf_numsrc as *const _ as usize }, + 140usize, + concat!( + "Alignment of field: ", + stringify!(group_filter), + "::", + stringify!(gf_numsrc) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const group_filter)).gf_slist as *const _ as usize }, + 144usize, + concat!( + "Alignment of field: ", + stringify!(group_filter), + "::", + stringify!(gf_slist) + ) + ); } impl Default for group_filter { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -502,28 +725,51 @@ pub struct in_pktinfo { } #[test] fn bindgen_test_layout_in_pktinfo() { - assert_eq!(::std::mem::size_of::<in_pktinfo>() , 12usize , concat ! ( - "Size of: " , stringify ! ( in_pktinfo ) )); - assert_eq! (::std::mem::align_of::<in_pktinfo>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( in_pktinfo ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const in_pktinfo ) ) . ipi_ifindex as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( in_pktinfo ) , "::" , - stringify ! ( ipi_ifindex ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const in_pktinfo ) ) . ipi_spec_dst as * const - _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( in_pktinfo ) , "::" , - stringify ! ( ipi_spec_dst ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const in_pktinfo ) ) . ipi_addr as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( in_pktinfo ) , "::" , - stringify ! ( ipi_addr ) )); + assert_eq!( + ::std::mem::size_of::<in_pktinfo>(), + 12usize, + concat!("Size of: ", stringify!(in_pktinfo)) + ); + assert_eq!( + ::std::mem::align_of::<in_pktinfo>(), + 4usize, + concat!("Alignment of ", stringify!(in_pktinfo)) + ); + assert_eq!( + unsafe { &(*(0 as *const in_pktinfo)).ipi_ifindex as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(in_pktinfo), + "::", + stringify!(ipi_ifindex) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const in_pktinfo)).ipi_spec_dst as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(in_pktinfo), + "::", + stringify!(ipi_spec_dst) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const in_pktinfo)).ipi_addr as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(in_pktinfo), + "::", + stringify!(ipi_addr) + ) + ); } impl Clone for in_pktinfo { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -535,31 +781,59 @@ pub struct sockaddr_in { } #[test] fn bindgen_test_layout_sockaddr_in() { - assert_eq!(::std::mem::size_of::<sockaddr_in>() , 16usize , concat ! ( - "Size of: " , stringify ! ( sockaddr_in ) )); - assert_eq! (::std::mem::align_of::<sockaddr_in>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( sockaddr_in ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_in ) ) . sin_family as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_in ) , "::" , - stringify ! ( sin_family ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_in ) ) . sin_port as * const _ - as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_in ) , "::" , - stringify ! ( sin_port ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_in ) ) . sin_addr as * const _ - as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_in ) , "::" , - stringify ! ( sin_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const sockaddr_in ) ) . __pad as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( sockaddr_in ) , "::" , - stringify ! ( __pad ) )); + assert_eq!( + ::std::mem::size_of::<sockaddr_in>(), + 16usize, + concat!("Size of: ", stringify!(sockaddr_in)) + ); + assert_eq!( + ::std::mem::align_of::<sockaddr_in>(), + 4usize, + concat!("Alignment of ", stringify!(sockaddr_in)) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_in)).sin_family as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_in), + "::", + stringify!(sin_family) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_in)).sin_port as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_in), + "::", + stringify!(sin_port) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_in)).sin_addr as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_in), + "::", + stringify!(sin_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sockaddr_in)).__pad as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(sockaddr_in), + "::", + stringify!(__pad) + ) + ); } impl Clone for sockaddr_in { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } diff --git a/net_sys/src/lib.rs b/net_sys/src/lib.rs index 594cbec..5e2df00 100644 --- a/net_sys/src/lib.rs +++ b/net_sys/src/lib.rs @@ -27,8 +27,8 @@ pub mod inn; // generated with bindgen /usr/include/linux/sockios.h --no-unstable-rust // --constified-enum '*' --with-derive-default pub mod sockios; -pub use iff::*; pub use if_tun::*; +pub use iff::*; pub use inn::*; pub use sockios::*; diff --git a/net_util/src/lib.rs b/net_util/src/lib.rs index 0826729..06c3f17 100644 --- a/net_util/src/lib.rs +++ b/net_util/src/lib.rs @@ -8,7 +8,7 @@ extern crate sys_util; use std::fmt; use std::fs::File; -use std::io::{Read, Write, Result as IoResult}; +use std::io::{Read, Result as IoResult, Write}; use std::mem; use std::net; use std::num::ParseIntError; @@ -18,8 +18,8 @@ use std::str::FromStr; use libc::EPERM; -use sys_util::{Error as SysError}; -use sys_util::{ioctl_with_val, ioctl_with_ref, ioctl_with_mut_ref}; +use sys_util::Error as SysError; +use sys_util::{ioctl_with_mut_ref, ioctl_with_ref, ioctl_with_val}; #[derive(Debug)] pub enum Error { @@ -86,7 +86,6 @@ pub enum MacAddressError { InvalidNumOctets(usize), /// Failed to parse octet. ParseOctet(ParseIntError), - } impl fmt::Display for MacAddressError { @@ -137,14 +136,11 @@ impl FromStr for MacAddress { impl fmt::Display for MacAddress { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, - "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", - self.addr[0], - self.addr[1], - self.addr[2], - self.addr[3], - self.addr[4], - self.addr[5]) + write!( + f, + "{:02X}:{:02X}:{:02X}:{:02X}:{:02X}:{:02X}", + self.addr[0], self.addr[1], self.addr[2], self.addr[3], self.addr[4], self.addr[5] + ) } } @@ -201,8 +197,10 @@ impl TapT for Tap { // Open calls are safe because we give a constant nul-terminated // string and verify the result. let fd = unsafe { - libc::open(b"/dev/net/tun\0".as_ptr() as *const c_char, - libc::O_RDWR | libc::O_NONBLOCK | libc::O_CLOEXEC) + libc::open( + b"/dev/net/tun\0".as_ptr() as *const c_char, + libc::O_RDWR | libc::O_NONBLOCK | libc::O_CLOEXEC, + ) }; if fd < 0 { return Err(Error::OpenTun(SysError::last())); @@ -222,9 +220,10 @@ impl TapT for Tap { let ifru_flags = ifreq.ifr_ifru.ifru_flags.as_mut(); let name_slice = &mut ifrn_name[..TUNTAP_DEV_FORMAT.len()]; name_slice.copy_from_slice(TUNTAP_DEV_FORMAT); - *ifru_flags = (net_sys::IFF_TAP | - net_sys::IFF_NO_PI | - if vnet_hdr { net_sys::IFF_VNET_HDR } else { 0 }) as c_short; + *ifru_flags = (net_sys::IFF_TAP + | net_sys::IFF_NO_PI + | if vnet_hdr { net_sys::IFF_VNET_HDR } else { 0 }) + as c_short; } // ioctl is safe since we call it with a valid tap fd and check the return @@ -242,9 +241,9 @@ impl TapT for Tap { // Safe since only the name is accessed, and it's cloned out. Ok(Tap { - tap_file: tuntap, - if_name: unsafe { ifreq.ifr_ifrn.ifrn_name.as_ref().clone() }, - }) + tap_file: tuntap, + if_name: unsafe { ifreq.ifr_ifrn.ifrn_name.as_ref().clone() }, + }) } fn ip_addr(&self) -> Result<net::Ipv4Addr> { @@ -252,9 +251,9 @@ impl TapT for Tap { let mut ifreq = self.get_ifreq(); // ioctl is safe. Called with a valid sock fd, and we check the return. - let ret = unsafe { ioctl_with_mut_ref(&sock, - net_sys::sockios::SIOCGIFADDR as c_ulong, - &mut ifreq) }; + let ret = unsafe { + ioctl_with_mut_ref(&sock, net_sys::sockios::SIOCGIFADDR as c_ulong, &mut ifreq) + }; if ret < 0 { return Err(Error::IoctlError(SysError::last())); } @@ -292,9 +291,13 @@ impl TapT for Tap { let mut ifreq = self.get_ifreq(); // ioctl is safe. Called with a valid sock fd, and we check the return. - let ret = unsafe { ioctl_with_mut_ref(&sock, - net_sys::sockios::SIOCGIFNETMASK as c_ulong, - &mut ifreq) }; + let ret = unsafe { + ioctl_with_mut_ref( + &sock, + net_sys::sockios::SIOCGIFNETMASK as c_ulong, + &mut ifreq, + ) + }; if ret < 0 { return Err(Error::IoctlError(SysError::last())); } @@ -332,9 +335,13 @@ impl TapT for Tap { let mut ifreq = self.get_ifreq(); // ioctl is safe. Called with a valid sock fd, and we check the return. - let ret = unsafe { ioctl_with_mut_ref(&sock, - net_sys::sockios::SIOCGIFHWADDR as c_ulong, - &mut ifreq) }; + let ret = unsafe { + ioctl_with_mut_ref( + &sock, + net_sys::sockios::SIOCGIFHWADDR as c_ulong, + &mut ifreq, + ) + }; if ret < 0 { return Err(Error::IoctlError(SysError::last())); } @@ -344,7 +351,7 @@ impl TapT for Tap { // This is safe since the MacAddress struct is already sized to match the C sockaddr // struct. The address family has also been checked. - Ok(unsafe { mem::transmute(*ifru_hwaddr)} ) + Ok(unsafe { mem::transmute(*ifru_hwaddr) }) } fn set_mac_address(&self, mac_addr: MacAddress) -> Result<()> { @@ -389,8 +396,8 @@ impl TapT for Tap { // We only access one field of the ifru union, hence this is safe. unsafe { let ifru_flags = ifreq.ifr_ifru.ifru_flags.as_mut(); - *ifru_flags = (net_sys::net_device_flags_IFF_UP | - net_sys::net_device_flags_IFF_RUNNING) as i16; + *ifru_flags = + (net_sys::net_device_flags_IFF_UP | net_sys::net_device_flags_IFF_RUNNING) as i16; } // ioctl is safe. Called with a valid sock fd, and we check the return. @@ -460,8 +467,8 @@ impl FromRawFd for Tap { pub mod fakes { use super::*; - use std::fs::OpenOptions; use std::fs::remove_file; + use std::fs::OpenOptions; const TMP_FILE: &str = "/tmp/crosvm_tap_test_file"; @@ -477,7 +484,7 @@ pub mod fakes { .append(true) .create(true) .open(TMP_FILE) - .unwrap() + .unwrap(), }) } @@ -608,14 +615,17 @@ mod tests { fn tap_get_ifreq() { let tap = Tap::new(true).unwrap(); let ret = tap.get_ifreq(); - assert_eq!("__BindgenUnionField", format!("{:?}", ret.ifr_ifrn.ifrn_name)); + assert_eq!( + "__BindgenUnionField", + format!("{:?}", ret.ifr_ifrn.ifrn_name) + ); } fn assert_ok_or_perm_denied<T>(res: Result<T>) { match res { // We won't have permission in test environments; allow that - Ok(_t) => {}, - Err(Error::IoctlError(ref e)) if e.errno() == EPERM => {}, + Ok(_t) => {} + Err(Error::IoctlError(ref e)) if e.errno() == EPERM => {} Err(e) => panic!("Unexpected Error:\n{:?}", e), } } diff --git a/p9/src/protocol/messages.rs b/p9/src/protocol/messages.rs index 23f0d9f..b10312b 100644 --- a/p9/src/protocol/messages.rs +++ b/p9/src/protocol/messages.rs @@ -281,7 +281,7 @@ impl WireFormat for Tframe { )), }?; - Ok(Tframe { tag: tag, msg: msg }) + Ok(Tframe { tag, msg }) } } @@ -691,7 +691,7 @@ impl WireFormat for Rframe { )), }?; - Ok(Rframe { tag: tag, msg: msg }) + Ok(Rframe { tag, msg }) } } diff --git a/p9/src/protocol/wire_format.rs b/p9/src/protocol/wire_format.rs index 3dae0f9..afdc097 100644 --- a/p9/src/protocol/wire_format.rs +++ b/p9/src/protocol/wire_format.rs @@ -59,7 +59,7 @@ macro_rules! uint_wire_format_impl { Ok(result) } } - } + }; } uint_wire_format_impl!(u8); uint_wire_format_impl!(u16); @@ -128,7 +128,6 @@ impl<T: WireFormat> WireFormat for Vec<T> { } } - /// A type that encodes an arbitrary number of bytes of data. Typically used for Rread /// Twrite messages. This differs from a `Vec<u8>` in that it encodes the number of bytes /// using a `u32` instead of a `u16`. @@ -384,24 +383,24 @@ mod test { #[test] fn invalid_string_decode() { let _ = <String as WireFormat>::decode(&mut Cursor::new(&[ - 0x06, 0x00, 0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf + 0x06, 0x00, 0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf, ])).expect_err("surrogate code point"); let _ = <String as WireFormat>::decode(&mut Cursor::new(&[ - 0x05, 0x00, 0xf8, 0x80, 0x80, 0x80, 0xbf + 0x05, 0x00, 0xf8, 0x80, 0x80, 0x80, 0xbf, ])).expect_err("overlong sequence"); - let _ = <String as WireFormat>::decode(&mut Cursor::new(&[ - 0x04, 0x00, 0xf4, 0x90, 0x80, 0x80 - ])).expect_err("out of range"); + let _ = + <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0xf4, 0x90, 0x80, 0x80])) + .expect_err("out of range"); - let _ = <String as WireFormat>::decode(&mut Cursor::new(&[ - 0x04, 0x00, 0x63, 0x61, 0x66, 0xe9 - ])).expect_err("ISO-8859-1"); + let _ = + <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0x63, 0x61, 0x66, 0xe9])) + .expect_err("ISO-8859-1"); - let _ = <String as WireFormat>::decode(&mut Cursor::new(&[ - 0x04, 0x00, 0xb0, 0xa1, 0xb0, 0xa2 - ])).expect_err("EUC-KR"); + let _ = + <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0xb0, 0xa1, 0xb0, 0xa2])) + .expect_err("EUC-KR"); } #[test] diff --git a/p9/src/server.rs b/p9/src/server.rs index 8f1d649..d3d7547 100644 --- a/p9/src/server.rs +++ b/p9/src/server.rs @@ -121,7 +121,7 @@ fn metadata_to_qid(metadata: &fs::Metadata) -> Qid { }; Qid { - ty: ty, + ty, // TODO: deal with the 2038 problem before 2038 version: metadata.st_mtime() as u32, path: metadata.st_ino(), @@ -345,7 +345,8 @@ impl Server { } // We need to walk the tree. First get the starting path. - let (buf, oldmd) = self.fids + let (buf, oldmd) = self + .fids .get(&walk.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF)) .map(|fid| (fid.path.to_path_buf(), fid.metadata.clone()))?; @@ -389,7 +390,8 @@ impl Server { fn read(&mut self, read: &Tread) -> io::Result<Rmessage> { // Thankfully, `read` cannot be used to read directories in 9P2000.L. - let file = self.fids + let file = self + .fids .get_mut(&read.fid) .and_then(|fid| fid.file.as_mut()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -413,7 +415,8 @@ impl Server { } fn write(&mut self, write: &Twrite) -> io::Result<Rmessage> { - let file = self.fids + let file = self + .fids .get_mut(&write.fid) .and_then(|fid| fid.file.as_mut()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -452,10 +455,12 @@ impl Server { } fn statfs(&mut self, statfs: &Tstatfs) -> io::Result<Rmessage> { - let fid = self.fids + let fid = self + .fids .get(&statfs.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; - let path = fid.path + let path = fid + .path .to_str() .and_then(|path| CString::new(path).ok()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?; @@ -484,7 +489,8 @@ impl Server { } fn lopen(&mut self, lopen: &Tlopen) -> io::Result<Rmessage> { - let fid = self.fids + let fid = self + .fids .get_mut(&lopen.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; // We always open files with O_CLOEXEC. @@ -515,7 +521,8 @@ impl Server { } fn lcreate(&mut self, lcreate: &Tlcreate) -> io::Result<Rmessage> { - let fid = self.fids + let fid = self + .fids .get_mut(&lcreate.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -566,13 +573,15 @@ impl Server { fn rename(&mut self, rename: &Trename) -> io::Result<Rmessage> { let newname = Path::new(&rename.name); - let buf = self.fids + let buf = self + .fids .get(&rename.dfid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF)) .map(|dfid| dfid.path.to_path_buf())?; let newpath = join_path(buf, newname, &*self.root)?; - let fid = self.fids + let fid = self + .fids .get_mut(&rename.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EINVAL))?; @@ -590,7 +599,8 @@ impl Server { } fn get_attr(&mut self, get_attr: &Tgetattr) -> io::Result<Rmessage> { - let fid = self.fids + let fid = self + .fids .get_mut(&get_attr.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -627,7 +637,8 @@ impl Server { return Err(io::Error::from_raw_os_error(libc::EPERM)); } - let fid = self.fids + let fid = self + .fids .get_mut(&set_attr.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; let file = fs::OpenOptions::new().write(true).open(&fid.path)?; @@ -696,7 +707,8 @@ impl Server { } fn readdir(&mut self, readdir: &Treaddir) -> io::Result<Rmessage> { - let fid = self.fids + let fid = self + .fids .get_mut(&readdir.fid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -735,10 +747,10 @@ impl Server { .map_err(|_| io::Error::from_raw_os_error(libc::EINVAL))?; let mut out = Dirent { - qid: qid, + qid, offset: 0, // set below - ty: ty, - name: name, + ty, + name, }; offset += out.byte_size() as u64; @@ -752,7 +764,8 @@ impl Server { fid.dirents = Some(dirents.collect::<io::Result<Vec<Dirent>>>()?); } - let mut entries = fid.dirents + let mut entries = fid + .dirents .as_ref() .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))? .iter() @@ -793,7 +806,8 @@ impl Server { } fn fsync(&mut self, fsync: &Tfsync) -> io::Result<Rmessage> { - let file = self.fids + let file = self + .fids .get(&fsync.fid) .and_then(|fid| fid.file.as_ref()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -817,13 +831,15 @@ impl Server { fn link(&mut self, link: &Tlink) -> io::Result<Rmessage> { let newname = Path::new(&link.name); - let buf = self.fids + let buf = self + .fids .get(&link.dfid) .map(|dfid| dfid.path.to_path_buf()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; let newpath = join_path(buf, newname, &*self.root)?; - let path = self.fids + let path = self + .fids .get(&link.fid) .map(|fid| &fid.path) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -833,7 +849,8 @@ impl Server { } fn mkdir(&mut self, mkdir: &Tmkdir) -> io::Result<Rmessage> { - let fid = self.fids + let fid = self + .fids .get(&mkdir.dfid) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -852,14 +869,16 @@ impl Server { fn rename_at(&mut self, rename_at: &Trenameat) -> io::Result<Rmessage> { let oldname = Path::new(&rename_at.oldname); - let oldbuf = self.fids + let oldbuf = self + .fids .get(&rename_at.olddirfid) .map(|dfid| dfid.path.to_path_buf()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; let oldpath = join_path(oldbuf, oldname, &*self.root)?; let newname = Path::new(&rename_at.newname); - let newbuf = self.fids + let newbuf = self + .fids .get(&rename_at.newdirfid) .map(|dfid| dfid.path.to_path_buf()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; @@ -871,7 +890,8 @@ impl Server { fn unlink_at(&mut self, unlink_at: &Tunlinkat) -> io::Result<Rmessage> { let name = Path::new(&unlink_at.name); - let buf = self.fids + let buf = self + .fids .get(&unlink_at.dirfd) .map(|fid| fid.path.to_path_buf()) .ok_or_else(|| io::Error::from_raw_os_error(libc::EBADF))?; diff --git a/plugin_proto/build.rs b/plugin_proto/build.rs index 5e30fcd..852a1ae 100644 --- a/plugin_proto/build.rs +++ b/plugin_proto/build.rs @@ -13,15 +13,15 @@ fn main() { let out_dir = PathBuf::from(env::var("OUT_DIR").unwrap()); protoc_rust::run(protoc_rust::Args { - out_dir: out_dir.as_os_str().to_str().unwrap(), - input: &["protos/plugin.proto"], - includes: &["protos"], - }) - .expect("protoc"); + out_dir: out_dir.as_os_str().to_str().unwrap(), + input: &["protos/plugin.proto"], + includes: &["protos"], + }).expect("protoc"); let mut mod_out = fs::File::create(out_dir.join("proto_include.rs")).unwrap(); - writeln!(mod_out, - "#[path = \"{}\"] pub mod plugin_proto;\npub use plugin_proto::*;", - out_dir.join("plugin.rs").display()) - .unwrap(); + writeln!( + mod_out, + "#[path = \"{}\"] pub mod plugin_proto;\npub use plugin_proto::*;", + out_dir.join("plugin.rs").display() + ).unwrap(); } diff --git a/plugin_proto/src/lib.rs b/plugin_proto/src/lib.rs index c28635a..ff95be9 100644 --- a/plugin_proto/src/lib.rs +++ b/plugin_proto/src/lib.rs @@ -1,5 +1,5 @@ -extern crate protobuf; extern crate kvm_sys; +extern crate protobuf; include!(concat!(env!("OUT_DIR"), "/proto_include.rs")); /// Converts protobuf representation of CpuId data into KVM format. diff --git a/qcow/src/qcow.rs b/qcow/src/qcow.rs index fd25053..0e08c14 100644 --- a/qcow/src/qcow.rs +++ b/qcow/src/qcow.rs @@ -182,19 +182,21 @@ impl QcowHeader { autoclear_features: 0, refcount_order: DEFAULT_REFCOUNT_ORDER, header_size: V3_BARE_HEADER_SIZE, - } + } } /// Write the header to `file`. pub fn write_to<F: Write + Seek>(&self, file: &mut F) -> Result<()> { // Writes the next u32 to the file. fn write_u32_to_file<F: Write>(f: &mut F, value: u32) -> Result<()> { - f.write_u32::<BigEndian>(value).map_err(Error::WritingHeader) + f.write_u32::<BigEndian>(value) + .map_err(Error::WritingHeader) } // Writes the next u64 to the file. fn write_u64_to_file<F: Write>(f: &mut F, value: u64) -> Result<()> { - f.write_u64::<BigEndian>(value).map_err(Error::WritingHeader) + f.write_u64::<BigEndian>(value) + .map_err(Error::WritingHeader) } write_u32_to_file(file, self.magic)?; @@ -221,10 +223,10 @@ impl QcowHeader { // Zeros out the l1 and refcount table clusters. let cluster_size = 0x01u64 << self.cluster_bits; let refcount_blocks_size = u64::from(self.refcount_table_clusters) * cluster_size; - file.seek(SeekFrom::Start(self.refcount_table_offset + refcount_blocks_size - 2)) - .map_err(Error::WritingHeader)?; - file.write(&[0u8]) - .map_err(Error::WritingHeader)?; + file.seek(SeekFrom::Start( + self.refcount_table_offset + refcount_blocks_size - 2, + )).map_err(Error::WritingHeader)?; + file.write(&[0u8]).map_err(Error::WritingHeader)?; Ok(()) } @@ -311,18 +313,20 @@ impl QcowFile { offset_is_cluster_boundary(header.refcount_table_offset, header.cluster_bits)?; offset_is_cluster_boundary(header.snapshots_offset, header.cluster_bits)?; - let mut raw_file = QcowRawFile::from(file, cluster_size).ok_or(Error::InvalidClusterSize)?; + let mut raw_file = + QcowRawFile::from(file, cluster_size).ok_or(Error::InvalidClusterSize)?; let l2_size = cluster_size / size_of::<u64>() as u64; let num_clusters = div_round_up_u64(header.size, u64::from(cluster_size)); let num_l2_clusters = div_round_up_u64(num_clusters, l2_size); - let l1_table = VecCache::from_vec(raw_file - .read_pointer_table( - header.l1_table_offset, - num_l2_clusters, - Some(L1_TABLE_OFFSET_MASK), - ) - .map_err(Error::ReadingHeader)?); + let l1_table = VecCache::from_vec( + raw_file + .read_pointer_table( + header.l1_table_offset, + num_l2_clusters, + Some(L1_TABLE_OFFSET_MASK), + ).map_err(Error::ReadingHeader)?, + ); let num_clusters = div_round_up_u64(header.size, u64::from(cluster_size)) as u32; let refcount_clusters = @@ -374,8 +378,8 @@ impl QcowFile { // Set the refcount for each refcount table cluster. let cluster_size = 0x01u64 << qcow.header.cluster_bits; let refcount_table_base = qcow.header.refcount_table_offset as u64; - let end_cluster_addr = refcount_table_base + - u64::from(qcow.header.refcount_table_clusters) * cluster_size; + let end_cluster_addr = + refcount_table_base + u64::from(qcow.header.refcount_table_clusters) * cluster_size; let mut cluster_addr = 0; while cluster_addr < end_cluster_addr { @@ -423,8 +427,7 @@ impl QcowFile { evicted.get_values(), CLUSTER_USED_FLAG, ) - }) - .map_err(Error::EvictingCache)?; + }).map_err(Error::EvictingCache)?; } // The index must exist as it was just inserted if it didn't already. @@ -729,9 +732,13 @@ impl QcowFile { // This cluster is no longer in use; deallocate the storage. // The underlying FS may not support FALLOC_FL_PUNCH_HOLE, // so don't treat an error as fatal. Future reads will return zeros anyways. - let _ = fallocate(self.raw_file.file_mut(), - FallocateMode::PunchHole, true, - cluster_addr, cluster_size); + let _ = fallocate( + self.raw_file.file_mut(), + FallocateMode::PunchHole, + true, + cluster_addr, + cluster_size, + ); self.unref_clusters.push(cluster_addr); } Ok(()) @@ -813,8 +820,11 @@ impl QcowFile { // The index must be valid from when we insterted it. let addr = self.l1_table[*l1_index]; if addr != 0 { - self.raw_file - .write_pointer_table(addr, l2_table.get_values(), CLUSTER_USED_FLAG)?; + self.raw_file.write_pointer_table( + addr, + l2_table.get_values(), + CLUSTER_USED_FLAG, + )?; } else { return Err(std::io::Error::from_raw_os_error(EINVAL)); } @@ -829,8 +839,11 @@ impl QcowFile { // guaranteed to be valid. let mut sync_required = false; if self.l1_table.dirty() { - self.raw_file - .write_pointer_table(self.header.l1_table_offset, &self.l1_table.get_values(), 0)?; + self.raw_file.write_pointer_table( + self.header.l1_table_offset, + &self.l1_table.get_values(), + 0, + )?; self.l1_table.mark_clean(); sync_required = true; } @@ -890,18 +903,16 @@ impl Seek for QcowFile { SeekFrom::Start(off) => Some(off), SeekFrom::End(off) => { if off < 0 { - 0i64.checked_sub(off).and_then(|increment| { - self.virtual_size().checked_sub(increment as u64) - }) + 0i64.checked_sub(off) + .and_then(|increment| self.virtual_size().checked_sub(increment as u64)) } else { self.virtual_size().checked_add(off as u64) } } SeekFrom::Current(off) => { if off < 0 { - 0i64.checked_sub(off).and_then(|increment| { - self.current_offset.checked_sub(increment as u64) - }) + 0i64.checked_sub(off) + .and_then(|increment| self.current_offset.checked_sub(increment as u64)) } else { self.current_offset.checked_add(off as u64) } @@ -1004,9 +1015,9 @@ fn div_round_up_u32(dividend: u32, divisor: u32) -> u32 { #[cfg(test)] mod tests { + use super::*; use std::fs::File; use std::io::{Read, Seek, SeekFrom, Write}; - use super::*; use sys_util::SharedMemory; fn valid_header() -> Vec<u8> { @@ -1060,7 +1071,9 @@ mod tests { let header = QcowHeader::create_for_size(0x10_0000); let shm = SharedMemory::new(None).unwrap(); let mut disk_file: File = shm.into(); - header.write_to(&mut disk_file).expect("Failed to write header to shm."); + header + .write_to(&mut disk_file) + .expect("Failed to write header to shm."); disk_file.seek(SeekFrom::Start(0)).unwrap(); QcowFile::from(disk_file).expect("Failed to create Qcow from default Header"); } @@ -1093,9 +1106,8 @@ mod tests { fn write_read_start() { with_basic_file(&valid_header(), |disk_file: File| { let mut q = QcowFile::from(disk_file).unwrap(); - q.write(b"test first bytes").expect( - "Failed to write test string.", - ); + q.write(b"test first bytes") + .expect("Failed to write test string."); let mut buf = [0u8; 4]; q.seek(SeekFrom::Start(0)).expect("Failed to seek."); q.read(&mut buf).expect("Failed to read."); @@ -1198,93 +1210,354 @@ mod tests { // Write transactions from mkfs.ext4. let xfers: Vec<Transfer> = vec![ - Transfer {write: false, addr: 0xfff0000}, - Transfer {write: false, addr: 0xfffe000}, - Transfer {write: false, addr: 0x0}, - Transfer {write: false, addr: 0x1000}, - Transfer {write: false, addr: 0xffff000}, - Transfer {write: false, addr: 0xffdf000}, - Transfer {write: false, addr: 0xfff8000}, - Transfer {write: false, addr: 0xffe0000}, - Transfer {write: false, addr: 0xffce000}, - Transfer {write: false, addr: 0xffb6000}, - Transfer {write: false, addr: 0xffab000}, - Transfer {write: false, addr: 0xffa4000}, - Transfer {write: false, addr: 0xff8e000}, - Transfer {write: false, addr: 0xff86000}, - Transfer {write: false, addr: 0xff84000}, - Transfer {write: false, addr: 0xff89000}, - Transfer {write: false, addr: 0xfe7e000}, - Transfer {write: false, addr: 0x100000}, - Transfer {write: false, addr: 0x3000}, - Transfer {write: false, addr: 0x7000}, - Transfer {write: false, addr: 0xf000}, - Transfer {write: false, addr: 0x2000}, - Transfer {write: false, addr: 0x4000}, - Transfer {write: false, addr: 0x5000}, - Transfer {write: false, addr: 0x6000}, - Transfer {write: false, addr: 0x8000}, - Transfer {write: false, addr: 0x9000}, - Transfer {write: false, addr: 0xa000}, - Transfer {write: false, addr: 0xb000}, - Transfer {write: false, addr: 0xc000}, - Transfer {write: false, addr: 0xd000}, - Transfer {write: false, addr: 0xe000}, - Transfer {write: false, addr: 0x10000}, - Transfer {write: false, addr: 0x11000}, - Transfer {write: false, addr: 0x12000}, - Transfer {write: false, addr: 0x13000}, - Transfer {write: false, addr: 0x14000}, - Transfer {write: false, addr: 0x15000}, - Transfer {write: false, addr: 0x16000}, - Transfer {write: false, addr: 0x17000}, - Transfer {write: false, addr: 0x18000}, - Transfer {write: false, addr: 0x19000}, - Transfer {write: false, addr: 0x1a000}, - Transfer {write: false, addr: 0x1b000}, - Transfer {write: false, addr: 0x1c000}, - Transfer {write: false, addr: 0x1d000}, - Transfer {write: false, addr: 0x1e000}, - Transfer {write: false, addr: 0x1f000}, - Transfer {write: false, addr: 0x21000}, - Transfer {write: false, addr: 0x22000}, - Transfer {write: false, addr: 0x24000}, - Transfer {write: false, addr: 0x40000}, - Transfer {write: false, addr: 0x0}, - Transfer {write: false, addr: 0x3000}, - Transfer {write: false, addr: 0x7000}, - Transfer {write: false, addr: 0x0}, - Transfer {write: false, addr: 0x1000}, - Transfer {write: false, addr: 0x2000}, - Transfer {write: false, addr: 0x3000}, - Transfer {write: false, addr: 0x0}, - Transfer {write: false, addr: 0x449000}, - Transfer {write: false, addr: 0x48000}, - Transfer {write: false, addr: 0x48000}, - Transfer {write: false, addr: 0x448000}, - Transfer {write: false, addr: 0x44a000}, - Transfer {write: false, addr: 0x48000}, - Transfer {write: false, addr: 0x48000}, - Transfer {write: true, addr: 0x0}, - Transfer {write: true, addr: 0x448000}, - Transfer {write: true, addr: 0x449000}, - Transfer {write: true, addr: 0x44a000}, - Transfer {write: true, addr: 0xfff0000}, - Transfer {write: true, addr: 0xfff1000}, - Transfer {write: true, addr: 0xfff2000}, - Transfer {write: true, addr: 0xfff3000}, - Transfer {write: true, addr: 0xfff4000}, - Transfer {write: true, addr: 0xfff5000}, - Transfer {write: true, addr: 0xfff6000}, - Transfer {write: true, addr: 0xfff7000}, - Transfer {write: true, addr: 0xfff8000}, - Transfer {write: true, addr: 0xfff9000}, - Transfer {write: true, addr: 0xfffa000}, - Transfer {write: true, addr: 0xfffb000}, - Transfer {write: true, addr: 0xfffc000}, - Transfer {write: true, addr: 0xfffd000}, - Transfer {write: true, addr: 0xfffe000}, - Transfer {write: true, addr: 0xffff000}, + Transfer { + write: false, + addr: 0xfff0000, + }, + Transfer { + write: false, + addr: 0xfffe000, + }, + Transfer { + write: false, + addr: 0x0, + }, + Transfer { + write: false, + addr: 0x1000, + }, + Transfer { + write: false, + addr: 0xffff000, + }, + Transfer { + write: false, + addr: 0xffdf000, + }, + Transfer { + write: false, + addr: 0xfff8000, + }, + Transfer { + write: false, + addr: 0xffe0000, + }, + Transfer { + write: false, + addr: 0xffce000, + }, + Transfer { + write: false, + addr: 0xffb6000, + }, + Transfer { + write: false, + addr: 0xffab000, + }, + Transfer { + write: false, + addr: 0xffa4000, + }, + Transfer { + write: false, + addr: 0xff8e000, + }, + Transfer { + write: false, + addr: 0xff86000, + }, + Transfer { + write: false, + addr: 0xff84000, + }, + Transfer { + write: false, + addr: 0xff89000, + }, + Transfer { + write: false, + addr: 0xfe7e000, + }, + Transfer { + write: false, + addr: 0x100000, + }, + Transfer { + write: false, + addr: 0x3000, + }, + Transfer { + write: false, + addr: 0x7000, + }, + Transfer { + write: false, + addr: 0xf000, + }, + Transfer { + write: false, + addr: 0x2000, + }, + Transfer { + write: false, + addr: 0x4000, + }, + Transfer { + write: false, + addr: 0x5000, + }, + Transfer { + write: false, + addr: 0x6000, + }, + Transfer { + write: false, + addr: 0x8000, + }, + Transfer { + write: false, + addr: 0x9000, + }, + Transfer { + write: false, + addr: 0xa000, + }, + Transfer { + write: false, + addr: 0xb000, + }, + Transfer { + write: false, + addr: 0xc000, + }, + Transfer { + write: false, + addr: 0xd000, + }, + Transfer { + write: false, + addr: 0xe000, + }, + Transfer { + write: false, + addr: 0x10000, + }, + Transfer { + write: false, + addr: 0x11000, + }, + Transfer { + write: false, + addr: 0x12000, + }, + Transfer { + write: false, + addr: 0x13000, + }, + Transfer { + write: false, + addr: 0x14000, + }, + Transfer { + write: false, + addr: 0x15000, + }, + Transfer { + write: false, + addr: 0x16000, + }, + Transfer { + write: false, + addr: 0x17000, + }, + Transfer { + write: false, + addr: 0x18000, + }, + Transfer { + write: false, + addr: 0x19000, + }, + Transfer { + write: false, + addr: 0x1a000, + }, + Transfer { + write: false, + addr: 0x1b000, + }, + Transfer { + write: false, + addr: 0x1c000, + }, + Transfer { + write: false, + addr: 0x1d000, + }, + Transfer { + write: false, + addr: 0x1e000, + }, + Transfer { + write: false, + addr: 0x1f000, + }, + Transfer { + write: false, + addr: 0x21000, + }, + Transfer { + write: false, + addr: 0x22000, + }, + Transfer { + write: false, + addr: 0x24000, + }, + Transfer { + write: false, + addr: 0x40000, + }, + Transfer { + write: false, + addr: 0x0, + }, + Transfer { + write: false, + addr: 0x3000, + }, + Transfer { + write: false, + addr: 0x7000, + }, + Transfer { + write: false, + addr: 0x0, + }, + Transfer { + write: false, + addr: 0x1000, + }, + Transfer { + write: false, + addr: 0x2000, + }, + Transfer { + write: false, + addr: 0x3000, + }, + Transfer { + write: false, + addr: 0x0, + }, + Transfer { + write: false, + addr: 0x449000, + }, + Transfer { + write: false, + addr: 0x48000, + }, + Transfer { + write: false, + addr: 0x48000, + }, + Transfer { + write: false, + addr: 0x448000, + }, + Transfer { + write: false, + addr: 0x44a000, + }, + Transfer { + write: false, + addr: 0x48000, + }, + Transfer { + write: false, + addr: 0x48000, + }, + Transfer { + write: true, + addr: 0x0, + }, + Transfer { + write: true, + addr: 0x448000, + }, + Transfer { + write: true, + addr: 0x449000, + }, + Transfer { + write: true, + addr: 0x44a000, + }, + Transfer { + write: true, + addr: 0xfff0000, + }, + Transfer { + write: true, + addr: 0xfff1000, + }, + Transfer { + write: true, + addr: 0xfff2000, + }, + Transfer { + write: true, + addr: 0xfff3000, + }, + Transfer { + write: true, + addr: 0xfff4000, + }, + Transfer { + write: true, + addr: 0xfff5000, + }, + Transfer { + write: true, + addr: 0xfff6000, + }, + Transfer { + write: true, + addr: 0xfff7000, + }, + Transfer { + write: true, + addr: 0xfff8000, + }, + Transfer { + write: true, + addr: 0xfff9000, + }, + Transfer { + write: true, + addr: 0xfffa000, + }, + Transfer { + write: true, + addr: 0xfffb000, + }, + Transfer { + write: true, + addr: 0xfffc000, + }, + Transfer { + write: true, + addr: 0xfffd000, + }, + Transfer { + write: true, + addr: 0xfffe000, + }, + Transfer { + write: true, + addr: 0xffff000, + }, ]; for xfer in xfers.iter() { @@ -1309,11 +1582,15 @@ mod tests { let mut readback = [0u8; BLOCK_SIZE]; for i in 0..NUM_BLOCKS { let seek_offset = OFFSET + i * BLOCK_SIZE; - qcow_file.seek(SeekFrom::Start(seek_offset as u64)).expect("Failed to seek."); + qcow_file + .seek(SeekFrom::Start(seek_offset as u64)) + .expect("Failed to seek."); let nwritten = qcow_file.write(&data).expect("Failed to write test data."); assert_eq!(nwritten, BLOCK_SIZE); // Read back the data to check it was written correctly. - qcow_file.seek(SeekFrom::Start(seek_offset as u64)).expect("Failed to seek."); + qcow_file + .seek(SeekFrom::Start(seek_offset as u64)) + .expect("Failed to seek."); let nread = qcow_file.read(&mut readback).expect("Failed to read."); assert_eq!(nread, BLOCK_SIZE); for (orig, read) in data.iter().zip(readback.iter()) { @@ -1330,7 +1607,9 @@ mod tests { // Check the data again after the writes have happened. for i in 0..NUM_BLOCKS { let seek_offset = OFFSET + i * BLOCK_SIZE; - qcow_file.seek(SeekFrom::Start(seek_offset as u64)).expect("Failed to seek."); + qcow_file + .seek(SeekFrom::Start(seek_offset as u64)) + .expect("Failed to seek."); let nread = qcow_file.read(&mut readback).expect("Failed to read."); assert_eq!(nread, BLOCK_SIZE); for (orig, read) in data.iter().zip(readback.iter()) { diff --git a/qcow/src/refcount.rs b/qcow/src/refcount.rs index 13906a1..a39dd3f 100644 --- a/qcow/src/refcount.rs +++ b/qcow/src/refcount.rs @@ -92,8 +92,7 @@ impl RefCount { self.refblock_cache .insert(table_index, table, |index, evicted| { raw_file.write_refcount_block(ref_table[index], evicted.get_values()) - }) - .map_err(Error::EvictingRefCounts)?; + }).map_err(Error::EvictingRefCounts)?; } else { if block_addr_disk == 0 { return Err(Error::NeedNewCluster); @@ -173,8 +172,7 @@ impl RefCount { self.refblock_cache .insert(table_index, table, |index, evicted| { raw_file.write_refcount_block(ref_table[index], evicted.get_values()) - }) - .map_err(Error::EvictingRefCounts)?; + }).map_err(Error::EvictingRefCounts)?; } Ok(self.refblock_cache.get(&table_index).unwrap()[block_index]) } @@ -205,8 +203,7 @@ impl RefCount { self.refblock_cache .insert(table_index, table, |index, evicted| { raw_file.write_refcount_block(ref_table[index], evicted.get_values()) - }) - .map_err(Error::EvictingRefCounts)?; + }).map_err(Error::EvictingRefCounts)?; } // The index must exist as it was just inserted if it didn't already. Ok(Some( diff --git a/qcow/src/vec_cache.rs b/qcow/src/vec_cache.rs index 667f45b..e8b08c6 100644 --- a/qcow/src/vec_cache.rs +++ b/qcow/src/vec_cache.rs @@ -146,29 +146,25 @@ mod tests { .insert(0, NumCache(5), |index, _| { evicted = Some(index); Ok(()) - }) - .unwrap(); + }).unwrap(); assert_eq!(evicted, None); cache .insert(1, NumCache(6), |index, _| { evicted = Some(index); Ok(()) - }) - .unwrap(); + }).unwrap(); assert_eq!(evicted, None); cache .insert(2, NumCache(7), |index, _| { evicted = Some(index); Ok(()) - }) - .unwrap(); + }).unwrap(); assert_eq!(evicted, None); cache .insert(3, NumCache(8), |index, _| { evicted = Some(index); Ok(()) - }) - .unwrap(); + }).unwrap(); assert!(evicted.is_some()); // Check that three of the four items inserted are still there and that the most recently diff --git a/resources/src/gpu_allocator.rs b/resources/src/gpu_allocator.rs index ea38ba4..9f98bcf 100644 --- a/resources/src/gpu_allocator.rs +++ b/resources/src/gpu_allocator.rs @@ -42,8 +42,12 @@ pub trait GpuMemoryAllocator { /// * `width` - Width of buffer. /// * `height` - Height of buffer. /// * `format` - Fourcc format of buffer. - fn allocate(&self, width: u32, height: u32, format: u32) - -> sys_util::Result<(File, GpuMemoryDesc)>; + fn allocate( + &self, + width: u32, + height: u32, + format: u32, + ) -> sys_util::Result<(File, GpuMemoryDesc)>; } #[cfg(feature = "wl-dmabuf")] @@ -53,9 +57,12 @@ pub struct GpuBufferDevice { #[cfg(feature = "wl-dmabuf")] impl GpuMemoryAllocator for GpuBufferDevice { - fn allocate(&self, width: u32, height: u32, format: u32) -> - sys_util::Result<(File, GpuMemoryDesc)> - { + fn allocate( + &self, + width: u32, + height: u32, + format: u32, + ) -> sys_util::Result<(File, GpuMemoryDesc)> { let buffer = match self.device.create_buffer( width, height, @@ -66,7 +73,8 @@ impl GpuMemoryAllocator for GpuBufferDevice { // fall-back to a less efficient meachnisms for presentation if // neccesary. In practice, linear buffers for commonly used formats // will also support scanout and texturing. - gpu_buffer::Flags::empty().use_linear(true)) { + gpu_buffer::Flags::empty().use_linear(true), + ) { Ok(v) => v, Err(_) => return Err(sys_util::Error::new(EINVAL)), }; @@ -81,8 +89,10 @@ impl GpuMemoryAllocator for GpuBufferDevice { for i in 0..buffer.num_planes() { // Use stride and offset for plane if handle matches first plane. if buffer.plane_handle(i) == buffer.plane_handle(0) { - desc.planes[i] = GpuMemoryPlaneDesc { stride: buffer.plane_stride(i), - offset: buffer.plane_offset(i) } + desc.planes[i] = GpuMemoryPlaneDesc { + stride: buffer.plane_stride(i), + offset: buffer.plane_offset(i), + } } } @@ -95,8 +105,8 @@ pub fn create_gpu_memory_allocator() -> Result<Option<Box<GpuMemoryAllocator>>, let undesired: &[&str] = &["vgem", "pvr"]; let fd = gpu_buffer::rendernode::open_device(undesired) .map_err(|_| GpuAllocatorError::OpenGpuBufferDevice)?; - let device = gpu_buffer::Device::new(fd) - .map_err(|_| GpuAllocatorError::CreateGpuBufferDevice)?; + let device = + gpu_buffer::Device::new(fd).map_err(|_| GpuAllocatorError::CreateGpuBufferDevice)?; Ok(Some(Box::new(GpuBufferDevice { device }))) } diff --git a/resources/src/system_allocator.rs b/resources/src/system_allocator.rs index 4ca04ae..57618ac 100644 --- a/resources/src/system_allocator.rs +++ b/resources/src/system_allocator.rs @@ -43,11 +43,16 @@ impl SystemAllocator { /// * `mmio_size` - The size of MMIO space. /// * `create_gpu_allocator` - If true, enable gpu memory allocation. /// * `first_irq` - The first irq number to give out. - fn new(io_base: Option<u64>, io_size: Option<u64>, - dev_base: u64, dev_size: u64, - mmio_base: u64, mmio_size: u64, - create_gpu_allocator: bool, - first_irq: u32) -> Option<Self> { + fn new( + io_base: Option<u64>, + io_size: Option<u64>, + dev_base: u64, + dev_size: u64, + mmio_base: u64, + mmio_size: u64, + create_gpu_allocator: bool, + first_irq: u32, + ) -> Option<Self> { let page_size = pagesize() as u64; Some(SystemAllocator { io_address_space: if let (Some(b), Some(s)) = (io_base, io_size) { @@ -137,12 +142,20 @@ impl AddressRanges { self } - pub fn create_allocator(&self, first_irq: u32, - gpu_allocation: bool) -> Option<SystemAllocator> { - SystemAllocator::new(self.io_base, self.io_size, - self.device_base?, self.device_size?, - self.mmio_base?, self.mmio_size?, - gpu_allocation, - first_irq) + pub fn create_allocator( + &self, + first_irq: u32, + gpu_allocation: bool, + ) -> Option<SystemAllocator> { + SystemAllocator::new( + self.io_base, + self.io_size, + self.device_base?, + self.device_size?, + self.mmio_base?, + self.mmio_size?, + gpu_allocation, + first_irq, + ) } } diff --git a/src/argument.rs b/src/argument.rs index 03eda0e..edcaadc 100644 --- a/src/argument.rs +++ b/src/argument.rs @@ -71,9 +71,9 @@ impl fmt::Display for Error { &Error::UnknownArgument(ref s) => write!(f, "unknown argument: {}", s), &Error::ExpectedArgument(ref s) => write!(f, "expected argument: {}", s), &Error::InvalidValue { - ref value, - expected, - } => write!(f, "invalid value {:?}: {}", value, expected), + ref value, + expected, + } => write!(f, "invalid value {:?}: {}", value, expected), &Error::TooManyArguments(ref s) => write!(f, "too many arguments: {}", s), &Error::ExpectedValue(ref s) => write!(f, "expected parameter value: {}", s), &Error::PrintHelp => write!(f, "help was requested"), @@ -132,7 +132,7 @@ impl Argument { Argument { value: Some(value), long: "", - help: help, + help, ..Default::default() } } @@ -140,29 +140,30 @@ impl Argument { pub fn value(long: &'static str, value: &'static str, help: &'static str) -> Argument { Argument { value: Some(value), - long: long, - help: help, + long, + help, ..Default::default() } } - pub fn short_value(short: char, - long: &'static str, - value: &'static str, - help: &'static str) - -> Argument { + pub fn short_value( + short: char, + long: &'static str, + value: &'static str, + help: &'static str, + ) -> Argument { Argument { value: Some(value), short: Some(short), - long: long, - help: help, + long, + help, } } pub fn flag(long: &'static str, help: &'static str) -> Argument { Argument { - long: long, - help: help, + long, + help, ..Default::default() } } @@ -170,17 +171,18 @@ impl Argument { pub fn short_flag(short: char, long: &'static str, help: &'static str) -> Argument { Argument { short: Some(short), - long: long, - help: help, + long, + help, ..Default::default() } } } fn parse_arguments<I, R, F>(args: I, mut f: F) -> Result<()> - where I: Iterator<Item = R>, - R: AsRef<str>, - F: FnMut(&str, Option<&str>) -> Result<()> +where + I: Iterator<Item = R>, + R: AsRef<str>, + F: FnMut(&str, Option<&str>) -> Result<()>, { enum State { // Initial state at the start and after finishing a single argument/value. @@ -204,19 +206,23 @@ fn parse_arguments<I, R, F>(args: I, mut f: F) -> Result<()> let name = iter.next().unwrap(); let value = iter.next().unwrap(); if name.is_empty() { - return Err(Error::Syntax("expected parameter name before `=`" - .to_owned())); + return Err(Error::Syntax( + "expected parameter name before `=`".to_owned(), + )); } if value.is_empty() { - return Err(Error::Syntax("expected parameter value after `=`" - .to_owned())); + return Err(Error::Syntax( + "expected parameter value after `=`".to_owned(), + )); } f(name, Some(value))?; State::Top } else { if let Err(e) = f(param, None) { if let Error::ExpectedValue(_) = e { - State::Value { name: param.to_owned() } + State::Value { + name: param.to_owned(), + } } else { return Err(e); } @@ -226,14 +232,17 @@ fn parse_arguments<I, R, F>(args: I, mut f: F) -> Result<()> } } else if arg.starts_with("-") { if arg.len() == 1 { - return Err(Error::Syntax("expected argument short name after `-`" - .to_owned())); + return Err(Error::Syntax( + "expected argument short name after `-`".to_owned(), + )); } let name = &arg[1..2]; let value = if arg.len() > 2 { Some(&arg[2..]) } else { None }; if let Err(e) = f(name, value) { if let Error::ExpectedValue(_) = e { - State::Value { name: name.to_owned() } + State::Value { + name: name.to_owned(), + } } else { return Err(e); } @@ -268,9 +277,10 @@ fn parse_arguments<I, R, F>(args: I, mut f: F) -> Result<()> /// /// See the [module level](index.html) example for a usage example. pub fn set_arguments<I, R, F>(args: I, arg_list: &[Argument], mut f: F) -> Result<()> - where I: Iterator<Item = R>, - R: AsRef<str>, - F: FnMut(&str, Option<&str>) -> Result<()> +where + I: Iterator<Item = R>, + R: AsRef<str>, + F: FnMut(&str, Option<&str>) -> Result<()>, { parse_arguments(args, |name, value| { let mut matches = None; @@ -302,10 +312,12 @@ pub fn set_arguments<I, R, F>(args: I, arg_list: &[Argument], mut f: F) -> Resul /// Usage information is printed according to the help fields in `args` with a leading usage line. /// The usage line is of the format "`program_name` [ARGUMENTS] `required_arg`". pub fn print_help(program_name: &str, required_arg: &str, args: &[Argument]) { - println!("Usage: {} {}{}\n", - program_name, - if args.is_empty() { "" } else { "[ARGUMENTS] " }, - required_arg); + println!( + "Usage: {} {}{}\n", + program_name, + if args.is_empty() { "" } else { "[ARGUMENTS] " }, + required_arg + ); if args.is_empty() { return; } @@ -357,54 +369,57 @@ mod tests { #[test] fn mixed_args() { - let arguments = - [Argument::positional("FILES", "files to operate on"), - Argument::short_value('p', "program", "PROGRAM", "Program to apply to each file"), - Argument::short_value('c', "cpus", "N", "Number of CPUs to use. (default: 1)"), - Argument::flag("unmount", "Unmount the root"), - Argument::short_flag('h', "help", "Print help message.")]; + let arguments = [ + Argument::positional("FILES", "files to operate on"), + Argument::short_value('p', "program", "PROGRAM", "Program to apply to each file"), + Argument::short_value('c', "cpus", "N", "Number of CPUs to use. (default: 1)"), + Argument::flag("unmount", "Unmount the root"), + Argument::short_flag('h', "help", "Print help message."), + ]; let mut unmount = false; - let match_res = set_arguments(["--cpus", "3", "--program", "hello", "--unmount", "file"] - .iter(), - &arguments[..], - |name, value| { - match name { - "" => assert_eq!(value.unwrap(), "file"), - "program" => assert_eq!(value.unwrap(), "hello"), - "cpus" => { - let c: u32 = value - .unwrap() - .parse() - .map_err(|_| { - Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this value for `cpus` needs to be integer", - } - })?; - assert_eq!(c, 3); - } - "unmount" => unmount = true, - "help" => return Err(Error::PrintHelp), - _ => unreachable!(), - }; - Ok(()) - }); + let match_res = set_arguments( + ["--cpus", "3", "--program", "hello", "--unmount", "file"].iter(), + &arguments[..], + |name, value| { + match name { + "" => assert_eq!(value.unwrap(), "file"), + "program" => assert_eq!(value.unwrap(), "hello"), + "cpus" => { + let c: u32 = value.unwrap().parse().map_err(|_| Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "this value for `cpus` needs to be integer", + })?; + assert_eq!(c, 3); + } + "unmount" => unmount = true, + "help" => return Err(Error::PrintHelp), + _ => unreachable!(), + }; + Ok(()) + }, + ); assert!(match_res.is_ok()); assert!(unmount); } #[test] fn name_value_pair() { - let arguments = - [Argument::short_value('c', "cpus", "N", "Number of CPUs to use. (default: 1)")]; - let match_res = set_arguments(["-c", "5", "--cpus", "5", "-c5", "--cpus=5"].iter(), - &arguments[..], - |name, value| { - assert_eq!(name, "cpus"); - assert_eq!(value, Some("5")); - Ok(()) - }); + let arguments = [Argument::short_value( + 'c', + "cpus", + "N", + "Number of CPUs to use. (default: 1)", + )]; + let match_res = set_arguments( + ["-c", "5", "--cpus", "5", "-c5", "--cpus=5"].iter(), + &arguments[..], + |name, value| { + assert_eq!(name, "cpus"); + assert_eq!(value, Some("5")); + Ok(()) + }, + ); assert!(match_res.is_ok()); } } diff --git a/src/linux.rs b/src/linux.rs index 1496998..91ea1ae 100644 --- a/src/linux.rs +++ b/src/linux.rs @@ -4,11 +4,11 @@ use std; use std::cmp::min; +use std::error; use std::ffi::CStr; use std::fmt; -use std::error; use std::fs::{File, OpenOptions}; -use std::io::{self, Read, stdin}; +use std::io::{self, stdin, Read}; use std::mem; use std::os::unix::io::{FromRawFd, RawFd}; use std::os::unix::net::UnixDatagram; @@ -17,12 +17,12 @@ use std::str; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::{Arc, Barrier}; use std::thread; -use std::time::Duration; use std::thread::JoinHandle; +use std::time::Duration; use libc::{self, c_int}; -use rand::thread_rng; use rand::distributions::{IndependentSample, Range}; +use rand::thread_rng; use byteorder::{ByteOrder, LittleEndian}; use devices::{self, PciDevice}; @@ -30,8 +30,8 @@ use io_jail::{self, Minijail}; use kvm::*; use net_util::Tap; use qcow::{self, QcowFile}; -use sys_util::*; use sys_util; +use sys_util::*; use vhost; use vm_control::VmRequest; @@ -41,10 +41,10 @@ use VirtIoDeviceInfo; use arch::{self, LinuxArch, RunnableLinuxVm, VirtioDeviceStub, VmComponents}; -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -use x86_64::X8664arch as Arch; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] use aarch64::AArch64 as Arch; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +use x86_64::X8664arch as Arch; #[derive(Debug)] pub enum Error { @@ -136,15 +136,19 @@ impl fmt::Display for Error { &Error::QcowDeviceCreate(ref e) => { write!(f, "failed to read qcow formatted file {:?}", e) } - &Error::ReadLowmemAvailable(ref e) => { - write!(f, "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}", e) - } - &Error::ReadLowmemMargin(ref e) => { - write!(f, "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}", e) - } + &Error::ReadLowmemAvailable(ref e) => write!( + f, + "failed to read /sys/kernel/mm/chromeos-low_mem/available: {}", + e + ), + &Error::ReadLowmemMargin(ref e) => write!( + f, + "failed to read /sys/kernel/mm/chromeos-low_mem/margin: {}", + e + ), &Error::RegisterBalloon(ref e) => { write!(f, "error registering balloon device: {:?}", e) - }, + } &Error::RegisterBlock(ref e) => write!(f, "error registering block device: {:?}", e), &Error::RegisterGpu(ref e) => write!(f, "error registering gpu device: {:?}", e), &Error::RegisterNet(ref e) => write!(f, "error registering net device: {:?}", e), @@ -234,12 +238,13 @@ fn create_base_minijail(root: &Path, seccomp_policy: &Path) -> Result<Minijail> Ok(j) } -fn create_virtio_devs(cfg: VirtIoDeviceInfo, - mem: &GuestMemory, - _exit_evt: &EventFd, - wayland_device_socket: UnixDatagram, - balloon_device_socket: UnixDatagram) - -> std::result::Result<Vec<VirtioDeviceStub>, Box<error::Error>> { +fn create_virtio_devs( + cfg: VirtIoDeviceInfo, + mem: &GuestMemory, + _exit_evt: &EventFd, + wayland_device_socket: UnixDatagram, + balloon_device_socket: UnixDatagram, +) -> std::result::Result<Vec<VirtioDeviceStub>, Box<error::Error>> { static DEFAULT_PIVOT_ROOT: &'static str = "/var/empty"; let mut devs = Vec::new(); @@ -256,7 +261,9 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, if !disk.path.is_file() { return Err(Box::new(Error::InvalidFdPath)); } - let raw_fd = disk.path.file_name() + let raw_fd = disk + .path + .file_name() .and_then(|fd_osstr| fd_osstr.to_str()) .and_then(|fd_str| fd_str.parse::<c_int>().ok()) .ok_or(Error::InvalidFdPath)?; @@ -278,26 +285,34 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, flock(&raw_image, lock_op, true).map_err(Error::DiskImageLock)?; let block_box: Box<devices::virtio::VirtioDevice> = match disk.disk_type { - DiskType::FlatFile => { // Access as a raw block device. - Box::new(devices::virtio::Block::new(raw_image, disk.read_only) - .map_err(|e| Error::BlockDeviceNew(e))?) + DiskType::FlatFile => { + // Access as a raw block device. + Box::new( + devices::virtio::Block::new(raw_image, disk.read_only) + .map_err(|e| Error::BlockDeviceNew(e))?, + ) } - DiskType::Qcow => { // Valid qcow header present - let qcow_image = QcowFile::from(raw_image) - .map_err(|e| Error::QcowDeviceCreate(e))?; - Box::new(devices::virtio::Block::new(qcow_image, disk.read_only) - .map_err(|e| Error::BlockDeviceNew(e))?) + DiskType::Qcow => { + // Valid qcow header present + let qcow_image = + QcowFile::from(raw_image).map_err(|e| Error::QcowDeviceCreate(e))?; + Box::new( + devices::virtio::Block::new(qcow_image, disk.read_only) + .map_err(|e| Error::BlockDeviceNew(e))?, + ) } }; let jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("block_device.policy"); Some(create_base_minijail(empty_root_path, &policy_path)?) - } - else { + } else { None }; - devs.push(VirtioDeviceStub {dev: block_box, jail}); + devs.push(VirtioDeviceStub { + dev: block_box, + jail, + }); } let rng_box = Box::new(devices::virtio::Rng::new().map_err(Error::RngDeviceNew)?); @@ -307,24 +322,31 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, } else { None }; - devs.push(VirtioDeviceStub {dev: rng_box, jail: rng_jail}); - - let balloon_box = Box::new(devices::virtio::Balloon::new(balloon_device_socket) - .map_err(Error::BalloonDeviceNew)?); + devs.push(VirtioDeviceStub { + dev: rng_box, + jail: rng_jail, + }); + + let balloon_box = Box::new( + devices::virtio::Balloon::new(balloon_device_socket).map_err(Error::BalloonDeviceNew)?, + ); let balloon_jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("balloon_device.policy"); Some(create_base_minijail(empty_root_path, &policy_path)?) } else { None }; - devs.push(VirtioDeviceStub {dev: balloon_box, jail: balloon_jail}); + devs.push(VirtioDeviceStub { + dev: balloon_box, + jail: balloon_jail, + }); // We checked above that if the IP is defined, then the netmask is, too. if let Some(tap_fd) = cfg.tap_fd { // Safe because we ensure that we get a unique handle to the fd. let tap = unsafe { Tap::from_raw_fd(validate_raw_fd(tap_fd)?) }; - let net_box = Box::new(devices::virtio::Net::from(tap) - .map_err(|e| Error::NetDeviceNew(e))?); + let net_box = + Box::new(devices::virtio::Net::from(tap).map_err(|e| Error::NetDeviceNew(e))?); let jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("net_device.policy"); @@ -334,19 +356,24 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, None }; - devs.push(VirtioDeviceStub {dev: net_box, jail}); + devs.push(VirtioDeviceStub { dev: net_box, jail }); } else if let Some(host_ip) = cfg.host_ip { if let Some(netmask) = cfg.netmask { if let Some(mac_address) = cfg.mac_address { let net_box: Box<devices::virtio::VirtioDevice> = if cfg.vhost_net { - Box::new(devices::virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(host_ip, - netmask, - mac_address, - &mem) - .map_err(|e| Error::VhostNetDeviceNew(e))?) + Box::new( + devices::virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new( + host_ip, + netmask, + mac_address, + &mem, + ).map_err(|e| Error::VhostNetDeviceNew(e))?, + ) } else { - Box::new(devices::virtio::Net::<Tap>::new(host_ip, netmask, mac_address) - .map_err(|e| Error::NetDeviceNew(e))?) + Box::new( + devices::virtio::Net::<Tap>::new(host_ip, netmask, mac_address) + .map_err(|e| Error::NetDeviceNew(e))?, + ) }; let jail = if cfg.multiprocess { @@ -361,24 +388,31 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, None }; - devs.push(VirtioDeviceStub {dev: net_box, jail}); + devs.push(VirtioDeviceStub { dev: net_box, jail }); } } } if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() { - let wayland_socket_dir = wayland_socket_path.parent().ok_or(Error::InvalidWaylandPath)?; - let wayland_socket_name = wayland_socket_path.file_name().ok_or(Error::InvalidWaylandPath)?; + let wayland_socket_dir = wayland_socket_path + .parent() + .ok_or(Error::InvalidWaylandPath)?; + let wayland_socket_name = wayland_socket_path + .file_name() + .ok_or(Error::InvalidWaylandPath)?; let jailed_wayland_dir = Path::new("/wayland"); let jailed_wayland_path = jailed_wayland_dir.join(wayland_socket_name); - let wl_box = Box::new(devices::virtio::Wl::new(if cfg.multiprocess { - &jailed_wayland_path - } else { - wayland_socket_path.as_path() - }, - wayland_device_socket) - .map_err(Error::WaylandDeviceNew)?); + let wl_box = Box::new( + devices::virtio::Wl::new( + if cfg.multiprocess { + &jailed_wayland_path + } else { + wayland_socket_path.as_path() + }, + wayland_device_socket, + ).map_err(Error::WaylandDeviceNew)?, + ); let jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("wl_device.policy"); @@ -386,10 +420,13 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, // Create a tmpfs in the device's root directory so that we can bind mount the wayland // socket directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. - jail.mount_with_data(Path::new("none"), Path::new("/"), "tmpfs", - (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, - "size=67108864") - .unwrap(); + jail.mount_with_data( + Path::new("none"), + Path::new("/"), + "tmpfs", + (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, + "size=67108864", + ).unwrap(); // Bind mount the wayland socket's directory into jail's root. This is necessary since // each new wayland context must open() the socket. If the wayland socket is ever @@ -426,15 +463,13 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, } else { None }; - devs.push(VirtioDeviceStub { - dev: wl_box, - jail, - }); + devs.push(VirtioDeviceStub { dev: wl_box, jail }); } if let Some(cid) = cfg.cid { - let vsock_box = Box::new(devices::virtio::vhost::Vsock::new(cid, &mem) - .map_err(Error::VhostVsockDeviceNew)?); + let vsock_box = Box::new( + devices::virtio::vhost::Vsock::new(cid, &mem).map_err(Error::VhostVsockDeviceNew)?, + ); let jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("vhost_vsock_device.policy"); @@ -444,7 +479,10 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, None }; - devs.push(VirtioDeviceStub {dev: vsock_box, jail}); + devs.push(VirtioDeviceStub { + dev: vsock_box, + jail, + }); } #[cfg(feature = "gpu")] @@ -453,15 +491,14 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, if let Some(wayland_socket_path) = cfg.wayland_socket_path.as_ref() { let jailed_wayland_path = Path::new("/wayland-0"); - let gpu_box = - Box::new(devices::virtio::Gpu::new(_exit_evt - .try_clone() - .map_err(Error::CloneEventFd)?, - if cfg.multiprocess { - &jailed_wayland_path - } else { - wayland_socket_path.as_path() - })); + let gpu_box = Box::new(devices::virtio::Gpu::new( + _exit_evt.try_clone().map_err(Error::CloneEventFd)?, + if cfg.multiprocess { + &jailed_wayland_path + } else { + wayland_socket_path.as_path() + }, + )); let jail = if cfg.multiprocess { let policy_path: PathBuf = cfg.seccomp_policy_dir.join("gpu_device.policy"); @@ -469,11 +506,13 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, // Create a tmpfs in the device's root directory so that we can bind mount the // dri directory into it. The size=67108864 is size=64*1024*1024 or size=64MB. - jail.mount_with_data(Path::new("none"), Path::new("/"), "tmpfs", - (libc::MS_NOSUID | libc::MS_NODEV | - libc::MS_NOEXEC) as usize, - "size=67108864") - .unwrap(); + jail.mount_with_data( + Path::new("none"), + Path::new("/"), + "tmpfs", + (libc::MS_NOSUID | libc::MS_NODEV | libc::MS_NOEXEC) as usize, + "size=67108864", + ).unwrap(); // Device nodes required for DRM. let sys_dev_char_path = Path::new("/sys/dev/char"); @@ -483,16 +522,13 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, jail.mount_bind(sys_devices_path, sys_devices_path, false) .unwrap(); let drm_dri_path = Path::new("/dev/dri"); - jail.mount_bind(drm_dri_path, drm_dri_path, false) - .unwrap(); + jail.mount_bind(drm_dri_path, drm_dri_path, false).unwrap(); // Libraries that are required when mesa drivers are dynamically loaded. let lib_path = Path::new("/lib64"); - jail.mount_bind(lib_path, lib_path, false) - .unwrap(); + jail.mount_bind(lib_path, lib_path, false).unwrap(); let usr_lib_path = Path::new("/usr/lib64"); - jail.mount_bind(usr_lib_path, usr_lib_path, false) - .unwrap(); + jail.mount_bind(usr_lib_path, usr_lib_path, false).unwrap(); // Bind mount the wayland socket into jail's root. This is necessary since each // new wayland context must open() the socket. @@ -527,7 +563,7 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, } else { None }; - devs.push(VirtioDeviceStub {dev: gpu_box, jail}); + devs.push(VirtioDeviceStub { dev: gpu_box, jail }); } } } @@ -575,7 +611,7 @@ fn create_virtio_devs(cfg: VirtIoDeviceInfo, let p9_box = Box::new(devices::virtio::P9::new(root, tag).map_err(Error::P9DeviceNew)?); - devs.push(VirtioDeviceStub {dev: p9_box, jail}); + devs.push(VirtioDeviceStub { dev: p9_box, jail }); } Ok(devs) @@ -592,13 +628,15 @@ fn setup_vcpu_signal_handler() -> Result<()> { Ok(()) } -fn run_vcpu(vcpu: Vcpu, - cpu_id: u32, - start_barrier: Arc<Barrier>, - io_bus: devices::Bus, - mmio_bus: devices::Bus, - exit_evt: EventFd, - kill_signaled: Arc<AtomicBool>) -> Result<JoinHandle<()>> { +fn run_vcpu( + vcpu: Vcpu, + cpu_id: u32, + start_barrier: Arc<Barrier>, + io_bus: devices::Bus, + mmio_bus: devices::Bus, + exit_evt: EventFd, + kill_signaled: Arc<AtomicBool>, +) -> Result<JoinHandle<()>> { thread::Builder::new() .name(format!("crosvm_vcpu{}", cpu_id)) .spawn(move || { @@ -645,20 +683,20 @@ fn run_vcpu(vcpu: Vcpu, VcpuExit::Hlt => break, VcpuExit::Shutdown => break, VcpuExit::SystemEvent(_, _) => - //TODO handle reboot and crash events - kill_signaled.store(true, Ordering::SeqCst), + //TODO handle reboot and crash events + { + kill_signaled.store(true, Ordering::SeqCst) + } r => warn!("unexpected vcpu exit: {:?}", r), } } - Err(e) => { - match e.errno() { - libc::EAGAIN | libc::EINTR => {}, - _ => { - error!("vcpu hit unknown error: {:?}", e); - break; - } + Err(e) => match e.errno() { + libc::EAGAIN | libc::EINTR => {} + _ => { + error!("vcpu hit unknown error: {:?}", e); + break; } - } + }, } if kill_signaled.load(Ordering::SeqCst) { break; @@ -671,8 +709,7 @@ fn run_vcpu(vcpu: Vcpu, exit_evt .write(1) .expect("failed to signal vcpu exit eventfd"); - }) - .map_err(Error::SpawnVcpu) + }).map_err(Error::SpawnVcpu) } // Reads the contents of a file and converts them into a u64. @@ -682,9 +719,12 @@ fn file_to_u64<P: AsRef<Path>>(path: P) -> io::Result<u64> { let mut buf = [0u8; 32]; let count = file.read(&mut buf)?; - let content = str::from_utf8(&buf[..count]) - .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; - content.trim().parse().map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) + let content = + str::from_utf8(&buf[..count]).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?; + content + .trim() + .parse() + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) } pub fn run_config(cfg: Config) -> Result<()> { @@ -718,26 +758,32 @@ pub fn run_config(cfg: Config) -> Result<()> { let dgram = UnixDatagram::bind(path).map_err(Error::CreateSocket)?; control_sockets.push(UnlinkUnixDatagram(dgram)); }; - let (wayland_host_socket, wayland_device_socket) = UnixDatagram::pair() - .map_err(Error::CreateSocket)?; + let (wayland_host_socket, wayland_device_socket) = + UnixDatagram::pair().map_err(Error::CreateSocket)?; control_sockets.push(UnlinkUnixDatagram(wayland_host_socket)); // Balloon gets a special socket so balloon requests can be forwarded from the main process. - let (balloon_host_socket, balloon_device_socket) = UnixDatagram::pair() - .map_err(Error::CreateSocket)?; + let (balloon_host_socket, balloon_device_socket) = + UnixDatagram::pair().map_err(Error::CreateSocket)?; let virtio_dev_info = cfg.virtio_dev_info; - let linux = Arch::build_vm(components, - |m, e| create_virtio_devs(virtio_dev_info, m, e, - wayland_device_socket, - balloon_device_socket)) - .map_err(Error::BuildingVm)?; + let linux = Arch::build_vm(components, |m, e| { + create_virtio_devs( + virtio_dev_info, + m, + e, + wayland_device_socket, + balloon_device_socket, + ) + }).map_err(Error::BuildingVm)?; run_control(linux, control_sockets, balloon_host_socket, sigchld_fd) } -fn run_control(mut linux: RunnableLinuxVm, - control_sockets: Vec<UnlinkUnixDatagram>, - balloon_host_socket: UnixDatagram, - sigchld_fd: SignalFd) -> Result<()> { +fn run_control( + mut linux: RunnableLinuxVm, + control_sockets: Vec<UnlinkUnixDatagram>, + balloon_host_socket: UnixDatagram, + sigchld_fd: SignalFd, +) -> Result<()> { // Paths to get the currently available memory and the low memory threshold. const LOWMEM_MARGIN: &'static str = "/sys/kernel/mm/chromeos-low_mem/margin"; const LOWMEM_AVAILABLE: &'static str = "/sys/kernel/mm/chromeos-low_mem/available"; @@ -776,30 +822,42 @@ fn run_control(mut linux: RunnableLinuxVm, .expect("failed to set terminal raw mode"); let poll_ctx = PollContext::new().map_err(Error::CreatePollContext)?; - poll_ctx.add(&linux.exit_evt, Token::Exit).map_err(Error::PollContextAdd)?; + poll_ctx + .add(&linux.exit_evt, Token::Exit) + .map_err(Error::PollContextAdd)?; if let Err(e) = poll_ctx.add(&stdin_handle, Token::Stdin) { warn!("failed to add stdin to poll context: {:?}", e); } - poll_ctx.add(&sigchld_fd, Token::ChildSignal).map_err(Error::PollContextAdd)?; + poll_ctx + .add(&sigchld_fd, Token::ChildSignal) + .map_err(Error::PollContextAdd)?; for (index, socket) in control_sockets.iter().enumerate() { - poll_ctx.add(socket.as_ref(), Token::VmControl{ index }).map_err(Error::PollContextAdd)?; + poll_ctx + .add(socket.as_ref(), Token::VmControl { index }) + .map_err(Error::PollContextAdd)?; } // Watch for low memory notifications and take memory back from the VM. let low_mem = File::open("/dev/chromeos-low-mem").ok(); if let Some(ref low_mem) = low_mem { - poll_ctx.add(low_mem, Token::LowMemory).map_err(Error::PollContextAdd)?; + poll_ctx + .add(low_mem, Token::LowMemory) + .map_err(Error::PollContextAdd)?; } else { warn!("Unable to open low mem indicator, maybe not a chrome os kernel"); } // Used to rate limit balloon requests. let mut lowmem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?; - poll_ctx.add(&lowmem_timer, Token::LowmemTimer).map_err(Error::PollContextAdd)?; + poll_ctx + .add(&lowmem_timer, Token::LowmemTimer) + .map_err(Error::PollContextAdd)?; // Used to check whether it's ok to start giving memory back to the VM. let mut freemem_timer = TimerFd::new().map_err(Error::CreateTimerFd)?; - poll_ctx.add(&freemem_timer, Token::CheckAvailableMemory).map_err(Error::PollContextAdd)?; + poll_ctx + .add(&freemem_timer, Token::CheckAvailableMemory) + .map_err(Error::PollContextAdd)?; // Used to add jitter to timer values so that we don't have a thundering herd problem when // multiple VMs are running. @@ -813,13 +871,15 @@ fn run_control(mut linux: RunnableLinuxVm, let kill_signaled = Arc::new(AtomicBool::new(false)); setup_vcpu_signal_handler()?; for (cpu_id, vcpu) in linux.vcpus.into_iter().enumerate() { - let handle = run_vcpu(vcpu, - cpu_id as u32, - vcpu_thread_barrier.clone(), - linux.io_bus.clone(), - linux.mmio_bus.clone(), - linux.exit_evt.try_clone().map_err(Error::CloneEventFd)?, - kill_signaled.clone())?; + let handle = run_vcpu( + vcpu, + cpu_id as u32, + vcpu_thread_barrier.clone(), + linux.io_bus.clone(), + linux.mmio_bus.clone(), + linux.exit_evt.try_clone().map_err(Error::CloneEventFd)?, + kill_signaled.clone(), + )?; vcpu_handles.push(handle); } vcpu_thread_barrier.wait(); @@ -846,18 +906,19 @@ fn run_control(mut linux: RunnableLinuxVm, Ok(0) => { // Zero-length read indicates EOF. Remove from pollables. let _ = poll_ctx.delete(&stdin_handle); - }, + } Err(e) => { warn!("error while reading stdin: {:?}", e); let _ = poll_ctx.delete(&stdin_handle); - }, + } Ok(count) => { - linux.stdio_serial + linux + .stdio_serial .lock() .unwrap() .queue_input_bytes(&out[..count]) .expect("failed to queue bytes into serial port"); - }, + } } } Token::ChildSignal => { @@ -865,11 +926,13 @@ fn run_control(mut linux: RunnableLinuxVm, loop { let result = sigchld_fd.read().map_err(Error::SignalFd)?; if let Some(siginfo) = result { - error!("child {} died: signo {}, status {}, code {}", - siginfo.ssi_pid, - siginfo.ssi_signo, - siginfo.ssi_status, - siginfo.ssi_code); + error!( + "child {} died: signo {}, status {}, code {}", + siginfo.ssi_pid, + siginfo.ssi_signo, + siginfo.ssi_status, + siginfo.ssi_code + ); } break 'poll; } @@ -887,16 +950,18 @@ fn run_control(mut linux: RunnableLinuxVm, // Otherwise see if we can free up some memory. let margin = file_to_u64(LOWMEM_MARGIN).map_err(Error::ReadLowmemMargin)?; - let available = file_to_u64(LOWMEM_AVAILABLE).map_err(Error::ReadLowmemAvailable)?; + let available = + file_to_u64(LOWMEM_AVAILABLE).map_err(Error::ReadLowmemAvailable)?; // `available` and `margin` are specified in MB while `balloon_memory_increment` is in // bytes. So to correctly compare them we need to turn the increment value into MB. - if available >= margin + 2*(balloon_memory_increment >> 20) { - current_balloon_memory = if current_balloon_memory >= balloon_memory_increment { - current_balloon_memory - balloon_memory_increment - } else { - 0 - }; + if available >= margin + 2 * (balloon_memory_increment >> 20) { + current_balloon_memory = + if current_balloon_memory >= balloon_memory_increment { + current_balloon_memory - balloon_memory_increment + } else { + 0 + }; let mut buf = [0u8; mem::size_of::<u64>()]; LittleEndian::write_u64(&mut buf, current_balloon_memory); if let Err(e) = balloon_host_socket.send(&buf) { @@ -907,9 +972,10 @@ fn run_control(mut linux: RunnableLinuxVm, Token::LowMemory => { if let Some(ref low_mem) = low_mem { let old_balloon_memory = current_balloon_memory; - current_balloon_memory = - min(current_balloon_memory + balloon_memory_increment, - max_balloon_memory); + current_balloon_memory = min( + current_balloon_memory + balloon_memory_increment, + max_balloon_memory, + ); if current_balloon_memory != old_balloon_memory { let mut buf = [0u8; mem::size_of::<u64>()]; LittleEndian::write_u64(&mut buf, current_balloon_memory); @@ -925,7 +991,9 @@ fn run_control(mut linux: RunnableLinuxVm, // they don't all start ballooning at exactly the same time. let lowmem_dur = Duration::from_millis(1000 + lowmem_jitter_ms.ind_sample(&mut rng)); - lowmem_timer.reset(lowmem_dur, None).map_err(Error::ResetTimerFd)?; + lowmem_timer + .reset(lowmem_dur, None) + .map_err(Error::ResetTimerFd)?; // Also start a timer to check when we can start giving memory back. Do the // first check after a minute (with jitter) and subsequent checks after @@ -945,7 +1013,9 @@ fn run_control(mut linux: RunnableLinuxVm, if let Some(ref low_mem) = low_mem { // Start polling the lowmem device again. - poll_ctx.add(low_mem, Token::LowMemory).map_err(Error::PollContextAdd)?; + poll_ctx + .add(low_mem, Token::LowMemory) + .map_err(Error::PollContextAdd)?; } } Token::VmControl { index } => { @@ -953,11 +1023,12 @@ fn run_control(mut linux: RunnableLinuxVm, match VmRequest::recv(socket.as_ref()) { Ok(request) => { let mut running = true; - let response = - request.execute(&mut linux.vm, - &mut linux.resources, - &mut running, - &balloon_host_socket); + let response = request.execute( + &mut linux.vm, + &mut linux.resources, + &mut running, + &balloon_host_socket, + ); if let Err(e) = response.send(socket.as_ref()) { error!("failed to send VmResponse: {:?}", e); } @@ -978,19 +1049,19 @@ fn run_control(mut linux: RunnableLinuxVm, // read. if !event.readable() { match event.token() { - Token::Exit => {}, + Token::Exit => {} Token::Stdin => { let _ = poll_ctx.delete(&stdin_handle); - }, - Token::ChildSignal => {}, - Token::CheckAvailableMemory => {}, - Token::LowMemory => {}, - Token::LowmemTimer => {}, + } + Token::ChildSignal => {} + Token::CheckAvailableMemory => {} + Token::LowMemory => {} + Token::LowmemTimer => {} Token::VmControl { index } => { if let Some(socket) = control_sockets.get(index as usize) { let _ = poll_ctx.delete(socket.as_ref()); } - }, + } } } } diff --git a/src/main.rs b/src/main.rs index 8e065ed..28bc09e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,34 +4,34 @@ //! Runs a virtual machine under KVM -extern crate arch; #[cfg(any(target_arch = "arm", target_arch = "aarch64"))] extern crate aarch64; +extern crate arch; +extern crate byteorder; extern crate devices; -extern crate libc; extern crate io_jail; +extern crate kernel_cmdline; +extern crate kernel_loader; extern crate kvm; extern crate kvm_sys; -#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] -extern crate x86_64; -extern crate kernel_loader; -extern crate kernel_cmdline; -extern crate byteorder; +extern crate libc; extern crate net_util; extern crate qcow; +#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] +extern crate x86_64; #[macro_use] extern crate sys_util; -extern crate resources; -extern crate vhost; -extern crate vm_control; extern crate data_model; +#[cfg(feature = "wl-dmabuf")] +extern crate gpu_buffer; #[cfg(feature = "plugin")] extern crate plugin_proto; #[cfg(feature = "plugin")] extern crate protobuf; -#[cfg(feature = "wl-dmabuf")] -extern crate gpu_buffer; extern crate rand; +extern crate resources; +extern crate vhost; +extern crate vm_control; pub mod argument; pub mod linux; @@ -47,10 +47,10 @@ use std::string::String; use std::thread::sleep; use std::time::Duration; -use sys_util::{getpid, kill_process_group, reap_child, syslog}; use qcow::QcowFile; +use sys_util::{getpid, kill_process_group, reap_child, syslog}; -use argument::{Argument, set_arguments, print_help}; +use argument::{print_help, set_arguments, Argument}; use vm_control::VmRequest; static SECCOMP_POLICY_DIR: &'static str = "/usr/share/policy/crosvm"; @@ -140,7 +140,7 @@ fn wait_all_children() -> bool { return false; } // We reaped one child, so continue reaping. - _ => {}, + _ => {} } } // There's no timeout option for waitpid which reap_child calls internally, so our only @@ -156,18 +156,20 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: match name { "" => { if cfg.plugin.is_some() { - return Err(argument::Error::TooManyArguments("`plugin` can not be used with kernel" - .to_owned())); + return Err(argument::Error::TooManyArguments( + "`plugin` can not be used with kernel".to_owned(), + )); } else if !cfg.kernel_path.as_os_str().is_empty() { - return Err(argument::Error::TooManyArguments("expected exactly one kernel path" - .to_owned())); + return Err(argument::Error::TooManyArguments( + "expected exactly one kernel path".to_owned(), + )); } else { let kernel_path = PathBuf::from(value.unwrap()); if !kernel_path.exists() { return Err(argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this kernel path does not exist", - }); + value: value.unwrap().to_owned(), + expected: "this kernel path does not exist", + }); } cfg.kernel_path = kernel_path; } @@ -177,127 +179,140 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: } "cpus" => { if cfg.vcpu_count.is_some() { - return Err(argument::Error::TooManyArguments("`cpus` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`cpus` already given".to_owned(), + )); } cfg.vcpu_count = - Some(value - .unwrap() - .parse() - .map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this value for `cpus` needs to be integer", - } - })?) + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "this value for `cpus` needs to be integer", + })?, + ) } "mem" => { if cfg.memory.is_some() { - return Err(argument::Error::TooManyArguments("`mem` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`mem` already given".to_owned(), + )); } cfg.memory = - Some(value - .unwrap() - .parse() - .map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this value for `mem` needs to be integer", - } - })?) + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "this value for `mem` needs to be integer", + })?, + ) } "root" | "disk" | "rwdisk" | "qcow" | "rwqcow" => { let disk_path = PathBuf::from(value.unwrap()); if !disk_path.exists() { return Err(argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this disk path does not exist", - }); + value: value.unwrap().to_owned(), + expected: "this disk path does not exist", + }); } if name == "root" { if cfg.virtio_dev_info.disks.len() >= 26 { - return Err(argument::Error::TooManyArguments("ran out of letters for to assign to root disk".to_owned())); + return Err(argument::Error::TooManyArguments( + "ran out of letters for to assign to root disk".to_owned(), + )); } - cfg.params - .push(format!("root=/dev/vd{} ro", - char::from('a' as u8 + cfg.virtio_dev_info.disks.len() as u8))); + cfg.params.push(format!( + "root=/dev/vd{} ro", + char::from('a' as u8 + cfg.virtio_dev_info.disks.len() as u8) + )); } - cfg.virtio_dev_info.disks - .push(DiskOption { - path: disk_path, - read_only: !name.starts_with("rw"), - disk_type: if name.ends_with("qcow") { - DiskType::Qcow - } else { - DiskType::FlatFile - }, - }); + cfg.virtio_dev_info.disks.push(DiskOption { + path: disk_path, + read_only: !name.starts_with("rw"), + disk_type: if name.ends_with("qcow") { + DiskType::Qcow + } else { + DiskType::FlatFile + }, + }); } "host_ip" => { if cfg.virtio_dev_info.host_ip.is_some() { - return Err(argument::Error::TooManyArguments("`host_ip` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`host_ip` already given".to_owned(), + )); } cfg.virtio_dev_info.host_ip = - Some(value - .unwrap() - .parse() - .map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "`host_ip` needs to be in the form \"x.x.x.x\"", - } - })?) + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "`host_ip` needs to be in the form \"x.x.x.x\"", + })?, + ) } "netmask" => { if cfg.virtio_dev_info.netmask.is_some() { - return Err(argument::Error::TooManyArguments("`netmask` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`netmask` already given".to_owned(), + )); } cfg.virtio_dev_info.netmask = - Some(value - .unwrap() - .parse() - .map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "`netmask` needs to be in the form \"x.x.x.x\"", - } - })?) + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "`netmask` needs to be in the form \"x.x.x.x\"", + })?, + ) } "mac" => { if cfg.virtio_dev_info.mac_address.is_some() { - return Err(argument::Error::TooManyArguments("`mac` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`mac` already given".to_owned(), + )); } cfg.virtio_dev_info.mac_address = - Some(value - .unwrap() - .parse() - .map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "`mac` needs to be in the form \"XX:XX:XX:XX:XX:XX\"", - } - })?) + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "`mac` needs to be in the form \"XX:XX:XX:XX:XX:XX\"", + })?, + ) } "wayland-sock" => { if cfg.virtio_dev_info.wayland_socket_path.is_some() { - return Err(argument::Error::TooManyArguments("`wayland-sock` already given" - .to_owned())); + return Err(argument::Error::TooManyArguments( + "`wayland-sock` already given".to_owned(), + )); } let wayland_socket_path = PathBuf::from(value.unwrap()); if !wayland_socket_path.exists() { return Err(argument::Error::InvalidValue { - value: value.unwrap().to_string(), - expected: "Wayland socket does not exist", - }); + value: value.unwrap().to_string(), + expected: "Wayland socket does not exist", + }); } cfg.virtio_dev_info.wayland_socket_path = Some(wayland_socket_path); } #[cfg(feature = "wl-dmabuf")] - "wayland-dmabuf" => { - cfg.virtio_dev_info.wayland_dmabuf = true - } + "wayland-dmabuf" => cfg.virtio_dev_info.wayland_dmabuf = true, "socket" => { if cfg.socket_path.is_some() { - return Err(argument::Error::TooManyArguments("`socket` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`socket` already given".to_owned(), + )); } let mut socket_path = PathBuf::from(value.unwrap()); if socket_path.is_dir() { @@ -305,9 +320,9 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: } if socket_path.exists() { return Err(argument::Error::InvalidValue { - value: socket_path.to_string_lossy().into_owned(), - expected: "this socket path already exists", - }); + value: socket_path.to_string_lossy().into_owned(), + expected: "this socket path already exists", + }); } cfg.socket_path = Some(socket_path); } @@ -319,31 +334,40 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: } "cid" => { if cfg.virtio_dev_info.cid.is_some() { - return Err(argument::Error::TooManyArguments("`cid` alread given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`cid` alread given".to_owned(), + )); } - cfg.virtio_dev_info.cid = Some(value.unwrap().parse().map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this value for `cid` must be an unsigned integer", - } - })?); + cfg.virtio_dev_info.cid = + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "this value for `cid` must be an unsigned integer", + })?, + ); } "shared-dir" => { // Formatted as <src:tag>. let param = value.unwrap(); let mut components = param.splitn(2, ':'); - let src = PathBuf::from(components.next().ok_or_else(|| { - argument::Error::InvalidValue { - value: param.to_owned(), - expected: "missing source path for `shared-dir`", - } - })?); - let tag = components.next().ok_or_else(|| { - argument::Error::InvalidValue { + let src = + PathBuf::from( + components + .next() + .ok_or_else(|| argument::Error::InvalidValue { + value: param.to_owned(), + expected: "missing source path for `shared-dir`", + })?, + ); + let tag = components + .next() + .ok_or_else(|| argument::Error::InvalidValue { value: param.to_owned(), expected: "missing tag for `shared-dir`", - } - })?.to_owned(); + })?.to_owned(); if !src.is_dir() { return Err(argument::Error::InvalidValue { @@ -357,38 +381,46 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: "seccomp-policy-dir" => { // `value` is Some because we are in this match so it's safe to unwrap. cfg.virtio_dev_info.seccomp_policy_dir = PathBuf::from(value.unwrap()); - }, + } "plugin" => { if !cfg.kernel_path.as_os_str().is_empty() { - return Err(argument::Error::TooManyArguments("`plugin` can not be used with kernel".to_owned())); + return Err(argument::Error::TooManyArguments( + "`plugin` can not be used with kernel".to_owned(), + )); } else if cfg.plugin.is_some() { - return Err(argument::Error::TooManyArguments("`plugin` already given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`plugin` already given".to_owned(), + )); } let plugin = PathBuf::from(value.unwrap().to_owned()); if plugin.is_relative() { return Err(argument::Error::InvalidValue { - value: plugin.to_string_lossy().into_owned(), - expected: "the plugin path must be an absolute path", - }) + value: plugin.to_string_lossy().into_owned(), + expected: "the plugin path must be an absolute path", + }); } cfg.plugin = Some(plugin); - }, + } "plugin-root" => { cfg.plugin_root = Some(PathBuf::from(value.unwrap().to_owned())); - }, - "vhost-net" => { - cfg.virtio_dev_info.vhost_net = true - }, + } + "vhost-net" => cfg.virtio_dev_info.vhost_net = true, "tap-fd" => { if cfg.virtio_dev_info.tap_fd.is_some() { - return Err(argument::Error::TooManyArguments("`tap-fd` alread given".to_owned())); + return Err(argument::Error::TooManyArguments( + "`tap-fd` alread given".to_owned(), + )); } - cfg.virtio_dev_info.tap_fd = Some(value.unwrap().parse().map_err(|_| { - argument::Error::InvalidValue { - value: value.unwrap().to_owned(), - expected: "this value for `tap-fd` must be an unsigned integer", - } - })?); + cfg.virtio_dev_info.tap_fd = + Some( + value + .unwrap() + .parse() + .map_err(|_| argument::Error::InvalidValue { + value: value.unwrap().to_owned(), + expected: "this value for `tap-fd` must be an unsigned integer", + })?, + ); } "gpu" => { cfg.virtio_dev_info.gpu = true; @@ -399,7 +431,6 @@ fn set_argument(cfg: &mut Config, name: &str, value: Option<&str>) -> argument:: Ok(()) } - fn run_vm(args: std::env::Args) -> std::result::Result<(), ()> { let arguments = &[Argument::positional("KERNEL", "bzImage of kernel to run"), @@ -453,37 +484,54 @@ fn run_vm(args: std::env::Args) -> std::result::Result<(), ()> { Argument::short_flag('h', "help", "Print help message.")]; let mut cfg = Config::default(); - let match_res = set_arguments(args, &arguments[..], |name, value| set_argument(&mut cfg, name, value)).and_then(|_| { + let match_res = set_arguments(args, &arguments[..], |name, value| { + set_argument(&mut cfg, name, value) + }).and_then(|_| { if cfg.kernel_path.as_os_str().is_empty() && cfg.plugin.is_none() { return Err(argument::Error::ExpectedArgument("`KERNEL`".to_owned())); } - if cfg.virtio_dev_info.host_ip.is_some() || cfg.virtio_dev_info.netmask.is_some() - || cfg.virtio_dev_info.mac_address.is_some() { + if cfg.virtio_dev_info.host_ip.is_some() + || cfg.virtio_dev_info.netmask.is_some() + || cfg.virtio_dev_info.mac_address.is_some() + { if cfg.virtio_dev_info.host_ip.is_none() { - return Err(argument::Error::ExpectedArgument("`host_ip` missing from network config".to_owned())); + return Err(argument::Error::ExpectedArgument( + "`host_ip` missing from network config".to_owned(), + )); } if cfg.virtio_dev_info.netmask.is_none() { - return Err(argument::Error::ExpectedArgument("`netmask` missing from network config".to_owned())); + return Err(argument::Error::ExpectedArgument( + "`netmask` missing from network config".to_owned(), + )); } if cfg.virtio_dev_info.mac_address.is_none() { - return Err(argument::Error::ExpectedArgument("`mac` missing from network config".to_owned())); + return Err(argument::Error::ExpectedArgument( + "`mac` missing from network config".to_owned(), + )); } } if cfg.plugin_root.is_some() && cfg.plugin.is_none() { - return Err(argument::Error::ExpectedArgument("`plugin-root` requires `plugin`".to_owned())); - } - if cfg.virtio_dev_info.tap_fd.is_some() && (cfg.virtio_dev_info.host_ip.is_some() || - cfg.virtio_dev_info.netmask.is_some() || - cfg.virtio_dev_info.mac_address.is_some()) { + return Err(argument::Error::ExpectedArgument( + "`plugin-root` requires `plugin`".to_owned(), + )); + } + if cfg.virtio_dev_info.tap_fd.is_some() + && (cfg.virtio_dev_info.host_ip.is_some() + || cfg.virtio_dev_info.netmask.is_some() + || cfg.virtio_dev_info.mac_address.is_some()) + { return Err(argument::Error::TooManyArguments( - "`tap_fd` and any of `host_ip`, `netmask`, or `mac` are mutually exclusive".to_owned())); + "`tap_fd` and any of `host_ip`, `netmask`, or `mac` are mutually exclusive" + .to_owned(), + )); } Ok(()) }); match match_res { #[cfg(feature = "plugin")] - Ok(()) if cfg.plugin.is_some() => { + Ok(()) if cfg.plugin.is_some() => + { match plugin::run_config(cfg) { Ok(_) => { info!("crosvm and plugin have exited normally"); @@ -495,18 +543,16 @@ fn run_vm(args: std::env::Args) -> std::result::Result<(), ()> { } } } - Ok(()) => { - match linux::run_config(cfg) { - Ok(_) => { - info!("crosvm has exited normally"); - Ok(()) - } - Err(e) => { - error!("{}", e); - Err(()) - } + Ok(()) => match linux::run_config(cfg) { + Ok(_) => { + info!("crosvm has exited normally"); + Ok(()) } - } + Err(e) => { + error!("{}", e); + Err(()) + } + }, Err(argument::Error::PrintHelp) => { print_help("crosvm run", "KERNEL", &arguments[..]); Ok(()) @@ -527,14 +573,15 @@ fn stop_vms(args: std::env::Args) -> std::result::Result<(), ()> { let mut return_result = Ok(()); for socket_path in args { match UnixDatagram::unbound().and_then(|s| { - s.connect(&socket_path)?; - Ok(s) - }) { + s.connect(&socket_path)?; + Ok(s) + }) { Ok(s) => { if let Err(e) = VmRequest::Exit.send(&s) { - error!("failed to send stop request to socket at '{}': {:?}", - socket_path, - e); + error!( + "failed to send stop request to socket at '{}': {:?}", + socket_path, e + ); } } Err(e) => { @@ -557,20 +604,21 @@ fn balloon_vms(mut args: std::env::Args) -> std::result::Result<(), ()> { Err(_) => { error!("Failed to parse number of pages"); return Err(()); - }, + } }; let mut return_result = Ok(()); for socket_path in args { match UnixDatagram::unbound().and_then(|s| { - s.connect(&socket_path)?; - Ok(s) - }) { + s.connect(&socket_path)?; + Ok(s) + }) { Ok(s) => { if let Err(e) = VmRequest::BalloonAdjust(num_pages).send(&s) { - error!("failed to send balloon request to socket at '{}': {:?}", - socket_path, - e); + error!( + "failed to send balloon request to socket at '{}': {:?}", + socket_path, e + ); } } Err(e) => { @@ -594,7 +642,7 @@ fn create_qcow2(mut args: std::env::Args) -> std::result::Result<(), ()> { Err(_) => { error!("Failed to parse size of the disk."); return Err(()); - }, + } }; let file = OpenOptions::new() @@ -607,11 +655,10 @@ fn create_qcow2(mut args: std::env::Args) -> std::result::Result<(), ()> { () })?; - QcowFile::new(file, size) - .map_err(|e| { - error!("Failed to create qcow file at '{}': {:?}", file_path, e); - () - })?; + QcowFile::new(file, size).map_err(|e| { + error!("Failed to create qcow file at '{}': {:?}", file_path, e); + () + })?; Ok(()) } @@ -642,18 +689,10 @@ fn crosvm_main() -> std::result::Result<(), ()> { print_usage(); Ok(()) } - Some("stop") => { - stop_vms(args) - } - Some("run") => { - run_vm(args) - } - Some("balloon") => { - balloon_vms(args) - } - Some("create_qcow2") => { - create_qcow2(args) - } + Some("stop") => stop_vms(args), + Some("run") => run_vm(args), + Some("balloon") => balloon_vms(args), + Some("create_qcow2") => create_qcow2(args), Some(c) => { println!("invalid subcommand: {:?}", c); print_usage(); diff --git a/src/plugin/mod.rs b/src/plugin/mod.rs index ef55afe..ddff643 100644 --- a/src/plugin/mod.rs +++ b/src/plugin/mod.rs @@ -8,7 +8,7 @@ mod vcpu; use std::fmt; use std::fs::File; use std::io; -use std::os::unix::io::{IntoRawFd, FromRawFd}; +use std::os::unix::io::{FromRawFd, IntoRawFd}; use std::os::unix::net::UnixDatagram; use std::path::Path; use std::result; @@ -17,17 +17,21 @@ use std::sync::{Arc, Barrier}; use std::thread; use std::time::{Duration, Instant}; -use libc::{socketpair, ioctl, c_ulong, AF_UNIX, SOCK_SEQPACKET, FIOCLEX, EAGAIN, EINTR, EINVAL, - ENOENT, EPERM, EDEADLK, EEXIST, EBADF, EOVERFLOW, SIGCHLD, MS_NOSUID, MS_NODEV}; +use libc::{ + c_ulong, ioctl, socketpair, AF_UNIX, EAGAIN, EBADF, EDEADLK, EEXIST, EINTR, EINVAL, ENOENT, + EOVERFLOW, EPERM, FIOCLEX, MS_NODEV, MS_NOSUID, SIGCHLD, SOCK_SEQPACKET, +}; use protobuf::ProtobufError; use io_jail::{self, Minijail}; -use kvm::{Kvm, Vm, Vcpu, VcpuExit, IoeventAddress, NoDatamatch}; +use kvm::{IoeventAddress, Kvm, NoDatamatch, Vcpu, VcpuExit, Vm}; use net_util::{Error as TapError, Tap, TapT}; -use sys_util::{EventFd, MmapError, Killable, SignalFd, SignalFdError, PollContext, PollToken, - GuestMemory, Result as SysResult, Error as SysError, block_signal, clear_signal, - SIGRTMIN, register_signal_handler, geteuid, getegid}; +use sys_util::{ + block_signal, clear_signal, getegid, geteuid, register_signal_handler, Error as SysError, + EventFd, GuestMemory, Killable, MmapError, PollContext, PollToken, Result as SysResult, + SignalFd, SignalFdError, SIGRTMIN, +}; use Config; @@ -123,7 +127,9 @@ impl fmt::Display for Error { Error::MountPlugin(ref e) => write!(f, "failed to mount: {}", e), Error::MountPluginLib(ref e) => write!(f, "failed to mount: {}", e), Error::MountRoot(ref e) => write!(f, "failed to mount: {}", e), - Error::NoRootDir => write!(f, "no root directory for jailed process to pivot root into"), + Error::NoRootDir => { + write!(f, "no root directory for jailed process to pivot root into") + } Error::ParsePivotRoot(ref e) => write!(f, "failed to set jail pivot root: {}", e), Error::ParseSeccomp(ref e) => write!(f, "failed to parse jail seccomp filter: {}", e), Error::PluginFailed(ref e) => write!(f, "plugin exited with error: {}", e), @@ -154,14 +160,11 @@ impl fmt::Display for Error { signo, status, code, - } => { - write!(f, - "process {} died with signal {}, status {}, and code {}", - pid, - signo, - status, - code) - } + } => write!( + f, + "process {} died with signal {}, status {}, and code {}", + pid, signo, status, code + ), Error::SignalFd(ref e) => write!(f, "failed to read signal fd: {:?}", e), Error::SpawnVcpu(ref e) => write!(f, "error spawning vcpu thread: {}", e), Error::TapOpen(ref e) => write!(f, "error opening tap device: {:?}", e), @@ -185,7 +188,10 @@ fn new_seqpacket_pair() -> SysResult<(UnixDatagram, UnixDatagram)> { let ret = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, fds.as_mut_ptr()); if ret == 0 { ioctl(fds[0], FIOCLEX); - Ok((UnixDatagram::from_raw_fd(fds[0]), UnixDatagram::from_raw_fd(fds[1]))) + Ok(( + UnixDatagram::from_raw_fd(fds[0]), + UnixDatagram::from_raw_fd(fds[1]), + )) } else { Err(SysError::last()) } @@ -242,12 +248,13 @@ fn create_plugin_jail(root: &Path, seccomp_policy: &Path) -> Result<Minijail> { // Create a tmpfs in the plugin's root directory so that we can bind mount it's executable // file into it. The size=67108864 is size=64*1024*1024 or size=64MB. - j.mount_with_data(Path::new("none"), - Path::new("/"), - "tmpfs", - (MS_NOSUID | MS_NODEV) as usize, - "size=67108864") - .map_err(Error::MountRoot)?; + j.mount_with_data( + Path::new("none"), + Path::new("/"), + "tmpfs", + (MS_NOSUID | MS_NODEV) as usize, + "size=67108864", + ).map_err(Error::MountRoot)?; Ok(j) } @@ -277,8 +284,14 @@ enum PluginObject { length: u32, datamatch: u64, }, - Memory { slot: u32, length: usize }, - IrqEvent { irq_id: u32, evt: EventFd }, + Memory { + slot: u32, + length: usize, + }, + IrqEvent { + irq_id: u32, + evt: EventFd, + }, } impl PluginObject { @@ -289,119 +302,114 @@ impl PluginObject { addr, length, datamatch, - } => { - match length { - 0 => vm.unregister_ioevent(&evt, addr, NoDatamatch), - 1 => vm.unregister_ioevent(&evt, addr, datamatch as u8), - 2 => vm.unregister_ioevent(&evt, addr, datamatch as u16), - 4 => vm.unregister_ioevent(&evt, addr, datamatch as u32), - 8 => vm.unregister_ioevent(&evt, addr, datamatch as u64), - _ => Err(SysError::new(EINVAL)), - } - } + } => match length { + 0 => vm.unregister_ioevent(&evt, addr, NoDatamatch), + 1 => vm.unregister_ioevent(&evt, addr, datamatch as u8), + 2 => vm.unregister_ioevent(&evt, addr, datamatch as u16), + 4 => vm.unregister_ioevent(&evt, addr, datamatch as u32), + 8 => vm.unregister_ioevent(&evt, addr, datamatch as u64), + _ => Err(SysError::new(EINVAL)), + }, PluginObject::Memory { slot, .. } => vm.remove_device_memory(slot).and(Ok(())), PluginObject::IrqEvent { irq_id, evt } => vm.unregister_irqfd(&evt, irq_id), } } } -pub fn run_vcpus(kvm: &Kvm, - vm: &Vm, - plugin: &Process, - vcpu_count: u32, - kill_signaled: &Arc<AtomicBool>, - exit_evt: &EventFd, - vcpu_handles: &mut Vec<thread::JoinHandle<()>>) - -> Result<()> { +pub fn run_vcpus( + kvm: &Kvm, + vm: &Vm, + plugin: &Process, + vcpu_count: u32, + kill_signaled: &Arc<AtomicBool>, + exit_evt: &EventFd, + vcpu_handles: &mut Vec<thread::JoinHandle<()>>, +) -> Result<()> { let vcpu_thread_barrier = Arc::new(Barrier::new((vcpu_count) as usize)); for cpu_id in 0..vcpu_count { let kill_signaled = kill_signaled.clone(); let vcpu_thread_barrier = vcpu_thread_barrier.clone(); let vcpu_exit_evt = exit_evt.try_clone().map_err(Error::CloneEventFd)?; let vcpu_plugin = plugin.create_vcpu(cpu_id)?; - let vcpu = Vcpu::new(cpu_id as c_ulong, kvm, vm) - .map_err(Error::CreateVcpu)?; - - vcpu_handles.push(thread::Builder::new() - .name(format!("crosvm_vcpu{}", cpu_id)) - .spawn(move || { - unsafe { - extern "C" fn handle_signal() {} - // Our signal handler does nothing and is trivially async signal safe. - // We need to install this signal handler even though we do block - // the signal below, to ensure that this signal will interrupt - // execution of KVM_RUN (this is implementation issue). - register_signal_handler(SIGRTMIN() + 0, handle_signal) - .expect("failed to register vcpu signal handler"); - } - - // We do not really want the signal handler to run... - block_signal(SIGRTMIN() + 0).expect("failed to block signal"); - // Tell KVM to not block anything when entering kvm run - // because we will be using first RT signal to kick the VCPU. - vcpu.set_signal_mask(&[]) - .expect("failed to set up KVM VCPU signal mask"); + let vcpu = Vcpu::new(cpu_id as c_ulong, kvm, vm).map_err(Error::CreateVcpu)?; + + vcpu_handles.push( + thread::Builder::new() + .name(format!("crosvm_vcpu{}", cpu_id)) + .spawn(move || { + unsafe { + extern "C" fn handle_signal() {} + // Our signal handler does nothing and is trivially async signal safe. + // We need to install this signal handler even though we do block + // the signal below, to ensure that this signal will interrupt + // execution of KVM_RUN (this is implementation issue). + register_signal_handler(SIGRTMIN() + 0, handle_signal) + .expect("failed to register vcpu signal handler"); + } - let res = vcpu_plugin.init(&vcpu); - vcpu_thread_barrier.wait(); - if let Err(e) = res { - error!("failed to initialize vcpu {}: {:?}", cpu_id, e); - } else { - loop { - let run_res = vcpu.run(); - match run_res { - Ok(run) => { - match run { - VcpuExit::IoIn(addr, data) => { - vcpu_plugin.io_read(addr as u64, data, &vcpu); - } - VcpuExit::IoOut(addr, data) => { - vcpu_plugin.io_write(addr as u64, data, &vcpu); - } - VcpuExit::MmioRead(addr, data) => { - vcpu_plugin.mmio_read(addr as u64, data, &vcpu); - } - VcpuExit::MmioWrite(addr, data) => { - vcpu_plugin.mmio_write(addr as u64, data, &vcpu); - } - VcpuExit::Hlt => break, - VcpuExit::Shutdown => break, - VcpuExit::InternalError => { - error!("vcpu {} has internal error", cpu_id); - break; - } - r => warn!("unexpected vcpu exit: {:?}", r), + // We do not really want the signal handler to run... + block_signal(SIGRTMIN() + 0).expect("failed to block signal"); + // Tell KVM to not block anything when entering kvm run + // because we will be using first RT signal to kick the VCPU. + vcpu.set_signal_mask(&[]) + .expect("failed to set up KVM VCPU signal mask"); + + let res = vcpu_plugin.init(&vcpu); + vcpu_thread_barrier.wait(); + if let Err(e) = res { + error!("failed to initialize vcpu {}: {:?}", cpu_id, e); + } else { + loop { + let run_res = vcpu.run(); + match run_res { + Ok(run) => match run { + VcpuExit::IoIn(addr, data) => { + vcpu_plugin.io_read(addr as u64, data, &vcpu); + } + VcpuExit::IoOut(addr, data) => { + vcpu_plugin.io_write(addr as u64, data, &vcpu); + } + VcpuExit::MmioRead(addr, data) => { + vcpu_plugin.mmio_read(addr as u64, data, &vcpu); + } + VcpuExit::MmioWrite(addr, data) => { + vcpu_plugin.mmio_write(addr as u64, data, &vcpu); + } + VcpuExit::Hlt => break, + VcpuExit::Shutdown => break, + VcpuExit::InternalError => { + error!("vcpu {} has internal error", cpu_id); + break; + } + r => warn!("unexpected vcpu exit: {:?}", r), + }, + Err(e) => match e.errno() { + EAGAIN | EINTR => {} + _ => { + error!("vcpu hit unknown error: {:?}", e); + break; + } + }, } - } - Err(e) => { - match e.errno() { - EAGAIN | EINTR => {} - _ => { - error!("vcpu hit unknown error: {:?}", e); - break; - } + if kill_signaled.load(Ordering::SeqCst) { + break; } - } - } - if kill_signaled.load(Ordering::SeqCst) { - break; - } - // Try to clear the signal that we use to kick VCPU if it is - // pending before attempting to handle pause requests. - clear_signal(SIGRTMIN() + 0).expect("failed to clear pending signal"); + // Try to clear the signal that we use to kick VCPU if it is + // pending before attempting to handle pause requests. + clear_signal(SIGRTMIN() + 0).expect("failed to clear pending signal"); - if let Err(e) = vcpu_plugin.pre_run(&vcpu) { - error!("failed to process pause on vcpu {}: {:?}", cpu_id, e); - break; + if let Err(e) = vcpu_plugin.pre_run(&vcpu) { + error!("failed to process pause on vcpu {}: {:?}", cpu_id, e); + break; + } + } } - } - } - vcpu_exit_evt - .write(1) - .expect("failed to signal vcpu exit eventfd"); - }) - .map_err(Error::SpawnVcpu)?); + vcpu_exit_evt + .write(1) + .expect("failed to signal vcpu exit eventfd"); + }).map_err(Error::SpawnVcpu)?, + ); } Ok(()) } @@ -504,8 +512,9 @@ pub fn run_config(cfg: Config) -> Result<()> { 'poll: loop { // After we have waited long enough, it's time to give up and exit. if dying_instant - .map(|i| i.elapsed() >= duration_to_die) - .unwrap_or(false) { + .map(|i| i.elapsed() >= duration_to_die) + .unwrap_or(false) + { break; } @@ -559,11 +568,11 @@ pub fn run_config(cfg: Config) -> Result<()> { // plugin process, report it as an error. if res.is_ok() { res = Err(Error::SigChild { - pid: siginfo.ssi_pid, - signo: siginfo.ssi_signo, - status: siginfo.ssi_status, - code: siginfo.ssi_code, - }) + pid: siginfo.ssi_pid, + signo: siginfo.ssi_signo, + status: siginfo.ssi_status, + code: siginfo.ssi_code, + }) } } Ok(None) => break, // No more signals to read. @@ -586,11 +595,13 @@ pub fn run_config(cfg: Config) -> Result<()> { } } Token::Plugin { index } => { - match plugin.handle_socket(index, - &kvm, - &mut vm, - &vcpu_handles, - tap_opt.as_ref()) { + match plugin.handle_socket( + index, + &kvm, + &mut vm, + &vcpu_handles, + tap_opt.as_ref(), + ) { Ok(_) => {} // A HUP is an expected event for a socket, so don't bother warning about // it. @@ -608,21 +619,23 @@ pub fn run_config(cfg: Config) -> Result<()> { } if vcpu_handles.is_empty() && dying_instant.is_none() && plugin.is_started() { - let res = run_vcpus(&kvm, - &vm, - &plugin, - vcpu_count, - &kill_signaled, - &exit_evt, - &mut vcpu_handles); + let res = run_vcpus( + &kvm, + &vm, + &plugin, + vcpu_count, + &kill_signaled, + &exit_evt, + &mut vcpu_handles, + ); if let Err(e) = res { dying_instant.get_or_insert(Instant::now()); error!("failed to start vcpus: {}", e); } } - redo_poll_ctx_sockets = !sockets_to_drop.is_empty() || - plugin.sockets().len() != plugin_socket_count; + redo_poll_ctx_sockets = + !sockets_to_drop.is_empty() || plugin.sockets().len() != plugin_socket_count; // Cleanup all of the sockets that we have determined were disconnected or suffered some // other error. diff --git a/src/plugin/process.rs b/src/plugin/process.rs index 71c16c0..c99e3b6 100644 --- a/src/plugin/process.rs +++ b/src/plugin/process.rs @@ -2,7 +2,7 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::collections::hash_map::{HashMap, Entry, VacantEntry}; +use std::collections::hash_map::{Entry, HashMap, VacantEntry}; use std::env::set_var; use std::fs::File; use std::mem::transmute; @@ -17,17 +17,19 @@ use std::thread::JoinHandle; use net_util; use net_util::Error as NetError; -use libc::{waitpid, pid_t, EINVAL, ENODATA, ENOTTY, WNOHANG, WIFEXITED, WEXITSTATUS, WTERMSIG}; +use libc::{pid_t, waitpid, EINVAL, ENODATA, ENOTTY, WEXITSTATUS, WIFEXITED, WNOHANG, WTERMSIG}; use protobuf; use protobuf::Message; use io_jail::Minijail; -use kvm::{Vm, IoeventAddress, NoDatamatch, IrqSource, IrqRoute, PicId, dirty_log_bitmap_size}; -use kvm_sys::{kvm_pic_state, kvm_ioapic_state, kvm_pit_state2}; -use sys_util::{EventFd, MemoryMapping, Killable, ScmSocket, SharedMemory, GuestAddress, - Result as SysResult, Error as SysError, SIGRTMIN}; +use kvm::{dirty_log_bitmap_size, IoeventAddress, IrqRoute, IrqSource, NoDatamatch, PicId, Vm}; +use kvm_sys::{kvm_ioapic_state, kvm_pic_state, kvm_pit_state2}; use plugin_proto::*; +use sys_util::{ + Error as SysError, EventFd, GuestAddress, Killable, MemoryMapping, Result as SysResult, + ScmSocket, SharedMemory, SIGRTMIN, +}; use super::*; @@ -45,47 +47,41 @@ unsafe impl DataInit for VmPitState {} fn get_vm_state(vm: &Vm, state_set: MainRequest_StateSet) -> SysResult<Vec<u8>> { Ok(match state_set { - MainRequest_StateSet::PIC0 => { - VmPicState(vm.get_pic_state(PicId::Primary)?) - .as_slice() - .to_vec() - } - MainRequest_StateSet::PIC1 => { - VmPicState(vm.get_pic_state(PicId::Secondary)?) - .as_slice() - .to_vec() - } - MainRequest_StateSet::IOAPIC => { - VmIoapicState(vm.get_ioapic_state()?).as_slice().to_vec() - } - MainRequest_StateSet::PIT => VmPitState(vm.get_pit_state()?).as_slice().to_vec(), - }) + MainRequest_StateSet::PIC0 => VmPicState(vm.get_pic_state(PicId::Primary)?) + .as_slice() + .to_vec(), + MainRequest_StateSet::PIC1 => VmPicState(vm.get_pic_state(PicId::Secondary)?) + .as_slice() + .to_vec(), + MainRequest_StateSet::IOAPIC => VmIoapicState(vm.get_ioapic_state()?).as_slice().to_vec(), + MainRequest_StateSet::PIT => VmPitState(vm.get_pit_state()?).as_slice().to_vec(), + }) } fn set_vm_state(vm: &Vm, state_set: MainRequest_StateSet, state: &[u8]) -> SysResult<()> { match state_set { - MainRequest_StateSet::PIC0 => { - vm.set_pic_state(PicId::Primary, - &VmPicState::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - MainRequest_StateSet::PIC1 => { - vm.set_pic_state(PicId::Secondary, - &VmPicState::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - MainRequest_StateSet::IOAPIC => { - vm.set_ioapic_state(&VmIoapicState::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - MainRequest_StateSet::PIT => { - vm.set_pit_state(&VmPitState::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } + MainRequest_StateSet::PIC0 => vm.set_pic_state( + PicId::Primary, + &VmPicState::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + MainRequest_StateSet::PIC1 => vm.set_pic_state( + PicId::Secondary, + &VmPicState::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + MainRequest_StateSet::IOAPIC => vm.set_ioapic_state( + &VmIoapicState::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + MainRequest_StateSet::PIT => vm.set_pit_state( + &VmPitState::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), } } @@ -132,20 +128,22 @@ impl Process { /// Set the `jail` argument to spawn the plugin process within the preconfigured jail. /// Due to an API limitation in libminijail necessitating that this function set an environment /// variable, this function is not thread-safe. - pub fn new(cpu_count: u32, - cmd: &Path, - args: &[&str], - jail: Option<Minijail>) - -> Result<Process> { - let (request_socket, child_socket) = new_seqpacket_pair().map_err(Error::CreateMainSocket)?; - - let mut vcpu_sockets: Vec<(UnixDatagram, UnixDatagram)> = Vec::with_capacity(cpu_count as - usize); + pub fn new( + cpu_count: u32, + cmd: &Path, + args: &[&str], + jail: Option<Minijail>, + ) -> Result<Process> { + let (request_socket, child_socket) = + new_seqpacket_pair().map_err(Error::CreateMainSocket)?; + + let mut vcpu_sockets: Vec<(UnixDatagram, UnixDatagram)> = + Vec::with_capacity(cpu_count as usize); for _ in 0..cpu_count { vcpu_sockets.push(new_seqpacket_pair().map_err(Error::CreateVcpuSocket)?); } - let mut per_vcpu_states: Vec<Arc<Mutex<PerVcpuState>>> = Vec::with_capacity(cpu_count as - usize); + let mut per_vcpu_states: Vec<Arc<Mutex<PerVcpuState>>> = + Vec::with_capacity(cpu_count as usize); // TODO(zachr): replace with `resize_default` when that stabilizes. Using a plain `resize` // is incorrect because each element in the `Vec` will contain a shared reference to the // same `PerVcpuState` instance. This happens because `resize` fills new slots using clones @@ -160,28 +158,26 @@ impl Process { jail.run(cmd, &[0, 1, 2, child_socket.as_raw_fd()], args) .map_err(Error::PluginRunJail)? } - None => { - Command::new(cmd) - .args(args) - .env("CROSVM_SOCKET", child_socket.as_raw_fd().to_string()) - .spawn() - .map_err(Error::PluginSpawn)? - .id() as pid_t - } + None => Command::new(cmd) + .args(args) + .env("CROSVM_SOCKET", child_socket.as_raw_fd().to_string()) + .spawn() + .map_err(Error::PluginSpawn)? + .id() as pid_t, }; Ok(Process { - started: false, - plugin_pid, - request_sockets: vec![request_socket], - objects: Default::default(), - shared_vcpu_state: Default::default(), - per_vcpu_states, - kill_evt: EventFd::new().map_err(Error::CreateEventFd)?, - vcpu_sockets, - request_buffer: vec![0; MAX_DATAGRAM_SIZE], - response_buffer: Vec::new(), - }) + started: false, + plugin_pid, + request_sockets: vec![request_socket], + objects: Default::default(), + shared_vcpu_state: Default::default(), + per_vcpu_states, + kill_evt: EventFd::new().map_err(Error::CreateEventFd)?, + vcpu_sockets, + request_buffer: vec![0; MAX_DATAGRAM_SIZE], + response_buffer: Vec::new(), + }) } /// Creates a VCPU plugin connection object, used by a VCPU run loop to communicate with the @@ -195,9 +191,11 @@ impl Process { .0 .try_clone() .map_err(Error::CloneVcpuSocket)?; - Ok(PluginVcpu::new(self.shared_vcpu_state.clone(), - self.per_vcpu_states[cpu_id as usize].clone(), - vcpu_socket)) + Ok(PluginVcpu::new( + self.shared_vcpu_state.clone(), + self.per_vcpu_states[cpu_id as usize].clone(), + vcpu_socket, + )) } /// Returns if the plugin process indicated the VM was ready to start. @@ -267,7 +265,8 @@ impl Process { _ => { // Trivially safe if unsafe { WIFEXITED(status) } { - match unsafe { WEXITSTATUS(status) } { // Trivially safe + match unsafe { WEXITSTATUS(status) } { + // Trivially safe 0 => Ok(ProcessStatus::Success), code => Ok(ProcessStatus::Fail(code)), } @@ -279,10 +278,11 @@ impl Process { } } - fn handle_io_event(entry: VacantEntry<u32, PluginObject>, - vm: &mut Vm, - io_event: &MainRequest_Create_IoEvent) - -> SysResult<RawFd> { + fn handle_io_event( + entry: VacantEntry<u32, PluginObject>, + vm: &mut Vm, + io_event: &MainRequest_Create_IoEvent, + ) -> SysResult<RawFd> { let evt = EventFd::new()?; let addr = match io_event.space { AddressSpace::IOPORT => IoeventAddress::Pio(io_event.address), @@ -299,24 +299,24 @@ impl Process { let fd = evt.as_raw_fd(); entry.insert(PluginObject::IoEvent { - evt, - addr, - length: io_event.length, - datamatch: io_event.datamatch, - }); + evt, + addr, + length: io_event.length, + datamatch: io_event.datamatch, + }); Ok(fd) } - - fn handle_memory(entry: VacantEntry<u32, PluginObject>, - vm: &mut Vm, - memfd: File, - offset: u64, - start: u64, - length: u64, - read_only: bool, - dirty_log: bool) - -> SysResult<()> { + fn handle_memory( + entry: VacantEntry<u32, PluginObject>, + vm: &mut Vm, + memfd: File, + offset: u64, + start: u64, + length: u64, + read_only: bool, + dirty_log: bool, + ) -> SysResult<()> { let shm = SharedMemory::from_raw_fd(memfd)?; // Checking the seals ensures the plugin process won't shrink the mmapped file, causing us // to SIGBUS in the future. @@ -334,9 +334,9 @@ impl Process { .map_err(mmap_to_sys_err)?; let slot = vm.add_device_memory(GuestAddress(start), mem, read_only, dirty_log)?; entry.insert(PluginObject::Memory { - slot, - length: length as usize, - }); + slot, + length: length as usize, + }); Ok(()) } @@ -356,42 +356,43 @@ impl Process { } } - fn handle_set_irq_routing(vm: &mut Vm, - irq_routing: &MainRequest_SetIrqRouting) - -> SysResult<()> { + fn handle_set_irq_routing( + vm: &mut Vm, + irq_routing: &MainRequest_SetIrqRouting, + ) -> SysResult<()> { let mut routes = Vec::with_capacity(irq_routing.routes.len()); for route in irq_routing.routes.iter() { routes.push(IrqRoute { - gsi: route.irq_id, - source: if route.has_irqchip() { - let irqchip = route.get_irqchip(); - IrqSource::Irqchip { - chip: irqchip.irqchip, - pin: irqchip.pin, - } - } else if route.has_msi() { - let msi = route.get_msi(); - IrqSource::Msi { - address: msi.address, - data: msi.data, - } - } else { - // Because route is a oneof field in the proto definition, this should - // only happen if a new variant gets added without updating this chained - // if block. - return Err(SysError::new(EINVAL)); - }, - }); + gsi: route.irq_id, + source: if route.has_irqchip() { + let irqchip = route.get_irqchip(); + IrqSource::Irqchip { + chip: irqchip.irqchip, + pin: irqchip.pin, + } + } else if route.has_msi() { + let msi = route.get_msi(); + IrqSource::Msi { + address: msi.address, + data: msi.data, + } + } else { + // Because route is a oneof field in the proto definition, this should + // only happen if a new variant gets added without updating this chained + // if block. + return Err(SysError::new(EINVAL)); + }, + }); } vm.set_gsi_routing(&routes[..]) } fn handle_pause_vcpus(&self, vcpu_handles: &[JoinHandle<()>], cpu_mask: u64, user_data: u64) { - for (cpu_id, (handle, per_cpu_state)) in - vcpu_handles - .iter() - .zip(self.per_vcpu_states.iter()) - .enumerate() { + for (cpu_id, (handle, per_cpu_state)) in vcpu_handles + .iter() + .zip(self.per_vcpu_states.iter()) + .enumerate() + { if cpu_mask & (1 << cpu_id) != 0 { per_cpu_state.lock().unwrap().request_pause(user_data); if let Err(e) = handle.kill(SIGRTMIN() + 0) { @@ -401,9 +402,10 @@ impl Process { } } - fn handle_get_net_config(tap: &net_util::Tap, - config: &mut MainResponse_GetNetConfig) - -> SysResult<()> { + fn handle_get_net_config( + tap: &net_util::Tap, + config: &mut MainResponse_GetNetConfig, + ) -> SysResult<()> { // Log any NetError so that the cause can be found later, but extract and return the // underlying errno for the client as well. fn map_net_error(s: &str, e: NetError) -> SysError { @@ -411,15 +413,15 @@ impl Process { e.sys_error() } - let ip_addr = tap.ip_addr() - .map_err(|e| map_net_error("IP address", e))?; + let ip_addr = tap.ip_addr().map_err(|e| map_net_error("IP address", e))?; config.set_host_ipv4_address(u32::from(ip_addr)); let netmask = tap.netmask().map_err(|e| map_net_error("netmask", e))?; config.set_netmask(u32::from(netmask)); let result_mac_addr = config.mut_host_mac_address(); - let mac_addr_octets = tap.mac_address() + let mac_addr_octets = tap + .mac_address() .map_err(|e| map_net_error("mac address", e))? .octets(); result_mac_addr.resize(mac_addr_octets.len(), 0); @@ -433,13 +435,14 @@ impl Process { /// /// The `vm` is used to service request that affect the VM. The `vcpu_handles` slice is used to /// interrupt a VCPU thread currently running in the VM if the socket request it. - pub fn handle_socket(&mut self, - index: usize, - kvm: &Kvm, - vm: &mut Vm, - vcpu_handles: &[JoinHandle<()>], - tap: Option<&Tap>) - -> Result<()> { + pub fn handle_socket( + &mut self, + index: usize, + kvm: &Kvm, + vm: &mut Vm, + vcpu_handles: &[JoinHandle<()>], + tap: Option<&Tap>, + ) -> Result<()> { let (msg_size, request_file) = self.request_sockets[index] .recv_with_fd(&mut self.request_buffer) .map_err(Error::PluginSocketRecv)?; @@ -470,38 +473,38 @@ impl Process { } else if create.has_memory() { let memory = create.get_memory(); match request_file { - Some(memfd) => { - Self::handle_memory(entry, - vm, - memfd, - memory.offset, - memory.start, - memory.length, - memory.read_only, - memory.dirty_log) - } + Some(memfd) => Self::handle_memory( + entry, + vm, + memfd, + memory.offset, + memory.start, + memory.length, + memory.read_only, + memory.dirty_log, + ), None => Err(SysError::new(EBADF)), } } else if create.has_irq_event() { let irq_event = create.get_irq_event(); match (EventFd::new(), EventFd::new()) { - (Ok(evt), Ok(resample_evt)) => { - match vm.register_irqfd_resample(&evt, - &resample_evt, - irq_event.irq_id) { - Ok(()) => { - response_fds.push(evt.as_raw_fd()); - response_fds.push(resample_evt.as_raw_fd()); - response_files.push(downcast_file(resample_evt)); - entry.insert(PluginObject::IrqEvent { - irq_id: irq_event.irq_id, - evt, - }); - Ok(()) - } - Err(e) => Err(e), + (Ok(evt), Ok(resample_evt)) => match vm.register_irqfd_resample( + &evt, + &resample_evt, + irq_event.irq_id, + ) { + Ok(()) => { + response_fds.push(evt.as_raw_fd()); + response_fds.push(resample_evt.as_raw_fd()); + response_files.push(downcast_file(resample_evt)); + entry.insert(PluginObject::IrqEvent { + irq_id: irq_event.irq_id, + evt, + }); + Ok(()) } - } + Err(e) => Err(e), + }, (Err(e), _) | (_, Err(e)) => Err(e), } } else { diff --git a/src/plugin/vcpu.rs b/src/plugin/vcpu.rs index 5ff5366..76c58cc 100644 --- a/src/plugin/vcpu.rs +++ b/src/plugin/vcpu.rs @@ -4,21 +4,23 @@ use std::cell::{Cell, RefCell}; use std::cmp::min; -use std::cmp::{self, Ord, PartialOrd, PartialEq}; +use std::cmp::{self, Ord, PartialEq, PartialOrd}; use std::collections::btree_set::BTreeSet; use std::mem::size_of; use std::os::unix::net::UnixDatagram; use std::sync::{Arc, Mutex, RwLock}; -use libc::{EINVAL, EPROTO, ENOENT, EPERM, EPIPE, EDEADLK, ENOTTY}; +use libc::{EDEADLK, EINVAL, ENOENT, ENOTTY, EPERM, EPIPE, EPROTO}; use protobuf; use protobuf::Message; use data_model::DataInit; -use kvm::{Vcpu, CpuId}; -use kvm_sys::{kvm_regs, kvm_sregs, kvm_fpu, kvm_debugregs, kvm_xcrs, kvm_msrs, kvm_msr_entry, - KVM_CPUID_FLAG_SIGNIFCANT_INDEX, kvm_lapic_state, kvm_mp_state, kvm_vcpu_events}; +use kvm::{CpuId, Vcpu}; +use kvm_sys::{ + kvm_debugregs, kvm_fpu, kvm_lapic_state, kvm_mp_state, kvm_msr_entry, kvm_msrs, kvm_regs, + kvm_sregs, kvm_vcpu_events, kvm_xcrs, KVM_CPUID_FLAG_SIGNIFCANT_INDEX, +}; use plugin_proto::*; use super::*; @@ -81,65 +83,56 @@ unsafe impl DataInit for VcpuEvents {} fn get_vcpu_state(vcpu: &Vcpu, state_set: VcpuRequest_StateSet) -> SysResult<Vec<u8>> { Ok(match state_set { - VcpuRequest_StateSet::REGS => VcpuRegs(vcpu.get_regs()?).as_slice().to_vec(), - VcpuRequest_StateSet::SREGS => VcpuSregs(vcpu.get_sregs()?).as_slice().to_vec(), - VcpuRequest_StateSet::FPU => VcpuFpu(vcpu.get_fpu()?).as_slice().to_vec(), - VcpuRequest_StateSet::DEBUGREGS => { - VcpuDebugregs(vcpu.get_debugregs()?).as_slice().to_vec() - } - VcpuRequest_StateSet::XCREGS => VcpuXcregs(vcpu.get_xcrs()?).as_slice().to_vec(), - VcpuRequest_StateSet::LAPIC => VcpuLapicState(vcpu.get_lapic()?).as_slice().to_vec(), - VcpuRequest_StateSet::MP => VcpuMpState(vcpu.get_mp_state()?).as_slice().to_vec(), - VcpuRequest_StateSet::EVENTS => VcpuEvents(vcpu.get_vcpu_events()?).as_slice().to_vec(), - }) + VcpuRequest_StateSet::REGS => VcpuRegs(vcpu.get_regs()?).as_slice().to_vec(), + VcpuRequest_StateSet::SREGS => VcpuSregs(vcpu.get_sregs()?).as_slice().to_vec(), + VcpuRequest_StateSet::FPU => VcpuFpu(vcpu.get_fpu()?).as_slice().to_vec(), + VcpuRequest_StateSet::DEBUGREGS => VcpuDebugregs(vcpu.get_debugregs()?).as_slice().to_vec(), + VcpuRequest_StateSet::XCREGS => VcpuXcregs(vcpu.get_xcrs()?).as_slice().to_vec(), + VcpuRequest_StateSet::LAPIC => VcpuLapicState(vcpu.get_lapic()?).as_slice().to_vec(), + VcpuRequest_StateSet::MP => VcpuMpState(vcpu.get_mp_state()?).as_slice().to_vec(), + VcpuRequest_StateSet::EVENTS => VcpuEvents(vcpu.get_vcpu_events()?).as_slice().to_vec(), + }) } fn set_vcpu_state(vcpu: &Vcpu, state_set: VcpuRequest_StateSet, state: &[u8]) -> SysResult<()> { match state_set { VcpuRequest_StateSet::REGS => { - vcpu.set_regs(&VcpuRegs::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) + vcpu.set_regs(&VcpuRegs::from_slice(state).ok_or(SysError::new(EINVAL))?.0) } VcpuRequest_StateSet::SREGS => { - vcpu.set_sregs(&VcpuSregs::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) + vcpu.set_sregs(&VcpuSregs::from_slice(state).ok_or(SysError::new(EINVAL))?.0) } VcpuRequest_StateSet::FPU => { - vcpu.set_fpu(&VcpuFpu::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - VcpuRequest_StateSet::DEBUGREGS => { - vcpu.set_debugregs(&VcpuDebugregs::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - VcpuRequest_StateSet::XCREGS => { - vcpu.set_xcrs(&VcpuXcregs::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - VcpuRequest_StateSet::LAPIC => { - vcpu.set_lapic(&VcpuLapicState::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - VcpuRequest_StateSet::MP => { - vcpu.set_mp_state(&VcpuMpState::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) - } - VcpuRequest_StateSet::EVENTS => { - vcpu.set_vcpu_events(&VcpuEvents::from_slice(state) - .ok_or(SysError::new(EINVAL))? - .0) + vcpu.set_fpu(&VcpuFpu::from_slice(state).ok_or(SysError::new(EINVAL))?.0) } + VcpuRequest_StateSet::DEBUGREGS => vcpu.set_debugregs( + &VcpuDebugregs::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + VcpuRequest_StateSet::XCREGS => vcpu.set_xcrs( + &VcpuXcregs::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + VcpuRequest_StateSet::LAPIC => vcpu.set_lapic( + &VcpuLapicState::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + VcpuRequest_StateSet::MP => vcpu.set_mp_state( + &VcpuMpState::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), + VcpuRequest_StateSet::EVENTS => vcpu.set_vcpu_events( + &VcpuEvents::from_slice(state) + .ok_or(SysError::new(EINVAL))? + .0, + ), } } - /// State shared by every VCPU, grouped together to make edits to the state coherent across VCPUs. #[derive(Default)] pub struct SharedVcpuState { @@ -171,10 +164,7 @@ impl SharedVcpuState { IoSpace::Mmio => &mut self.mmio_regions, }; - match space - .range(..Range(last_address, 0)) - .next_back() - .cloned() { + match space.range(..Range(last_address, 0)).next_back().cloned() { Some(Range(existing_start, _)) if existing_start >= start => Err(SysError::new(EPERM)), _ => { space.insert(Range(start, length)); @@ -291,10 +281,11 @@ pub struct PluginVcpu { impl PluginVcpu { /// Creates the plugin state and connection container for a VCPU thread. - pub fn new(shared_vcpu_state: Arc<RwLock<SharedVcpuState>>, - per_vcpu_state: Arc<Mutex<PerVcpuState>>, - connection: UnixDatagram) - -> PluginVcpu { + pub fn new( + shared_vcpu_state: Arc<RwLock<SharedVcpuState>>, + per_vcpu_state: Arc<Mutex<PerVcpuState>>, + connection: UnixDatagram, + ) -> PluginVcpu { PluginVcpu { shared_vcpu_state, per_vcpu_state, @@ -320,7 +311,8 @@ impl PluginVcpu { /// to this VCPU. pub fn pre_run(&self, vcpu: &Vcpu) -> SysResult<()> { let request = { - let mut lock = self.per_vcpu_state + let mut lock = self + .per_vcpu_state .lock() .map_err(|_| SysError::new(EDEADLK))?; lock.pause_request.take() @@ -403,11 +395,11 @@ impl PluginVcpu { let mut request_buffer = self.request_buffer.borrow_mut(); request_buffer.resize(MAX_VCPU_DATAGRAM_SIZE, 0); - let msg_size = self.connection + let msg_size = self + .connection .recv(&mut request_buffer) .map_err(io_to_sys_err)?; - let mut request = protobuf::parse_from_bytes::<VcpuRequest>(&request_buffer[..msg_size]) .map_err(proto_to_sys_err)?; @@ -449,9 +441,9 @@ impl PluginVcpu { let mut msr_entries = Vec::with_capacity(entry_indices.len()); for &index in entry_indices { msr_entries.push(kvm_msr_entry { - index, - ..Default::default() - }); + index, + ..Default::default() + }); } match vcpu.get_msrs(&mut msr_entries) { Ok(()) => { @@ -465,8 +457,8 @@ impl PluginVcpu { } else if request.has_set_msrs() { response.mut_set_msrs(); let request_entries = &request.get_set_msrs().entries; - let vec_size_bytes = size_of::<kvm_msrs>() + - (request_entries.len() * size_of::<kvm_msr_entry>()); + let vec_size_bytes = + size_of::<kvm_msrs>() + (request_entries.len() * size_of::<kvm_msr_entry>()); let vec: Vec<u8> = vec![0; vec_size_bytes]; let kvm_msrs: &mut kvm_msrs = unsafe { // Converting the vector's memory to a struct is unsafe. Carefully using the read- @@ -493,7 +485,8 @@ impl PluginVcpu { { let cpuid_entries = cpuid.mut_entries_slice(); for (request_entry, cpuid_entry) in - request_entries.iter().zip(cpuid_entries.iter_mut()) { + request_entries.iter().zip(cpuid_entries.iter_mut()) + { cpuid_entry.function = request_entry.function; if request_entry.has_index { cpuid_entry.index = request_entry.index; diff --git a/sys_util/src/errno.rs b/sys_util/src/errno.rs index b2c2977..0f9b5f2 100644 --- a/sys_util/src/errno.rs +++ b/sys_util/src/errno.rs @@ -2,10 +2,10 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::result; -use std::io; use std::error; use std::fmt::{self, Display}; +use std::io; +use std::result; use libc::__errno_location; diff --git a/sys_util/src/eventfd.rs b/sys_util/src/eventfd.rs index 3d6b850..9deb726 100644 --- a/sys_util/src/eventfd.rs +++ b/sys_util/src/eventfd.rs @@ -2,13 +2,13 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::mem; use std::fs::File; +use std::mem; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; -use libc::{read, write, eventfd, dup, c_void}; +use libc::{c_void, dup, eventfd, read, write}; -use {Result, errno_result}; +use {errno_result, Result}; /// A safe wrapper around a Linux eventfd (man 2 eventfd). /// @@ -29,7 +29,9 @@ impl EventFd { } // This is safe because we checked ret for success and know the kernel gave us an fd that we // own. - Ok(EventFd { eventfd: unsafe { File::from_raw_fd(ret) } }) + Ok(EventFd { + eventfd: unsafe { File::from_raw_fd(ret) }, + }) } /// Adds `v` to the eventfd's count, blocking until this won't overflow the count. @@ -37,9 +39,11 @@ impl EventFd { // This is safe because we made this fd and the pointer we pass can not overflow because we // give the syscall's size parameter properly. let ret = unsafe { - write(self.as_raw_fd(), - &v as *const u64 as *const c_void, - mem::size_of::<u64>()) + write( + self.as_raw_fd(), + &v as *const u64 as *const c_void, + mem::size_of::<u64>(), + ) }; if ret <= 0 { return errno_result(); @@ -53,9 +57,11 @@ impl EventFd { let ret = unsafe { // This is safe because we made this fd and the pointer we pass can not overflow because // we give the syscall's size parameter properly. - read(self.as_raw_fd(), - &mut buf as *mut u64 as *mut c_void, - mem::size_of::<u64>()) + read( + self.as_raw_fd(), + &mut buf as *mut u64 as *mut c_void, + mem::size_of::<u64>(), + ) }; if ret <= 0 { return errno_result(); @@ -73,7 +79,9 @@ impl EventFd { } // This is safe because we checked ret for success and know the kernel gave us an fd that we // own. - Ok(EventFd { eventfd: unsafe { File::from_raw_fd(ret) } }) + Ok(EventFd { + eventfd: unsafe { File::from_raw_fd(ret) }, + }) } } @@ -86,7 +94,7 @@ impl AsRawFd for EventFd { impl FromRawFd for EventFd { unsafe fn from_raw_fd(fd: RawFd) -> Self { EventFd { - eventfd: File::from_raw_fd(fd) + eventfd: File::from_raw_fd(fd), } } } diff --git a/sys_util/src/file_flags.rs b/sys_util/src/file_flags.rs index c8a3637..93da9bb 100644 --- a/sys_util/src/file_flags.rs +++ b/sys_util/src/file_flags.rs @@ -4,9 +4,9 @@ use std::os::unix::io::AsRawFd; -use libc::{fcntl, F_GETFL, O_ACCMODE, O_RDONLY, O_WRONLY, O_RDWR, EINVAL}; +use libc::{fcntl, EINVAL, F_GETFL, O_ACCMODE, O_RDONLY, O_RDWR, O_WRONLY}; -use {Error, Result, errno_result}; +use {errno_result, Error, Result}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum FileFlags { diff --git a/sys_util/src/fork.rs b/sys_util/src/fork.rs index dd7af22..426b2ae 100644 --- a/sys_util/src/fork.rs +++ b/sys_util/src/fork.rs @@ -10,7 +10,7 @@ use std::result; use errno_result; -use libc::{syscall, SIGCHLD, CLONE_NEWUSER, CLONE_NEWPID, c_long, pid_t}; +use libc::{c_long, pid_t, syscall, CLONE_NEWPID, CLONE_NEWUSER, SIGCHLD}; use syscall_defines::linux::LinuxSyscall::SYS_clone; @@ -58,7 +58,8 @@ fn count_dir_entries<P: AsRef<Path>>(path: P) -> io::Result<usize> { /// * `ns` - What namespace the new process will have (see NAMESPACES(7)). /// * `post_clone_cb` - Callback to run in the new process pub fn clone_process<F>(ns: CloneNamespace, post_clone_cb: F) -> result::Result<pid_t, CloneError> - where F: FnOnce() +where + F: FnOnce(), { match count_dir_entries("/proc/self/task") { Ok(1) => {} @@ -119,8 +120,7 @@ mod tests { } else { evt_fd_fork.write(2).unwrap() } - }) - .expect("failed to clone"); + }).expect("failed to clone"); assert_eq!(evt_fd.read(), Ok(1)); } @@ -131,8 +131,7 @@ mod tests { clone_process(CloneNamespace::Inherit, || { assert!(false); - }) - .expect("failed to clone"); + }).expect("failed to clone"); // This should never happen; if pid != getpid() { diff --git a/sys_util/src/guest_memory.rs b/sys_util/src/guest_memory.rs index 04ef124..604ef49 100644 --- a/sys_util/src/guest_memory.rs +++ b/sys_util/src/guest_memory.rs @@ -4,14 +4,14 @@ //! Track memory regions that are mapped to the guest VM. +use std::error::{self, Error as GuestMemoryError}; +use std::fmt::{self, Display}; use std::io::{Read, Write}; use std::result; use std::sync::Arc; -use std::error::{self, Error as GuestMemoryError}; -use std::fmt::{self, Display}; -use data_model::DataInit; use data_model::volatile_memory::*; +use data_model::DataInit; use guest_address::GuestAddress; use mmap::{self, MemoryMapping}; @@ -27,14 +27,10 @@ pub type Result<T> = result::Result<T, Error>; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::InvalidGuestAddress(_) => - "Invalid Guest Address", - &Error::MemoryAccess(_, _) => - "Invalid Guest Memory Access", - &Error::MemoryMappingFailed(_) => - "Failed to map guest memory", - &Error::MemoryRegionOverlap => - "Memory regions overlap", + &Error::InvalidGuestAddress(_) => "Invalid Guest Address", + &Error::MemoryAccess(_, _) => "Invalid Guest Memory Access", + &Error::MemoryMappingFailed(_) => "Failed to map guest memory", + &Error::MemoryRegionOverlap => "Memory regions overlap", } } } @@ -52,7 +48,9 @@ struct MemoryRegion { fn region_end(region: &MemoryRegion) -> GuestAddress { // unchecked_add is safe as the region bounds were checked when it was created. - region.guest_base.unchecked_add(region.mapping.size() as u64) + region + .guest_base + .unchecked_add(region.mapping.size() as u64) } /// Tracks a memory region and where it is mapped in the guest. @@ -68,22 +66,26 @@ impl GuestMemory { let mut regions = Vec::<MemoryRegion>::new(); for range in ranges.iter() { if let Some(last) = regions.last() { - if last.guest_base - .checked_add(last.mapping.size() as u64) - .map_or(true, |a| a > range.0) { + if last + .guest_base + .checked_add(last.mapping.size() as u64) + .map_or(true, |a| a > range.0) + { return Err(Error::MemoryRegionOverlap); } } - let mapping = MemoryMapping::new(range.1 as usize) - .map_err(Error::MemoryMappingFailed)?; + let mapping = + MemoryMapping::new(range.1 as usize).map_err(Error::MemoryMappingFailed)?; regions.push(MemoryRegion { - mapping: mapping, - guest_base: range.0, - }); + mapping, + guest_base: range.0, + }); } - Ok(GuestMemory { regions: Arc::new(regions) }) + Ok(GuestMemory { + regions: Arc::new(regions), + }) } /// Returns the end address of memory. @@ -107,8 +109,7 @@ impl GuestMemory { } /// Returns the total size of memory in bytes. - pub fn memory_size(&self) -> u64 - { + pub fn memory_size(&self) -> u64 { self.regions .iter() .map(|region| region.mapping.size() as u64) @@ -142,26 +143,32 @@ impl GuestMemory { /// Perform the specified action on each region's addresses. pub fn with_regions<F, E>(&self, cb: F) -> result::Result<(), E> - where F: Fn(usize, GuestAddress, usize, usize) -> result::Result<(), E> + where + F: Fn(usize, GuestAddress, usize, usize) -> result::Result<(), E>, { for (index, region) in self.regions.iter().enumerate() { - cb(index, - region.guest_base, - region.mapping.size(), - region.mapping.as_ptr() as usize)?; + cb( + index, + region.guest_base, + region.mapping.size(), + region.mapping.as_ptr() as usize, + )?; } Ok(()) } /// Perform the specified action on each region's addresses mutably. pub fn with_regions_mut<F, E>(&self, mut cb: F) -> result::Result<(), E> - where F: FnMut(usize, GuestAddress, usize, usize) -> result::Result<(), E> + where + F: FnMut(usize, GuestAddress, usize, usize) -> result::Result<(), E>, { for (index, region) in self.regions.iter().enumerate() { - cb(index, - region.guest_base, - region.mapping.size(), - region.mapping.as_ptr() as usize)?; + cb( + index, + region.guest_base, + region.mapping.size(), + region.mapping.as_ptr() as usize, + )?; } Ok(()) } @@ -210,10 +217,11 @@ impl GuestMemory { /// Ok(()) /// # } /// ``` - pub fn read_slice_at_addr(&self, - mut buf: &mut [u8], - guest_addr: GuestAddress) - -> Result<usize> { + pub fn read_slice_at_addr( + &self, + mut buf: &mut [u8], + guest_addr: GuestAddress, + ) -> Result<usize> { self.do_in_region(guest_addr, move |mapping, offset| { mapping .read_slice(buf, offset) @@ -298,12 +306,14 @@ impl GuestMemory { /// # Ok(rand_val) /// # } /// ``` - pub fn read_to_memory<F>(&self, - guest_addr: GuestAddress, - src: &mut F, - count: usize) - -> Result<()> - where F: Read + pub fn read_to_memory<F>( + &self, + guest_addr: GuestAddress, + src: &mut F, + count: usize, + ) -> Result<()> + where + F: Read, { self.do_in_region(guest_addr, move |mapping, offset| { mapping @@ -336,12 +346,14 @@ impl GuestMemory { /// # Ok(()) /// # } /// ``` - pub fn write_from_memory<F>(&self, - guest_addr: GuestAddress, - dst: &mut F, - count: usize) - -> Result<()> - where F: Write + pub fn write_from_memory<F>( + &self, + guest_addr: GuestAddress, + dst: &mut F, + count: usize, + ) -> Result<()> + where + F: Write, { self.do_in_region(guest_addr, move |mapping, offset| { mapping @@ -379,11 +391,15 @@ impl GuestMemory { } pub fn do_in_region<F, T>(&self, guest_addr: GuestAddress, cb: F) -> Result<T> - where F: FnOnce(&MemoryMapping, usize) -> Result<T> + where + F: FnOnce(&MemoryMapping, usize) -> Result<T>, { for region in self.regions.iter() { if guest_addr >= region.guest_base && guest_addr < region_end(region) { - return cb(®ion.mapping, guest_addr.offset_from(region.guest_base) as usize); + return cb( + ®ion.mapping, + guest_addr.offset_from(region.guest_base) as usize, + ); } } Err(Error::InvalidGuestAddress(guest_addr)) @@ -395,8 +411,8 @@ impl VolatileMemory for GuestMemory { for region in self.regions.iter() { if offset >= region.guest_base.0 && offset < region_end(region).0 { return region - .mapping - .get_slice(offset - region.guest_base.0, count); + .mapping + .get_slice(offset - region.guest_base.0, count); } } Err(VolatileMemoryError::OutOfBounds { addr: offset }) @@ -477,14 +493,15 @@ mod tests { let size_region1 = 0x1000; let start_region2 = GuestAddress(0x10000); let size_region2 = 0x2000; - let gm = GuestMemory::new(&vec![(start_region1, size_region1), - (start_region2, size_region2)]).unwrap(); + let gm = GuestMemory::new(&vec![ + (start_region1, size_region1), + (start_region2, size_region2), + ]).unwrap(); let mem_size = gm.memory_size(); assert_eq!(mem_size, size_region1 + size_region2); } - // Get the base address of the mapping for a GuestAddress. fn get_mapping(mem: &GuestMemory, addr: GuestAddress) -> Result<*const u8> { mem.do_in_region(addr, |mapping, _| Ok(mapping.as_ptr() as *const u8)) diff --git a/sys_util/src/handle_eintr.rs b/sys_util/src/handle_eintr.rs index 4bf16da..4faab07 100644 --- a/sys_util/src/handle_eintr.rs +++ b/sys_util/src/handle_eintr.rs @@ -120,22 +120,20 @@ impl<T> InterruptibleResult for io::Result<T> { /// ``` #[macro_export] macro_rules! handle_eintr { - ($x:expr) => ( - { - use $crate::handle_eintr::InterruptibleResult; - let res; - loop { - match $x { - ref v if v.is_interrupted() => continue, - v => { - res = v; - break; - } + ($x:expr) => {{ + use $crate::handle_eintr::InterruptibleResult; + let res; + loop { + match $x { + ref v if v.is_interrupted() => continue, + v => { + res = v; + break; } } - res } - ) + res + }}; } /// Macro that retries the given expression every time its result indicates it was interrupted. @@ -144,19 +142,17 @@ macro_rules! handle_eintr { /// Most of reentrant functions use this way of signalling errors. #[macro_export] macro_rules! handle_eintr_rc { - ($x:expr) => ( - { - use libc::EINTR; - let mut res; - loop { - res = $x; - if res != EINTR { - break; - } + ($x:expr) => {{ + use libc::EINTR; + let mut res; + loop { + res = $x; + if res != EINTR { + break; } - res } - ) + res + }}; } /// Macro that retries the given expression every time its result indicates it was interrupted. @@ -165,20 +161,18 @@ macro_rules! handle_eintr_rc { /// Most of standard non-reentrant libc functions use this way of signalling errors. #[macro_export] macro_rules! handle_eintr_errno { - ($x:expr) => ( - { - use $crate::Error; - use libc::EINTR; - let mut res; - loop { - res = $x; - if res != -1 || Error::last() != Error::new(EINTR) { - break; - } + ($x:expr) => {{ + use libc::EINTR; + use $crate::Error; + let mut res; + loop { + res = $x; + if res != -1 || Error::last() != Error::new(EINTR) { + break; } - res } - ) + res + }}; } #[cfg(test)] @@ -194,7 +188,11 @@ mod tests { { let mut dummy = || { count -= 1; - if count > 0 { EINTR } else { 0 } + if count > 0 { + EINTR + } else { + 0 + } }; let res = handle_eintr_rc!(dummy()); assert_eq!(res, 0); @@ -208,7 +206,12 @@ mod tests { { let mut dummy = || { count -= 1; - if count > 0 { set_errno(EINTR); -1 } else { 56 } + if count > 0 { + set_errno(EINTR); + -1 + } else { + 56 + } }; let res = handle_eintr_errno!(dummy()); assert_eq!(res, 56); @@ -241,7 +244,10 @@ mod tests { let mut dummy = || { count -= 1; if count > 99 { - Err(io::Error::new(io::ErrorKind::Interrupted, "interrupted again :(")) + Err(io::Error::new( + io::ErrorKind::Interrupted, + "interrupted again :(", + )) } else { Ok(32) } diff --git a/sys_util/src/ioctl.rs b/sys_util/src/ioctl.rs index edfa3be..31d21c9 100644 --- a/sys_util/src/ioctl.rs +++ b/sys_util/src/ioctl.rs @@ -12,47 +12,65 @@ use libc; /// Raw macro to declare a function that returns an ioctl number. #[macro_export] macro_rules! ioctl_ioc_nr { - ($name:ident, $dir:expr, $ty:expr, $nr:expr, $size:expr) => ( + ($name:ident, $dir:expr, $ty:expr, $nr:expr, $size:expr) => { #[allow(non_snake_case)] pub fn $name() -> ::std::os::raw::c_ulong { - (($dir << $crate::ioctl::_IOC_DIRSHIFT) | - ($ty << $crate::ioctl::_IOC_TYPESHIFT) | - ($nr<< $crate::ioctl::_IOC_NRSHIFT) | - ($size << $crate::ioctl::_IOC_SIZESHIFT)) as ::std::os::raw::c_ulong + (($dir << $crate::ioctl::_IOC_DIRSHIFT) + | ($ty << $crate::ioctl::_IOC_TYPESHIFT) + | ($nr << $crate::ioctl::_IOC_NRSHIFT) + | ($size << $crate::ioctl::_IOC_SIZESHIFT)) as ::std::os::raw::c_ulong } - ) + }; } /// Declare an ioctl that transfers no data. #[macro_export] macro_rules! ioctl_io_nr { - ($name:ident, $ty:expr, $nr:expr) => ( + ($name:ident, $ty:expr, $nr:expr) => { ioctl_ioc_nr!($name, $crate::ioctl::_IOC_NONE, $ty, $nr, 0); - ) + }; } /// Declare an ioctl that reads data. #[macro_export] macro_rules! ioctl_ior_nr { - ($name:ident, $ty:expr, $nr:expr, $size:ty) => ( - ioctl_ioc_nr!($name, $crate::ioctl::_IOC_READ, $ty, $nr, ::std::mem::size_of::<$size>() as u32); - ) + ($name:ident, $ty:expr, $nr:expr, $size:ty) => { + ioctl_ioc_nr!( + $name, + $crate::ioctl::_IOC_READ, + $ty, + $nr, + ::std::mem::size_of::<$size>() as u32 + ); + }; } /// Declare an ioctl that writes data. #[macro_export] macro_rules! ioctl_iow_nr { - ($name:ident, $ty:expr, $nr:expr, $size:ty) => ( - ioctl_ioc_nr!($name, $crate::ioctl::_IOC_WRITE, $ty, $nr, ::std::mem::size_of::<$size>() as u32); - ) + ($name:ident, $ty:expr, $nr:expr, $size:ty) => { + ioctl_ioc_nr!( + $name, + $crate::ioctl::_IOC_WRITE, + $ty, + $nr, + ::std::mem::size_of::<$size>() as u32 + ); + }; } /// Declare an ioctl that reads and writes data. #[macro_export] macro_rules! ioctl_iowr_nr { - ($name:ident, $ty:expr, $nr:expr, $size:ty) => ( - ioctl_ioc_nr!($name, $crate::ioctl::_IOC_READ | $crate::ioctl::_IOC_WRITE, $ty, $nr, ::std::mem::size_of::<$size>() as u32); - ) + ($name:ident, $ty:expr, $nr:expr, $size:ty) => { + ioctl_ioc_nr!( + $name, + $crate::ioctl::_IOC_READ | $crate::ioctl::_IOC_WRITE, + $ty, + $nr, + ::std::mem::size_of::<$size>() as u32 + ); + }; } pub const _IOC_NRBITS: c_uint = 8; @@ -109,12 +127,12 @@ pub unsafe fn ioctl_with_mut_ptr<F: AsRawFd, T>(fd: &F, nr: c_ulong, arg: *mut T #[cfg(test)] mod tests { const TUNTAP: ::std::os::raw::c_uint = 0x54; - const VHOST: ::std::os::raw::c_uint = 0xaf; + const VHOST: ::std::os::raw::c_uint = 0xaf; - ioctl_io_nr!(VHOST_SET_OWNER, VHOST, 0x01); - ioctl_ior_nr!(TUNGETFEATURES, TUNTAP, 0xcf, ::std::os::raw::c_uint); - ioctl_iow_nr!(TUNSETQUEUE, TUNTAP, 0xd9, ::std::os::raw::c_int); - ioctl_iowr_nr!(VHOST_GET_VRING_BASE, VHOST, 0x12, ::std::os::raw::c_int); + ioctl_io_nr!(VHOST_SET_OWNER, VHOST, 0x01); + ioctl_ior_nr!(TUNGETFEATURES, TUNTAP, 0xcf, ::std::os::raw::c_uint); + ioctl_iow_nr!(TUNSETQUEUE, TUNTAP, 0xd9, ::std::os::raw::c_int); + ioctl_iowr_nr!(VHOST_GET_VRING_BASE, VHOST, 0x12, ::std::os::raw::c_int); #[test] fn ioctl_macros() { diff --git a/sys_util/src/lib.rs b/sys_util/src/lib.rs index 511ee7e..94ccebc 100644 --- a/sys_util/src/lib.rs +++ b/sys_util/src/lib.rs @@ -17,59 +17,61 @@ pub mod handle_eintr; pub mod ioctl; #[macro_use] pub mod syslog; -mod mmap; -mod shm; -mod eventfd; mod errno; +mod eventfd; +mod file_flags; +mod fork; mod guest_address; mod guest_memory; +mod mmap; +mod passwd; mod poll; -mod struct_util; -mod tempdir; -mod terminal; +mod shm; pub mod signal; -mod fork; mod signalfd; mod sock_ctrl_msg; -mod passwd; -mod file_flags; +mod struct_util; +mod tempdir; +mod terminal; mod timerfd; mod write_zeroes; -pub use mmap::*; -pub use shm::*; -pub use eventfd::*; -pub use errno::{Error, Result}; use errno::errno_result; +pub use errno::{Error, Result}; +pub use eventfd::*; +pub use file_flags::*; +pub use fork::*; pub use guest_address::*; pub use guest_memory::*; +pub use ioctl::*; +pub use mmap::*; +pub use passwd::*; pub use poll::*; -pub use struct_util::*; -pub use tempdir::*; -pub use terminal::*; +pub use poll_token_derive::*; +pub use shm::*; pub use signal::*; -pub use fork::*; pub use signalfd::*; -pub use ioctl::*; pub use sock_ctrl_msg::*; -pub use passwd::*; -pub use poll_token_derive::*; -pub use file_flags::*; +pub use struct_util::*; +pub use tempdir::*; +pub use terminal::*; pub use timerfd::*; -pub use mmap::Error as MmapError; pub use guest_memory::Error as GuestMemoryError; +pub use mmap::Error as MmapError; pub use signalfd::Error as SignalFdError; -pub use write_zeroes::WriteZeroes as WriteZeroes; +pub use write_zeroes::WriteZeroes; use std::ffi::CStr; -use std::fs::{File, remove_file}; +use std::fs::{remove_file, File}; use std::os::unix::io::{AsRawFd, FromRawFd}; use std::os::unix::net::UnixDatagram; use std::ptr; -use libc::{kill, syscall, sysconf, waitpid, pipe2, c_long, pid_t, uid_t, gid_t, _SC_PAGESIZE, - SIGKILL, WNOHANG, O_CLOEXEC}; +use libc::{ + c_long, gid_t, kill, pid_t, pipe2, syscall, sysconf, uid_t, waitpid, O_CLOEXEC, SIGKILL, + WNOHANG, _SC_PAGESIZE, +}; use syscall_defines::linux::LinuxSyscall::SYS_getpid; @@ -80,7 +82,6 @@ pub fn pagesize() -> usize { unsafe { sysconf(_SC_PAGESIZE) as usize } } - /// Uses the system's page size in bytes to round the given value up to the nearest page boundary. #[inline(always)] pub fn round_up_to_page_size(v: usize) -> usize { @@ -161,12 +162,12 @@ pub enum FallocateMode { } // TODO(dverkamp): Remove this once fallocate64 is available in libc. -extern { +extern "C" { pub fn fallocate64( fd: libc::c_int, mode: libc::c_int, offset: libc::off64_t, - len: libc::off64_t + len: libc::off64_t, ) -> libc::c_int; } @@ -176,7 +177,7 @@ pub fn fallocate( mode: FallocateMode, keep_size: bool, offset: u64, - len: u64 + len: u64, ) -> Result<()> { let offset = if offset > libc::off64_t::max_value() as u64 { return Err(Error::new(libc::EINVAL)); @@ -278,7 +279,7 @@ pub fn pipe(close_on_exec: bool) -> Result<(File, File)> { Ok(unsafe { ( File::from_raw_fd(pipe_fds[0]), - File::from_raw_fd(pipe_fds[1]) + File::from_raw_fd(pipe_fds[1]), ) }) } @@ -302,4 +303,3 @@ impl Drop for UnlinkUnixDatagram { } } } - diff --git a/sys_util/src/mmap.rs b/sys_util/src/mmap.rs index ced48b1..5de433c 100644 --- a/sys_util/src/mmap.rs +++ b/sys_util/src/mmap.rs @@ -7,8 +7,8 @@ use std; use std::io::{Read, Write}; -use std::ptr::null_mut; use std::os::unix::io::AsRawFd; +use std::ptr::null_mut; use libc; @@ -59,12 +59,14 @@ impl MemoryMapping { // This is safe because we are creating an anonymous mapping in a place not already used by // any other area in this process. let addr = unsafe { - libc::mmap(null_mut(), - size, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_ANONYMOUS | libc::MAP_SHARED | libc::MAP_NORESERVE, - -1, - 0) + libc::mmap( + null_mut(), + size, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_ANONYMOUS | libc::MAP_SHARED | libc::MAP_NORESERVE, + -1, + 0, + ) }; if addr == libc::MAP_FAILED { return Err(Error::SystemCallFailed(errno::Error::last())); @@ -72,13 +74,15 @@ impl MemoryMapping { // This is safe because we call madvise with a valid address and size, and we check the // return value. We only warn about an error because failure here is not fatal to the mmap. if unsafe { libc::madvise(addr, size, libc::MADV_DONTDUMP) } == -1 { - warn!("failed madvise(MADV_DONTDUMP) on mmap: {:?}", - errno::Error::last()); + warn!( + "failed madvise(MADV_DONTDUMP) on mmap: {:?}", + errno::Error::last() + ); } Ok(MemoryMapping { - addr: addr as *mut u8, - size: size, - }) + addr: addr as *mut u8, + size, + }) } /// Maps the first `size` bytes of the given `fd`. @@ -103,12 +107,14 @@ impl MemoryMapping { // This is safe because we are creating a mapping in a place not already used by any other // area in this process. let addr = unsafe { - libc::mmap(null_mut(), - size, - libc::PROT_READ | libc::PROT_WRITE, - libc::MAP_SHARED, - fd.as_raw_fd(), - offset as libc::off_t) + libc::mmap( + null_mut(), + size, + libc::PROT_READ | libc::PROT_WRITE, + libc::MAP_SHARED, + fd.as_raw_fd(), + offset as libc::off_t, + ) }; if addr == libc::MAP_FAILED { return Err(Error::SystemCallFailed(errno::Error::last())); @@ -116,13 +122,15 @@ impl MemoryMapping { // This is safe because we call madvise with a valid address and size, and we check the // return value. We only warn about an error because failure here is not fatal to the mmap. if unsafe { libc::madvise(addr, size, libc::MADV_DONTDUMP) } == -1 { - warn!("failed madvise(MADV_DONTDUMP) on mmap: {:?}", - errno::Error::last()); + warn!( + "failed madvise(MADV_DONTDUMP) on mmap: {:?}", + errno::Error::last() + ); } Ok(MemoryMapping { - addr: addr as *mut u8, - size: size, - }) + addr: addr as *mut u8, + size, + }) } /// Returns a pointer to the begining of the memory region. Should only be @@ -237,7 +245,9 @@ impl MemoryMapping { unsafe { // This is safe because by definition Copy types can have their bits // set arbitrarily and still be valid. - Ok(std::ptr::read_volatile(&self.as_slice()[offset..] as *const _ as *const T)) + Ok(std::ptr::read_volatile( + &self.as_slice()[offset..] as *const _ as *const T, + )) } } @@ -265,9 +275,11 @@ impl MemoryMapping { /// # } /// ``` pub fn read_to_memory<F>(&self, mem_offset: usize, src: &mut F, count: usize) -> Result<()> - where F: Read + where + F: Read, { - let mem_end = self.range_end(mem_offset, count) + let mem_end = self + .range_end(mem_offset, count) .map_err(|_| Error::InvalidRange(mem_offset, count))?; unsafe { // It is safe to overwrite the volatile memory. Acessing the guest @@ -302,9 +314,11 @@ impl MemoryMapping { /// # } /// ``` pub fn write_from_memory<F>(&self, mem_offset: usize, dst: &mut F, count: usize) -> Result<()> - where F: Write + where + F: Write, { - let mem_end = self.range_end(mem_offset, count) + let mem_end = self + .range_end(mem_offset, count) .map_err(|_| Error::InvalidRange(mem_offset, count))?; unsafe { // It is safe to read from volatile memory. Acessing the guest @@ -324,9 +338,11 @@ impl MemoryMapping { let ret = unsafe { // madvising away the region is the same as the guest changing it. // Next time it is read, it may return zero pages. - libc::madvise((self.addr as usize + mem_offset) as *mut _, - count, - libc::MADV_REMOVE) + libc::madvise( + (self.addr as usize + mem_offset) as *mut _, + count, + libc::MADV_REMOVE, + ) }; if ret < 0 { Err(Error::InvalidRange(mem_offset, count)) @@ -349,8 +365,7 @@ impl MemoryMapping { // Check that offset+count is valid and return the sum. fn range_end(&self, offset: usize, count: usize) -> Result<usize> { - let mem_end = offset.checked_add(count) - .ok_or(Error::InvalidAddress)?; + let mem_end = offset.checked_add(count).ok_or(Error::InvalidAddress)?; if mem_end > self.size() { return Err(Error::InvalidAddress); } @@ -448,12 +463,13 @@ mod tests { fn slice_overflow_error() { let m = MemoryMapping::new(5).unwrap(); let res = m.get_slice(std::u64::MAX, 3).unwrap_err(); - assert_eq!(res, - VolatileMemoryError::Overflow { - base: std::u64::MAX, - offset: 3, - }); - + assert_eq!( + res, + VolatileMemoryError::Overflow { + base: std::u64::MAX, + offset: 3, + } + ); } #[test] fn slice_oob_error() { diff --git a/sys_util/src/passwd.rs b/sys_util/src/passwd.rs index 215cdd3..7181ba0 100644 --- a/sys_util/src/passwd.rs +++ b/sys_util/src/passwd.rs @@ -9,9 +9,9 @@ use std::mem; use std::ptr; use libc; -use libc::{c_char, gid_t, uid_t, getgrnam_r, getpwnam_r}; +use libc::{c_char, getgrnam_r, getpwnam_r, gid_t, uid_t}; -use {Result, errno_result}; +use {errno_result, Result}; /// Safe wrapper for getting a uid from a user name with `getpwnam_r(3)`. #[inline(always)] @@ -29,11 +29,13 @@ pub fn get_user_id(user_name: &CStr) -> Result<uid_t> { // This call is safe as long as it behaves as described in the man page. We pass in valid // pointers to stack-allocated buffers, and the length check for the scratch buffer is correct. unsafe { - handle_eintr_rc!(getpwnam_r(user_name.as_ptr(), - &mut passwd, - buf.as_mut_ptr(), - buf.len(), - &mut passwd_result)) + handle_eintr_rc!(getpwnam_r( + user_name.as_ptr(), + &mut passwd, + buf.as_mut_ptr(), + buf.len(), + &mut passwd_result + )) }; if passwd_result.is_null() { @@ -59,11 +61,13 @@ pub fn get_group_id(group_name: &CStr) -> Result<gid_t> { // This call is safe as long as it behaves as described in the man page. We pass in valid // pointers to stack-allocated buffers, and the length check for the scratch buffer is correct. unsafe { - handle_eintr_rc!(getgrnam_r(group_name.as_ptr(), - &mut group, - buf.as_mut_ptr(), - buf.len(), - &mut group_result)) + handle_eintr_rc!(getgrnam_r( + group_name.as_ptr(), + &mut group, + buf.as_mut_ptr(), + buf.len(), + &mut group_result + )) }; if group_result.is_null() { diff --git a/sys_util/src/poll.rs b/sys_util/src/poll.rs index f7b5f23..aa90330 100644 --- a/sys_util/src/poll.rs +++ b/sys_util/src/poll.rs @@ -2,22 +2,24 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::cell::{RefCell, Cell, Ref}; +use std::cell::{Cell, Ref, RefCell}; use std::cmp::min; use std::fs::File; use std::i32; use std::i64; use std::marker::PhantomData; -use std::os::unix::io::{RawFd, AsRawFd, IntoRawFd, FromRawFd}; +use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::ptr::null_mut; use std::slice; use std::thread; use std::time::Duration; -use libc::{c_int, EPOLL_CLOEXEC, EPOLLIN, EPOLLOUT, EPOLLHUP, EPOLL_CTL_ADD, EPOLL_CTL_MOD, - EPOLL_CTL_DEL, epoll_create1, epoll_ctl, epoll_wait, epoll_event}; +use libc::{ + c_int, epoll_create1, epoll_ctl, epoll_event, epoll_wait, EPOLLHUP, EPOLLIN, EPOLLOUT, + EPOLL_CLOEXEC, EPOLL_CTL_ADD, EPOLL_CTL_DEL, EPOLL_CTL_MOD, +}; -use {Result, errno_result}; +use {errno_result, Result}; const POLL_CONTEXT_MAX_EVENTS: usize = 16; @@ -121,7 +123,8 @@ impl<'a, T: PollToken> PollEvent<'a, T> { /// An iterator over some (sub)set of events returned by `PollContext::wait`. pub struct PollEventIter<'a, I, T> - where I: Iterator<Item = &'a epoll_event> +where + I: Iterator<Item = &'a epoll_event>, { mask: u32, iter: I, @@ -129,20 +132,19 @@ pub struct PollEventIter<'a, I, T> } impl<'a, I, T> Iterator for PollEventIter<'a, I, T> - where I: Iterator<Item = &'a epoll_event>, - T: PollToken +where + I: Iterator<Item = &'a epoll_event>, + T: PollToken, { type Item = PollEvent<'a, T>; fn next(&mut self) -> Option<Self::Item> { let mask = self.mask; self.iter .find(|event| (event.events & mask) != 0) - .map(|event| { - PollEvent { - event, - token: PhantomData, - } - }) + .map(|event| PollEvent { + event, + token: PhantomData, + }) } } @@ -293,13 +295,13 @@ impl<T: PollToken> PollContext<T> { return errno_result(); } Ok(PollContext { - epoll_ctx: unsafe { File::from_raw_fd(epoll_fd) }, - events: RefCell::new([epoll_event { events: 0, u64: 0 }; POLL_CONTEXT_MAX_EVENTS]), - hangups: Cell::new(0), - max_hangups: Cell::new(0), - // Safe because the `epoll_fd` is valid and we hold unique ownership. - tokens: PhantomData, - }) + epoll_ctx: unsafe { File::from_raw_fd(epoll_fd) }, + events: RefCell::new([epoll_event { events: 0, u64: 0 }; POLL_CONTEXT_MAX_EVENTS]), + hangups: Cell::new(0), + max_hangups: Cell::new(0), + // Safe because the `epoll_fd` is valid and we hold unique ownership. + tokens: PhantomData, + }) } /// Adds the given `fd` to this context and associates the given `token` with the `fd`'s @@ -326,10 +328,12 @@ impl<T: PollToken> PollContext<T> { // Safe because we give a valid epoll FD and FD to watch, as well as a valid epoll_event // structure. Then we check the return value. let ret = unsafe { - epoll_ctl(self.epoll_ctx.as_raw_fd(), - EPOLL_CTL_ADD, - fd.as_raw_fd(), - &mut evt) + epoll_ctl( + self.epoll_ctx.as_raw_fd(), + EPOLL_CTL_ADD, + fd.as_raw_fd(), + &mut evt, + ) }; if ret < 0 { return errno_result(); @@ -351,10 +355,12 @@ impl<T: PollToken> PollContext<T> { // Safe because we give a valid epoll FD and FD to modify, as well as a valid epoll_event // structure. Then we check the return value. let ret = unsafe { - epoll_ctl(self.epoll_ctx.as_raw_fd(), - EPOLL_CTL_MOD, - fd.as_raw_fd(), - &mut evt) + epoll_ctl( + self.epoll_ctx.as_raw_fd(), + EPOLL_CTL_MOD, + fd.as_raw_fd(), + &mut evt, + ) }; if ret < 0 { return errno_result(); @@ -372,10 +378,12 @@ impl<T: PollToken> PollContext<T> { // Safe because we give a valid epoll FD and FD to stop watching. Then we check the return // value. let ret = unsafe { - epoll_ctl(self.epoll_ctx.as_raw_fd(), - EPOLL_CTL_DEL, - fd.as_raw_fd(), - null_mut()) + epoll_ctl( + self.epoll_ctx.as_raw_fd(), + EPOLL_CTL_DEL, + fd.as_raw_fd(), + null_mut(), + ) }; if ret < 0 { return errno_result(); @@ -415,8 +423,10 @@ impl<T: PollToken> PollContext<T> { let old_hangups = self.hangups.get(); let max_hangups = self.max_hangups.get(); if old_hangups <= max_hangups && old_hangups + new_hangups > max_hangups { - warn!("busy poll wait loop with hungup FDs detected on thread {}", - thread::current().name().unwrap_or("")); + warn!( + "busy poll wait loop with hungup FDs detected on thread {}", + thread::current().name().unwrap_or("") + ); // This panic is helpful for tests of this functionality. #[cfg(test)] panic!("hungup busy loop detected"); @@ -463,10 +473,12 @@ impl<T: PollToken> PollContext<T> { // Safe because we give an epoll context and a properly sized epoll_events array // pointer, which we trust the kernel to fill in properly. unsafe { - handle_eintr_errno!(epoll_wait(self.epoll_ctx.as_raw_fd(), - &mut epoll_events[0], - max_events, - timeout_millis)) + handle_eintr_errno!(epoll_wait( + self.epoll_ctx.as_raw_fd(), + &mut epoll_events[0], + max_events, + timeout_millis + )) } }; if ret < 0 { @@ -496,12 +508,11 @@ impl<T: PollToken> IntoRawFd for PollContext<T> { } } - #[cfg(test)] mod tests { use super::*; - use std::time::Instant; use std::os::unix::net::UnixStream; + use std::time::Instant; use EventFd; #[test] @@ -596,15 +607,25 @@ mod tests { Omega, } - assert_eq!(Token::from_raw_token(Token::Alpha.as_raw_token()), - Token::Alpha); - assert_eq!(Token::from_raw_token(Token::Beta.as_raw_token()), - Token::Beta); - assert_eq!(Token::from_raw_token(Token::Gamma(55).as_raw_token()), - Token::Gamma(55)); - assert_eq!(Token::from_raw_token(Token::Delta { index: 100 }.as_raw_token()), - Token::Delta { index: 100 }); - assert_eq!(Token::from_raw_token(Token::Omega.as_raw_token()), - Token::Omega); + assert_eq!( + Token::from_raw_token(Token::Alpha.as_raw_token()), + Token::Alpha + ); + assert_eq!( + Token::from_raw_token(Token::Beta.as_raw_token()), + Token::Beta + ); + assert_eq!( + Token::from_raw_token(Token::Gamma(55).as_raw_token()), + Token::Gamma(55) + ); + assert_eq!( + Token::from_raw_token(Token::Delta { index: 100 }.as_raw_token()), + Token::Delta { index: 100 } + ); + assert_eq!( + Token::from_raw_token(Token::Omega.as_raw_token()), + Token::Omega + ); } } diff --git a/sys_util/src/shm.rs b/sys_util/src/shm.rs index c6e2884..6f74ecf 100644 --- a/sys_util/src/shm.rs +++ b/sys_util/src/shm.rs @@ -5,16 +5,17 @@ use std::ffi::CStr; use std::fs::File; use std::io::{Seek, SeekFrom}; -use std::os::unix::io::{AsRawFd, IntoRawFd, FromRawFd, RawFd}; +use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; -use libc::{self, off64_t, c_long, c_int, c_uint, c_char, close, syscall, ftruncate64, fcntl, - F_ADD_SEALS, F_GET_SEALS, F_SEAL_GROW, F_SEAL_SHRINK, F_SEAL_WRITE, F_SEAL_SEAL, - MFD_ALLOW_SEALING}; +use libc::{ + self, c_char, c_int, c_long, c_uint, close, fcntl, ftruncate64, off64_t, syscall, F_ADD_SEALS, + F_GET_SEALS, F_SEAL_GROW, F_SEAL_SEAL, F_SEAL_SHRINK, F_SEAL_WRITE, MFD_ALLOW_SEALING, +}; use errno; use syscall_defines::linux::LinuxSyscall::SYS_memfd_create; -use {Result, errno_result}; +use {errno_result, Result}; /// A shared memory file descriptor and its size. pub struct SharedMemory { @@ -105,7 +106,8 @@ impl SharedMemory { /// /// The file descriptor is opened with the close on exec flag and allows memfd sealing. pub fn new(name: Option<&CStr>) -> Result<SharedMemory> { - let shm_name = name.map(|n| n.as_ptr()) + let shm_name = name + .map(|n| n.as_ptr()) .unwrap_or(b"/crosvm_shm\0".as_ptr() as *const c_char); // The following are safe because we give a valid C string and check the // results of the memfd_create call. @@ -128,9 +130,9 @@ impl SharedMemory { let mut file = unsafe { File::from_raw_fd(fd.into_raw_fd()) }; let file_size = file.seek(SeekFrom::End(0))?; Ok(SharedMemory { - fd: file, - size: file_size as u64, - }) + fd: file, + size: file_size as u64, + }) } /// Gets the memfd seals that have already been added to this. @@ -221,14 +223,18 @@ mod tests { #[test] fn new() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let shm = SharedMemory::new(None).expect("failed to create shared memory"); assert_eq!(shm.size(), 0); } #[test] fn new_sized() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let mut shm = SharedMemory::new(None).expect("failed to create shared memory"); shm.set_size(1024) .expect("failed to set shared memory size"); @@ -237,7 +243,9 @@ mod tests { #[test] fn new_huge() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let mut shm = SharedMemory::new(None).expect("failed to create shared memory"); shm.set_size(0x7fff_ffff_ffff_ffff) .expect("failed to set shared memory size"); @@ -246,7 +254,9 @@ mod tests { #[test] fn new_too_huge() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let mut shm = SharedMemory::new(None).expect("failed to create shared memory"); shm.set_size(0x8000_0000_0000_0000).unwrap_err(); assert_eq!(shm.size(), 0); @@ -254,7 +264,9 @@ mod tests { #[test] fn new_named() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let name = "very unique name"; let cname = CString::new(name).unwrap(); let shm = SharedMemory::new(Some(&cname)).expect("failed to create shared memory"); @@ -282,7 +294,9 @@ mod tests { #[test] fn mmap_page() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let mut shm = SharedMemory::new(None).expect("failed to create shared memory"); shm.set_size(4096) .expect("failed to set shared memory size"); @@ -292,8 +306,10 @@ mod tests { let mmap2 = MemoryMapping::from_fd(&shm, shm.size() as usize).expect("failed to map shared memory"); - assert_ne!(mmap1.get_slice(0, 1).unwrap().as_ptr(), - mmap2.get_slice(0, 1).unwrap().as_ptr()); + assert_ne!( + mmap1.get_slice(0, 1).unwrap().as_ptr(), + mmap2.get_slice(0, 1).unwrap().as_ptr() + ); mmap1 .get_slice(0, 4096) @@ -315,8 +331,7 @@ mod tests { shm.set_size(8092) .expect("failed to set shared memory size"); - let mmap1 = - MemoryMapping::from_fd_offset(&shm, shm.size() as usize, 4096) + let mmap1 = MemoryMapping::from_fd_offset(&shm, shm.size() as usize, 4096) .expect("failed to map shared memory"); let mmap2 = MemoryMapping::from_fd(&shm, shm.size() as usize).expect("failed to map shared memory"); diff --git a/sys_util/src/signal.rs b/sys_util/src/signal.rs index 0bba761..69e0fd0 100644 --- a/sys_util/src/signal.rs +++ b/sys_util/src/signal.rs @@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use libc::{c_int, sigaction, SA_RESTART, timespec, - sigset_t, siginfo_t, - sigaddset, sigemptyset, sigismember, sigpending, sigtimedwait, - pthread_t, pthread_kill, pthread_sigmask, - SIG_BLOCK, SIG_UNBLOCK, EAGAIN, EINTR, EINVAL }; +use libc::{ + c_int, pthread_kill, pthread_sigmask, pthread_t, sigaction, sigaddset, sigemptyset, siginfo_t, + sigismember, sigpending, sigset_t, sigtimedwait, timespec, EAGAIN, EINTR, EINVAL, SA_RESTART, + SIG_BLOCK, SIG_UNBLOCK, +}; use std::mem; +use std::os::unix::thread::JoinHandleExt; use std::ptr::{null, null_mut}; use std::result; use std::thread::JoinHandle; -use std::os::unix::thread::JoinHandleExt; use {errno, errno_result}; @@ -179,7 +179,10 @@ pub fn clear_signal(num: c_int) -> SignalResult<()> { // of libc calls. unsafe { let mut siginfo: siginfo_t = mem::zeroed(); - let ts = timespec { tv_sec: 0, tv_nsec: 0 }; + let ts = timespec { + tv_sec: 0, + tv_nsec: 0, + }; // Attempt to consume one instance of pending signal. If signal // is not pending, the call will fail with EAGAIN or EINTR. let ret = sigtimedwait(&sigset, &mut siginfo, &ts); @@ -209,8 +212,7 @@ pub fn clear_signal(num: c_int) -> SignalResult<()> { // This is do-while loop condition. ret != 0 } - } - {} + } {} Ok(()) } diff --git a/sys_util/src/signalfd.rs b/sys_util/src/signalfd.rs index 3dad3a7..c4fd92d 100644 --- a/sys_util/src/signalfd.rs +++ b/sys_util/src/signalfd.rs @@ -2,14 +2,14 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::mem; -use std::result; use std::fs::File; +use std::mem; use std::os::raw::c_int; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; +use std::result; -use libc::{read, c_void, signalfd, signalfd_siginfo}; -use libc::{EAGAIN, SFD_NONBLOCK, SFD_CLOEXEC}; +use libc::{c_void, read, signalfd, signalfd_siginfo}; +use libc::{EAGAIN, SFD_CLOEXEC, SFD_NONBLOCK}; use errno; use signal; @@ -63,7 +63,7 @@ impl SignalFd { unsafe { Ok(SignalFd { signalfd: File::from_raw_fd(fd), - signal: signal, + signal, }) } } @@ -80,9 +80,11 @@ impl SignalFd { // was specified. signalfds will always read in increments of // sizeof(signalfd_siginfo); see man 2 signalfd. let ret = unsafe { - read(self.signalfd.as_raw_fd(), - &mut siginfo as *mut signalfd_siginfo as *mut c_void, - siginfo_size) + read( + self.signalfd.as_raw_fd(), + &mut siginfo as *mut signalfd_siginfo as *mut c_void, + siginfo_size, + ) }; if ret < 0 { @@ -121,7 +123,7 @@ impl Drop for SignalFd { mod tests { use super::*; - use libc::{raise, sigset_t, sigismember, pthread_sigmask}; + use libc::{pthread_sigmask, raise, sigismember, sigset_t}; use signal::SIGRTMIN; use std::ptr::null; @@ -147,7 +149,8 @@ mod tests { let sigid = SIGRTMIN() + 2; // Put the SignalFd in a block where it will be dropped at the end. - #[allow(unused_variables)] { + #[allow(unused_variables)] + { let sigrt_fd = SignalFd::new(sigid).unwrap(); unsafe { let mut sigset: sigset_t = mem::zeroed(); diff --git a/sys_util/src/sock_ctrl_msg.rs b/sys_util/src/sock_ctrl_msg.rs index ebbf9db..61f664c 100644 --- a/sys_util/src/sock_ctrl_msg.rs +++ b/sys_util/src/sock_ctrl_msg.rs @@ -7,39 +7,39 @@ use std::fs::File; use std::mem::size_of; -use std::os::unix::io::{AsRawFd, RawFd, FromRawFd}; +use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::net::{UnixDatagram, UnixStream}; use std::ptr::{copy_nonoverlapping, null_mut, write_unaligned}; -use libc::{c_void, c_long, iovec, msghdr, cmsghdr, sendmsg, recvmsg, SOL_SOCKET, SCM_RIGHTS, - MSG_NOSIGNAL}; +use libc::{ + c_long, c_void, cmsghdr, iovec, msghdr, recvmsg, sendmsg, MSG_NOSIGNAL, SCM_RIGHTS, SOL_SOCKET, +}; use data_model::VolatileSlice; -use {Result, Error}; +use {Error, Result}; // Each of the following macros performs the same function as their C counterparts. They are each // macros because they are used to size statically allocated arrays. macro_rules! CMSG_ALIGN { - ($len:expr) => ( + ($len:expr) => { (($len) + size_of::<c_long>() - 1) & !(size_of::<c_long>() - 1) - ) + }; } macro_rules! CMSG_SPACE { - ($len:expr) => ( + ($len:expr) => { size_of::<cmsghdr>() + CMSG_ALIGN!($len) - ) + }; } macro_rules! CMSG_LEN { - ($len:expr) => ( + ($len:expr) => { size_of::<cmsghdr>() + ($len) - ) + }; } - // This function (macro in the C version) is not used in any compile time constant slots, so is just // an ordinary function. The returned pointer is hard coded to be RawFd because that's all that this // module supports. @@ -55,15 +55,16 @@ fn CMSG_DATA(cmsg_buffer: *mut u8) -> *mut RawFd { fn get_next_cmsg(msghdr: &msghdr, cmsg: &cmsghdr, cmsg_ptr: *mut u8) -> *mut u8 { let next_cmsg = cmsg_ptr.wrapping_offset(CMSG_ALIGN!(cmsg.cmsg_len) as isize); if next_cmsg - .wrapping_offset(1) - .wrapping_sub(msghdr.msg_control as usize) as usize > msghdr.msg_controllen { + .wrapping_offset(1) + .wrapping_sub(msghdr.msg_control as usize) as usize + > msghdr.msg_controllen + { null_mut() } else { next_cmsg } } - const CMSG_BUFFER_INLINE_CAPACITY: usize = CMSG_SPACE!(size_of::<RawFd>() * 32); enum CmsgBuffer { @@ -118,9 +119,11 @@ fn raw_sendmsg<D: IntoIovec>(fd: RawFd, out_data: D, out_fds: &[RawFd]) -> Resul write_unaligned(cmsg_buffer.as_mut_ptr() as *mut cmsghdr, cmsg); // Safe because the cmsg_buffer was allocated to be large enough to hold out_fds.len() // file descriptors. - copy_nonoverlapping(out_fds.as_ptr(), - CMSG_DATA(cmsg_buffer.as_mut_ptr()), - out_fds.len()); + copy_nonoverlapping( + out_fds.as_ptr(), + CMSG_DATA(cmsg_buffer.as_mut_ptr()), + out_fds.len(), + ); } msg.msg_control = cmsg_buffer.as_mut_ptr() as *mut c_void; @@ -184,9 +187,11 @@ fn raw_recvmsg(fd: RawFd, in_data: &mut [u8], in_fds: &mut [RawFd]) -> Result<(u if cmsg.cmsg_level == SOL_SOCKET && cmsg.cmsg_type == SCM_RIGHTS { let fd_count = (cmsg.cmsg_len - CMSG_LEN!(0)) / size_of::<RawFd>(); unsafe { - copy_nonoverlapping(CMSG_DATA(cmsg_ptr), - in_fds[in_fds_count..(in_fds_count + fd_count)].as_mut_ptr(), - fd_count); + copy_nonoverlapping( + CMSG_DATA(cmsg_ptr), + in_fds[in_fds_count..(in_fds_count + fd_count)].as_mut_ptr(), + fd_count, + ); } in_fds_count += fd_count; } @@ -194,7 +199,6 @@ fn raw_recvmsg(fd: RawFd, in_data: &mut [u8], in_fds: &mut [RawFd]) -> Result<(u cmsg_ptr = get_next_cmsg(&msg, &cmsg, cmsg_ptr); } - Ok((total_read as usize, in_fds_count)) } @@ -246,10 +250,8 @@ pub trait ScmSocket { Some(unsafe { File::from_raw_fd(fd[0]) }) }; Ok((read_count, file)) - } - /// Receives data and file descriptors from the socket. /// /// On success, returns the number of bytes and file descriptors received as a tuple @@ -334,22 +336,36 @@ mod tests { #[test] fn buffer_len() { assert_eq!(CMSG_SPACE!(0 * size_of::<RawFd>()), size_of::<cmsghdr>()); - assert_eq!(CMSG_SPACE!(1 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>()); + assert_eq!( + CMSG_SPACE!(1 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() + ); if size_of::<RawFd>() == 4 { - assert_eq!(CMSG_SPACE!(2 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>()); - assert_eq!(CMSG_SPACE!(3 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>() * 2); - assert_eq!(CMSG_SPACE!(4 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>() * 2); + assert_eq!( + CMSG_SPACE!(2 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() + ); + assert_eq!( + CMSG_SPACE!(3 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() * 2 + ); + assert_eq!( + CMSG_SPACE!(4 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() * 2 + ); } else if size_of::<RawFd>() == 8 { - assert_eq!(CMSG_SPACE!(2 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>() * 2); - assert_eq!(CMSG_SPACE!(3 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>() * 3); - assert_eq!(CMSG_SPACE!(4 * size_of::<RawFd>()), - size_of::<cmsghdr>() + size_of::<c_long>() * 4); + assert_eq!( + CMSG_SPACE!(2 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() * 2 + ); + assert_eq!( + CMSG_SPACE!(3 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() * 3 + ); + assert_eq!( + CMSG_SPACE!(4 * size_of::<RawFd>()), + size_of::<cmsghdr>() + size_of::<c_long>() * 4 + ); } } @@ -357,14 +373,16 @@ mod tests { fn send_recv_no_fd() { let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair"); - let write_count = s1.send_with_fds([1u8, 1, 2, 21, 34, 55].as_ref(), &[]) + let write_count = s1 + .send_with_fds([1u8, 1, 2, 21, 34, 55].as_ref(), &[]) .expect("failed to send data"); assert_eq!(write_count, 6); let mut buf = [0; 6]; let mut files = [0; 1]; - let (read_count, file_count) = s2.recv_with_fds(&mut buf[..], &mut files) + let (read_count, file_count) = s2 + .recv_with_fds(&mut buf[..], &mut files) .expect("failed to recv data"); assert_eq!(read_count, 6); @@ -377,7 +395,8 @@ mod tests { let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair"); let evt = EventFd::new().expect("failed to create eventfd"); - let write_count = s1.send_with_fd([].as_ref(), evt.as_raw_fd()) + let write_count = s1 + .send_with_fd([].as_ref(), evt.as_raw_fd()) .expect("failed to send fd"); assert_eq!(write_count, 0); @@ -403,14 +422,16 @@ mod tests { let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair"); let evt = EventFd::new().expect("failed to create eventfd"); - let write_count = s1.send_with_fds([237].as_ref(), &[evt.as_raw_fd()]) + let write_count = s1 + .send_with_fds([237].as_ref(), &[evt.as_raw_fd()]) .expect("failed to send fd"); assert_eq!(write_count, 1); let mut files = [0; 2]; let mut buf = [0u8]; - let (read_count, file_count) = s2.recv_with_fds(&mut buf, &mut files) + let (read_count, file_count) = s2 + .recv_with_fds(&mut buf, &mut files) .expect("failed to recv fd"); assert_eq!(read_count, 1); diff --git a/sys_util/src/struct_util.rs b/sys_util/src/struct_util.rs index 05625b1..3d8def2 100644 --- a/sys_util/src/struct_util.rs +++ b/sys_util/src/struct_util.rs @@ -38,17 +38,19 @@ pub unsafe fn read_struct<T: Copy, F: Read>(f: &mut F, out: &mut T) -> Result<() pub unsafe fn read_struct_slice<T: Copy, F: Read>(f: &mut F, len: usize) -> Result<Vec<T>> { let mut out: Vec<T> = Vec::with_capacity(len); out.set_len(len); - let out_slice = std::slice::from_raw_parts_mut(out.as_ptr() as *mut T as *mut u8, - mem::size_of::<T>() * len); + let out_slice = std::slice::from_raw_parts_mut( + out.as_ptr() as *mut T as *mut u8, + mem::size_of::<T>() * len, + ); f.read_exact(out_slice).map_err(|_| Error::ReadStruct)?; Ok(out) } #[cfg(test)] mod test { + use super::*; use std::io::Cursor; use std::mem; - use super::*; #[derive(Clone, Copy, Debug, Default, PartialEq)] struct TestRead { @@ -70,8 +72,10 @@ mod test { }; let source = unsafe { // Don't worry it's a test - std::slice::from_raw_parts(&orig as *const _ as *const u8, - std::mem::size_of::<TestRead>()) + std::slice::from_raw_parts( + &orig as *const _ as *const u8, + std::mem::size_of::<TestRead>(), + ) }; assert_eq!(mem::size_of::<TestRead>(), mem::size_of_val(&source)); let mut tr: TestRead = Default::default(); @@ -92,8 +96,10 @@ mod test { }; let source = unsafe { // Don't worry it's a test - std::slice::from_raw_parts(&orig as *const _ as *const u8, - std::mem::size_of::<TestRead>() - 1) + std::slice::from_raw_parts( + &orig as *const _ as *const u8, + std::mem::size_of::<TestRead>() - 1, + ) }; let mut tr: TestRead = Default::default(); unsafe { @@ -103,31 +109,35 @@ mod test { #[test] fn struct_slice_read() { - let orig = vec![TestRead { - a: 0x7766554433221100, - b: 0x88, - c: 0x99, - d: 0xaa, - e: 0xbb, - }, - TestRead { - a: 0x7867564534231201, - b: 0x02, - c: 0x13, - d: 0x24, - e: 0x35, - }, - TestRead { - a: 0x7a69584736251403, - b: 0x04, - c: 0x15, - d: 0x26, - e: 0x37, - }]; + let orig = vec![ + TestRead { + a: 0x7766554433221100, + b: 0x88, + c: 0x99, + d: 0xaa, + e: 0xbb, + }, + TestRead { + a: 0x7867564534231201, + b: 0x02, + c: 0x13, + d: 0x24, + e: 0x35, + }, + TestRead { + a: 0x7a69584736251403, + b: 0x04, + c: 0x15, + d: 0x26, + e: 0x37, + }, + ]; let source = unsafe { // Don't worry it's a test - std::slice::from_raw_parts(orig.as_ptr() as *const u8, - std::mem::size_of::<TestRead>() * 3) + std::slice::from_raw_parts( + orig.as_ptr() as *const u8, + std::mem::size_of::<TestRead>() * 3, + ) }; let tr: Vec<TestRead> = unsafe { read_struct_slice(&mut Cursor::new(source), 3).unwrap() }; diff --git a/sys_util/src/syslog.rs b/sys_util/src/syslog.rs index 81aea6b..50f8393 100644 --- a/sys_util/src/syslog.rs +++ b/sys_util/src/syslog.rs @@ -28,8 +28,8 @@ use std::env; use std::ffi::{OsStr, OsString}; use std::fmt; use std::fs::File; -use std::io::{Write, Cursor, ErrorKind, stderr}; use std::io; +use std::io::{stderr, Cursor, ErrorKind, Write}; use std::mem; use std::os::unix::io::{AsRawFd, FromRawFd, RawFd}; use std::os::unix::net::UnixDatagram; @@ -38,8 +38,10 @@ use std::ptr::null; use std::str::from_utf8; use std::sync::{Mutex, MutexGuard, Once, ONCE_INIT}; -use libc::{tm, time, time_t, localtime_r, gethostname, openlog, closelog, fcntl, c_char, LOG_NDELAY, - LOG_PERROR, LOG_PID, LOG_USER, F_GETFD}; +use libc::{ + c_char, closelog, fcntl, gethostname, localtime_r, openlog, time, time_t, tm, F_GETFD, + LOG_NDELAY, LOG_PERROR, LOG_PID, LOG_USER, +}; use getpid; @@ -151,7 +153,9 @@ fn openlog_and_get_socket() -> Result<UnixDatagram, Error> { // closelog first in case there was already a file descriptor open. Safe because it takes no // arguments and just closes an open file descriptor. Does nothing if the file descriptor // was not already open. - unsafe { closelog(); } + unsafe { + closelog(); + } // Ordinarily libc's FD for the syslog connection can't be accessed, but we can guess that the // FD that openlog will be getting is the lowest unused FD. To guarantee that an FD is opened in @@ -189,12 +193,12 @@ impl State { fn new() -> Result<State, Error> { let s = openlog_and_get_socket()?; Ok(State { - stderr: true, - socket: Some(s), - file: None, - hostname: get_hostname().ok(), - proc_name: get_proc_name(), - }) + stderr: true, + socket: Some(s), + file: None, + hostname: get_hostname().ok(), + proc_name: get_proc_name(), + }) } } @@ -213,10 +217,10 @@ fn new_mutex_ptr<T>(inner: T) -> *const Mutex<T> { pub fn init() -> Result<(), Error> { let mut err = Error::Poisoned; STATE_ONCE.call_once(|| match State::new() { - // Safe because STATE mutation is guarded by `Once`. - Ok(state) => unsafe { STATE = new_mutex_ptr(state) }, - Err(e) => err = e, - }); + // Safe because STATE mutation is guarded by `Once`. + Ok(state) => unsafe { STATE = new_mutex_ptr(state) }, + Err(e) => err = e, + }); if unsafe { STATE.is_null() } { Err(err) @@ -238,12 +242,12 @@ fn lock() -> Result<MutexGuard<'static, State>, Error> { // Attempts to lock and retrieve the state. Returns from the function silently on failure. macro_rules! lock { - () => ( + () => { match lock() { Ok(s) => s, _ => return, }; - ) + }; } /// Replaces the hostname reported in each syslog message. @@ -294,7 +298,7 @@ pub fn echo_syslog(enable: bool) -> Result<(), Error> { let mut state = lock().map_err(|_| Error::Poisoned)?; match state.socket.take() { - Some(_) if enable => {}, + Some(_) if enable => {} Some(s) => { // Because `openlog_and_get_socket` actually just "borrows" the syslog FD, this module // does not own the syslog connection and therefore should not destroy it. @@ -355,20 +359,18 @@ fn send_buf(socket: &UnixDatagram, buf: &[u8]) { for _ in 0..SEND_RETRY { match socket.send(&buf[..]) { Ok(_) => break, - Err(e) => { - match e.kind() { - ErrorKind::ConnectionRefused | - ErrorKind::ConnectionReset | - ErrorKind::ConnectionAborted | - ErrorKind::NotConnected => { - let res = socket.connect(SYSLOG_PATH); - if res.is_err() { - break; - } + Err(e) => match e.kind() { + ErrorKind::ConnectionRefused + | ErrorKind::ConnectionReset + | ErrorKind::ConnectionAborted + | ErrorKind::NotConnected => { + let res = socket.connect(SYSLOG_PATH); + if res.is_err() { + break; } - _ => {} } - } + _ => {} + }, } } } @@ -415,8 +417,9 @@ fn get_localtime() -> tm { /// # } /// ``` pub fn log(pri: Priority, fac: Facility, file_name: &str, line: u32, args: fmt::Arguments) { - const MONTHS: [&'static str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", - "Sep", "Oct", "Nov", "Dec"]; + const MONTHS: [&'static str; 12] = [ + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", + ]; let mut state = lock!(); let mut buf = [0u8; 1024]; @@ -425,7 +428,9 @@ pub fn log(pri: Priority, fac: Facility, file_name: &str, line: u32, args: fmt:: let prifac = (pri as u8) | (fac as u8); let (res, len) = { let mut buf_cursor = Cursor::new(&mut buf[..]); - (write!(&mut buf_cursor, + ( + write!( + &mut buf_cursor, "<{}>{} {:02} {:02}:{:02}:{:02} {} {}[{}]: [{}:{}] {}", prifac, MONTHS[tm.tm_mon as usize], @@ -433,21 +438,15 @@ pub fn log(pri: Priority, fac: Facility, file_name: &str, line: u32, args: fmt:: tm.tm_hour, tm.tm_min, tm.tm_sec, - state - .hostname - .as_ref() - .map(|s| s.as_ref()) - .unwrap_or("-"), - state - .proc_name - .as_ref() - .map(|s| s.as_ref()) - .unwrap_or("-"), + state.hostname.as_ref().map(|s| s.as_ref()).unwrap_or("-"), + state.proc_name.as_ref().map(|s| s.as_ref()).unwrap_or("-"), getpid(), file_name, line, - args), - buf_cursor.position() as usize) + args + ), + buf_cursor.position() as usize, + ) }; if res.is_ok() { @@ -457,13 +456,14 @@ pub fn log(pri: Priority, fac: Facility, file_name: &str, line: u32, args: fmt:: let (res, len) = { let mut buf_cursor = Cursor::new(&mut buf[..]); - (write!(&mut buf_cursor, + ( + write!( + &mut buf_cursor, "[{}:{}:{}] {}\n", - pri, - file_name, - line, - args), - buf_cursor.position() as usize) + pri, file_name, line, args + ), + buf_cursor.position() as usize, + ) }; if res.is_ok() { if let Some(ref mut file) = state.file { @@ -521,11 +521,11 @@ macro_rules! debug { mod tests { use super::*; - use libc::{shm_unlink, shm_open, O_RDWR, O_CREAT, O_EXCL}; + use libc::{shm_open, shm_unlink, O_CREAT, O_EXCL, O_RDWR}; - use std::os::unix::io::FromRawFd; use std::ffi::CStr; use std::io::{Read, Seek, SeekFrom}; + use std::os::unix::io::FromRawFd; #[test] fn init_syslog() { @@ -540,34 +540,39 @@ mod tests { assert!(fds.len() >= 1); for fd in fds { assert!(fd >= 0); - } } #[test] fn syslog_log() { init().unwrap(); - log(Priority::Error, + log( + Priority::Error, Facility::User, file!(), line!(), - format_args!("hello syslog")); + format_args!("hello syslog"), + ); } #[test] fn proc_name() { init().unwrap(); - log(Priority::Error, + log( + Priority::Error, Facility::User, file!(), line!(), - format_args!("before proc name")); + format_args!("before proc name"), + ); set_proc_name("sys_util-test"); - log(Priority::Error, + log( + Priority::Error, Facility::User, file!(), line!(), - format_args!("after proc name")); + format_args!("after proc name"), + ); } #[test] @@ -581,16 +586,17 @@ mod tests { File::from_raw_fd(fd) }; - let syslog_file = file.try_clone() - .expect("error cloning shared memory file"); + let syslog_file = file.try_clone().expect("error cloning shared memory file"); echo_file(Some(syslog_file)); const TEST_STR: &'static str = "hello shared memory file"; - log(Priority::Error, + log( + Priority::Error, Facility::User, file!(), line!(), - format_args!("{}", TEST_STR)); + format_args!("{}", TEST_STR), + ); file.seek(SeekFrom::Start(0)) .expect("error seeking shared memory file"); diff --git a/sys_util/src/tempdir.rs b/sys_util/src/tempdir.rs index de36c69..28f61c3 100644 --- a/sys_util/src/tempdir.rs +++ b/sys_util/src/tempdir.rs @@ -12,7 +12,7 @@ use std::path::PathBuf; use libc; -use {Result, errno_result}; +use {errno_result, Result}; /// Create and remove a temporary directory. The directory will be maintained for the lifetime of /// the `TempDir` object. @@ -51,7 +51,9 @@ impl TempDir { return errno_result(); } dir_bytes.pop(); // Remove the null becasue from_vec can't handle it. - Ok(TempDir { path: Some(PathBuf::from(OsString::from_vec(dir_bytes))) }) + Ok(TempDir { + path: Some(PathBuf::from(OsString::from_vec(dir_bytes))), + }) } /// Removes the temporary directory. Calling this is optional as dropping a `TempDir` object diff --git a/sys_util/src/terminal.rs b/sys_util/src/terminal.rs index 211fb15..24cb170 100644 --- a/sys_util/src/terminal.rs +++ b/sys_util/src/terminal.rs @@ -2,14 +2,16 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::mem::zeroed; use std::io::StdinLock; +use std::mem::zeroed; use std::os::unix::io::RawFd; -use libc::{fcntl, tcgetattr, tcsetattr, isatty, read, c_int, termios, STDIN_FILENO, TCSANOW, - ICANON, ECHO, ISIG, O_NONBLOCK, F_GETFL, F_SETFL}; +use libc::{ + c_int, fcntl, isatty, read, tcgetattr, tcsetattr, termios, ECHO, F_GETFL, F_SETFL, ICANON, + ISIG, O_NONBLOCK, STDIN_FILENO, TCSANOW, +}; -use {Result, errno_result}; +use {errno_result, Result}; fn modify_mode<F: FnOnce(&mut termios)>(fd: RawFd, f: F) -> Result<()> { // Safe because we check the return value of isatty. @@ -44,7 +46,6 @@ fn get_flags(fd: RawFd) -> Result<c_int> { Ok(ret) } - fn set_flags(fd: RawFd, flags: c_int) -> Result<()> { // Safe because we supply the third parameter and we check the return result. let ret = unsafe { fcntl(fd, F_SETFL, flags) }; diff --git a/sys_util/src/timerfd.rs b/sys_util/src/timerfd.rs index 6effd22..5233ab3 100644 --- a/sys_util/src/timerfd.rs +++ b/sys_util/src/timerfd.rs @@ -8,9 +8,9 @@ use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::ptr; use std::time::Duration; -use libc::{self, CLOCK_MONOTONIC, TFD_CLOEXEC, timerfd_create, timerfd_gettime, timerfd_settime}; +use libc::{self, timerfd_create, timerfd_gettime, timerfd_settime, CLOCK_MONOTONIC, TFD_CLOEXEC}; -use {Result, errno_result}; +use {errno_result, Result}; /// A safe wrapper around a Linux timerfd (man 2 timerfd_create). pub struct TimerFd(File); @@ -26,7 +26,7 @@ impl TimerFd { } // Safe because we uniquely own the file descriptor. - Ok(TimerFd(unsafe { File::from_raw_fd(ret) } )) + Ok(TimerFd(unsafe { File::from_raw_fd(ret) })) } /// Sets the timer to expire after `dur`. If `interval` is not `None` it represents @@ -60,9 +60,11 @@ impl TimerFd { // Safe because this will only modify |buf| and we check the return value. let ret = unsafe { - libc::read(self.as_raw_fd(), - &mut count as *mut _ as *mut libc::c_void, - mem::size_of_val(&count)) + libc::read( + self.as_raw_fd(), + &mut count as *mut _ as *mut libc::c_void, + mem::size_of_val(&count), + ) }; if ret < 0 { return errno_result(); @@ -93,7 +95,7 @@ impl TimerFd { let spec: libc::itimerspec = unsafe { mem::zeroed() }; // Safe because this doesn't modify any memory and we check the return value. - let ret = unsafe { timerfd_settime(self.as_raw_fd(), 0, &spec, ptr::null_mut()) }; + let ret = unsafe { timerfd_settime(self.as_raw_fd(), 0, &spec, ptr::null_mut()) }; if ret < 0 { return errno_result(); } @@ -149,7 +151,8 @@ mod tests { let dur = Duration::from_millis(200); let interval = Duration::from_millis(100); - tfd.reset(dur.clone(), Some(interval)).expect("failed to arm timer"); + tfd.reset(dur.clone(), Some(interval)) + .expect("failed to arm timer"); sleep(dur * 3); diff --git a/sys_util/src/write_zeroes.rs b/sys_util/src/write_zeroes.rs index bc26254..31ea652 100644 --- a/sys_util/src/write_zeroes.rs +++ b/sys_util/src/write_zeroes.rs @@ -60,7 +60,8 @@ mod tests { .read(true) .write(true) .create(true) - .open(&path).unwrap(); + .open(&path) + .unwrap(); f.set_len(16384).unwrap(); // Write buffer of non-zero bytes to offset 1234 @@ -125,7 +126,8 @@ mod tests { .read(true) .write(true) .create(true) - .open(&path).unwrap(); + .open(&path) + .unwrap(); f.set_len(16384).unwrap(); // Write buffer of non-zero bytes diff --git a/syscall_defines/src/lib.rs b/syscall_defines/src/lib.rs index c1cbb51..cf016ab 100644 --- a/syscall_defines/src/lib.rs +++ b/syscall_defines/src/lib.rs @@ -2,18 +2,18 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#[cfg(target_arch="x86_64")] -#[path="linux-x86_64/mod.rs"] +#[cfg(target_arch = "x86_64")] +#[path = "linux-x86_64/mod.rs"] pub mod linux; -#[cfg(target_arch="x86")] -#[path="linux-x86/mod.rs"] +#[cfg(target_arch = "x86")] +#[path = "linux-x86/mod.rs"] pub mod linux; -#[cfg(target_arch="aarch64")] -#[path="linux-aarch64/mod.rs"] +#[cfg(target_arch = "aarch64")] +#[path = "linux-aarch64/mod.rs"] pub mod linux; -#[cfg(target_arch="arm")] -#[path="linux-arm/mod.rs"] -pub mod linux; \ No newline at end of file +#[cfg(target_arch = "arm")] +#[path = "linux-arm/mod.rs"] +pub mod linux; diff --git a/tests/plugins.rs b/tests/plugins.rs index 67e68e6..27bbc47 100644 --- a/tests/plugins.rs +++ b/tests/plugins.rs @@ -9,17 +9,17 @@ extern crate sys_util; use rand::{thread_rng, Rng}; -use std::ffi::OsString; -use std::fs::{File, remove_file}; -use std::io::{Write, Read}; use std::env::{current_exe, var_os}; +use std::ffi::OsString; +use std::fs::{remove_file, File}; +use std::io::{Read, Write}; +use std::os::unix::io::AsRawFd; use std::path::{Path, PathBuf}; use std::process::{Command, Stdio}; use std::thread::sleep; -use std::os::unix::io::AsRawFd; use std::time::Duration; -use sys_util::{SharedMemory, ioctl}; +use sys_util::{ioctl, SharedMemory}; struct RemovePath(PathBuf); impl Drop for RemovePath { @@ -34,32 +34,27 @@ fn get_target_path() -> PathBuf { current_exe() .ok() .map(|mut path| { - path.pop(); - path - }) - .expect("failed to get crosvm binary directory") + path.pop(); + path + }).expect("failed to get crosvm binary directory") } fn get_crosvm_path() -> PathBuf { current_exe() .ok() .map(|mut path| { - path.pop(); - if path.ends_with("deps") { - path.pop(); - } - path - }) - .expect("failed to get crosvm binary directory") + path.pop(); + if path.ends_with("deps") { + path.pop(); + } + path + }).expect("failed to get crosvm binary directory") } fn build_plugin(src: &str) -> RemovePath { let libcrosvm_plugin_dir = get_target_path(); let mut out_bin = libcrosvm_plugin_dir.clone(); - out_bin.push(thread_rng() - .gen_ascii_chars() - .take(10) - .collect::<String>()); + out_bin.push(thread_rng().gen_ascii_chars().take(10).collect::<String>()); let mut child = Command::new(var_os("CC").unwrap_or(OsString::from("cc"))) .args(&["-Icrosvm_plugin", "-pthread", "-o"]) // crosvm.h location and set output path. .arg(&out_bin) @@ -90,21 +85,24 @@ fn run_plugin(bin_path: &Path, with_sandbox: bool) { let mut crosvm_path = get_crosvm_path(); crosvm_path.push("crosvm"); let mut cmd = Command::new(crosvm_path); - cmd.args(&["run", - "-c", - "1", - "--host_ip", - "100.115.92.5", - "--netmask", - "255.255.255.252", - "--mac", - "de:21:e8:47:6b:6a", - "--seccomp-policy-dir", - "tests", - "--plugin"]) - .arg(bin_path - .canonicalize() - .expect("failed to canonicalize plugin path")); + cmd.args(&[ + "run", + "-c", + "1", + "--host_ip", + "100.115.92.5", + "--netmask", + "255.255.255.252", + "--mac", + "de:21:e8:47:6b:6a", + "--seccomp-policy-dir", + "tests", + "--plugin", + ]).arg( + bin_path + .canonicalize() + .expect("failed to canonicalize plugin path"), + ); if !with_sandbox { cmd.arg("--disable-sandbox"); } @@ -204,20 +202,23 @@ impl Default for MiniPlugin { fn test_mini_plugin(plugin: &MiniPlugin) { // Adds a preamble to ensure the output opcodes are 16-bit real mode and the lables start at the // load address. - let assembly_src = format!("org 0x{:x}\nbits 16\n{}", - plugin.load_address, - plugin.assembly_src); + let assembly_src = format!( + "org 0x{:x}\nbits 16\n{}", + plugin.load_address, plugin.assembly_src + ); // Builds the assembly and convert it to a C literal array format. let assembly = build_assembly(&assembly_src); let assembly_hex = format_as_hex(&assembly); // Glues the pieces of this plugin together and tests the completed plugin. - let generated_src = format!(include_str!("mini_plugin_template.c"), - mem_size = plugin.mem_size, - load_address = plugin.load_address, - assembly_code = assembly_hex, - src = plugin.src); + let generated_src = format!( + include_str!("mini_plugin_template.c"), + mem_size = plugin.mem_size, + load_address = plugin.load_address, + assembly_code = assembly_hex, + src = plugin.src + ); test_plugin(&generated_src); } diff --git a/vhost/src/lib.rs b/vhost/src/lib.rs index e0aefdb..96a3421 100644 --- a/vhost/src/lib.rs +++ b/vhost/src/lib.rs @@ -19,8 +19,8 @@ use std::mem; use std::os::unix::io::AsRawFd; use std::ptr::null; -use sys_util::{EventFd, GuestAddress, GuestMemory, GuestMemoryError}; use sys_util::{ioctl, ioctl_with_mut_ref, ioctl_with_ptr, ioctl_with_ref}; +use sys_util::{EventFd, GuestAddress, GuestMemory, GuestMemoryError}; #[derive(Debug)] pub enum Error { @@ -71,9 +71,7 @@ pub trait Vhost: AsRawFd + std::marker::Sized { // This ioctl is called on a valid vhost_net fd and has its // return value checked. let ret = unsafe { - ioctl_with_mut_ref(self, - virtio_sys::VHOST_GET_FEATURES(), - &mut avail_features) + ioctl_with_mut_ref(self, virtio_sys::VHOST_GET_FEATURES(), &mut avail_features) }; if ret < 0 { return ioctl_result(); @@ -89,8 +87,7 @@ pub trait Vhost: AsRawFd + std::marker::Sized { fn set_features(&self, features: u64) -> Result<()> { // This ioctl is called on a valid vhost_net fd and has its // return value checked. - let ret = - unsafe { ioctl_with_ref(self, virtio_sys::VHOST_SET_FEATURES(), &features) }; + let ret = unsafe { ioctl_with_ref(self, virtio_sys::VHOST_SET_FEATURES(), &features) }; if ret < 0 { return ioctl_result(); } @@ -100,8 +97,8 @@ pub trait Vhost: AsRawFd + std::marker::Sized { /// Set the guest memory mappings for vhost to use. fn set_mem_table(&self) -> Result<()> { let num_regions = self.mem().num_regions() as usize; - let vec_size_bytes = mem::size_of::<virtio_sys::vhost_memory>() + - (num_regions * mem::size_of::<virtio_sys::vhost_memory_region>()); + let vec_size_bytes = mem::size_of::<virtio_sys::vhost_memory>() + + (num_regions * mem::size_of::<virtio_sys::vhost_memory_region>()); let mut bytes: Vec<u8> = vec![0; vec_size_bytes]; // Convert bytes pointer to a vhost_memory mut ref. The vector has been // sized correctly to ensure it can hold vhost_memory and N regions. @@ -112,26 +109,23 @@ pub trait Vhost: AsRawFd + std::marker::Sized { // we correctly specify the size to match the amount of backing memory. let vhost_regions = unsafe { vhost_memory.regions.as_mut_slice(num_regions as usize) }; - let _ = self.mem() - .with_regions_mut::<_, ()>(|index, guest_addr, size, host_addr| { - vhost_regions[index] = virtio_sys::vhost_memory_region { - guest_phys_addr: guest_addr.offset() as u64, - memory_size: size as u64, - userspace_addr: host_addr as u64, - flags_padding: 0u64, - }; - Ok(()) - }); - + let _ = self + .mem() + .with_regions_mut::<_, ()>(|index, guest_addr, size, host_addr| { + vhost_regions[index] = virtio_sys::vhost_memory_region { + guest_phys_addr: guest_addr.offset() as u64, + memory_size: size as u64, + userspace_addr: host_addr as u64, + flags_padding: 0u64, + }; + Ok(()) + }); // This ioctl is called with a pointer that is valid for the lifetime // of this function. The kernel will make its own copy of the memory // tables. As always, check the return value. - let ret = unsafe { - ioctl_with_ptr(self, - virtio_sys::VHOST_SET_MEM_TABLE(), - bytes.as_ptr()) - }; + let ret = + unsafe { ioctl_with_ptr(self, virtio_sys::VHOST_SET_MEM_TABLE(), bytes.as_ptr()) }; if ret < 0 { return ioctl_result(); } @@ -151,11 +145,7 @@ pub trait Vhost: AsRawFd + std::marker::Sized { // This ioctl is called on a valid vhost_net fd and has its // return value checked. - let ret = unsafe { - ioctl_with_ref(self, - virtio_sys::VHOST_SET_VRING_NUM(), - &vring_state) - }; + let ret = unsafe { ioctl_with_ref(self, virtio_sys::VHOST_SET_VRING_NUM(), &vring_state) }; if ret < 0 { return ioctl_result(); } @@ -163,34 +153,37 @@ pub trait Vhost: AsRawFd + std::marker::Sized { } // TODO(smbarber): This is copypasta. Eliminate the copypasta. - fn is_valid(&self, - queue_max_size: u16, - queue_size: u16, - desc_addr: GuestAddress, - avail_addr: GuestAddress, - used_addr: GuestAddress) -> bool { + fn is_valid( + &self, + queue_max_size: u16, + queue_size: u16, + desc_addr: GuestAddress, + avail_addr: GuestAddress, + used_addr: GuestAddress, + ) -> bool { let desc_table_size = 16 * queue_size as usize; let avail_ring_size = 6 + 2 * queue_size as usize; let used_ring_size = 6 + 8 * queue_size as usize; - if queue_size > queue_max_size || queue_size == 0 || - (queue_size & (queue_size - 1)) != 0 { + if queue_size > queue_max_size || queue_size == 0 || (queue_size & (queue_size - 1)) != 0 { false } else if desc_addr - .checked_add(desc_table_size as u64) - .map_or(true, |v| !self.mem().address_in_range(v)) { + .checked_add(desc_table_size as u64) + .map_or(true, |v| !self.mem().address_in_range(v)) + { false } else if avail_addr - .checked_add(avail_ring_size as u64) - .map_or(true, |v| !self.mem().address_in_range(v)) { + .checked_add(avail_ring_size as u64) + .map_or(true, |v| !self.mem().address_in_range(v)) + { false } else if used_addr - .checked_add(used_ring_size as u64) - .map_or(true, |v| !self.mem().address_in_range(v)) { + .checked_add(used_ring_size as u64) + .map_or(true, |v| !self.mem().address_in_range(v)) + { false } else { true } - } /// Set the addresses for a given vring. @@ -204,43 +197,43 @@ pub trait Vhost: AsRawFd + std::marker::Sized { /// * `used_addr` - Used ring buffer address. /// * `avail_addr` - Available ring buffer address. /// * `log_addr` - Optional address for logging. - fn set_vring_addr(&self, - queue_max_size: u16, - queue_size: u16, - queue_index: usize, - flags: u32, - desc_addr: GuestAddress, - used_addr: GuestAddress, - avail_addr: GuestAddress, - log_addr: Option<GuestAddress>) - -> Result<()> { + fn set_vring_addr( + &self, + queue_max_size: u16, + queue_size: u16, + queue_index: usize, + flags: u32, + desc_addr: GuestAddress, + used_addr: GuestAddress, + avail_addr: GuestAddress, + log_addr: Option<GuestAddress>, + ) -> Result<()> { // TODO(smbarber): Refactor out virtio from crosvm so we can // validate a Queue struct directly. if !self.is_valid(queue_max_size, queue_size, desc_addr, used_addr, avail_addr) { return Err(Error::InvalidQueue); } - let desc_addr = self.mem() + let desc_addr = self + .mem() .get_host_address(desc_addr) .map_err(Error::DescriptorTableAddress)?; - let used_addr = self.mem() + let used_addr = self + .mem() .get_host_address(used_addr) .map_err(Error::UsedAddress)?; - let avail_addr = self.mem() + let avail_addr = self + .mem() .get_host_address(avail_addr) .map_err(Error::AvailAddress)?; let log_addr = match log_addr { None => null(), - Some(a) => { - self.mem() - .get_host_address(a) - .map_err(Error::LogAddress)? - }, + Some(a) => self.mem().get_host_address(a).map_err(Error::LogAddress)?, }; let vring_addr = virtio_sys::vhost_vring_addr { index: queue_index as u32, - flags: flags, + flags, desc_user_addr: desc_addr as u64, used_user_addr: used_addr as u64, avail_user_addr: avail_addr as u64, @@ -249,11 +242,7 @@ pub trait Vhost: AsRawFd + std::marker::Sized { // This ioctl is called on a valid vhost_net fd and has its // return value checked. - let ret = unsafe { - ioctl_with_ref(self, - virtio_sys::VHOST_SET_VRING_ADDR(), - &vring_addr) - }; + let ret = unsafe { ioctl_with_ref(self, virtio_sys::VHOST_SET_VRING_ADDR(), &vring_addr) }; if ret < 0 { return ioctl_result(); } @@ -273,11 +262,7 @@ pub trait Vhost: AsRawFd + std::marker::Sized { // This ioctl is called on a valid vhost_net fd and has its // return value checked. - let ret = unsafe { - ioctl_with_ref(self, - virtio_sys::VHOST_SET_VRING_BASE(), - &vring_state) - }; + let ret = unsafe { ioctl_with_ref(self, virtio_sys::VHOST_SET_VRING_BASE(), &vring_state) }; if ret < 0 { return ioctl_result(); } @@ -297,11 +282,7 @@ pub trait Vhost: AsRawFd + std::marker::Sized { // This ioctl is called on a valid vhost_net fd and has its // return value checked. - let ret = unsafe { - ioctl_with_ref(self, - virtio_sys::VHOST_SET_VRING_CALL(), - &vring_file) - }; + let ret = unsafe { ioctl_with_ref(self, virtio_sys::VHOST_SET_VRING_CALL(), &vring_file) }; if ret < 0 { return ioctl_result(); } @@ -410,7 +391,8 @@ mod tests { GuestAddress(0x0), GuestAddress(0x0), GuestAddress(0x0), - None); + None, + ); assert_ok_or_known_failure(res); } diff --git a/vhost/src/net.rs b/vhost/src/net.rs index 1d3f94e..0f1cd86 100644 --- a/vhost/src/net.rs +++ b/vhost/src/net.rs @@ -93,8 +93,8 @@ impl<T> AsRawFd for Net<T> { pub mod fakes { use super::*; - use std::fs::OpenOptions; use std::fs::remove_file; + use std::fs::OpenOptions; const TMP_FILE: &str = "/tmp/crosvm_vhost_test_file"; diff --git a/virtio_sys/src/lib.rs b/virtio_sys/src/lib.rs index 299bc44..8d6285c 100644 --- a/virtio_sys/src/lib.rs +++ b/virtio_sys/src/lib.rs @@ -38,8 +38,28 @@ ioctl_iow_nr!(VHOST_SET_VRING_ERR, VHOST, 0x22, vhost_vring_file); ioctl_iow_nr!(VHOST_NET_SET_BACKEND, VHOST, 0x30, vhost_vring_file); ioctl_iow_nr!(VHOST_SCSI_SET_ENDPOINT, VHOST, 0x40, vhost_scsi_target); ioctl_iow_nr!(VHOST_SCSI_CLEAR_ENDPOINT, VHOST, 0x41, vhost_scsi_target); -ioctl_iow_nr!(VHOST_SCSI_GET_ABI_VERSION, VHOST, 0x42, ::std::os::raw::c_int); -ioctl_iow_nr!(VHOST_SCSI_SET_EVENTS_MISSED, VHOST, 0x43, ::std::os::raw::c_uint); -ioctl_iow_nr!(VHOST_SCSI_GET_EVENTS_MISSED, VHOST, 0x44, ::std::os::raw::c_uint); -ioctl_iow_nr!(VHOST_VSOCK_SET_GUEST_CID, VHOST, 0x60, ::std::os::raw::c_ulonglong); +ioctl_iow_nr!( + VHOST_SCSI_GET_ABI_VERSION, + VHOST, + 0x42, + ::std::os::raw::c_int +); +ioctl_iow_nr!( + VHOST_SCSI_SET_EVENTS_MISSED, + VHOST, + 0x43, + ::std::os::raw::c_uint +); +ioctl_iow_nr!( + VHOST_SCSI_GET_EVENTS_MISSED, + VHOST, + 0x44, + ::std::os::raw::c_uint +); +ioctl_iow_nr!( + VHOST_VSOCK_SET_GUEST_CID, + VHOST, + 0x60, + ::std::os::raw::c_ulonglong +); ioctl_iow_nr!(VHOST_VSOCK_SET_RUNNING, VHOST, 0x61, ::std::os::raw::c_int); diff --git a/virtio_sys/src/vhost.rs b/virtio_sys/src/vhost.rs index d295660..397ca8c 100644 --- a/virtio_sys/src/vhost.rs +++ b/virtio_sys/src/vhost.rs @@ -3,13 +3,15 @@ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>); -impl <T> __IncompleteArrayField<T> { +impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData) } #[inline] - pub unsafe fn as_ptr(&self) -> *const T { ::std::mem::transmute(self) } + pub unsafe fn as_ptr(&self) -> *const T { + ::std::mem::transmute(self) + } #[inline] pub unsafe fn as_mut_ptr(&mut self) -> *mut T { ::std::mem::transmute(self) @@ -23,16 +25,18 @@ impl <T> __IncompleteArrayField<T> { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } -impl <T> ::std::fmt::Debug for __IncompleteArrayField<T> { +impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } -impl <T> ::std::clone::Clone for __IncompleteArrayField<T> { +impl<T> ::std::clone::Clone for __IncompleteArrayField<T> { #[inline] - fn clone(&self) -> Self { Self::new() } + fn clone(&self) -> Self { + Self::new() + } } -impl <T> ::std::marker::Copy for __IncompleteArrayField<T> { } +impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {} pub const __BITS_PER_LONG: ::std::os::raw::c_uint = 64; pub const __FD_SETSIZE: ::std::os::raw::c_uint = 1024; pub const _IOC_NRBITS: ::std::os::raw::c_uint = 8; @@ -167,18 +171,31 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>() , 128usize , concat ! - ( "Size of: " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (::std::mem::align_of::<__kernel_fd_set>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fd_set ) ) . fds_bits as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fd_set ) , - "::" , stringify ! ( fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_sighandler_t = ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int)>; @@ -209,18 +226,31 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (::std::mem::align_of::<__kernel_fsid_t>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fsid_t ) ) . val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fsid_t ) , - "::" , stringify ! ( val ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_off_t = __kernel_long_t; pub type __kernel_loff_t = ::std::os::raw::c_longlong; @@ -270,33 +300,61 @@ pub struct vring_desc { } #[test] fn bindgen_test_layout_vring_desc() { - assert_eq!(::std::mem::size_of::<vring_desc>() , 16usize , concat ! ( - "Size of: " , stringify ! ( vring_desc ) )); - assert_eq! (::std::mem::align_of::<vring_desc>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( vring_desc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . addr as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . len as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( len ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . flags as * const _ as - usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . next as * const _ as - usize } , 14usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( next ) )); + assert_eq!( + ::std::mem::size_of::<vring_desc>(), + 16usize, + concat!("Size of: ", stringify!(vring_desc)) + ); + assert_eq!( + ::std::mem::align_of::<vring_desc>(), + 8usize, + concat!("Alignment of ", stringify!(vring_desc)) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).addr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).len as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).flags as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).next as *const _ as usize }, + 14usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(next) + ) + ); } impl Clone for vring_desc { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -307,13 +365,21 @@ pub struct vring_avail { } #[test] fn bindgen_test_layout_vring_avail() { - assert_eq!(::std::mem::size_of::<vring_avail>() , 4usize , concat ! ( - "Size of: " , stringify ! ( vring_avail ) )); - assert_eq! (::std::mem::align_of::<vring_avail>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( vring_avail ) )); + assert_eq!( + ::std::mem::size_of::<vring_avail>(), + 4usize, + concat!("Size of: ", stringify!(vring_avail)) + ); + assert_eq!( + ::std::mem::align_of::<vring_avail>(), + 2usize, + concat!("Alignment of ", stringify!(vring_avail)) + ); } impl Clone for vring_avail { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -323,23 +389,41 @@ pub struct vring_used_elem { } #[test] fn bindgen_test_layout_vring_used_elem() { - assert_eq!(::std::mem::size_of::<vring_used_elem>() , 8usize , concat ! ( - "Size of: " , stringify ! ( vring_used_elem ) )); - assert_eq! (::std::mem::align_of::<vring_used_elem>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( vring_used_elem ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_used_elem ) ) . id as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_used_elem ) , - "::" , stringify ! ( id ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_used_elem ) ) . len as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_used_elem ) , - "::" , stringify ! ( len ) )); + assert_eq!( + ::std::mem::size_of::<vring_used_elem>(), + 8usize, + concat!("Size of: ", stringify!(vring_used_elem)) + ); + assert_eq!( + ::std::mem::align_of::<vring_used_elem>(), + 4usize, + concat!("Alignment of ", stringify!(vring_used_elem)) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_used_elem)).id as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vring_used_elem), + "::", + stringify!(id) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_used_elem)).len as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vring_used_elem), + "::", + stringify!(len) + ) + ); } impl Clone for vring_used_elem { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -351,13 +435,21 @@ pub struct vring_used { } #[test] fn bindgen_test_layout_vring_used() { - assert_eq!(::std::mem::size_of::<vring_used>() , 4usize , concat ! ( - "Size of: " , stringify ! ( vring_used ) )); - assert_eq! (::std::mem::align_of::<vring_used>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( vring_used ) )); + assert_eq!( + ::std::mem::size_of::<vring_used>(), + 4usize, + concat!("Size of: ", stringify!(vring_used)) + ); + assert_eq!( + ::std::mem::align_of::<vring_used>(), + 4usize, + concat!("Alignment of ", stringify!(vring_used)) + ); } impl Clone for vring_used { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -369,36 +461,66 @@ pub struct vring { } #[test] fn bindgen_test_layout_vring() { - assert_eq!(::std::mem::size_of::<vring>() , 32usize , concat ! ( - "Size of: " , stringify ! ( vring ) )); - assert_eq! (::std::mem::align_of::<vring>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( vring ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . num as * const _ as usize } , - 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( num ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . desc as * const _ as usize } - , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( desc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . avail as * const _ as usize } - , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( avail ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . used as * const _ as usize } - , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( used ) )); + assert_eq!( + ::std::mem::size_of::<vring>(), + 32usize, + concat!("Size of: ", stringify!(vring)) + ); + assert_eq!( + ::std::mem::align_of::<vring>(), + 8usize, + concat!("Alignment of ", stringify!(vring)) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).num as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(num) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).desc as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(desc) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).avail as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(avail) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).used as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(used) + ) + ); } impl Clone for vring { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } impl Default for vring { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -408,23 +530,41 @@ pub struct vhost_vring_state { } #[test] fn bindgen_test_layout_vhost_vring_state() { - assert_eq!(::std::mem::size_of::<vhost_vring_state>() , 8usize , concat ! - ( "Size of: " , stringify ! ( vhost_vring_state ) )); - assert_eq! (::std::mem::align_of::<vhost_vring_state>() , 4usize , concat - ! ( "Alignment of " , stringify ! ( vhost_vring_state ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_state ) ) . index as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_state ) , - "::" , stringify ! ( index ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_state ) ) . num as * const _ - as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_state ) , - "::" , stringify ! ( num ) )); + assert_eq!( + ::std::mem::size_of::<vhost_vring_state>(), + 8usize, + concat!("Size of: ", stringify!(vhost_vring_state)) + ); + assert_eq!( + ::std::mem::align_of::<vhost_vring_state>(), + 4usize, + concat!("Alignment of ", stringify!(vhost_vring_state)) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_state)).index as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_state), + "::", + stringify!(index) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_state)).num as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_state), + "::", + stringify!(num) + ) + ); } impl Clone for vhost_vring_state { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -434,23 +574,41 @@ pub struct vhost_vring_file { } #[test] fn bindgen_test_layout_vhost_vring_file() { - assert_eq!(::std::mem::size_of::<vhost_vring_file>() , 8usize , concat ! ( - "Size of: " , stringify ! ( vhost_vring_file ) )); - assert_eq! (::std::mem::align_of::<vhost_vring_file>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( vhost_vring_file ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_file ) ) . index as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_file ) , - "::" , stringify ! ( index ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_file ) ) . fd as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_file ) , - "::" , stringify ! ( fd ) )); + assert_eq!( + ::std::mem::size_of::<vhost_vring_file>(), + 8usize, + concat!("Size of: ", stringify!(vhost_vring_file)) + ); + assert_eq!( + ::std::mem::align_of::<vhost_vring_file>(), + 4usize, + concat!("Alignment of ", stringify!(vhost_vring_file)) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_file)).index as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_file), + "::", + stringify!(index) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_file)).fd as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_file), + "::", + stringify!(fd) + ) + ); } impl Clone for vhost_vring_file { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -464,43 +622,81 @@ pub struct vhost_vring_addr { } #[test] fn bindgen_test_layout_vhost_vring_addr() { - assert_eq!(::std::mem::size_of::<vhost_vring_addr>() , 40usize , concat ! - ( "Size of: " , stringify ! ( vhost_vring_addr ) )); - assert_eq! (::std::mem::align_of::<vhost_vring_addr>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( vhost_vring_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_addr ) ) . index as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_addr ) , - "::" , stringify ! ( index ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_addr ) ) . flags as * const _ - as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_addr ) , - "::" , stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_addr ) ) . desc_user_addr as - * const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_addr ) , - "::" , stringify ! ( desc_user_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_addr ) ) . used_user_addr as - * const _ as usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_addr ) , - "::" , stringify ! ( used_user_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_addr ) ) . avail_user_addr as - * const _ as usize } , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_addr ) , - "::" , stringify ! ( avail_user_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_vring_addr ) ) . log_guest_addr as - * const _ as usize } , 32usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_vring_addr ) , - "::" , stringify ! ( log_guest_addr ) )); + assert_eq!( + ::std::mem::size_of::<vhost_vring_addr>(), + 40usize, + concat!("Size of: ", stringify!(vhost_vring_addr)) + ); + assert_eq!( + ::std::mem::align_of::<vhost_vring_addr>(), + 8usize, + concat!("Alignment of ", stringify!(vhost_vring_addr)) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_addr)).index as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_addr), + "::", + stringify!(index) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_addr)).flags as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_addr), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_addr)).desc_user_addr as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_addr), + "::", + stringify!(desc_user_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_addr)).used_user_addr as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_addr), + "::", + stringify!(used_user_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_addr)).avail_user_addr as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_addr), + "::", + stringify!(avail_user_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_vring_addr)).log_guest_addr as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(vhost_vring_addr), + "::", + stringify!(log_guest_addr) + ) + ); } impl Clone for vhost_vring_addr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -512,34 +708,61 @@ pub struct vhost_memory_region { } #[test] fn bindgen_test_layout_vhost_memory_region() { - assert_eq!(::std::mem::size_of::<vhost_memory_region>() , 32usize , concat - ! ( "Size of: " , stringify ! ( vhost_memory_region ) )); - assert_eq! (::std::mem::align_of::<vhost_memory_region>() , 8usize , - concat ! ( - "Alignment of " , stringify ! ( vhost_memory_region ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory_region ) ) . guest_phys_addr - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory_region ) , - "::" , stringify ! ( guest_phys_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory_region ) ) . memory_size as - * const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory_region ) , - "::" , stringify ! ( memory_size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory_region ) ) . userspace_addr - as * const _ as usize } , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory_region ) , - "::" , stringify ! ( userspace_addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory_region ) ) . flags_padding - as * const _ as usize } , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory_region ) , - "::" , stringify ! ( flags_padding ) )); + assert_eq!( + ::std::mem::size_of::<vhost_memory_region>(), + 32usize, + concat!("Size of: ", stringify!(vhost_memory_region)) + ); + assert_eq!( + ::std::mem::align_of::<vhost_memory_region>(), + 8usize, + concat!("Alignment of ", stringify!(vhost_memory_region)) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory_region)).guest_phys_addr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory_region), + "::", + stringify!(guest_phys_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory_region)).memory_size as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory_region), + "::", + stringify!(memory_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory_region)).userspace_addr as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory_region), + "::", + stringify!(userspace_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory_region)).flags_padding as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory_region), + "::", + stringify!(flags_padding) + ) + ); } impl Clone for vhost_memory_region { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Default, Copy)] @@ -551,28 +774,51 @@ pub struct vhost_memory { } #[test] fn bindgen_test_layout_vhost_memory() { - assert_eq!(::std::mem::size_of::<vhost_memory>() , 8usize , concat ! ( - "Size of: " , stringify ! ( vhost_memory ) )); - assert_eq! (::std::mem::align_of::<vhost_memory>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( vhost_memory ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory ) ) . nregions as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory ) , "::" , - stringify ! ( nregions ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory ) ) . padding as * const _ - as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory ) , "::" , - stringify ! ( padding ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_memory ) ) . regions as * const _ - as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_memory ) , "::" , - stringify ! ( regions ) )); + assert_eq!( + ::std::mem::size_of::<vhost_memory>(), + 8usize, + concat!("Size of: ", stringify!(vhost_memory)) + ); + assert_eq!( + ::std::mem::align_of::<vhost_memory>(), + 8usize, + concat!("Alignment of ", stringify!(vhost_memory)) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory)).nregions as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory), + "::", + stringify!(nregions) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory)).padding as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory), + "::", + stringify!(padding) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_memory)).regions as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vhost_memory), + "::", + stringify!(regions) + ) + ); } impl Clone for vhost_memory { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] pub struct vhost_scsi_target { @@ -583,31 +829,59 @@ pub struct vhost_scsi_target { } #[test] fn bindgen_test_layout_vhost_scsi_target() { - assert_eq!(::std::mem::size_of::<vhost_scsi_target>() , 232usize , concat - ! ( "Size of: " , stringify ! ( vhost_scsi_target ) )); - assert_eq! (::std::mem::align_of::<vhost_scsi_target>() , 4usize , concat - ! ( "Alignment of " , stringify ! ( vhost_scsi_target ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_scsi_target ) ) . abi_version as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_scsi_target ) , - "::" , stringify ! ( abi_version ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_scsi_target ) ) . vhost_wwpn as * - const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_scsi_target ) , - "::" , stringify ! ( vhost_wwpn ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_scsi_target ) ) . vhost_tpgt as * - const _ as usize } , 228usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_scsi_target ) , - "::" , stringify ! ( vhost_tpgt ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vhost_scsi_target ) ) . reserved as * - const _ as usize } , 230usize , concat ! ( - "Alignment of field: " , stringify ! ( vhost_scsi_target ) , - "::" , stringify ! ( reserved ) )); + assert_eq!( + ::std::mem::size_of::<vhost_scsi_target>(), + 232usize, + concat!("Size of: ", stringify!(vhost_scsi_target)) + ); + assert_eq!( + ::std::mem::align_of::<vhost_scsi_target>(), + 4usize, + concat!("Alignment of ", stringify!(vhost_scsi_target)) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_scsi_target)).abi_version as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vhost_scsi_target), + "::", + stringify!(abi_version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_scsi_target)).vhost_wwpn as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vhost_scsi_target), + "::", + stringify!(vhost_wwpn) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_scsi_target)).vhost_tpgt as *const _ as usize }, + 228usize, + concat!( + "Alignment of field: ", + stringify!(vhost_scsi_target), + "::", + stringify!(vhost_tpgt) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vhost_scsi_target)).reserved as *const _ as usize }, + 230usize, + concat!( + "Alignment of field: ", + stringify!(vhost_scsi_target), + "::", + stringify!(reserved) + ) + ); } impl Default for vhost_scsi_target { - fn default() -> Self { unsafe { ::std::mem::zeroed() } } + fn default() -> Self { + unsafe { ::std::mem::zeroed() } + } } diff --git a/virtio_sys/src/virtio_net.rs b/virtio_sys/src/virtio_net.rs index a8ff84a..e626e24 100644 --- a/virtio_sys/src/virtio_net.rs +++ b/virtio_sys/src/virtio_net.rs @@ -3,13 +3,15 @@ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>); -impl <T> __IncompleteArrayField<T> { +impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData) } #[inline] - pub unsafe fn as_ptr(&self) -> *const T { ::std::mem::transmute(self) } + pub unsafe fn as_ptr(&self) -> *const T { + ::std::mem::transmute(self) + } #[inline] pub unsafe fn as_mut_ptr(&mut self) -> *mut T { ::std::mem::transmute(self) @@ -23,16 +25,18 @@ impl <T> __IncompleteArrayField<T> { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } -impl <T> ::std::fmt::Debug for __IncompleteArrayField<T> { +impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } -impl <T> ::std::clone::Clone for __IncompleteArrayField<T> { +impl<T> ::std::clone::Clone for __IncompleteArrayField<T> { #[inline] - fn clone(&self) -> Self { Self::new() } + fn clone(&self) -> Self { + Self::new() + } } -impl <T> ::std::marker::Copy for __IncompleteArrayField<T> { } +impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {} pub const __BITS_PER_LONG: ::std::os::raw::c_uint = 64; pub const __FD_SETSIZE: ::std::os::raw::c_uint = 1024; pub const VIRTIO_ID_NET: ::std::os::raw::c_uint = 1; @@ -214,18 +218,31 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>() , 128usize , concat ! - ( "Size of: " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (::std::mem::align_of::<__kernel_fd_set>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fd_set ) ) . fds_bits as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fd_set ) , - "::" , stringify ! ( fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_sighandler_t = ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int)>; @@ -256,18 +273,31 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (::std::mem::align_of::<__kernel_fsid_t>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fsid_t ) ) . val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fsid_t ) , - "::" , stringify ! ( val ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_off_t = __kernel_long_t; pub type __kernel_loff_t = ::std::os::raw::c_longlong; @@ -298,28 +328,51 @@ pub struct ethhdr { } #[test] fn bindgen_test_layout_ethhdr() { - assert_eq!(::std::mem::size_of::<ethhdr>() , 14usize , concat ! ( - "Size of: " , stringify ! ( ethhdr ) )); - assert_eq! (::std::mem::align_of::<ethhdr>() , 1usize , concat ! ( - "Alignment of " , stringify ! ( ethhdr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ethhdr ) ) . h_dest as * const _ as usize - } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( ethhdr ) , "::" , - stringify ! ( h_dest ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ethhdr ) ) . h_source as * const _ as - usize } , 6usize , concat ! ( - "Alignment of field: " , stringify ! ( ethhdr ) , "::" , - stringify ! ( h_source ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const ethhdr ) ) . h_proto as * const _ as - usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( ethhdr ) , "::" , - stringify ! ( h_proto ) )); + assert_eq!( + ::std::mem::size_of::<ethhdr>(), + 14usize, + concat!("Size of: ", stringify!(ethhdr)) + ); + assert_eq!( + ::std::mem::align_of::<ethhdr>(), + 1usize, + concat!("Alignment of ", stringify!(ethhdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const ethhdr)).h_dest as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ethhdr), + "::", + stringify!(h_dest) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ethhdr)).h_source as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(ethhdr), + "::", + stringify!(h_source) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ethhdr)).h_proto as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(ethhdr), + "::", + stringify!(h_proto) + ) + ); } impl Clone for ethhdr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C, packed)] #[derive(Debug, Copy)] @@ -331,34 +384,61 @@ pub struct virtio_net_config { } #[test] fn bindgen_test_layout_virtio_net_config() { - assert_eq!(::std::mem::size_of::<virtio_net_config>() , 12usize , concat ! - ( "Size of: " , stringify ! ( virtio_net_config ) )); - assert_eq! (::std::mem::align_of::<virtio_net_config>() , 1usize , concat - ! ( "Alignment of " , stringify ! ( virtio_net_config ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_config ) ) . mac as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_config ) , - "::" , stringify ! ( mac ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_config ) ) . status as * const - _ as usize } , 6usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_config ) , - "::" , stringify ! ( status ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_config ) ) . - max_virtqueue_pairs as * const _ as usize } , 8usize , concat - ! ( - "Alignment of field: " , stringify ! ( virtio_net_config ) , - "::" , stringify ! ( max_virtqueue_pairs ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_config ) ) . mtu as * const _ - as usize } , 10usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_config ) , - "::" , stringify ! ( mtu ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_config>(), + 12usize, + concat!("Size of: ", stringify!(virtio_net_config)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_config>(), + 1usize, + concat!("Alignment of ", stringify!(virtio_net_config)) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_config)).mac as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_config), + "::", + stringify!(mac) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_config)).status as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_config), + "::", + stringify!(status) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_config)).max_virtqueue_pairs as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_config), + "::", + stringify!(max_virtqueue_pairs) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_config)).mtu as *const _ as usize }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_config), + "::", + stringify!(mtu) + ) + ); } impl Clone for virtio_net_config { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -373,48 +453,91 @@ pub struct virtio_net_hdr_v1 { } #[test] fn bindgen_test_layout_virtio_net_hdr_v1() { - assert_eq!(::std::mem::size_of::<virtio_net_hdr_v1>() , 12usize , concat ! - ( "Size of: " , stringify ! ( virtio_net_hdr_v1 ) )); - assert_eq! (::std::mem::align_of::<virtio_net_hdr_v1>() , 2usize , concat - ! ( "Alignment of " , stringify ! ( virtio_net_hdr_v1 ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . flags as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . gso_type as * - const _ as usize } , 1usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( gso_type ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . hdr_len as * - const _ as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( hdr_len ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . gso_size as * - const _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( gso_size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . csum_start as * - const _ as usize } , 6usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( csum_start ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . csum_offset as * - const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( csum_offset ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_v1 ) ) . num_buffers as * - const _ as usize } , 10usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr_v1 ) , - "::" , stringify ! ( num_buffers ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_hdr_v1>(), + 12usize, + concat!("Size of: ", stringify!(virtio_net_hdr_v1)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_hdr_v1>(), + 2usize, + concat!("Alignment of ", stringify!(virtio_net_hdr_v1)) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).flags as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).gso_type as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(gso_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).hdr_len as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(hdr_len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).gso_size as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(gso_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).csum_start as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(csum_start) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).csum_offset as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(csum_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_v1)).num_buffers as *const _ as usize }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_v1), + "::", + stringify!(num_buffers) + ) + ); } impl Clone for virtio_net_hdr_v1 { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -428,43 +551,81 @@ pub struct virtio_net_hdr { } #[test] fn bindgen_test_layout_virtio_net_hdr() { - assert_eq!(::std::mem::size_of::<virtio_net_hdr>() , 10usize , concat ! ( - "Size of: " , stringify ! ( virtio_net_hdr ) )); - assert_eq! (::std::mem::align_of::<virtio_net_hdr>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( virtio_net_hdr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr ) ) . flags as * const _ - as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr ) , "::" - , stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr ) ) . gso_type as * const - _ as usize } , 1usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr ) , "::" - , stringify ! ( gso_type ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr ) ) . hdr_len as * const _ - as usize } , 2usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr ) , "::" - , stringify ! ( hdr_len ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr ) ) . gso_size as * const - _ as usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr ) , "::" - , stringify ! ( gso_size ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr ) ) . csum_start as * - const _ as usize } , 6usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr ) , "::" - , stringify ! ( csum_start ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr ) ) . csum_offset as * - const _ as usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_hdr ) , "::" - , stringify ! ( csum_offset ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_hdr>(), + 10usize, + concat!("Size of: ", stringify!(virtio_net_hdr)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_hdr>(), + 2usize, + concat!("Alignment of ", stringify!(virtio_net_hdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr)).flags as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr)).gso_type as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr), + "::", + stringify!(gso_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr)).hdr_len as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr), + "::", + stringify!(hdr_len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr)).gso_size as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr), + "::", + stringify!(gso_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr)).csum_start as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr), + "::", + stringify!(csum_start) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr)).csum_offset as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr), + "::", + stringify!(csum_offset) + ) + ); } impl Clone for virtio_net_hdr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -474,26 +635,41 @@ pub struct virtio_net_hdr_mrg_rxbuf { } #[test] fn bindgen_test_layout_virtio_net_hdr_mrg_rxbuf() { - assert_eq!(::std::mem::size_of::<virtio_net_hdr_mrg_rxbuf>() , 12usize , - concat ! ( - "Size of: " , stringify ! ( virtio_net_hdr_mrg_rxbuf ) )); - assert_eq! (::std::mem::align_of::<virtio_net_hdr_mrg_rxbuf>() , 2usize , - concat ! ( - "Alignment of " , stringify ! ( virtio_net_hdr_mrg_rxbuf ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_mrg_rxbuf ) ) . hdr as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( - virtio_net_hdr_mrg_rxbuf ) , "::" , stringify ! ( hdr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_hdr_mrg_rxbuf ) ) . - num_buffers as * const _ as usize } , 10usize , concat ! ( - "Alignment of field: " , stringify ! ( - virtio_net_hdr_mrg_rxbuf ) , "::" , stringify ! ( num_buffers - ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_hdr_mrg_rxbuf>(), + 12usize, + concat!("Size of: ", stringify!(virtio_net_hdr_mrg_rxbuf)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_hdr_mrg_rxbuf>(), + 2usize, + concat!("Alignment of ", stringify!(virtio_net_hdr_mrg_rxbuf)) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_mrg_rxbuf)).hdr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_mrg_rxbuf), + "::", + stringify!(hdr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_hdr_mrg_rxbuf)).num_buffers as *const _ as usize }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_hdr_mrg_rxbuf), + "::", + stringify!(num_buffers) + ) + ); } impl Clone for virtio_net_hdr_mrg_rxbuf { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C, packed)] #[derive(Debug, Copy)] @@ -503,24 +679,41 @@ pub struct virtio_net_ctrl_hdr { } #[test] fn bindgen_test_layout_virtio_net_ctrl_hdr() { - assert_eq!(::std::mem::size_of::<virtio_net_ctrl_hdr>() , 2usize , concat - ! ( "Size of: " , stringify ! ( virtio_net_ctrl_hdr ) )); - assert_eq! (::std::mem::align_of::<virtio_net_ctrl_hdr>() , 1usize , - concat ! ( - "Alignment of " , stringify ! ( virtio_net_ctrl_hdr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_ctrl_hdr ) ) . class as * - const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_ctrl_hdr ) , - "::" , stringify ! ( class ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_ctrl_hdr ) ) . cmd as * const - _ as usize } , 1usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_ctrl_hdr ) , - "::" , stringify ! ( cmd ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_ctrl_hdr>(), + 2usize, + concat!("Size of: ", stringify!(virtio_net_ctrl_hdr)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_ctrl_hdr>(), + 1usize, + concat!("Alignment of ", stringify!(virtio_net_ctrl_hdr)) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_ctrl_hdr)).class as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_ctrl_hdr), + "::", + stringify!(class) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_ctrl_hdr)).cmd as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_ctrl_hdr), + "::", + stringify!(cmd) + ) + ); } impl Clone for virtio_net_ctrl_hdr { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type virtio_net_ctrl_ack = __u8; #[repr(C, packed)] @@ -531,14 +724,21 @@ pub struct virtio_net_ctrl_mac { } #[test] fn bindgen_test_layout_virtio_net_ctrl_mac() { - assert_eq!(::std::mem::size_of::<virtio_net_ctrl_mac>() , 4usize , concat - ! ( "Size of: " , stringify ! ( virtio_net_ctrl_mac ) )); - assert_eq! (::std::mem::align_of::<virtio_net_ctrl_mac>() , 1usize , - concat ! ( - "Alignment of " , stringify ! ( virtio_net_ctrl_mac ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_ctrl_mac>(), + 4usize, + concat!("Size of: ", stringify!(virtio_net_ctrl_mac)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_ctrl_mac>(), + 1usize, + concat!("Alignment of ", stringify!(virtio_net_ctrl_mac)) + ); } impl Clone for virtio_net_ctrl_mac { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -547,16 +747,29 @@ pub struct virtio_net_ctrl_mq { } #[test] fn bindgen_test_layout_virtio_net_ctrl_mq() { - assert_eq!(::std::mem::size_of::<virtio_net_ctrl_mq>() , 2usize , concat ! - ( "Size of: " , stringify ! ( virtio_net_ctrl_mq ) )); - assert_eq! (::std::mem::align_of::<virtio_net_ctrl_mq>() , 2usize , concat - ! ( "Alignment of " , stringify ! ( virtio_net_ctrl_mq ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const virtio_net_ctrl_mq ) ) . virtqueue_pairs - as * const _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( virtio_net_ctrl_mq ) , - "::" , stringify ! ( virtqueue_pairs ) )); + assert_eq!( + ::std::mem::size_of::<virtio_net_ctrl_mq>(), + 2usize, + concat!("Size of: ", stringify!(virtio_net_ctrl_mq)) + ); + assert_eq!( + ::std::mem::align_of::<virtio_net_ctrl_mq>(), + 2usize, + concat!("Alignment of ", stringify!(virtio_net_ctrl_mq)) + ); + assert_eq!( + unsafe { &(*(0 as *const virtio_net_ctrl_mq)).virtqueue_pairs as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(virtio_net_ctrl_mq), + "::", + stringify!(virtqueue_pairs) + ) + ); } impl Clone for virtio_net_ctrl_mq { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } diff --git a/virtio_sys/src/virtio_ring.rs b/virtio_sys/src/virtio_ring.rs index 7524b98..b8a4842 100644 --- a/virtio_sys/src/virtio_ring.rs +++ b/virtio_sys/src/virtio_ring.rs @@ -3,13 +3,15 @@ #[repr(C)] #[derive(Default)] pub struct __IncompleteArrayField<T>(::std::marker::PhantomData<T>); -impl <T> __IncompleteArrayField<T> { +impl<T> __IncompleteArrayField<T> { #[inline] pub fn new() -> Self { __IncompleteArrayField(::std::marker::PhantomData) } #[inline] - pub unsafe fn as_ptr(&self) -> *const T { ::std::mem::transmute(self) } + pub unsafe fn as_ptr(&self) -> *const T { + ::std::mem::transmute(self) + } #[inline] pub unsafe fn as_mut_ptr(&mut self) -> *mut T { ::std::mem::transmute(self) @@ -23,16 +25,18 @@ impl <T> __IncompleteArrayField<T> { ::std::slice::from_raw_parts_mut(self.as_mut_ptr(), len) } } -impl <T> ::std::fmt::Debug for __IncompleteArrayField<T> { +impl<T> ::std::fmt::Debug for __IncompleteArrayField<T> { fn fmt(&self, fmt: &mut ::std::fmt::Formatter) -> ::std::fmt::Result { fmt.write_str("__IncompleteArrayField") } } -impl <T> ::std::clone::Clone for __IncompleteArrayField<T> { +impl<T> ::std::clone::Clone for __IncompleteArrayField<T> { #[inline] - fn clone(&self) -> Self { Self::new() } + fn clone(&self) -> Self { + Self::new() + } } -impl <T> ::std::marker::Copy for __IncompleteArrayField<T> { } +impl<T> ::std::marker::Copy for __IncompleteArrayField<T> {} pub const _STDINT_H: ::std::os::raw::c_uint = 1; pub const _FEATURES_H: ::std::os::raw::c_uint = 1; pub const _DEFAULT_SOURCE: ::std::os::raw::c_uint = 1; @@ -147,18 +151,31 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>() , 128usize , concat ! - ( "Size of: " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (::std::mem::align_of::<__kernel_fd_set>() , 8usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fd_set ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fd_set ) ) . fds_bits as * const - _ as usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fd_set ) , - "::" , stringify ! ( fds_bits ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_sighandler_t = ::std::option::Option<unsafe extern "C" fn(arg1: ::std::os::raw::c_int)>; @@ -189,18 +206,31 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>() , 8usize , concat ! ( - "Size of: " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (::std::mem::align_of::<__kernel_fsid_t>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( __kernel_fsid_t ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const __kernel_fsid_t ) ) . val as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( __kernel_fsid_t ) , - "::" , stringify ! ( val ) )); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } pub type __kernel_off_t = __kernel_long_t; pub type __kernel_loff_t = ::std::os::raw::c_longlong; @@ -232,33 +262,61 @@ pub struct vring_desc { } #[test] fn bindgen_test_layout_vring_desc() { - assert_eq!(::std::mem::size_of::<vring_desc>() , 16usize , concat ! ( - "Size of: " , stringify ! ( vring_desc ) )); - assert_eq! (::std::mem::align_of::<vring_desc>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( vring_desc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . addr as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( addr ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . len as * const _ as - usize } , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( len ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . flags as * const _ as - usize } , 12usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( flags ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_desc ) ) . next as * const _ as - usize } , 14usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_desc ) , "::" , - stringify ! ( next ) )); + assert_eq!( + ::std::mem::size_of::<vring_desc>(), + 16usize, + concat!("Size of: ", stringify!(vring_desc)) + ); + assert_eq!( + ::std::mem::align_of::<vring_desc>(), + 8usize, + concat!("Alignment of ", stringify!(vring_desc)) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).addr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).len as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).flags as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_desc)).next as *const _ as usize }, + 14usize, + concat!( + "Alignment of field: ", + stringify!(vring_desc), + "::", + stringify!(next) + ) + ); } impl Clone for vring_desc { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -269,13 +327,21 @@ pub struct vring_avail { } #[test] fn bindgen_test_layout_vring_avail() { - assert_eq!(::std::mem::size_of::<vring_avail>() , 4usize , concat ! ( - "Size of: " , stringify ! ( vring_avail ) )); - assert_eq! (::std::mem::align_of::<vring_avail>() , 2usize , concat ! ( - "Alignment of " , stringify ! ( vring_avail ) )); + assert_eq!( + ::std::mem::size_of::<vring_avail>(), + 4usize, + concat!("Size of: ", stringify!(vring_avail)) + ); + assert_eq!( + ::std::mem::align_of::<vring_avail>(), + 2usize, + concat!("Alignment of ", stringify!(vring_avail)) + ); } impl Clone for vring_avail { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -285,23 +351,41 @@ pub struct vring_used_elem { } #[test] fn bindgen_test_layout_vring_used_elem() { - assert_eq!(::std::mem::size_of::<vring_used_elem>() , 8usize , concat ! ( - "Size of: " , stringify ! ( vring_used_elem ) )); - assert_eq! (::std::mem::align_of::<vring_used_elem>() , 4usize , concat ! - ( "Alignment of " , stringify ! ( vring_used_elem ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_used_elem ) ) . id as * const _ as - usize } , 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_used_elem ) , - "::" , stringify ! ( id ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring_used_elem ) ) . len as * const _ as - usize } , 4usize , concat ! ( - "Alignment of field: " , stringify ! ( vring_used_elem ) , - "::" , stringify ! ( len ) )); + assert_eq!( + ::std::mem::size_of::<vring_used_elem>(), + 8usize, + concat!("Size of: ", stringify!(vring_used_elem)) + ); + assert_eq!( + ::std::mem::align_of::<vring_used_elem>(), + 4usize, + concat!("Alignment of ", stringify!(vring_used_elem)) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_used_elem)).id as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vring_used_elem), + "::", + stringify!(id) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring_used_elem)).len as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(vring_used_elem), + "::", + stringify!(len) + ) + ); } impl Clone for vring_used_elem { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -313,13 +397,21 @@ pub struct vring_used { } #[test] fn bindgen_test_layout_vring_used() { - assert_eq!(::std::mem::size_of::<vring_used>() , 4usize , concat ! ( - "Size of: " , stringify ! ( vring_used ) )); - assert_eq! (::std::mem::align_of::<vring_used>() , 4usize , concat ! ( - "Alignment of " , stringify ! ( vring_used ) )); + assert_eq!( + ::std::mem::size_of::<vring_used>(), + 4usize, + concat!("Size of: ", stringify!(vring_used)) + ); + assert_eq!( + ::std::mem::align_of::<vring_used>(), + 4usize, + concat!("Alignment of ", stringify!(vring_used)) + ); } impl Clone for vring_used { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } #[repr(C)] #[derive(Debug, Copy)] @@ -331,31 +423,59 @@ pub struct vring { } #[test] fn bindgen_test_layout_vring() { - assert_eq!(::std::mem::size_of::<vring>() , 32usize , concat ! ( - "Size of: " , stringify ! ( vring ) )); - assert_eq! (::std::mem::align_of::<vring>() , 8usize , concat ! ( - "Alignment of " , stringify ! ( vring ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . num as * const _ as usize } , - 0usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( num ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . desc as * const _ as usize } - , 8usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( desc ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . avail as * const _ as usize } - , 16usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( avail ) )); - assert_eq! (unsafe { - & ( * ( 0 as * const vring ) ) . used as * const _ as usize } - , 24usize , concat ! ( - "Alignment of field: " , stringify ! ( vring ) , "::" , - stringify ! ( used ) )); + assert_eq!( + ::std::mem::size_of::<vring>(), + 32usize, + concat!("Size of: ", stringify!(vring)) + ); + assert_eq!( + ::std::mem::align_of::<vring>(), + 8usize, + concat!("Alignment of ", stringify!(vring)) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).num as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(num) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).desc as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(desc) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).avail as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(avail) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const vring)).used as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(vring), + "::", + stringify!(used) + ) + ); } impl Clone for vring { - fn clone(&self) -> Self { *self } + fn clone(&self) -> Self { + *self + } } diff --git a/vm_control/src/lib.rs b/vm_control/src/lib.rs index fae2e1d..47e9d8c 100644 --- a/vm_control/src/lib.rs +++ b/vm_control/src/lib.rs @@ -14,8 +14,8 @@ extern crate byteorder; extern crate data_model; extern crate kvm; extern crate libc; -extern crate sys_util; extern crate resources; +extern crate sys_util; use std::fs::File; use std::io::{Seek, SeekFrom}; @@ -23,14 +23,15 @@ use std::os::unix::io::{AsRawFd, RawFd}; use std::os::unix::net::UnixDatagram; use std::result; -use libc::{ERANGE, EINVAL, ENODEV}; +use libc::{EINVAL, ENODEV, ERANGE}; use byteorder::{LittleEndian, WriteBytesExt}; use data_model::{DataInit, Le32, Le64, VolatileMemory}; -use sys_util::{EventFd, Result, Error as SysError, MmapError, MemoryMapping, ScmSocket, - GuestAddress}; -use resources::{GpuMemoryDesc, GpuMemoryPlaneDesc, SystemAllocator}; use kvm::{IoeventAddress, Vm}; +use resources::{GpuMemoryDesc, GpuMemoryPlaneDesc, SystemAllocator}; +use sys_util::{ + Error as SysError, EventFd, GuestAddress, MemoryMapping, MmapError, Result, ScmSocket, +}; #[derive(Debug, PartialEq)] /// An error during a request or response transaction. @@ -86,7 +87,11 @@ pub enum VmRequest { UnregisterMemory(u32), /// Allocate GPU buffer of a given size/format and register the memory into guest address space. /// The response variant is `VmResponse::AllocateAndRegisterGpuMemory` - AllocateAndRegisterGpuMemory { width: u32, height: u32, format: u32 }, + AllocateAndRegisterGpuMemory { + width: u32, + height: u32, + format: u32, + }, } const VM_REQUEST_TYPE_EXIT: u32 = 1; @@ -111,8 +116,12 @@ struct VmRequestStruct { // Safe because it only has data and has no implicit padding. unsafe impl DataInit for VmRequestStruct {} -fn register_memory(vm: &mut Vm, allocator: &mut SystemAllocator, - fd: &AsRawFd, size: usize) -> Result<(u64, u32)> { +fn register_memory( + vm: &mut Vm, + allocator: &mut SystemAllocator, + fd: &AsRawFd, + size: usize, +) -> Result<(u64, u32)> { let mmap = match MemoryMapping::from_fd(fd, size) { Ok(v) => v, Err(MmapError::SystemCallFailed(e)) => return Err(e), @@ -122,11 +131,10 @@ fn register_memory(vm: &mut Vm, allocator: &mut SystemAllocator, Some(a) => a, None => return Err(SysError::new(EINVAL)), }; - let slot = - match vm.add_device_memory(GuestAddress(addr), mmap, false, false) { - Ok(v) => v, - Err(e) => return Err(e), - }; + let slot = match vm.add_device_memory(GuestAddress(addr), mmap, false, false) { + Ok(v) => v, + Err(e) => return Err(e), + }; Ok((addr >> 12, slot)) } @@ -138,7 +146,8 @@ impl VmRequest { pub fn recv(s: &UnixDatagram) -> VmControlResult<VmRequest> { assert_eq!(VM_REQUEST_SIZE, std::mem::size_of::<VmRequestStruct>()); let mut buf = [0; VM_REQUEST_SIZE]; - let (read, file) = s.recv_with_fd(&mut buf) + let (read, file) = s + .recv_with_fd(&mut buf) .map_err(|e| VmControlError::Recv(e))?; if read != VM_REQUEST_SIZE { return Err(VmControlError::BadSize(read)); @@ -151,19 +160,22 @@ impl VmRequest { VM_REQUEST_TYPE_EXIT => Ok(VmRequest::Exit), VM_REQUEST_TYPE_REGISTER_MEMORY => { let fd = file.ok_or(VmControlError::ExpectFd)?; - Ok(VmRequest::RegisterMemory(MaybeOwnedFd::Owned(fd), - req.size.to_native() as usize)) + Ok(VmRequest::RegisterMemory( + MaybeOwnedFd::Owned(fd), + req.size.to_native() as usize, + )) } VM_REQUEST_TYPE_UNREGISTER_MEMORY => Ok(VmRequest::UnregisterMemory(req.slot.into())), VM_REQUEST_TYPE_BALLOON_ADJUST => { Ok(VmRequest::BalloonAdjust(req.num_pages.to_native() as i32)) - }, + } VM_REQUEST_TYPE_ALLOCATE_AND_REGISTER_GPU_MEMORY => { - Ok(VmRequest::AllocateAndRegisterGpuMemory { width: req.width.to_native(), - height: req.height.to_native(), - format: req.format.to_native() - }) - }, + Ok(VmRequest::AllocateAndRegisterGpuMemory { + width: req.width.to_native(), + height: req.height.to_native(), + format: req.format.to_native(), + }) + } _ => Err(VmControlError::InvalidType), } } @@ -192,13 +204,17 @@ impl VmRequest { &VmRequest::BalloonAdjust(pages) => { req.type_ = Le32::from(VM_REQUEST_TYPE_BALLOON_ADJUST); req.num_pages = Le32::from(pages as u32); - }, - &VmRequest::AllocateAndRegisterGpuMemory { width, height, format } => { + } + &VmRequest::AllocateAndRegisterGpuMemory { + width, + height, + format, + } => { req.type_ = Le32::from(VM_REQUEST_TYPE_ALLOCATE_AND_REGISTER_GPU_MEMORY); req.width = Le32::from(width as u32); req.height = Le32::from(height as u32); req.format = Le32::from(format as u32); - }, + } _ => return Err(VmControlError::InvalidType), } let mut buf = [0; VM_REQUEST_SIZE]; @@ -218,8 +234,13 @@ impl VmRequest { /// This does not return a result, instead encapsulating the success or failure in a /// `VmResponse` with the intended purpose of sending the response back over the socket that /// received this `VmRequest`. - pub fn execute(&self, vm: &mut Vm, sys_allocator: &mut SystemAllocator, running: &mut bool, - balloon_host_socket: &UnixDatagram) -> VmResponse { + pub fn execute( + &self, + vm: &mut Vm, + sys_allocator: &mut SystemAllocator, + running: &mut bool, + balloon_host_socket: &UnixDatagram, + ) -> VmResponse { *running = true; match self { &VmRequest::Exit => { @@ -232,41 +253,41 @@ impl VmRequest { Err(e) => VmResponse::Err(e), } } - &VmRequest::RegisterIrqfd(ref evt, irq) => { - match vm.register_irqfd(evt, irq) { - Ok(_) => VmResponse::Ok, - Err(e) => return VmResponse::Err(e), - } - } + &VmRequest::RegisterIrqfd(ref evt, irq) => match vm.register_irqfd(evt, irq) { + Ok(_) => VmResponse::Ok, + Err(e) => return VmResponse::Err(e), + }, &VmRequest::RegisterMemory(ref fd, size) => { match register_memory(vm, sys_allocator, fd, size) { Ok((pfn, slot)) => VmResponse::RegisterMemory { pfn, slot }, Err(e) => VmResponse::Err(e), } } - &VmRequest::UnregisterMemory(slot) => { - match vm.remove_device_memory(slot) { - Ok(_) => VmResponse::Ok, - Err(e) => VmResponse::Err(e), - } - } + &VmRequest::UnregisterMemory(slot) => match vm.remove_device_memory(slot) { + Ok(_) => VmResponse::Ok, + Err(e) => VmResponse::Err(e), + }, &VmRequest::BalloonAdjust(num_pages) => { let mut buf = [0u8; 4]; // write_i32 can't fail as the buffer is 4 bytes long. - (&mut buf[0..]).write_i32::<LittleEndian>(num_pages).unwrap(); + (&mut buf[0..]) + .write_i32::<LittleEndian>(num_pages) + .unwrap(); match balloon_host_socket.send(&buf) { Ok(_) => VmResponse::Ok, Err(_) => VmResponse::Err(SysError::last()), } } - &VmRequest::AllocateAndRegisterGpuMemory {width, height, format} => { + &VmRequest::AllocateAndRegisterGpuMemory { + width, + height, + format, + } => { let (mut fd, desc) = match sys_allocator.gpu_memory_allocator() { - Some(gpu_allocator) => { - match gpu_allocator.allocate(width, height, format) { - Ok(v) => v, - Err(e) => return VmResponse::Err(e), - } - } + Some(gpu_allocator) => match gpu_allocator.allocate(width, height, format) { + Ok(v) => v, + Err(e) => return VmResponse::Err(e), + }, None => return VmResponse::Err(SysError::new(ENODEV)), }; // Determine size of buffer using 0 byte seek from end. This is preferred over @@ -280,7 +301,8 @@ impl VmRequest { fd: MaybeOwnedFd::Owned(fd), pfn, slot, - desc }, + desc, + }, Err(e) => VmResponse::Err(e), } } @@ -301,7 +323,12 @@ pub enum VmResponse { RegisterMemory { pfn: u64, slot: u32 }, /// The request to allocate and register GPU memory into guest address space was successfully /// done at page frame number `pfn` and memory slot number `slot` for buffer with `desc`. - AllocateAndRegisterGpuMemory { fd: MaybeOwnedFd, pfn: u64, slot: u32, desc: GpuMemoryDesc }, + AllocateAndRegisterGpuMemory { + fd: MaybeOwnedFd, + pfn: u64, + slot: u32, + desc: GpuMemoryDesc, + }, } const VM_RESPONSE_TYPE_OK: u32 = 1; @@ -334,7 +361,8 @@ impl VmResponse { /// This should be called after the sending a `VmRequest` before sending another request. pub fn recv(s: &UnixDatagram) -> VmControlResult<VmResponse> { let mut buf = [0; VM_RESPONSE_SIZE]; - let (read, file) = s.recv_with_fd(&mut buf) + let (read, file) = s + .recv_with_fd(&mut buf) .map_err(|e| VmControlError::Recv(e))?; if read != VM_RESPONSE_SIZE { return Err(VmControlError::BadSize(read)); @@ -343,30 +371,36 @@ impl VmResponse { match resp.type_.into() { VM_RESPONSE_TYPE_OK => Ok(VmResponse::Ok), - VM_RESPONSE_TYPE_ERR => { - Ok(VmResponse::Err(SysError::new(resp.errno.to_native() as i32))) - } - VM_RESPONSE_TYPE_REGISTER_MEMORY => { - Ok(VmResponse::RegisterMemory { - pfn: resp.pfn.into(), - slot: resp.slot.into(), - }) - } + VM_RESPONSE_TYPE_ERR => Ok(VmResponse::Err(SysError::new( + resp.errno.to_native() as i32 + ))), + VM_RESPONSE_TYPE_REGISTER_MEMORY => Ok(VmResponse::RegisterMemory { + pfn: resp.pfn.into(), + slot: resp.slot.into(), + }), VM_RESPONSE_TYPE_ALLOCATE_AND_REGISTER_GPU_MEMORY => { let fd = file.ok_or(VmControlError::ExpectFd)?; Ok(VmResponse::AllocateAndRegisterGpuMemory { - fd: MaybeOwnedFd::Owned(fd), - pfn: resp.pfn.into(), - slot: resp.slot.into(), - desc: GpuMemoryDesc { - planes: [ GpuMemoryPlaneDesc { stride: resp.stride0.into(), - offset: resp.offset0.into() }, - GpuMemoryPlaneDesc { stride: resp.stride1.into(), - offset: resp.offset1.into() }, - GpuMemoryPlaneDesc { stride: resp.stride2.into(), - offset: resp.offset2.into() } ], - }, - }) + fd: MaybeOwnedFd::Owned(fd), + pfn: resp.pfn.into(), + slot: resp.slot.into(), + desc: GpuMemoryDesc { + planes: [ + GpuMemoryPlaneDesc { + stride: resp.stride0.into(), + offset: resp.offset0.into(), + }, + GpuMemoryPlaneDesc { + stride: resp.stride1.into(), + offset: resp.offset1.into(), + }, + GpuMemoryPlaneDesc { + stride: resp.stride2.into(), + offset: resp.offset2.into(), + }, + ], + }, + }) } _ => Err(VmControlError::InvalidType), } @@ -391,7 +425,12 @@ impl VmResponse { resp.pfn = Le64::from(pfn); resp.slot = Le32::from(slot); } - &VmResponse::AllocateAndRegisterGpuMemory {ref fd, pfn, slot, desc } => { + &VmResponse::AllocateAndRegisterGpuMemory { + ref fd, + pfn, + slot, + desc, + } => { fd_buf[0] = fd.as_raw_fd(); fd_len = 1; resp.type_ = Le32::from(VM_RESPONSE_TYPE_ALLOCATE_AND_REGISTER_GPU_MEMORY); @@ -413,7 +452,6 @@ impl VmResponse { } } - #[cfg(test)] mod tests { use super::*; @@ -435,7 +473,9 @@ mod tests { #[test] fn request_register_memory() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair"); let shm_size: usize = 4096; let mut shm = SharedMemory::new(None).unwrap(); @@ -612,7 +652,9 @@ mod tests { #[test] fn resp_allocate_and_register_gpu_memory() { - if !kernel_has_memfd() { return; } + if !kernel_has_memfd() { + return; + } let (s1, s2) = UnixDatagram::pair().expect("failed to create socket pair"); let shm_size: usize = 4096; let mut shm = SharedMemory::new(None).unwrap(); @@ -620,15 +662,26 @@ mod tests { let memory_pfn = 55; let memory_slot = 66; let memory_planes = [ - GpuMemoryPlaneDesc { stride: 32, offset: 84 }, - GpuMemoryPlaneDesc { stride: 48, offset: 96 }, - GpuMemoryPlaneDesc { stride: 64, offset: 112 } + GpuMemoryPlaneDesc { + stride: 32, + offset: 84, + }, + GpuMemoryPlaneDesc { + stride: 48, + offset: 96, + }, + GpuMemoryPlaneDesc { + stride: 64, + offset: 112, + }, ]; let r1 = VmResponse::AllocateAndRegisterGpuMemory { fd: MaybeOwnedFd::Borrowed(shm.as_raw_fd()), pfn: memory_pfn, slot: memory_slot, - desc: GpuMemoryDesc { planes: memory_planes }, + desc: GpuMemoryDesc { + planes: memory_planes, + }, }; r1.send(&s1).unwrap(); match VmResponse::recv(&s2).unwrap() { diff --git a/x86_64/build.rs b/x86_64/build.rs index 95b7a8c..77f3ae4 100644 --- a/x86_64/build.rs +++ b/x86_64/build.rs @@ -5,7 +5,5 @@ extern crate cc; fn main() { - cc::Build::new() - .file("host_cpuid.c") - .compile("host_cpuid"); + cc::Build::new().file("host_cpuid.c").compile("host_cpuid"); } diff --git a/x86_64/src/bootparam.rs b/x86_64/src/bootparam.rs index 2b90d35..51d6102 100644 --- a/x86_64/src/bootparam.rs +++ b/x86_64/src/bootparam.rs @@ -257,18 +257,26 @@ pub struct __kernel_fd_set { } #[test] fn bindgen_test_layout___kernel_fd_set() { - assert_eq!(::std::mem::size_of::<__kernel_fd_set>(), - 128usize, - concat!("Size of: ", stringify!(__kernel_fd_set))); - assert_eq!(::std::mem::align_of::<__kernel_fd_set>(), - 8usize, - concat!("Alignment of ", stringify!(__kernel_fd_set))); - assert_eq!(unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(__kernel_fd_set), - "::", - stringify!(fds_bits))); + assert_eq!( + ::std::mem::size_of::<__kernel_fd_set>(), + 128usize, + concat!("Size of: ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fd_set>(), + 8usize, + concat!("Alignment of ", stringify!(__kernel_fd_set)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fd_set)).fds_bits as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fd_set), + "::", + stringify!(fds_bits) + ) + ); } impl Clone for __kernel_fd_set { fn clone(&self) -> Self { @@ -304,18 +312,26 @@ pub struct __kernel_fsid_t { } #[test] fn bindgen_test_layout___kernel_fsid_t() { - assert_eq!(::std::mem::size_of::<__kernel_fsid_t>(), - 8usize, - concat!("Size of: ", stringify!(__kernel_fsid_t))); - assert_eq!(::std::mem::align_of::<__kernel_fsid_t>(), - 4usize, - concat!("Alignment of ", stringify!(__kernel_fsid_t))); - assert_eq!(unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(__kernel_fsid_t), - "::", - stringify!(val))); + assert_eq!( + ::std::mem::size_of::<__kernel_fsid_t>(), + 8usize, + concat!("Size of: ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + ::std::mem::align_of::<__kernel_fsid_t>(), + 4usize, + concat!("Alignment of ", stringify!(__kernel_fsid_t)) + ); + assert_eq!( + unsafe { &(*(0 as *const __kernel_fsid_t)).val as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(__kernel_fsid_t), + "::", + stringify!(val) + ) + ); } impl Clone for __kernel_fsid_t { fn clone(&self) -> Self { @@ -380,222 +396,366 @@ pub struct screen_info { } #[test] fn bindgen_test_layout_screen_info() { - assert_eq!(::std::mem::size_of::<screen_info>(), - 64usize, - concat!("Size of: ", stringify!(screen_info))); - assert_eq!(::std::mem::align_of::<screen_info>(), - 1usize, - concat!("Alignment of ", stringify!(screen_info))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_x as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_x))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_y as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_y))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).ext_mem_k as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(ext_mem_k))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_page as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_page))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_mode as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_mode))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_cols as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_cols))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).flags as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(flags))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).unused2 as *const _ as usize }, - 9usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(unused2))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_ega_bx as *const _ as usize }, - 10usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_ega_bx))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).unused3 as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(unused3))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_lines as *const _ as usize }, - 14usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_lines))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_isVGA as *const _ as usize }, - 15usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_isVGA))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).orig_video_points as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(orig_video_points))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).lfb_width as *const _ as usize }, - 18usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(lfb_width))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).lfb_height as *const _ as usize }, - 20usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(lfb_height))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).lfb_depth as *const _ as usize }, - 22usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(lfb_depth))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).lfb_base as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(lfb_base))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).lfb_size as *const _ as usize }, - 28usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(lfb_size))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).cl_magic as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(cl_magic))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).cl_offset as *const _ as usize }, - 34usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(cl_offset))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).lfb_linelength as *const _ as usize }, - 36usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(lfb_linelength))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).red_size as *const _ as usize }, - 38usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(red_size))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).red_pos as *const _ as usize }, - 39usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(red_pos))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).green_size as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(green_size))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).green_pos as *const _ as usize }, - 41usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(green_pos))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).blue_size as *const _ as usize }, - 42usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(blue_size))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).blue_pos as *const _ as usize }, - 43usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(blue_pos))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).rsvd_size as *const _ as usize }, - 44usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(rsvd_size))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).rsvd_pos as *const _ as usize }, - 45usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(rsvd_pos))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).vesapm_seg as *const _ as usize }, - 46usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(vesapm_seg))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).vesapm_off as *const _ as usize }, - 48usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(vesapm_off))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).pages as *const _ as usize }, - 50usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(pages))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).vesa_attributes as *const _ as usize }, - 52usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(vesa_attributes))); - assert_eq!(unsafe { &(*(0 as *const screen_info)).capabilities as *const _ as usize }, - 54usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(capabilities))); - assert_eq!(unsafe { &(*(0 as *const screen_info))._reserved as *const _ as usize }, - 58usize, - concat!("Alignment of field: ", - stringify!(screen_info), - "::", - stringify!(_reserved))); + assert_eq!( + ::std::mem::size_of::<screen_info>(), + 64usize, + concat!("Size of: ", stringify!(screen_info)) + ); + assert_eq!( + ::std::mem::align_of::<screen_info>(), + 1usize, + concat!("Alignment of ", stringify!(screen_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_x as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_x) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_y as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_y) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).ext_mem_k as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(ext_mem_k) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_page as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_page) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_mode as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_mode) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_cols as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_cols) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).flags as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).unused2 as *const _ as usize }, + 9usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(unused2) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_ega_bx as *const _ as usize }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_ega_bx) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).unused3 as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(unused3) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_lines as *const _ as usize }, + 14usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_lines) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_isVGA as *const _ as usize }, + 15usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_isVGA) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).orig_video_points as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(orig_video_points) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).lfb_width as *const _ as usize }, + 18usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(lfb_width) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).lfb_height as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(lfb_height) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).lfb_depth as *const _ as usize }, + 22usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(lfb_depth) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).lfb_base as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(lfb_base) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).lfb_size as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(lfb_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).cl_magic as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(cl_magic) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).cl_offset as *const _ as usize }, + 34usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(cl_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).lfb_linelength as *const _ as usize }, + 36usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(lfb_linelength) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).red_size as *const _ as usize }, + 38usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(red_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).red_pos as *const _ as usize }, + 39usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(red_pos) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).green_size as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(green_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).green_pos as *const _ as usize }, + 41usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(green_pos) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).blue_size as *const _ as usize }, + 42usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(blue_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).blue_pos as *const _ as usize }, + 43usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(blue_pos) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).rsvd_size as *const _ as usize }, + 44usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(rsvd_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).rsvd_pos as *const _ as usize }, + 45usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(rsvd_pos) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).vesapm_seg as *const _ as usize }, + 46usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(vesapm_seg) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).vesapm_off as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(vesapm_off) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).pages as *const _ as usize }, + 50usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(pages) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).vesa_attributes as *const _ as usize }, + 52usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(vesa_attributes) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info)).capabilities as *const _ as usize }, + 54usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(capabilities) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const screen_info))._reserved as *const _ as usize }, + 58usize, + concat!( + "Alignment of field: ", + stringify!(screen_info), + "::", + stringify!(_reserved) + ) + ); } impl Clone for screen_info { fn clone(&self) -> Self { @@ -619,66 +779,106 @@ pub struct apm_bios_info { } #[test] fn bindgen_test_layout_apm_bios_info() { - assert_eq!(::std::mem::size_of::<apm_bios_info>(), - 20usize, - concat!("Size of: ", stringify!(apm_bios_info))); - assert_eq!(::std::mem::align_of::<apm_bios_info>(), - 4usize, - concat!("Alignment of ", stringify!(apm_bios_info))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).version as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(version))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).cseg as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(cseg))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).offset as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(offset))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).cseg_16 as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(cseg_16))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).dseg as *const _ as usize }, - 10usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(dseg))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).flags as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(flags))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).cseg_len as *const _ as usize }, - 14usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(cseg_len))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).cseg_16_len as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(cseg_16_len))); - assert_eq!(unsafe { &(*(0 as *const apm_bios_info)).dseg_len as *const _ as usize }, - 18usize, - concat!("Alignment of field: ", - stringify!(apm_bios_info), - "::", - stringify!(dseg_len))); + assert_eq!( + ::std::mem::size_of::<apm_bios_info>(), + 20usize, + concat!("Size of: ", stringify!(apm_bios_info)) + ); + assert_eq!( + ::std::mem::align_of::<apm_bios_info>(), + 4usize, + concat!("Alignment of ", stringify!(apm_bios_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).version as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).cseg as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(cseg) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).offset as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).cseg_16 as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(cseg_16) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).dseg as *const _ as usize }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(dseg) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).flags as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).cseg_len as *const _ as usize }, + 14usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(cseg_len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).cseg_16_len as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(cseg_16_len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const apm_bios_info)).dseg_len as *const _ as usize }, + 18usize, + concat!( + "Alignment of field: ", + stringify!(apm_bios_info), + "::", + stringify!(dseg_len) + ) + ); } impl Clone for apm_bios_info { fn clone(&self) -> Self { @@ -727,41 +927,61 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_1 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_1>(), - 8usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_1>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_1)).base_address as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(base_address))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_1)).reserved1 as - *const _ as usize - }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_1)).reserved2 as - *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1), - "::", - stringify!(reserved2))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_1>(), + 8usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_1>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_1)).base_address as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1), + "::", + stringify!(base_address) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_1)).reserved1 as *const _ + as usize + }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_1)).reserved2 as *const _ + as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_1), + "::", + stringify!(reserved2) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_1 { fn clone(&self) -> Self { @@ -779,59 +999,86 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_2 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1__bindgen_ty_2() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_2>(), - 8usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_2>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).bus as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(bus))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).slot as - *const _ as usize - }, - 1usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(slot))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).function as - *const _ as usize - }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(function))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).channel as - *const _ as usize - }, - 3usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(channel))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).reserved as - *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_2>(), + 8usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_2>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).bus as *const _ as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), + "::", + stringify!(bus) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).slot as *const _ + as usize + }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), + "::", + stringify!(slot) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).function as *const _ + as usize + }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), + "::", + stringify!(function) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).channel as *const _ + as usize + }, + 3usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), + "::", + stringify!(channel) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_2)).reserved as *const _ + as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_2), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_2 { fn clone(&self) -> Self { @@ -845,23 +1092,35 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_3 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1__bindgen_ty_3() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_3>(), - 8usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_3))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_3>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_3))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_3)).reserved as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_3), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_3>(), + 8usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_3) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_3>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_3) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_3)).reserved as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_3), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_3 { fn clone(&self) -> Self { @@ -875,23 +1134,35 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_4 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1__bindgen_ty_4() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_4>(), - 8usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_4))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_4>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_4))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_4)).reserved as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_4), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_4>(), + 8usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_4) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_4>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_4) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_4)).reserved as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_4), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_4 { fn clone(&self) -> Self { @@ -905,23 +1176,35 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_5 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1__bindgen_ty_5() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_5>(), - 8usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_5))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_5>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_5))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_5)).reserved as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_5), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_5>(), + 8usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_5) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_5>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_5) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_5)).reserved as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_5), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_5 { fn clone(&self) -> Self { @@ -935,23 +1218,35 @@ pub struct edd_device_params__bindgen_ty_1__bindgen_ty_6 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1__bindgen_ty_6() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_6>(), - 8usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_6))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_6>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_6))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_6)).reserved as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_6), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1__bindgen_ty_6>(), + 8usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_6) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1__bindgen_ty_6>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_6) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_1__bindgen_ty_6)).reserved as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1__bindgen_ty_6), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_6 { fn clone(&self) -> Self { @@ -960,60 +1255,76 @@ impl Clone for edd_device_params__bindgen_ty_1__bindgen_ty_6 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_1>(), - 8usize, - concat!("Size of: ", stringify!(edd_device_params__bindgen_ty_1))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_1>(), - 1usize, - concat!("Alignment of ", stringify!(edd_device_params__bindgen_ty_1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1)).isa as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1), - "::", - stringify!(isa))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1)).pci as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1), - "::", - stringify!(pci))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1)).ibnd as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1), - "::", - stringify!(ibnd))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1)).xprs as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1), - "::", - stringify!(xprs))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1)).htpt as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1), - "::", - stringify!(htpt))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_1)).unknown as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_1), - "::", - stringify!(unknown))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_1>(), + 8usize, + concat!("Size of: ", stringify!(edd_device_params__bindgen_ty_1)) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_1>(), + 1usize, + concat!("Alignment of ", stringify!(edd_device_params__bindgen_ty_1)) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_1)).isa as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1), + "::", + stringify!(isa) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_1)).pci as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1), + "::", + stringify!(pci) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_1)).ibnd as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1), + "::", + stringify!(ibnd) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_1)).xprs as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1), + "::", + stringify!(xprs) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_1)).htpt as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1), + "::", + stringify!(htpt) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_1)).unknown as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_1), + "::", + stringify!(unknown) + ) + ); } impl Clone for edd_device_params__bindgen_ty_1 { fn clone(&self) -> Self { @@ -1046,59 +1357,87 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_1 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_1() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_1>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_1>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).device as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(device))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved1 as - *const _ as usize - }, - 1usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved2 as - *const _ as usize - }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(reserved2))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved3 as - *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(reserved3))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved4 as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), - "::", - stringify!(reserved4))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_1>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_1>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).device as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), + "::", + stringify!(device) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved1 as *const _ + as usize + }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved2 as *const _ + as usize + }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), + "::", + stringify!(reserved2) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved3 as *const _ + as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), + "::", + stringify!(reserved3) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_1)).reserved4 as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_1), + "::", + stringify!(reserved4) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_1 { fn clone(&self) -> Self { @@ -1117,68 +1456,99 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_2 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_2() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_2>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_2>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).device as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), - "::", - stringify!(device))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).lun as - *const _ as usize - }, - 1usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), - "::", - stringify!(lun))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved1 as - *const _ as usize - }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved2 as - *const _ as usize - }, - 3usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), - "::", - stringify!(reserved2))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved3 as - *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), - "::", - stringify!(reserved3))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved4 as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), - "::", - stringify!(reserved4))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_2>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_2>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).device as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), + "::", + stringify!(device) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).lun as *const _ as usize + }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), + "::", + stringify!(lun) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved1 as *const _ + as usize + }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved2 as *const _ + as usize + }, + 3usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), + "::", + stringify!(reserved2) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved3 as *const _ + as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), + "::", + stringify!(reserved3) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_2)).reserved4 as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_2), + "::", + stringify!(reserved4) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_2 { fn clone(&self) -> Self { @@ -1195,50 +1565,72 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_3 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_3() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_3>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_3>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).id as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), - "::", - stringify!(id))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).lun as - *const _ as usize - }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), - "::", - stringify!(lun))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).reserved1 as - *const _ as usize - }, - 10usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).reserved2 as - *const _ as usize - }, - 12usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), - "::", - stringify!(reserved2))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_3>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_3>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).id as *const _ as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), + "::", + stringify!(id) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).lun as *const _ as usize + }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), + "::", + stringify!(lun) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).reserved1 as *const _ + as usize + }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_3)).reserved2 as *const _ + as usize + }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_3), + "::", + stringify!(reserved2) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_3 { fn clone(&self) -> Self { @@ -1253,32 +1645,48 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_4 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_4() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_4>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_4>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_4)).serial_number as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4), - "::", - stringify!(serial_number))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_4)).reserved as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_4>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_4>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_4)).serial_number + as *const _ as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4), + "::", + stringify!(serial_number) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_4)).reserved as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_4), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_4 { fn clone(&self) -> Self { @@ -1293,32 +1701,47 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_5 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_5() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_5>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_5>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_5)).eui as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5), - "::", - stringify!(eui))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_5)).reserved as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_5>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_5>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_5)).eui as *const _ as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5), + "::", + stringify!(eui) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_5)).reserved as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_5), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_5 { fn clone(&self) -> Self { @@ -1333,32 +1756,47 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_6 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_6() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_6>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_6>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_6)).wwid as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6), - "::", - stringify!(wwid))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_6)).lun as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6), - "::", - stringify!(lun))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_6>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_6>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_6)).wwid as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6), + "::", + stringify!(wwid) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_6)).lun as *const _ as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_6), + "::", + stringify!(lun) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_6 { fn clone(&self) -> Self { @@ -1373,32 +1811,48 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_7 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_7() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_7>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_7>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_7)).identity_tag as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7), - "::", - stringify!(identity_tag))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_7)).reserved as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_7>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_7>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_7)).identity_tag as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7), + "::", + stringify!(identity_tag) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_7)).reserved as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_7), + "::", + stringify!(reserved) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_7 { fn clone(&self) -> Self { @@ -1414,41 +1868,61 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_8 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_8() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_8>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_8>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_8)).array_number as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8), - "::", - stringify!(array_number))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_8)).reserved1 as - *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_8)).reserved2 as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8), - "::", - stringify!(reserved2))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_8>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_8>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_8)).array_number as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8), + "::", + stringify!(array_number) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_8)).reserved1 as *const _ + as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_8)).reserved2 as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_8), + "::", + stringify!(reserved2) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_8 { fn clone(&self) -> Self { @@ -1466,59 +1940,87 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_9 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_9() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_9>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_9>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).device as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), - "::", - stringify!(device))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved1 as - *const _ as usize - }, - 1usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved2 as - *const _ as usize - }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), - "::", - stringify!(reserved2))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved3 as - *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), - "::", - stringify!(reserved3))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved4 as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), - "::", - stringify!(reserved4))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_9>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_9>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).device as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), + "::", + stringify!(device) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved1 as *const _ + as usize + }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved2 as *const _ + as usize + }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), + "::", + stringify!(reserved2) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved3 as *const _ + as usize + }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), + "::", + stringify!(reserved3) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_9)).reserved4 as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_9), + "::", + stringify!(reserved4) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_9 { fn clone(&self) -> Self { @@ -1533,32 +2035,48 @@ pub struct edd_device_params__bindgen_ty_2__bindgen_ty_10 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2__bindgen_ty_10() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_10>(), - 16usize, - concat!("Size of: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_10>(), - 1usize, - concat!("Alignment of ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_10)).reserved1 as - *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10), - "::", - stringify!(reserved1))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_10)).reserved2 as - *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10), - "::", - stringify!(reserved2))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2__bindgen_ty_10>(), + 16usize, + concat!( + "Size of: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10) + ) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2__bindgen_ty_10>(), + 1usize, + concat!( + "Alignment of ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_10)).reserved1 as *const _ + as usize + }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10), + "::", + stringify!(reserved1) + ) + ); + assert_eq!( + unsafe { + &(*(0 as *const edd_device_params__bindgen_ty_2__bindgen_ty_10)).reserved2 as *const _ + as usize + }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2__bindgen_ty_10), + "::", + stringify!(reserved2) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_10 { fn clone(&self) -> Self { @@ -1567,92 +2085,116 @@ impl Clone for edd_device_params__bindgen_ty_2__bindgen_ty_10 { } #[test] fn bindgen_test_layout_edd_device_params__bindgen_ty_2() { - assert_eq!(::std::mem::size_of::<edd_device_params__bindgen_ty_2>(), - 16usize, - concat!("Size of: ", stringify!(edd_device_params__bindgen_ty_2))); - assert_eq!(::std::mem::align_of::<edd_device_params__bindgen_ty_2>(), - 1usize, - concat!("Alignment of ", stringify!(edd_device_params__bindgen_ty_2))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).ata as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(ata))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).atapi as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(atapi))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).scsi as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(scsi))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).usb as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(usb))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).i1394 as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(i1394))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).fibre as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(fibre))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).i2o as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(i2o))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).raid as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(raid))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).sata as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(sata))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params__bindgen_ty_2)).unknown as *const _ as usize - }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params__bindgen_ty_2), - "::", - stringify!(unknown))); + assert_eq!( + ::std::mem::size_of::<edd_device_params__bindgen_ty_2>(), + 16usize, + concat!("Size of: ", stringify!(edd_device_params__bindgen_ty_2)) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params__bindgen_ty_2>(), + 1usize, + concat!("Alignment of ", stringify!(edd_device_params__bindgen_ty_2)) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).ata as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(ata) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).atapi as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(atapi) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).scsi as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(scsi) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).usb as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(usb) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).i1394 as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(i1394) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).fibre as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(fibre) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).i2o as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(i2o) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).raid as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(raid) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).sata as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(sata) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params__bindgen_ty_2)).unknown as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params__bindgen_ty_2), + "::", + stringify!(unknown) + ) + ); } impl Clone for edd_device_params__bindgen_ty_2 { fn clone(&self) -> Self { @@ -1661,132 +2203,196 @@ impl Clone for edd_device_params__bindgen_ty_2 { } #[test] fn bindgen_test_layout_edd_device_params() { - assert_eq!(::std::mem::size_of::<edd_device_params>(), - 74usize, - concat!("Size of: ", stringify!(edd_device_params))); - assert_eq!(::std::mem::align_of::<edd_device_params>(), - 1usize, - concat!("Alignment of ", stringify!(edd_device_params))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).length as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(length))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).info_flags as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(info_flags))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params)).num_default_cylinders as *const _ as usize - }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(num_default_cylinders))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params)).num_default_heads as *const _ as usize - }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(num_default_heads))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params)).sectors_per_track as *const _ as usize - }, - 12usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(sectors_per_track))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params)).number_of_sectors as *const _ as usize - }, - 16usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(number_of_sectors))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params)).bytes_per_sector as *const _ as usize - }, - 24usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(bytes_per_sector))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).dpte_ptr as *const _ as usize }, - 26usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(dpte_ptr))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).key as *const _ as usize }, - 30usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(key))); - assert_eq!(unsafe { - &(*(0 as *const edd_device_params)).device_path_info_length as *const _ as usize - }, - 32usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(device_path_info_length))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).reserved2 as *const _ as usize }, - 33usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(reserved2))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).reserved3 as *const _ as usize }, - 34usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(reserved3))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).host_bus_type as *const _ as usize }, - 36usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(host_bus_type))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).interface_type as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(interface_type))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).interface_path as *const _ as usize }, - 48usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(interface_path))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).device_path as *const _ as usize }, - 56usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(device_path))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).reserved4 as *const _ as usize }, - 72usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(reserved4))); - assert_eq!(unsafe { &(*(0 as *const edd_device_params)).checksum as *const _ as usize }, - 73usize, - concat!("Alignment of field: ", - stringify!(edd_device_params), - "::", - stringify!(checksum))); + assert_eq!( + ::std::mem::size_of::<edd_device_params>(), + 74usize, + concat!("Size of: ", stringify!(edd_device_params)) + ); + assert_eq!( + ::std::mem::align_of::<edd_device_params>(), + 1usize, + concat!("Alignment of ", stringify!(edd_device_params)) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).length as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).info_flags as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(info_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).num_default_cylinders as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(num_default_cylinders) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).num_default_heads as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(num_default_heads) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).sectors_per_track as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(sectors_per_track) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).number_of_sectors as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(number_of_sectors) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).bytes_per_sector as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(bytes_per_sector) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).dpte_ptr as *const _ as usize }, + 26usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(dpte_ptr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).key as *const _ as usize }, + 30usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(key) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).device_path_info_length as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(device_path_info_length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).reserved2 as *const _ as usize }, + 33usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(reserved2) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).reserved3 as *const _ as usize }, + 34usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(reserved3) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).host_bus_type as *const _ as usize }, + 36usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(host_bus_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).interface_type as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(interface_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).interface_path as *const _ as usize }, + 48usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(interface_path) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).device_path as *const _ as usize }, + 56usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(device_path) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).reserved4 as *const _ as usize }, + 72usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(reserved4) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_device_params)).checksum as *const _ as usize }, + 73usize, + concat!( + "Alignment of field: ", + stringify!(edd_device_params), + "::", + stringify!(checksum) + ) + ); } impl Clone for edd_device_params { fn clone(&self) -> Self { @@ -1806,54 +2412,86 @@ pub struct edd_info { } #[test] fn bindgen_test_layout_edd_info() { - assert_eq!(::std::mem::size_of::<edd_info>(), - 82usize, - concat!("Size of: ", stringify!(edd_info))); - assert_eq!(::std::mem::align_of::<edd_info>(), - 1usize, - concat!("Alignment of ", stringify!(edd_info))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).device as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(device))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).version as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(version))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).interface_support as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(interface_support))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).legacy_max_cylinder as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(legacy_max_cylinder))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).legacy_max_head as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(legacy_max_head))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).legacy_sectors_per_track as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(legacy_sectors_per_track))); - assert_eq!(unsafe { &(*(0 as *const edd_info)).params as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(edd_info), - "::", - stringify!(params))); + assert_eq!( + ::std::mem::size_of::<edd_info>(), + 82usize, + concat!("Size of: ", stringify!(edd_info)) + ); + assert_eq!( + ::std::mem::align_of::<edd_info>(), + 1usize, + concat!("Alignment of ", stringify!(edd_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).device as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(device) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).version as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).interface_support as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(interface_support) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).legacy_max_cylinder as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(legacy_max_cylinder) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).legacy_max_head as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(legacy_max_head) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).legacy_sectors_per_track as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(legacy_sectors_per_track) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd_info)).params as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(edd_info), + "::", + stringify!(params) + ) + ); } impl Clone for edd_info { fn clone(&self) -> Self { @@ -1870,36 +2508,56 @@ pub struct edd { } #[test] fn bindgen_test_layout_edd() { - assert_eq!(::std::mem::size_of::<edd>(), - 560usize, - concat!("Size of: ", stringify!(edd))); - assert_eq!(::std::mem::align_of::<edd>(), - 4usize, - concat!("Alignment of ", stringify!(edd))); - assert_eq!(unsafe { &(*(0 as *const edd)).mbr_signature as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(edd), - "::", - stringify!(mbr_signature))); - assert_eq!(unsafe { &(*(0 as *const edd)).edd_info as *const _ as usize }, - 64usize, - concat!("Alignment of field: ", - stringify!(edd), - "::", - stringify!(edd_info))); - assert_eq!(unsafe { &(*(0 as *const edd)).mbr_signature_nr as *const _ as usize }, - 556usize, - concat!("Alignment of field: ", - stringify!(edd), - "::", - stringify!(mbr_signature_nr))); - assert_eq!(unsafe { &(*(0 as *const edd)).edd_info_nr as *const _ as usize }, - 557usize, - concat!("Alignment of field: ", - stringify!(edd), - "::", - stringify!(edd_info_nr))); + assert_eq!( + ::std::mem::size_of::<edd>(), + 560usize, + concat!("Size of: ", stringify!(edd)) + ); + assert_eq!( + ::std::mem::align_of::<edd>(), + 4usize, + concat!("Alignment of ", stringify!(edd)) + ); + assert_eq!( + unsafe { &(*(0 as *const edd)).mbr_signature as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edd), + "::", + stringify!(mbr_signature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd)).edd_info as *const _ as usize }, + 64usize, + concat!( + "Alignment of field: ", + stringify!(edd), + "::", + stringify!(edd_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd)).mbr_signature_nr as *const _ as usize }, + 556usize, + concat!( + "Alignment of field: ", + stringify!(edd), + "::", + stringify!(mbr_signature_nr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const edd)).edd_info_nr as *const _ as usize }, + 557usize, + concat!( + "Alignment of field: ", + stringify!(edd), + "::", + stringify!(edd_info_nr) + ) + ); } impl Clone for edd { fn clone(&self) -> Self { @@ -1915,30 +2573,46 @@ pub struct e820entry { } #[test] fn bindgen_test_layout_e820entry() { - assert_eq!(::std::mem::size_of::<e820entry>(), - 20usize, - concat!("Size of: ", stringify!(e820entry))); - assert_eq!(::std::mem::align_of::<e820entry>(), - 1usize, - concat!("Alignment of ", stringify!(e820entry))); - assert_eq!(unsafe { &(*(0 as *const e820entry)).addr as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(e820entry), - "::", - stringify!(addr))); - assert_eq!(unsafe { &(*(0 as *const e820entry)).size as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(e820entry), - "::", - stringify!(size))); - assert_eq!(unsafe { &(*(0 as *const e820entry)).type_ as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(e820entry), - "::", - stringify!(type_))); + assert_eq!( + ::std::mem::size_of::<e820entry>(), + 20usize, + concat!("Size of: ", stringify!(e820entry)) + ); + assert_eq!( + ::std::mem::align_of::<e820entry>(), + 1usize, + concat!("Alignment of ", stringify!(e820entry)) + ); + assert_eq!( + unsafe { &(*(0 as *const e820entry)).addr as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(e820entry), + "::", + stringify!(addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const e820entry)).size as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(e820entry), + "::", + stringify!(size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const e820entry)).type_ as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(e820entry), + "::", + stringify!(type_) + ) + ); } impl Clone for e820entry { fn clone(&self) -> Self { @@ -1952,24 +2626,36 @@ pub struct e820map { } #[test] fn bindgen_test_layout_e820map() { - assert_eq!(::std::mem::size_of::<e820map>(), - 2564usize, - concat!("Size of: ", stringify!(e820map))); - assert_eq!(::std::mem::align_of::<e820map>(), - 4usize, - concat!("Alignment of ", stringify!(e820map))); - assert_eq!(unsafe { &(*(0 as *const e820map)).nr_map as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(e820map), - "::", - stringify!(nr_map))); - assert_eq!(unsafe { &(*(0 as *const e820map)).map as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(e820map), - "::", - stringify!(map))); + assert_eq!( + ::std::mem::size_of::<e820map>(), + 2564usize, + concat!("Size of: ", stringify!(e820map)) + ); + assert_eq!( + ::std::mem::align_of::<e820map>(), + 4usize, + concat!("Alignment of ", stringify!(e820map)) + ); + assert_eq!( + unsafe { &(*(0 as *const e820map)).nr_map as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(e820map), + "::", + stringify!(nr_map) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const e820map)).map as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(e820map), + "::", + stringify!(map) + ) + ); } impl Default for e820map { fn default() -> Self { @@ -1986,36 +2672,56 @@ pub struct ist_info { } #[test] fn bindgen_test_layout_ist_info() { - assert_eq!(::std::mem::size_of::<ist_info>(), - 16usize, - concat!("Size of: ", stringify!(ist_info))); - assert_eq!(::std::mem::align_of::<ist_info>(), - 4usize, - concat!("Alignment of ", stringify!(ist_info))); - assert_eq!(unsafe { &(*(0 as *const ist_info)).signature as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(ist_info), - "::", - stringify!(signature))); - assert_eq!(unsafe { &(*(0 as *const ist_info)).command as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(ist_info), - "::", - stringify!(command))); - assert_eq!(unsafe { &(*(0 as *const ist_info)).event as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(ist_info), - "::", - stringify!(event))); - assert_eq!(unsafe { &(*(0 as *const ist_info)).perf_level as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(ist_info), - "::", - stringify!(perf_level))); + assert_eq!( + ::std::mem::size_of::<ist_info>(), + 16usize, + concat!("Size of: ", stringify!(ist_info)) + ); + assert_eq!( + ::std::mem::align_of::<ist_info>(), + 4usize, + concat!("Alignment of ", stringify!(ist_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const ist_info)).signature as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(ist_info), + "::", + stringify!(signature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ist_info)).command as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(ist_info), + "::", + stringify!(command) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ist_info)).event as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(ist_info), + "::", + stringify!(event) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const ist_info)).perf_level as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(ist_info), + "::", + stringify!(perf_level) + ) + ); } impl Clone for ist_info { fn clone(&self) -> Self { @@ -2028,18 +2734,26 @@ pub struct edid_info { } #[test] fn bindgen_test_layout_edid_info() { - assert_eq!(::std::mem::size_of::<edid_info>(), - 128usize, - concat!("Size of: ", stringify!(edid_info))); - assert_eq!(::std::mem::align_of::<edid_info>(), - 1usize, - concat!("Alignment of ", stringify!(edid_info))); - assert_eq!(unsafe { &(*(0 as *const edid_info)).dummy as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(edid_info), - "::", - stringify!(dummy))); + assert_eq!( + ::std::mem::size_of::<edid_info>(), + 128usize, + concat!("Size of: ", stringify!(edid_info)) + ); + assert_eq!( + ::std::mem::align_of::<edid_info>(), + 1usize, + concat!("Alignment of ", stringify!(edid_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const edid_info)).dummy as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(edid_info), + "::", + stringify!(dummy) + ) + ); } impl Default for edid_info { fn default() -> Self { @@ -2056,36 +2770,56 @@ pub struct setup_data { } #[test] fn bindgen_test_layout_setup_data() { - assert_eq!(::std::mem::size_of::<setup_data>(), - 16usize, - concat!("Size of: ", stringify!(setup_data))); - assert_eq!(::std::mem::align_of::<setup_data>(), - 8usize, - concat!("Alignment of ", stringify!(setup_data))); - assert_eq!(unsafe { &(*(0 as *const setup_data)).next as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(setup_data), - "::", - stringify!(next))); - assert_eq!(unsafe { &(*(0 as *const setup_data)).type_ as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(setup_data), - "::", - stringify!(type_))); - assert_eq!(unsafe { &(*(0 as *const setup_data)).len as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(setup_data), - "::", - stringify!(len))); - assert_eq!(unsafe { &(*(0 as *const setup_data)).data as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(setup_data), - "::", - stringify!(data))); + assert_eq!( + ::std::mem::size_of::<setup_data>(), + 16usize, + concat!("Size of: ", stringify!(setup_data)) + ); + assert_eq!( + ::std::mem::align_of::<setup_data>(), + 8usize, + concat!("Alignment of ", stringify!(setup_data)) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_data)).next as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(setup_data), + "::", + stringify!(next) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_data)).type_ as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(setup_data), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_data)).len as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(setup_data), + "::", + stringify!(len) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_data)).data as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(setup_data), + "::", + stringify!(data) + ) + ); } impl Clone for setup_data { fn clone(&self) -> Self { @@ -2136,242 +2870,396 @@ pub struct setup_header { } #[test] fn bindgen_test_layout_setup_header() { - assert_eq!(::std::mem::size_of::<setup_header>(), - 119usize, - concat!("Size of: ", stringify!(setup_header))); - assert_eq!(::std::mem::align_of::<setup_header>(), - 1usize, - concat!("Alignment of ", stringify!(setup_header))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).setup_sects as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(setup_sects))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).root_flags as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(root_flags))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).syssize as *const _ as usize }, - 3usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(syssize))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).ram_size as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(ram_size))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).vid_mode as *const _ as usize }, - 9usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(vid_mode))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).root_dev as *const _ as usize }, - 11usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(root_dev))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).boot_flag as *const _ as usize }, - 13usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(boot_flag))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).jump as *const _ as usize }, - 15usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(jump))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).header as *const _ as usize }, - 17usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(header))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).version as *const _ as usize }, - 21usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(version))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).realmode_swtch as *const _ as usize }, - 23usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(realmode_swtch))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).start_sys as *const _ as usize }, - 27usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(start_sys))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).kernel_version as *const _ as usize }, - 29usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(kernel_version))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).type_of_loader as *const _ as usize }, - 31usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(type_of_loader))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).loadflags as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(loadflags))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).setup_move_size as *const _ as usize }, - 33usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(setup_move_size))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).code32_start as *const _ as usize }, - 35usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(code32_start))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).ramdisk_image as *const _ as usize }, - 39usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(ramdisk_image))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).ramdisk_size as *const _ as usize }, - 43usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(ramdisk_size))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).bootsect_kludge as *const _ as usize }, - 47usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(bootsect_kludge))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).heap_end_ptr as *const _ as usize }, - 51usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(heap_end_ptr))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).ext_loader_ver as *const _ as usize }, - 53usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(ext_loader_ver))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).ext_loader_type as *const _ as usize }, - 54usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(ext_loader_type))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).cmd_line_ptr as *const _ as usize }, - 55usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(cmd_line_ptr))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).initrd_addr_max as *const _ as usize }, - 59usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(initrd_addr_max))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).kernel_alignment as *const _ as usize }, - 63usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(kernel_alignment))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).relocatable_kernel as *const _ as usize }, - 67usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(relocatable_kernel))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).min_alignment as *const _ as usize }, - 68usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(min_alignment))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).xloadflags as *const _ as usize }, - 69usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(xloadflags))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).cmdline_size as *const _ as usize }, - 71usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(cmdline_size))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).hardware_subarch as *const _ as usize }, - 75usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(hardware_subarch))); - assert_eq!(unsafe { - &(*(0 as *const setup_header)).hardware_subarch_data as *const _ as usize - }, - 79usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(hardware_subarch_data))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).payload_offset as *const _ as usize }, - 87usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(payload_offset))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).payload_length as *const _ as usize }, - 91usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(payload_length))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).setup_data as *const _ as usize }, - 95usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(setup_data))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).pref_address as *const _ as usize }, - 103usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(pref_address))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).init_size as *const _ as usize }, - 111usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(init_size))); - assert_eq!(unsafe { &(*(0 as *const setup_header)).handover_offset as *const _ as usize }, - 115usize, - concat!("Alignment of field: ", - stringify!(setup_header), - "::", - stringify!(handover_offset))); + assert_eq!( + ::std::mem::size_of::<setup_header>(), + 119usize, + concat!("Size of: ", stringify!(setup_header)) + ); + assert_eq!( + ::std::mem::align_of::<setup_header>(), + 1usize, + concat!("Alignment of ", stringify!(setup_header)) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).setup_sects as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(setup_sects) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).root_flags as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(root_flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).syssize as *const _ as usize }, + 3usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(syssize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).ram_size as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(ram_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).vid_mode as *const _ as usize }, + 9usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(vid_mode) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).root_dev as *const _ as usize }, + 11usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(root_dev) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).boot_flag as *const _ as usize }, + 13usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(boot_flag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).jump as *const _ as usize }, + 15usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(jump) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).header as *const _ as usize }, + 17usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(header) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).version as *const _ as usize }, + 21usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).realmode_swtch as *const _ as usize }, + 23usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(realmode_swtch) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).start_sys as *const _ as usize }, + 27usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(start_sys) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).kernel_version as *const _ as usize }, + 29usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(kernel_version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).type_of_loader as *const _ as usize }, + 31usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(type_of_loader) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).loadflags as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(loadflags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).setup_move_size as *const _ as usize }, + 33usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(setup_move_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).code32_start as *const _ as usize }, + 35usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(code32_start) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).ramdisk_image as *const _ as usize }, + 39usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(ramdisk_image) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).ramdisk_size as *const _ as usize }, + 43usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(ramdisk_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).bootsect_kludge as *const _ as usize }, + 47usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(bootsect_kludge) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).heap_end_ptr as *const _ as usize }, + 51usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(heap_end_ptr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).ext_loader_ver as *const _ as usize }, + 53usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(ext_loader_ver) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).ext_loader_type as *const _ as usize }, + 54usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(ext_loader_type) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).cmd_line_ptr as *const _ as usize }, + 55usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(cmd_line_ptr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).initrd_addr_max as *const _ as usize }, + 59usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(initrd_addr_max) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).kernel_alignment as *const _ as usize }, + 63usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(kernel_alignment) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).relocatable_kernel as *const _ as usize }, + 67usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(relocatable_kernel) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).min_alignment as *const _ as usize }, + 68usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(min_alignment) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).xloadflags as *const _ as usize }, + 69usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(xloadflags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).cmdline_size as *const _ as usize }, + 71usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(cmdline_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).hardware_subarch as *const _ as usize }, + 75usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(hardware_subarch) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).hardware_subarch_data as *const _ as usize }, + 79usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(hardware_subarch_data) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).payload_offset as *const _ as usize }, + 87usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(payload_offset) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).payload_length as *const _ as usize }, + 91usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(payload_length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).setup_data as *const _ as usize }, + 95usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(setup_data) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).pref_address as *const _ as usize }, + 103usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(pref_address) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).init_size as *const _ as usize }, + 111usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(init_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const setup_header)).handover_offset as *const _ as usize }, + 115usize, + concat!( + "Alignment of field: ", + stringify!(setup_header), + "::", + stringify!(handover_offset) + ) + ); } impl Clone for setup_header { fn clone(&self) -> Self { @@ -2386,24 +3274,36 @@ pub struct sys_desc_table { } #[test] fn bindgen_test_layout_sys_desc_table() { - assert_eq!(::std::mem::size_of::<sys_desc_table>(), - 16usize, - concat!("Size of: ", stringify!(sys_desc_table))); - assert_eq!(::std::mem::align_of::<sys_desc_table>(), - 2usize, - concat!("Alignment of ", stringify!(sys_desc_table))); - assert_eq!(unsafe { &(*(0 as *const sys_desc_table)).length as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(sys_desc_table), - "::", - stringify!(length))); - assert_eq!(unsafe { &(*(0 as *const sys_desc_table)).table as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(sys_desc_table), - "::", - stringify!(table))); + assert_eq!( + ::std::mem::size_of::<sys_desc_table>(), + 16usize, + concat!("Size of: ", stringify!(sys_desc_table)) + ); + assert_eq!( + ::std::mem::align_of::<sys_desc_table>(), + 2usize, + concat!("Alignment of ", stringify!(sys_desc_table)) + ); + assert_eq!( + unsafe { &(*(0 as *const sys_desc_table)).length as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(sys_desc_table), + "::", + stringify!(length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const sys_desc_table)).table as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(sys_desc_table), + "::", + stringify!(table) + ) + ); } impl Clone for sys_desc_table { fn clone(&self) -> Self { @@ -2420,36 +3320,56 @@ pub struct olpc_ofw_header { } #[test] fn bindgen_test_layout_olpc_ofw_header() { - assert_eq!(::std::mem::size_of::<olpc_ofw_header>(), - 16usize, - concat!("Size of: ", stringify!(olpc_ofw_header))); - assert_eq!(::std::mem::align_of::<olpc_ofw_header>(), - 1usize, - concat!("Alignment of ", stringify!(olpc_ofw_header))); - assert_eq!(unsafe { &(*(0 as *const olpc_ofw_header)).ofw_magic as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(olpc_ofw_header), - "::", - stringify!(ofw_magic))); - assert_eq!(unsafe { &(*(0 as *const olpc_ofw_header)).ofw_version as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(olpc_ofw_header), - "::", - stringify!(ofw_version))); - assert_eq!(unsafe { &(*(0 as *const olpc_ofw_header)).cif_handler as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(olpc_ofw_header), - "::", - stringify!(cif_handler))); - assert_eq!(unsafe { &(*(0 as *const olpc_ofw_header)).irq_desc_table as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(olpc_ofw_header), - "::", - stringify!(irq_desc_table))); + assert_eq!( + ::std::mem::size_of::<olpc_ofw_header>(), + 16usize, + concat!("Size of: ", stringify!(olpc_ofw_header)) + ); + assert_eq!( + ::std::mem::align_of::<olpc_ofw_header>(), + 1usize, + concat!("Alignment of ", stringify!(olpc_ofw_header)) + ); + assert_eq!( + unsafe { &(*(0 as *const olpc_ofw_header)).ofw_magic as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(olpc_ofw_header), + "::", + stringify!(ofw_magic) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const olpc_ofw_header)).ofw_version as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(olpc_ofw_header), + "::", + stringify!(ofw_version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const olpc_ofw_header)).cif_handler as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(olpc_ofw_header), + "::", + stringify!(cif_handler) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const olpc_ofw_header)).irq_desc_table as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(olpc_ofw_header), + "::", + stringify!(irq_desc_table) + ) + ); } impl Clone for olpc_ofw_header { fn clone(&self) -> Self { @@ -2470,60 +3390,96 @@ pub struct efi_info { } #[test] fn bindgen_test_layout_efi_info() { - assert_eq!(::std::mem::size_of::<efi_info>(), - 32usize, - concat!("Size of: ", stringify!(efi_info))); - assert_eq!(::std::mem::align_of::<efi_info>(), - 4usize, - concat!("Alignment of ", stringify!(efi_info))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_loader_signature as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_loader_signature))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_systab as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_systab))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_memdesc_size as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_memdesc_size))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_memdesc_version as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_memdesc_version))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_memmap as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_memmap))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_memmap_size as *const _ as usize }, - 20usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_memmap_size))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_systab_hi as *const _ as usize }, - 24usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_systab_hi))); - assert_eq!(unsafe { &(*(0 as *const efi_info)).efi_memmap_hi as *const _ as usize }, - 28usize, - concat!("Alignment of field: ", - stringify!(efi_info), - "::", - stringify!(efi_memmap_hi))); + assert_eq!( + ::std::mem::size_of::<efi_info>(), + 32usize, + concat!("Size of: ", stringify!(efi_info)) + ); + assert_eq!( + ::std::mem::align_of::<efi_info>(), + 4usize, + concat!("Alignment of ", stringify!(efi_info)) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_loader_signature as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_loader_signature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_systab as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_systab) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_memdesc_size as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_memdesc_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_memdesc_version as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_memdesc_version) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_memmap as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_memmap) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_memmap_size as *const _ as usize }, + 20usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_memmap_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_systab_hi as *const _ as usize }, + 24usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_systab_hi) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const efi_info)).efi_memmap_hi as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(efi_info), + "::", + stringify!(efi_memmap_hi) + ) + ); } impl Clone for efi_info { fn clone(&self) -> Self { @@ -2567,206 +3523,336 @@ pub struct boot_params { } #[test] fn bindgen_test_layout_boot_params() { - assert_eq!(::std::mem::size_of::<boot_params>(), - 4096usize, - concat!("Size of: ", stringify!(boot_params))); - assert_eq!(::std::mem::align_of::<boot_params>(), - 1usize, - concat!("Alignment of ", stringify!(boot_params))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).screen_info as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(screen_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).apm_bios_info as *const _ as usize }, - 64usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(apm_bios_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad2 as *const _ as usize }, - 84usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad2))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).tboot_addr as *const _ as usize }, - 88usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(tboot_addr))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).ist_info as *const _ as usize }, - 96usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(ist_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad3 as *const _ as usize }, - 112usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad3))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).hd0_info as *const _ as usize }, - 128usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(hd0_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).hd1_info as *const _ as usize }, - 144usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(hd1_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).sys_desc_table as *const _ as usize }, - 160usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(sys_desc_table))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).olpc_ofw_header as *const _ as usize }, - 176usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(olpc_ofw_header))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).ext_ramdisk_image as *const _ as usize }, - 192usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(ext_ramdisk_image))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).ext_ramdisk_size as *const _ as usize }, - 196usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(ext_ramdisk_size))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).ext_cmd_line_ptr as *const _ as usize }, - 200usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(ext_cmd_line_ptr))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad4 as *const _ as usize }, - 204usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad4))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).edid_info as *const _ as usize }, - 320usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(edid_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).efi_info as *const _ as usize }, - 448usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(efi_info))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).alt_mem_k as *const _ as usize }, - 480usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(alt_mem_k))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).scratch as *const _ as usize }, - 484usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(scratch))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).e820_entries as *const _ as usize }, - 488usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(e820_entries))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).eddbuf_entries as *const _ as usize }, - 489usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(eddbuf_entries))); - assert_eq!(unsafe { - &(*(0 as *const boot_params)).edd_mbr_sig_buf_entries as *const _ as usize - }, - 490usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(edd_mbr_sig_buf_entries))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).kbd_status as *const _ as usize }, - 491usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(kbd_status))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad5 as *const _ as usize }, - 492usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad5))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).sentinel as *const _ as usize }, - 495usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(sentinel))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad6 as *const _ as usize }, - 496usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad6))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).hdr as *const _ as usize }, - 497usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(hdr))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad7 as *const _ as usize }, - 616usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad7))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).edd_mbr_sig_buffer as *const _ as usize }, - 656usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(edd_mbr_sig_buffer))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).e820_map as *const _ as usize }, - 720usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(e820_map))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad8 as *const _ as usize }, - 3280usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad8))); - assert_eq!(unsafe { &(*(0 as *const boot_params)).eddbuf as *const _ as usize }, - 3328usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(eddbuf))); - assert_eq!(unsafe { &(*(0 as *const boot_params))._pad9 as *const _ as usize }, - 3820usize, - concat!("Alignment of field: ", - stringify!(boot_params), - "::", - stringify!(_pad9))); + assert_eq!( + ::std::mem::size_of::<boot_params>(), + 4096usize, + concat!("Size of: ", stringify!(boot_params)) + ); + assert_eq!( + ::std::mem::align_of::<boot_params>(), + 1usize, + concat!("Alignment of ", stringify!(boot_params)) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).screen_info as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(screen_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).apm_bios_info as *const _ as usize }, + 64usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(apm_bios_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad2 as *const _ as usize }, + 84usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad2) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).tboot_addr as *const _ as usize }, + 88usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(tboot_addr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).ist_info as *const _ as usize }, + 96usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(ist_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad3 as *const _ as usize }, + 112usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad3) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).hd0_info as *const _ as usize }, + 128usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(hd0_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).hd1_info as *const _ as usize }, + 144usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(hd1_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).sys_desc_table as *const _ as usize }, + 160usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(sys_desc_table) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).olpc_ofw_header as *const _ as usize }, + 176usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(olpc_ofw_header) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).ext_ramdisk_image as *const _ as usize }, + 192usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(ext_ramdisk_image) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).ext_ramdisk_size as *const _ as usize }, + 196usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(ext_ramdisk_size) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).ext_cmd_line_ptr as *const _ as usize }, + 200usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(ext_cmd_line_ptr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad4 as *const _ as usize }, + 204usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad4) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).edid_info as *const _ as usize }, + 320usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(edid_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).efi_info as *const _ as usize }, + 448usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(efi_info) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).alt_mem_k as *const _ as usize }, + 480usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(alt_mem_k) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).scratch as *const _ as usize }, + 484usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(scratch) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).e820_entries as *const _ as usize }, + 488usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(e820_entries) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).eddbuf_entries as *const _ as usize }, + 489usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(eddbuf_entries) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).edd_mbr_sig_buf_entries as *const _ as usize }, + 490usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(edd_mbr_sig_buf_entries) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).kbd_status as *const _ as usize }, + 491usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(kbd_status) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad5 as *const _ as usize }, + 492usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad5) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).sentinel as *const _ as usize }, + 495usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(sentinel) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad6 as *const _ as usize }, + 496usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad6) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).hdr as *const _ as usize }, + 497usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(hdr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad7 as *const _ as usize }, + 616usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad7) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).edd_mbr_sig_buffer as *const _ as usize }, + 656usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(edd_mbr_sig_buffer) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).e820_map as *const _ as usize }, + 720usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(e820_map) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad8 as *const _ as usize }, + 3280usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad8) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params)).eddbuf as *const _ as usize }, + 3328usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(eddbuf) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const boot_params))._pad9 as *const _ as usize }, + 3820usize, + concat!( + "Alignment of field: ", + stringify!(boot_params), + "::", + stringify!(_pad9) + ) + ); } impl Default for boot_params { fn default() -> Self { diff --git a/x86_64/src/cpuid.rs b/x86_64/src/cpuid.rs index 36a2b28..0cfa32e 100644 --- a/x86_64/src/cpuid.rs +++ b/x86_64/src/cpuid.rs @@ -2,9 +2,9 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::result; -use std::fmt::{self, Display}; use std::error::{self, Error as CpuidError}; +use std::fmt::{self, Display}; +use std::result; use kvm; use sys_util; @@ -19,10 +19,8 @@ pub type Result<T> = result::Result<T, Error>; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::GetSupportedCpusFailed(_) => - "GetSupportedCpus ioctl failed", - &Error::SetSupportedCpusFailed(_) => - "SetSupportedCpus ioctl failed", + &Error::GetSupportedCpusFailed(_) => "GetSupportedCpus ioctl failed", + &Error::SetSupportedCpusFailed(_) => "SetSupportedCpus ioctl failed", } } } @@ -36,16 +34,16 @@ impl Display for Error { // This function is implemented in C because stable rustc does not // support inline assembly. extern "C" { - fn host_cpuid(func: u32, - func2: u32, - rEax: *mut u32, - rEbx: *mut u32, - rEcx: *mut u32, - rEdx: *mut u32) - -> (); + fn host_cpuid( + func: u32, + func2: u32, + rEax: *mut u32, + rEbx: *mut u32, + rEcx: *mut u32, + rEdx: *mut u32, + ) -> (); } - // CPUID bits in ebx, ecx, and edx. const EBX_CLFLUSH_CACHELINE: u32 = 8; // Flush a cache line size. const EBX_CLFLUSH_SIZE_SHIFT: u32 = 8; // Bytes flushed when executing CLFLUSH. @@ -65,31 +63,33 @@ fn filter_cpuid(cpu_id: u64, cpu_count: u64, kvm_cpuid: &mut kvm::CpuId) -> Resu if entry.index == 0 { entry.ecx |= 1 << ECX_HYPERVISOR_SHIFT; } - entry.ebx = (cpu_id << EBX_CPUID_SHIFT) as u32 | - (EBX_CLFLUSH_CACHELINE << EBX_CLFLUSH_SIZE_SHIFT); + entry.ebx = (cpu_id << EBX_CPUID_SHIFT) as u32 + | (EBX_CLFLUSH_CACHELINE << EBX_CLFLUSH_SIZE_SHIFT); if cpu_count > 1 { entry.ebx |= (cpu_count as u32) << EBX_CPU_COUNT_SHIFT; entry.edx |= 1 << EDX_HTT_SHIFT; } } - 2 | 0x80000005 | 0x80000006 => { - unsafe { - host_cpuid(entry.function, - 0, - &mut entry.eax as *mut u32, - &mut entry.ebx as *mut u32, - &mut entry.ecx as *mut u32, - &mut entry.edx as *mut u32); - } - } + 2 | 0x80000005 | 0x80000006 => unsafe { + host_cpuid( + entry.function, + 0, + &mut entry.eax as *mut u32, + &mut entry.ebx as *mut u32, + &mut entry.ecx as *mut u32, + &mut entry.edx as *mut u32, + ); + }, 4 => { unsafe { - host_cpuid(entry.function, - entry.index, - &mut entry.eax as *mut u32, - &mut entry.ebx as *mut u32, - &mut entry.ecx as *mut u32, - &mut entry.edx as *mut u32); + host_cpuid( + entry.function, + entry.index, + &mut entry.eax as *mut u32, + &mut entry.ebx as *mut u32, + &mut entry.ecx as *mut u32, + &mut entry.edx as *mut u32, + ); } entry.eax &= !0xFC000000; } @@ -114,7 +114,8 @@ fn filter_cpuid(cpu_id: u64, cpu_count: u64, kvm_cpuid: &mut kvm::CpuId) -> Resu /// * `cpu_id` - The index of the CPU `vcpu` is for. /// * `nrcpus` - The number of vcpus being used by this VM. pub fn setup_cpuid(kvm: &kvm::Kvm, vcpu: &kvm::Vcpu, cpu_id: u64, nrcpus: u64) -> Result<()> { - let mut kvm_cpuid = kvm.get_supported_cpuid() + let mut kvm_cpuid = kvm + .get_supported_cpuid() .map_err(Error::GetSupportedCpusFailed)?; filter_cpuid(cpu_id, nrcpus, &mut kvm_cpuid)?; @@ -144,8 +145,10 @@ mod tests { assert_eq!(entries[0].function, 0); assert_eq!(1, (entries[1].ebx >> EBX_CPUID_SHIFT) & 0x000000ff); assert_eq!(2, (entries[1].ebx >> EBX_CPU_COUNT_SHIFT) & 0x000000ff); - assert_eq!(EBX_CLFLUSH_CACHELINE, - (entries[1].ebx >> EBX_CLFLUSH_SIZE_SHIFT) & 0x000000ff); + assert_eq!( + EBX_CLFLUSH_CACHELINE, + (entries[1].ebx >> EBX_CLFLUSH_SIZE_SHIFT) & 0x000000ff + ); assert_ne!(0, entries[1].ecx & (1 << ECX_HYPERVISOR_SHIFT)); assert_ne!(0, entries[1].edx & (1 << EDX_HTT_SHIFT)); } diff --git a/x86_64/src/gdt.rs b/x86_64/src/gdt.rs index 06af094..7eb1ff7 100644 --- a/x86_64/src/gdt.rs +++ b/x86_64/src/gdt.rs @@ -8,18 +8,21 @@ use kvm_sys::kvm_segment; /// Constructor for a conventional segment GDT (or LDT) entry. Derived from the kernel's segment.h. pub fn gdt_entry(flags: u16, base: u32, limit: u32) -> u64 { - ((((base as u64) & 0xff000000u64) << (56 - 24)) | (((flags as u64) & 0x0000f0ffu64) << 40) | - (((limit as u64) & 0x000f0000u64) << (48 - 16)) | - (((base as u64) & 0x00ffffffu64) << 16) | (((limit as u64) & 0x0000ffffu64))) + ((((base as u64) & 0xff000000u64) << (56 - 24)) + | (((flags as u64) & 0x0000f0ffu64) << 40) + | (((limit as u64) & 0x000f0000u64) << (48 - 16)) + | (((base as u64) & 0x00ffffffu64) << 16) + | ((limit as u64) & 0x0000ffffu64)) } fn get_base(entry: u64) -> u64 { - ((((entry) & 0xFF00000000000000) >> 32) | (((entry) & 0x000000FF00000000) >> 16) | - (((entry) & 0x00000000FFFF0000) >> 16)) + ((((entry) & 0xFF00000000000000) >> 32) + | (((entry) & 0x000000FF00000000) >> 16) + | (((entry) & 0x00000000FFFF0000) >> 16)) } fn get_limit(entry: u64) -> u32 { - ((((entry) & 0x000F000000000000) >> 32) | (((entry) & 0x000000000000FFFF))) as u32 + ((((entry) & 0x000F000000000000) >> 32) | ((entry) & 0x000000000000FFFF)) as u32 } fn get_g(entry: u64) -> u8 { diff --git a/x86_64/src/interrupts.rs b/x86_64/src/interrupts.rs index 65bc621..5c469c8 100644 --- a/x86_64/src/interrupts.rs +++ b/x86_64/src/interrupts.rs @@ -2,11 +2,11 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::error::{self, Error as InterruptsError}; +use std::fmt::{self, Display}; use std::io::Cursor; use std::mem; use std::result; -use std::error::{self, Error as InterruptsError}; -use std::fmt::{self, Display}; use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt}; @@ -76,13 +76,17 @@ pub fn set_lint(vcpu: &kvm::Vcpu) -> Result<()> { let mut klapic = vcpu.get_lapic().map_err(Error::GetLapic)?; let lvt_lint0 = get_klapic_reg(&klapic, APIC_LVT0); - set_klapic_reg(&mut klapic, - APIC_LVT0, - set_apic_delivery_mode(lvt_lint0, APIC_MODE_EXTINT)); + set_klapic_reg( + &mut klapic, + APIC_LVT0, + set_apic_delivery_mode(lvt_lint0, APIC_MODE_EXTINT), + ); let lvt_lint1 = get_klapic_reg(&klapic, APIC_LVT1); - set_klapic_reg(&mut klapic, - APIC_LVT1, - set_apic_delivery_mode(lvt_lint1, APIC_MODE_NMI)); + set_klapic_reg( + &mut klapic, + APIC_LVT1, + set_apic_delivery_mode(lvt_lint1, APIC_MODE_NMI), + ); vcpu.set_lapic(&klapic).map_err(Error::SetLapic) } diff --git a/x86_64/src/lib.rs b/x86_64/src/lib.rs index a372a95..244aa45 100644 --- a/x86_64/src/lib.rs +++ b/x86_64/src/lib.rs @@ -6,13 +6,13 @@ extern crate arch; extern crate byteorder; extern crate data_model; extern crate devices; +extern crate kernel_cmdline; +extern crate kernel_loader; extern crate kvm; extern crate kvm_sys; extern crate libc; -extern crate sys_util; extern crate resources; -extern crate kernel_cmdline; -extern crate kernel_loader; +extern crate sys_util; #[allow(dead_code)] #[allow(non_upper_case_globals)] @@ -58,22 +58,22 @@ mod interrupts; mod mptable; mod regs; -use std::mem; -use std::result; use std::error::{self, Error as X86Error}; +use std::ffi::{CStr, CString}; use std::fmt::{self, Display}; use std::fs::File; -use std::ffi::{CStr, CString}; use std::io::{self, stdout}; +use std::mem; +use std::result; use std::sync::{Arc, Mutex}; use arch::{RunnableLinuxVm, VirtioDeviceStub, VmComponents}; use bootparam::boot_params; use bootparam::E820_RAM; use devices::{PciConfigIo, PciInterruptPin}; -use sys_util::{EventFd, GuestAddress, GuestMemory}; -use resources::{AddressRanges, SystemAllocator}; use kvm::*; +use resources::{AddressRanges, SystemAllocator}; +use sys_util::{EventFd, GuestAddress, GuestMemory}; #[derive(Debug)] pub enum Error { @@ -120,16 +120,13 @@ impl error::Error for Error { &Error::CreatePciRoot(_) => "failed to create a PCI root hub", &Error::CreateSocket(_) => "failed to create socket", &Error::CreateVcpu(_) => "failed to create VCPU", - &Error::KernelOffsetPastEnd => - "The kernel extends past the end of RAM", + &Error::KernelOffsetPastEnd => "The kernel extends past the end of RAM", &Error::RegisterIrqfd(_) => "Error registering an IrqFd", &Error::RegisterVsock(_) => "error registering virtual socket device", &Error::LoadCmdline(_) => "Error Loading command line", &Error::LoadKernel(_) => "Error Loading Kernel", - &Error::ZeroPageSetup => - "Error writing the zero page of guest memory", - &Error::ZeroPagePastRamEnd => - "The zero page extends past the end of guest_mem", + &Error::ZeroPageSetup => "Error writing the zero page of guest memory", + &Error::ZeroPagePastRamEnd => "The zero page extends past the end of guest_mem", &Error::E820Configuration => "Invalid e820 setup params", } } @@ -155,13 +152,14 @@ const CMDLINE_OFFSET: u64 = 0x20000; const CMDLINE_MAX_SIZE: u64 = KERNEL_START_OFFSET - CMDLINE_OFFSET; const X86_64_IRQ_BASE: u32 = 5; -fn configure_system(guest_mem: &GuestMemory, - kernel_addr: GuestAddress, - cmdline_addr: GuestAddress, - cmdline_size: usize, - num_cpus: u8, - pci_irqs: Vec<(u32, PciInterruptPin)>) - -> Result<()> { +fn configure_system( + guest_mem: &GuestMemory, + kernel_addr: GuestAddress, + cmdline_addr: GuestAddress, + cmdline_size: usize, + num_cpus: u8, + pci_irqs: Vec<(u32, PciInterruptPin)>, +) -> Result<()> { const EBDA_START: u64 = 0x0009fc00; const KERNEL_BOOT_FLAG_MAGIC: u16 = 0xaa55; const KERNEL_HDR_MAGIC: u32 = 0x53726448; @@ -186,27 +184,35 @@ fn configure_system(guest_mem: &GuestMemory, let mem_end = guest_mem.end_addr(); if mem_end < end_32bit_gap_start { - add_e820_entry(&mut params, - kernel_addr.offset() as u64, - mem_end.offset_from(kernel_addr) as u64, - E820_RAM)?; + add_e820_entry( + &mut params, + kernel_addr.offset() as u64, + mem_end.offset_from(kernel_addr) as u64, + E820_RAM, + )?; } else { - add_e820_entry(&mut params, - kernel_addr.offset() as u64, - end_32bit_gap_start.offset_from(kernel_addr) as u64, - E820_RAM)?; + add_e820_entry( + &mut params, + kernel_addr.offset() as u64, + end_32bit_gap_start.offset_from(kernel_addr) as u64, + E820_RAM, + )?; if mem_end > first_addr_past_32bits { - add_e820_entry(&mut params, - first_addr_past_32bits.offset() as u64, - mem_end.offset_from(first_addr_past_32bits) as u64, - E820_RAM)?; + add_e820_entry( + &mut params, + first_addr_past_32bits.offset() as u64, + mem_end.offset_from(first_addr_past_32bits) as u64, + E820_RAM, + )?; } } let zero_page_addr = GuestAddress(ZERO_PAGE_OFFSET); - guest_mem.checked_offset(zero_page_addr, mem::size_of::<boot_params>() as u64) + guest_mem + .checked_offset(zero_page_addr, mem::size_of::<boot_params>() as u64) .ok_or(Error::ZeroPagePastRamEnd)?; - guest_mem.write_obj_at_addr(params, zero_page_addr) + guest_mem + .write_obj_at_addr(params, zero_page_addr) .map_err(|_| Error::ZeroPageSetup)?; Ok(()) @@ -242,7 +248,10 @@ fn arch_memory_regions(size: u64) -> Vec<(GuestAddress, u64)> { } else { regions.push((GuestAddress(0), end_32bit_gap_start.offset())); if mem_end > first_addr_past_32bits { - regions.push((first_addr_past_32bits, mem_end.offset_from(first_addr_past_32bits))); + regions.push(( + first_addr_past_32bits, + mem_end.offset_from(first_addr_past_32bits), + )); } } @@ -251,11 +260,11 @@ fn arch_memory_regions(size: u64) -> Vec<(GuestAddress, u64)> { impl arch::LinuxArch for X8664arch { fn build_vm<F>(mut components: VmComponents, virtio_devs: F) -> Result<RunnableLinuxVm> - where - F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<VirtioDeviceStub>> + where + F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<VirtioDeviceStub>>, { - let mut resources = Self::get_resource_allocator(components.memory_mb, - components.wayland_dmabuf); + let mut resources = + Self::get_resource_allocator(components.memory_mb, components.wayland_dmabuf); let mem = Self::setup_memory(components.memory_mb)?; let kvm = Kvm::new().map_err(Error::CreateKvm)?; let mut vm = Self::create_vm(&kvm, mem.clone())?; @@ -263,10 +272,15 @@ impl arch::LinuxArch for X8664arch { let vcpu_count = components.vcpu_count; let mut vcpus = Vec::with_capacity(vcpu_count as usize); for cpu_id in 0..vcpu_count { - let vcpu = Vcpu::new(cpu_id as libc::c_ulong, &kvm, &vm) - .map_err(Error::CreateVcpu)?; - Self::configure_vcpu(vm.get_memory(), &kvm, &vm, &vcpu, - cpu_id as u64, vcpu_count as u64)?; + let vcpu = Vcpu::new(cpu_id as libc::c_ulong, &kvm, &vm).map_err(Error::CreateVcpu)?; + Self::configure_vcpu( + vm.get_memory(), + &kvm, + &vm, + &vcpu, + cpu_id as u64, + vcpu_count as u64, + )?; vcpus.push(vcpu); } @@ -275,27 +289,33 @@ impl arch::LinuxArch for X8664arch { let mut mmio_bus = devices::Bus::new(); - let (pci, pci_irqs) = arch::generate_pci_root(components.pci_devices, - &mut mmio_bus, - &mut resources, - &mut vm) - .map_err(Error::CreatePciRoot)?; + let (pci, pci_irqs) = arch::generate_pci_root( + components.pci_devices, + &mut mmio_bus, + &mut resources, + &mut vm, + ).map_err(Error::CreatePciRoot)?; let pci_bus = Arc::new(Mutex::new(PciConfigIo::new(pci))); let exit_evt = EventFd::new().map_err(Error::CreateEventFd)?; let (io_bus, stdio_serial) = Self::setup_io_bus( &mut vm, exit_evt.try_clone().map_err(Error::CloneEventFd)?, - Some(pci_bus.clone()))?; - + Some(pci_bus.clone()), + )?; // Create a list of mmio devices to be added. let mmio_devs = virtio_devs(&mem, &exit_evt)?; for stub in mmio_devs { - arch::register_mmio(&mut mmio_bus, &mut vm, stub.dev, stub.jail, - &mut resources, &mut cmdline) - .map_err(Error::RegisterVsock)?; + arch::register_mmio( + &mut mmio_bus, + &mut vm, + stub.dev, + stub.jail, + &mut resources, + &mut cmdline, + ).map_err(Error::RegisterVsock)?; } for param in components.extra_kernel_params { @@ -305,8 +325,13 @@ impl arch::LinuxArch for X8664arch { // separate out load_kernel from other setup to get a specific error for // kernel loading Self::load_kernel(&mem, &mut components.kernel_image)?; - Self::setup_system_memory(&mem, components.memory_mb, vcpu_count, - &CString::new(cmdline).unwrap(), pci_irqs)?; + Self::setup_system_memory( + &mem, + components.memory_mb, + vcpu_count, + &CString::new(cmdline).unwrap(), + pci_irqs, + )?; Ok(RunnableLinuxVm { vm, @@ -330,8 +355,7 @@ impl X8664arch { /// * `mem` - The memory to be used by the guest. /// * `kernel_image` - the File object for the specified kernel. fn load_kernel(mem: &GuestMemory, mut kernel_image: &mut File) -> Result<()> { - kernel_loader::load_kernel(mem, GuestAddress(KERNEL_START_OFFSET), - &mut kernel_image)?; + kernel_loader::load_kernel(mem, GuestAddress(KERNEL_START_OFFSET), &mut kernel_image)?; Ok(()) } @@ -343,13 +367,22 @@ impl X8664arch { /// * `mem` - The memory to be used by the guest. /// * `vcpu_count` - Number of virtual CPUs the guest will have. /// * `cmdline` - the kernel commandline - fn setup_system_memory(mem: &GuestMemory, _mem_size: u64, - vcpu_count: u32, cmdline: &CStr, - pci_irqs: Vec<(u32, PciInterruptPin)>) -> Result<()> { + fn setup_system_memory( + mem: &GuestMemory, + _mem_size: u64, + vcpu_count: u32, + cmdline: &CStr, + pci_irqs: Vec<(u32, PciInterruptPin)>, + ) -> Result<()> { kernel_loader::load_cmdline(mem, GuestAddress(CMDLINE_OFFSET), cmdline)?; - configure_system(mem, GuestAddress(KERNEL_START_OFFSET), - GuestAddress(CMDLINE_OFFSET), - cmdline.to_bytes().len() + 1, vcpu_count as u8, pci_irqs)?; + configure_system( + mem, + GuestAddress(KERNEL_START_OFFSET), + GuestAddress(CMDLINE_OFFSET), + cmdline.to_bytes().len() + 1, + vcpu_count as u8, + pci_irqs, + )?; Ok(()) } @@ -400,15 +433,16 @@ impl X8664arch { // Put device memory at a 2MB boundary after physical memory or 4gb, whichever is greater. const MB: u64 = 1024 * 1024; const GB: u64 = 1024 * MB; - let mem_size_round_2mb = (mem_size + 2*MB - 1) / (2*MB) * (2*MB); + let mem_size_round_2mb = (mem_size + 2 * MB - 1) / (2 * MB) * (2 * MB); std::cmp::max(mem_size_round_2mb, 4 * GB) / sys_util::pagesize() as u64 } /// This returns a minimal kernel command for this architecture fn get_base_linux_cmdline() -> kernel_cmdline::Cmdline { let mut cmdline = kernel_cmdline::Cmdline::new(CMDLINE_MAX_SIZE as usize); - cmdline.insert_str("console=ttyS0 noacpi reboot=k panic=1"). - unwrap(); + cmdline + .insert_str("console=ttyS0 noacpi reboot=k panic=1") + .unwrap(); cmdline } @@ -417,10 +451,11 @@ impl X8664arch { const MMIO_BASE: u64 = 0xe0000000; let device_addr_start = Self::get_base_dev_pfn(mem_size) * sys_util::pagesize() as u64; AddressRanges::new() - .add_io_addresses(0xc000, 0x10000) - .add_mmio_addresses(MMIO_BASE, 0x100000) - .add_device_addresses(device_addr_start, u64::max_value() - device_addr_start) - .create_allocator(X86_64_IRQ_BASE, gpu_allocation).unwrap() + .add_io_addresses(0xc000, 0x10000) + .add_mmio_addresses(MMIO_BASE, 0x100000) + .add_device_addresses(device_addr_start, u64::max_value() - device_addr_start) + .create_allocator(X86_64_IRQ_BASE, gpu_allocation) + .unwrap() } /// Sets up the IO bus for this platform @@ -429,8 +464,11 @@ impl X8664arch { /// /// * - `vm` the vm object /// * - `exit_evt` - the event fd object which should receive exit events - fn setup_io_bus(vm: &mut Vm, exit_evt: EventFd, pci: Option<Arc<Mutex<devices::PciConfigIo>>>) - -> Result<(devices::Bus, Arc<Mutex<devices::Serial>>)> { + fn setup_io_bus( + vm: &mut Vm, + exit_evt: EventFd, + pci: Option<Arc<Mutex<devices::PciConfigIo>>>, + ) -> Result<(devices::Bus, Arc<Mutex<devices::Serial>>)> { struct NoDevice; impl devices::BusDevice for NoDevice {} @@ -438,56 +476,84 @@ impl X8664arch { let com_evt_1_3 = EventFd::new().map_err(|e| Error::CreateEventFd(e))?; let com_evt_2_4 = EventFd::new().map_err(|e| Error::CreateEventFd(e))?; - let stdio_serial = - Arc::new(Mutex::new( - devices::Serial::new_out(com_evt_1_3.try_clone(). - map_err(|e| Error::CloneEventFd(e))?, - Box::new(stdout())))); + let stdio_serial = Arc::new(Mutex::new(devices::Serial::new_out( + com_evt_1_3 + .try_clone() + .map_err(|e| Error::CloneEventFd(e))?, + Box::new(stdout()), + ))); let nul_device = Arc::new(Mutex::new(NoDevice)); - io_bus.insert(stdio_serial.clone(), 0x3f8, 0x8, false).unwrap(); - io_bus.insert(Arc::new(Mutex::new( - devices::Serial::new_sink(com_evt_2_4.try_clone(). - map_err(|e| Error::CloneEventFd(e))?))), - 0x2f8, - 0x8, - false) - .unwrap(); - io_bus.insert(Arc::new(Mutex::new( - devices::Serial::new_sink(com_evt_1_3.try_clone(). - map_err(|e| Error::CloneEventFd(e))?))), - 0x3e8, - 0x8, - false) + io_bus + .insert(stdio_serial.clone(), 0x3f8, 0x8, false) .unwrap(); - io_bus.insert(Arc::new(Mutex::new( - devices::Serial::new_sink(com_evt_2_4.try_clone(). - map_err(|e| Error::CloneEventFd(e))?))), - 0x2e8, - 0x8, - false) + io_bus + .insert( + Arc::new(Mutex::new(devices::Serial::new_sink( + com_evt_2_4 + .try_clone() + .map_err(|e| Error::CloneEventFd(e))?, + ))), + 0x2f8, + 0x8, + false, + ).unwrap(); + io_bus + .insert( + Arc::new(Mutex::new(devices::Serial::new_sink( + com_evt_1_3 + .try_clone() + .map_err(|e| Error::CloneEventFd(e))?, + ))), + 0x3e8, + 0x8, + false, + ).unwrap(); + io_bus + .insert( + Arc::new(Mutex::new(devices::Serial::new_sink( + com_evt_2_4 + .try_clone() + .map_err(|e| Error::CloneEventFd(e))?, + ))), + 0x2e8, + 0x8, + false, + ).unwrap(); + io_bus + .insert(Arc::new(Mutex::new(devices::Cmos::new())), 0x70, 0x2, false) .unwrap(); - io_bus.insert(Arc::new(Mutex::new(devices::Cmos::new())), 0x70, 0x2, false) - .unwrap(); - io_bus.insert(Arc::new(Mutex::new( - devices::I8042Device::new(exit_evt.try_clone(). - map_err(|e| Error::CloneEventFd(e))?))), - 0x061, - 0x4, - false) - .unwrap(); - io_bus.insert(nul_device.clone(), 0x040, 0x8, false).unwrap(); // ignore pit - io_bus.insert(nul_device.clone(), 0x0ed, 0x1, false).unwrap(); // most likely this one does nothing - io_bus.insert(nul_device.clone(), 0x0f0, 0x2, false).unwrap(); // ignore fpu + io_bus + .insert( + Arc::new(Mutex::new(devices::I8042Device::new( + exit_evt.try_clone().map_err(|e| Error::CloneEventFd(e))?, + ))), + 0x061, + 0x4, + false, + ).unwrap(); + io_bus + .insert(nul_device.clone(), 0x040, 0x8, false) + .unwrap(); // ignore pit + io_bus + .insert(nul_device.clone(), 0x0ed, 0x1, false) + .unwrap(); // most likely this one does nothing + io_bus + .insert(nul_device.clone(), 0x0f0, 0x2, false) + .unwrap(); // ignore fpu if let Some(pci_root) = pci { io_bus.insert(pci_root, 0xcf8, 0x8, false).unwrap(); } else { // ignore pci. - io_bus.insert(nul_device.clone(), 0xcf8, 0x8, false).unwrap(); + io_bus + .insert(nul_device.clone(), 0xcf8, 0x8, false) + .unwrap(); } - vm.register_irqfd(&com_evt_1_3, 4).map_err(Error::RegisterIrqfd)?; - vm.register_irqfd(&com_evt_2_4, 3).map_err(Error::RegisterIrqfd)?; + vm.register_irqfd(&com_evt_1_3, 4) + .map_err(Error::RegisterIrqfd)?; + vm.register_irqfd(&com_evt_2_4, 3) + .map_err(Error::RegisterIrqfd)?; Ok((io_bus, stdio_serial)) } @@ -504,28 +570,31 @@ impl X8664arch { /// * `vcpu` - The VCPU object to configure. /// * `cpu_id` - The id of the given `vcpu`. /// * `num_cpus` - Number of virtual CPUs the guest will have. - fn configure_vcpu(guest_mem: &GuestMemory, - kvm: &Kvm, - _vm: &Vm, - vcpu: &Vcpu, - cpu_id: u64, - num_cpus: u64) - -> Result<()> { + fn configure_vcpu( + guest_mem: &GuestMemory, + kvm: &Kvm, + _vm: &Vm, + vcpu: &Vcpu, + cpu_id: u64, + num_cpus: u64, + ) -> Result<()> { let kernel_load_addr = GuestAddress(KERNEL_START_OFFSET); cpuid::setup_cpuid(kvm, vcpu, cpu_id, num_cpus)?; regs::setup_msrs(vcpu)?; - let kernel_end = guest_mem.checked_offset(kernel_load_addr, KERNEL_64BIT_ENTRY_OFFSET) + let kernel_end = guest_mem + .checked_offset(kernel_load_addr, KERNEL_64BIT_ENTRY_OFFSET) .ok_or(Error::KernelOffsetPastEnd)?; - regs::setup_regs(vcpu, - (kernel_end).offset() as u64, - BOOT_STACK_POINTER as u64, - ZERO_PAGE_OFFSET as u64)?; + regs::setup_regs( + vcpu, + (kernel_end).offset() as u64, + BOOT_STACK_POINTER as u64, + ZERO_PAGE_OFFSET as u64, + )?; regs::setup_fpu(vcpu)?; regs::setup_sregs(guest_mem, vcpu)?; interrupts::set_lint(vcpu)?; Ok(()) } - } #[cfg(test)] mod tests { diff --git a/x86_64/src/mpspec.rs b/x86_64/src/mpspec.rs index a418207..8106ef0 100644 --- a/x86_64/src/mpspec.rs +++ b/x86_64/src/mpspec.rs @@ -52,72 +52,116 @@ pub struct mpf_intel { } #[test] fn bindgen_test_layout_mpf_intel() { - assert_eq!(::std::mem::size_of::<mpf_intel>(), - 16usize, - concat!("Size of: ", stringify!(mpf_intel))); - assert_eq!(::std::mem::align_of::<mpf_intel>(), - 4usize, - concat!("Alignment of ", stringify!(mpf_intel))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).signature as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(signature))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).physptr as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(physptr))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).length as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(length))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).specification as *const _ as usize }, - 9usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(specification))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).checksum as *const _ as usize }, - 10usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(checksum))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).feature1 as *const _ as usize }, - 11usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(feature1))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).feature2 as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(feature2))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).feature3 as *const _ as usize }, - 13usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(feature3))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).feature4 as *const _ as usize }, - 14usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(feature4))); - assert_eq!(unsafe { &(*(0 as *const mpf_intel)).feature5 as *const _ as usize }, - 15usize, - concat!("Alignment of field: ", - stringify!(mpf_intel), - "::", - stringify!(feature5))); + assert_eq!( + ::std::mem::size_of::<mpf_intel>(), + 16usize, + concat!("Size of: ", stringify!(mpf_intel)) + ); + assert_eq!( + ::std::mem::align_of::<mpf_intel>(), + 4usize, + concat!("Alignment of ", stringify!(mpf_intel)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).signature as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(signature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).physptr as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(physptr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).length as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).specification as *const _ as usize }, + 9usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(specification) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).checksum as *const _ as usize }, + 10usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(checksum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).feature1 as *const _ as usize }, + 11usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(feature1) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).feature2 as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(feature2) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).feature3 as *const _ as usize }, + 13usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(feature3) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).feature4 as *const _ as usize }, + 14usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(feature4) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpf_intel)).feature5 as *const _ as usize }, + 15usize, + concat!( + "Alignment of field: ", + stringify!(mpf_intel), + "::", + stringify!(feature5) + ) + ); } impl Clone for mpf_intel { fn clone(&self) -> Self { @@ -141,78 +185,126 @@ pub struct mpc_table { } #[test] fn bindgen_test_layout_mpc_table() { - assert_eq!(::std::mem::size_of::<mpc_table>(), - 44usize, - concat!("Size of: ", stringify!(mpc_table))); - assert_eq!(::std::mem::align_of::<mpc_table>(), - 4usize, - concat!("Alignment of ", stringify!(mpc_table))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).signature as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(signature))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).length as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(length))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).spec as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(spec))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).checksum as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(checksum))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).oem as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(oem))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).productid as *const _ as usize }, - 16usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(productid))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).oemptr as *const _ as usize }, - 28usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(oemptr))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).oemsize as *const _ as usize }, - 32usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(oemsize))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).oemcount as *const _ as usize }, - 34usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(oemcount))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).lapic as *const _ as usize }, - 36usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(lapic))); - assert_eq!(unsafe { &(*(0 as *const mpc_table)).reserved as *const _ as usize }, - 40usize, - concat!("Alignment of field: ", - stringify!(mpc_table), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<mpc_table>(), + 44usize, + concat!("Size of: ", stringify!(mpc_table)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_table>(), + 4usize, + concat!("Alignment of ", stringify!(mpc_table)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).signature as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(signature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).length as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).spec as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(spec) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).checksum as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(checksum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).oem as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(oem) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).productid as *const _ as usize }, + 16usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(productid) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).oemptr as *const _ as usize }, + 28usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(oemptr) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).oemsize as *const _ as usize }, + 32usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(oemsize) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).oemcount as *const _ as usize }, + 34usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(oemcount) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).lapic as *const _ as usize }, + 36usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(lapic) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_table)).reserved as *const _ as usize }, + 40usize, + concat!( + "Alignment of field: ", + stringify!(mpc_table), + "::", + stringify!(reserved) + ) + ); } impl Clone for mpc_table { fn clone(&self) -> Self { @@ -232,54 +324,86 @@ pub struct mpc_cpu { } #[test] fn bindgen_test_layout_mpc_cpu() { - assert_eq!(::std::mem::size_of::<mpc_cpu>(), - 20usize, - concat!("Size of: ", stringify!(mpc_cpu))); - assert_eq!(::std::mem::align_of::<mpc_cpu>(), - 4usize, - concat!("Alignment of ", stringify!(mpc_cpu))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).type_ as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(type_))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).apicid as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(apicid))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).apicver as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(apicver))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).cpuflag as *const _ as usize }, - 3usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(cpuflag))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).cpufeature as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(cpufeature))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).featureflag as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(featureflag))); - assert_eq!(unsafe { &(*(0 as *const mpc_cpu)).reserved as *const _ as usize }, - 12usize, - concat!("Alignment of field: ", - stringify!(mpc_cpu), - "::", - stringify!(reserved))); + assert_eq!( + ::std::mem::size_of::<mpc_cpu>(), + 20usize, + concat!("Size of: ", stringify!(mpc_cpu)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_cpu>(), + 4usize, + concat!("Alignment of ", stringify!(mpc_cpu)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).type_ as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).apicid as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(apicid) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).apicver as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(apicver) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).cpuflag as *const _ as usize }, + 3usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(cpuflag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).cpufeature as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(cpufeature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).featureflag as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(featureflag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_cpu)).reserved as *const _ as usize }, + 12usize, + concat!( + "Alignment of field: ", + stringify!(mpc_cpu), + "::", + stringify!(reserved) + ) + ); } impl Clone for mpc_cpu { fn clone(&self) -> Self { @@ -295,30 +419,46 @@ pub struct mpc_bus { } #[test] fn bindgen_test_layout_mpc_bus() { - assert_eq!(::std::mem::size_of::<mpc_bus>(), - 8usize, - concat!("Size of: ", stringify!(mpc_bus))); - assert_eq!(::std::mem::align_of::<mpc_bus>(), - 1usize, - concat!("Alignment of ", stringify!(mpc_bus))); - assert_eq!(unsafe { &(*(0 as *const mpc_bus)).type_ as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_bus), - "::", - stringify!(type_))); - assert_eq!(unsafe { &(*(0 as *const mpc_bus)).busid as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(mpc_bus), - "::", - stringify!(busid))); - assert_eq!(unsafe { &(*(0 as *const mpc_bus)).bustype as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(mpc_bus), - "::", - stringify!(bustype))); + assert_eq!( + ::std::mem::size_of::<mpc_bus>(), + 8usize, + concat!("Size of: ", stringify!(mpc_bus)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_bus>(), + 1usize, + concat!("Alignment of ", stringify!(mpc_bus)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_bus)).type_ as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_bus), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_bus)).busid as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(mpc_bus), + "::", + stringify!(busid) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_bus)).bustype as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(mpc_bus), + "::", + stringify!(bustype) + ) + ); } impl Clone for mpc_bus { fn clone(&self) -> Self { @@ -336,42 +476,66 @@ pub struct mpc_ioapic { } #[test] fn bindgen_test_layout_mpc_ioapic() { - assert_eq!(::std::mem::size_of::<mpc_ioapic>(), - 8usize, - concat!("Size of: ", stringify!(mpc_ioapic))); - assert_eq!(::std::mem::align_of::<mpc_ioapic>(), - 4usize, - concat!("Alignment of ", stringify!(mpc_ioapic))); - assert_eq!(unsafe { &(*(0 as *const mpc_ioapic)).type_ as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_ioapic), - "::", - stringify!(type_))); - assert_eq!(unsafe { &(*(0 as *const mpc_ioapic)).apicid as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(mpc_ioapic), - "::", - stringify!(apicid))); - assert_eq!(unsafe { &(*(0 as *const mpc_ioapic)).apicver as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(mpc_ioapic), - "::", - stringify!(apicver))); - assert_eq!(unsafe { &(*(0 as *const mpc_ioapic)).flags as *const _ as usize }, - 3usize, - concat!("Alignment of field: ", - stringify!(mpc_ioapic), - "::", - stringify!(flags))); - assert_eq!(unsafe { &(*(0 as *const mpc_ioapic)).apicaddr as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpc_ioapic), - "::", - stringify!(apicaddr))); + assert_eq!( + ::std::mem::size_of::<mpc_ioapic>(), + 8usize, + concat!("Size of: ", stringify!(mpc_ioapic)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_ioapic>(), + 4usize, + concat!("Alignment of ", stringify!(mpc_ioapic)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_ioapic)).type_ as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_ioapic), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_ioapic)).apicid as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(mpc_ioapic), + "::", + stringify!(apicid) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_ioapic)).apicver as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(mpc_ioapic), + "::", + stringify!(apicver) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_ioapic)).flags as *const _ as usize }, + 3usize, + concat!( + "Alignment of field: ", + stringify!(mpc_ioapic), + "::", + stringify!(flags) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_ioapic)).apicaddr as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpc_ioapic), + "::", + stringify!(apicaddr) + ) + ); } impl Clone for mpc_ioapic { fn clone(&self) -> Self { @@ -391,54 +555,86 @@ pub struct mpc_intsrc { } #[test] fn bindgen_test_layout_mpc_intsrc() { - assert_eq!(::std::mem::size_of::<mpc_intsrc>(), - 8usize, - concat!("Size of: ", stringify!(mpc_intsrc))); - assert_eq!(::std::mem::align_of::<mpc_intsrc>(), - 2usize, - concat!("Alignment of ", stringify!(mpc_intsrc))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).type_ as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(type_))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).irqtype as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(irqtype))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).irqflag as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(irqflag))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).srcbus as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(srcbus))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).srcbusirq as *const _ as usize }, - 5usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(srcbusirq))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).dstapic as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(dstapic))); - assert_eq!(unsafe { &(*(0 as *const mpc_intsrc)).dstirq as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(mpc_intsrc), - "::", - stringify!(dstirq))); + assert_eq!( + ::std::mem::size_of::<mpc_intsrc>(), + 8usize, + concat!("Size of: ", stringify!(mpc_intsrc)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_intsrc>(), + 2usize, + concat!("Alignment of ", stringify!(mpc_intsrc)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).type_ as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).irqtype as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(irqtype) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).irqflag as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(irqflag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).srcbus as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(srcbus) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).srcbusirq as *const _ as usize }, + 5usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(srcbusirq) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).dstapic as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(dstapic) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_intsrc)).dstirq as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(mpc_intsrc), + "::", + stringify!(dstirq) + ) + ); } impl Clone for mpc_intsrc { fn clone(&self) -> Self { @@ -463,54 +659,86 @@ pub struct mpc_lintsrc { } #[test] fn bindgen_test_layout_mpc_lintsrc() { - assert_eq!(::std::mem::size_of::<mpc_lintsrc>(), - 8usize, - concat!("Size of: ", stringify!(mpc_lintsrc))); - assert_eq!(::std::mem::align_of::<mpc_lintsrc>(), - 2usize, - concat!("Alignment of ", stringify!(mpc_lintsrc))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).type_ as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(type_))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).irqtype as *const _ as usize }, - 1usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(irqtype))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).irqflag as *const _ as usize }, - 2usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(irqflag))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).srcbusid as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(srcbusid))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).srcbusirq as *const _ as usize }, - 5usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(srcbusirq))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).destapic as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(destapic))); - assert_eq!(unsafe { &(*(0 as *const mpc_lintsrc)).destapiclint as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(mpc_lintsrc), - "::", - stringify!(destapiclint))); + assert_eq!( + ::std::mem::size_of::<mpc_lintsrc>(), + 8usize, + concat!("Size of: ", stringify!(mpc_lintsrc)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_lintsrc>(), + 2usize, + concat!("Alignment of ", stringify!(mpc_lintsrc)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).type_ as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(type_) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).irqtype as *const _ as usize }, + 1usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(irqtype) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).irqflag as *const _ as usize }, + 2usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(irqflag) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).srcbusid as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(srcbusid) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).srcbusirq as *const _ as usize }, + 5usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(srcbusirq) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).destapic as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(destapic) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_lintsrc)).destapiclint as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(mpc_lintsrc), + "::", + stringify!(destapiclint) + ) + ); } impl Clone for mpc_lintsrc { fn clone(&self) -> Self { @@ -528,42 +756,66 @@ pub struct mpc_oemtable { } #[test] fn bindgen_test_layout_mpc_oemtable() { - assert_eq!(::std::mem::size_of::<mpc_oemtable>(), - 16usize, - concat!("Size of: ", stringify!(mpc_oemtable))); - assert_eq!(::std::mem::align_of::<mpc_oemtable>(), - 2usize, - concat!("Alignment of ", stringify!(mpc_oemtable))); - assert_eq!(unsafe { &(*(0 as *const mpc_oemtable)).signature as *const _ as usize }, - 0usize, - concat!("Alignment of field: ", - stringify!(mpc_oemtable), - "::", - stringify!(signature))); - assert_eq!(unsafe { &(*(0 as *const mpc_oemtable)).length as *const _ as usize }, - 4usize, - concat!("Alignment of field: ", - stringify!(mpc_oemtable), - "::", - stringify!(length))); - assert_eq!(unsafe { &(*(0 as *const mpc_oemtable)).rev as *const _ as usize }, - 6usize, - concat!("Alignment of field: ", - stringify!(mpc_oemtable), - "::", - stringify!(rev))); - assert_eq!(unsafe { &(*(0 as *const mpc_oemtable)).checksum as *const _ as usize }, - 7usize, - concat!("Alignment of field: ", - stringify!(mpc_oemtable), - "::", - stringify!(checksum))); - assert_eq!(unsafe { &(*(0 as *const mpc_oemtable)).mpc as *const _ as usize }, - 8usize, - concat!("Alignment of field: ", - stringify!(mpc_oemtable), - "::", - stringify!(mpc))); + assert_eq!( + ::std::mem::size_of::<mpc_oemtable>(), + 16usize, + concat!("Size of: ", stringify!(mpc_oemtable)) + ); + assert_eq!( + ::std::mem::align_of::<mpc_oemtable>(), + 2usize, + concat!("Alignment of ", stringify!(mpc_oemtable)) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_oemtable)).signature as *const _ as usize }, + 0usize, + concat!( + "Alignment of field: ", + stringify!(mpc_oemtable), + "::", + stringify!(signature) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_oemtable)).length as *const _ as usize }, + 4usize, + concat!( + "Alignment of field: ", + stringify!(mpc_oemtable), + "::", + stringify!(length) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_oemtable)).rev as *const _ as usize }, + 6usize, + concat!( + "Alignment of field: ", + stringify!(mpc_oemtable), + "::", + stringify!(rev) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_oemtable)).checksum as *const _ as usize }, + 7usize, + concat!( + "Alignment of field: ", + stringify!(mpc_oemtable), + "::", + stringify!(checksum) + ) + ); + assert_eq!( + unsafe { &(*(0 as *const mpc_oemtable)).mpc as *const _ as usize }, + 8usize, + concat!( + "Alignment of field: ", + stringify!(mpc_oemtable), + "::", + stringify!(mpc) + ) + ); } impl Clone for mpc_oemtable { fn clone(&self) -> Self { diff --git a/x86_64/src/mptable.rs b/x86_64/src/mptable.rs index 6ccb1d6..b7842b0 100644 --- a/x86_64/src/mptable.rs +++ b/x86_64/src/mptable.rs @@ -2,12 +2,12 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. +use std::error::{self, Error as MptableError}; +use std::fmt::{self, Display}; use std::io; use std::mem; use std::result; use std::slice; -use std::error::{self, Error as MptableError}; -use std::fmt::{self, Display}; use libc::c_char; @@ -43,18 +43,15 @@ pub enum Error { impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::NotEnoughMemory => - "There was too little guest memory to store the MP table", - &Error::AddressOverflow => - "The MP table has too little address space to be stored", + &Error::NotEnoughMemory => "There was too little guest memory to store the MP table", + &Error::AddressOverflow => "The MP table has too little address space to be stored", &Error::Clear => "Failure while zeroing out the memory for the MP table", &Error::WriteMpfIntel => "Failure to write the MP floating pointer", &Error::WriteMpcCpu => "Failure to write MP CPU entry", &Error::WriteMpcIoapic => "Failure to write MP ioapic entry", &Error::WriteMpcBus => "Failure to write MP bus entry", &Error::WriteMpcIntsrc => "Failure to write MP interrupt source entry", - &Error::WriteMpcLintsrc => - "Failure to write MP local interrupt source entry", + &Error::WriteMpcLintsrc => "Failure to write MP local interrupt source entry", &Error::WriteMpcTable => "Failure to write MP table header", } } @@ -105,17 +102,22 @@ fn mpf_intel_compute_checksum(v: &mpf_intel) -> u8 { } fn compute_mp_size(num_cpus: u8) -> usize { - mem::size_of::<mpf_intel>() + mem::size_of::<mpc_table>() + - mem::size_of::<mpc_cpu>() * (num_cpus as usize) + mem::size_of::<mpc_ioapic>() + - mem::size_of::<mpc_bus>() * 2 + mem::size_of::<mpc_intsrc>() + - mem::size_of::<mpc_intsrc>() * 16 + - mem::size_of::<mpc_lintsrc>() * 2 + mem::size_of::<mpf_intel>() + + mem::size_of::<mpc_table>() + + mem::size_of::<mpc_cpu>() * (num_cpus as usize) + + mem::size_of::<mpc_ioapic>() + + mem::size_of::<mpc_bus>() * 2 + + mem::size_of::<mpc_intsrc>() + + mem::size_of::<mpc_intsrc>() * 16 + + mem::size_of::<mpc_lintsrc>() * 2 } /// Performs setup of the MP table for the given `num_cpus`. -pub fn setup_mptable(mem: &GuestMemory, num_cpus: u8, - pci_irqs: Vec<(u32, PciInterruptPin)>) - -> Result<()> { +pub fn setup_mptable( + mem: &GuestMemory, + num_cpus: u8, + pci_irqs: Vec<(u32, PciInterruptPin)>, +) -> Result<()> { const PCI_BUS_ID: u8 = 0; const ISA_BUS_ID: u8 = 1; @@ -164,12 +166,11 @@ pub fn setup_mptable(mem: &GuestMemory, num_cpus: u8, mpc_cpu.type_ = MP_PROCESSOR as u8; mpc_cpu.apicid = cpu_id; mpc_cpu.apicver = APIC_VERSION; - mpc_cpu.cpuflag = CPU_ENABLED as u8 | - if cpu_id == 0 { - CPU_BOOTPROCESSOR as u8 - } else { - 0 - }; + mpc_cpu.cpuflag = CPU_ENABLED as u8 | if cpu_id == 0 { + CPU_BOOTPROCESSOR as u8 + } else { + 0 + }; mpc_cpu.cpufeature = CPU_STEPPING; mpc_cpu.featureflag = CPU_FEATURE_APIC | CPU_FEATURE_FPU; mem.write_obj_at_addr(mpc_cpu, base_mp) @@ -326,7 +327,6 @@ pub fn setup_mptable(mem: &GuestMemory, num_cpus: u8, Ok(()) } - #[cfg(test)] mod tests { use super::*; @@ -345,8 +345,10 @@ mod tests { #[test] fn bounds_check() { let num_cpus = 4; - let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), - compute_mp_size(num_cpus) as u64)]).unwrap(); + let mem = GuestMemory::new(&[( + GuestAddress(MPTABLE_START), + compute_mp_size(num_cpus) as u64, + )]).unwrap(); setup_mptable(&mem, num_cpus, Vec::new()).unwrap(); } @@ -354,8 +356,10 @@ mod tests { #[test] fn bounds_check_fails() { let num_cpus = 4; - let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), - (compute_mp_size(num_cpus) - 1) as u64)]).unwrap(); + let mem = GuestMemory::new(&[( + GuestAddress(MPTABLE_START), + (compute_mp_size(num_cpus) - 1) as u64, + )]).unwrap(); assert!(setup_mptable(&mem, num_cpus, Vec::new()).is_err()); } @@ -363,8 +367,10 @@ mod tests { #[test] fn mpf_intel_checksum() { let num_cpus = 1; - let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), - compute_mp_size(num_cpus) as u64)]).unwrap(); + let mem = GuestMemory::new(&[( + GuestAddress(MPTABLE_START), + compute_mp_size(num_cpus) as u64, + )]).unwrap(); setup_mptable(&mem, num_cpus, Vec::new()).unwrap(); @@ -376,8 +382,10 @@ mod tests { #[test] fn mpc_table_checksum() { let num_cpus = 4; - let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), - compute_mp_size(num_cpus) as u64)]).unwrap(); + let mem = GuestMemory::new(&[( + GuestAddress(MPTABLE_START), + compute_mp_size(num_cpus) as u64, + )]).unwrap(); setup_mptable(&mem, num_cpus, Vec::new()).unwrap(); @@ -407,8 +415,10 @@ mod tests { #[test] fn cpu_entry_count() { const MAX_CPUS: u8 = 0xff; - let mem = GuestMemory::new(&[(GuestAddress(MPTABLE_START), - compute_mp_size(MAX_CPUS) as u64)]).unwrap(); + let mem = GuestMemory::new(&[( + GuestAddress(MPTABLE_START), + compute_mp_size(MAX_CPUS) as u64, + )]).unwrap(); for i in 0..MAX_CPUS { setup_mptable(&mem, i, Vec::new()).unwrap(); @@ -416,9 +426,7 @@ mod tests { let mpf_intel: mpf_intel = mem.read_obj_from_addr(GuestAddress(MPTABLE_START)).unwrap(); let mpc_offset = GuestAddress(mpf_intel.physptr as u64); let mpc_table: mpc_table = mem.read_obj_from_addr(mpc_offset).unwrap(); - let mpc_end = mpc_offset - .checked_add(mpc_table.length as u64) - .unwrap(); + let mpc_end = mpc_offset.checked_add(mpc_table.length as u64).unwrap(); let mut entry_offset = mpc_offset .checked_add(mem::size_of::<mpc_table>() as u64) diff --git a/x86_64/src/regs.rs b/x86_64/src/regs.rs index 85d822a..977e19f 100644 --- a/x86_64/src/regs.rs +++ b/x86_64/src/regs.rs @@ -2,17 +2,17 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -use std::{mem, result}; use std::error::{self, Error as RegsError}; use std::fmt::{self, Display}; +use std::{mem, result}; +use gdt; use kvm; use kvm_sys::kvm_fpu; use kvm_sys::kvm_msr_entry; use kvm_sys::kvm_msrs; use kvm_sys::kvm_regs; use kvm_sys::kvm_sregs; -use gdt; use sys_util; use sys_util::{GuestAddress, GuestMemory}; @@ -44,27 +44,16 @@ pub type Result<T> = result::Result<T, Error>; impl error::Error for Error { fn description(&self) -> &str { match self { - &Error::MsrIoctlFailed(_) => - "Setting up msrs failed", - &Error::FpuIoctlFailed(_) => - "Failed to configure the FPU", - &Error::GetSRegsIoctlFailed(_) => - "Failed to get sregs for this cpu", - &Error::SettingRegistersIoctl(_) => - "Failed to set base registers for this cpu", - &Error::SetSRegsIoctlFailed(_) => - "Failed to set sregs for this cpu", - &Error::WriteGDTFailure => - "Writing the GDT to RAM failed", - &Error::WriteIDTFailure => - "Writing the IDT to RAM failed", - &Error::WritePML4Address => - "Writing PML4 to RAM failed", - &Error::WritePDPTEAddress => - "Writing PDPTE to RAM failed", - &Error::WritePDEAddress => - "Writing PDE to RAM failed", - + &Error::MsrIoctlFailed(_) => "Setting up msrs failed", + &Error::FpuIoctlFailed(_) => "Failed to configure the FPU", + &Error::GetSRegsIoctlFailed(_) => "Failed to get sregs for this cpu", + &Error::SettingRegistersIoctl(_) => "Failed to set base registers for this cpu", + &Error::SetSRegsIoctlFailed(_) => "Failed to set sregs for this cpu", + &Error::WriteGDTFailure => "Writing the GDT to RAM failed", + &Error::WriteIDTFailure => "Writing the IDT to RAM failed", + &Error::WritePML4Address => "Writing PML4 to RAM failed", + &Error::WritePDPTEAddress => "Writing PDPTE to RAM failed", + &Error::WritePDEAddress => "Writing PDE to RAM failed", } } } @@ -79,57 +68,57 @@ fn create_msr_entries() -> Vec<kvm_msr_entry> { let mut entries = Vec::<kvm_msr_entry>::new(); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_IA32_SYSENTER_CS, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_IA32_SYSENTER_CS, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_IA32_SYSENTER_ESP, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_IA32_SYSENTER_ESP, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_IA32_SYSENTER_EIP, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_IA32_SYSENTER_EIP, + data: 0x0, + ..Default::default() + }); // x86_64 specific msrs, we only run on x86_64 not x86 entries.push(kvm_msr_entry { - index: ::msr_index::MSR_STAR, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_STAR, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_CSTAR, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_CSTAR, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_KERNEL_GS_BASE, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_KERNEL_GS_BASE, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_SYSCALL_MASK, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_SYSCALL_MASK, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_LSTAR, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_LSTAR, + data: 0x0, + ..Default::default() + }); // end of x86_64 specific code entries.push(kvm_msr_entry { - index: ::msr_index::MSR_IA32_TSC, - data: 0x0, - ..Default::default() - }); + index: ::msr_index::MSR_IA32_TSC, + data: 0x0, + ..Default::default() + }); entries.push(kvm_msr_entry { - index: ::msr_index::MSR_IA32_MISC_ENABLE, - data: ::msr_index::MSR_IA32_MISC_ENABLE_FAST_STRING as u64, - ..Default::default() - }); + index: ::msr_index::MSR_IA32_MISC_ENABLE, + data: ::msr_index::MSR_IA32_MISC_ENABLE_FAST_STRING as u64, + ..Default::default() + }); entries } @@ -141,8 +130,8 @@ fn create_msr_entries() -> Vec<kvm_msr_entry> { /// * `vcpu` - Structure for the vcpu that holds the vcpu fd. pub fn setup_msrs(vcpu: &kvm::Vcpu) -> Result<()> { let entry_vec = create_msr_entries(); - let vec_size_bytes = mem::size_of::<kvm_msrs>() + - (entry_vec.len() * mem::size_of::<kvm_msr_entry>()); + let vec_size_bytes = + mem::size_of::<kvm_msrs>() + (entry_vec.len() * mem::size_of::<kvm_msr_entry>()); let vec: Vec<u8> = Vec::with_capacity(vec_size_bytes); let msrs: &mut kvm_msrs = unsafe { // Converting the vector's memory to a struct is unsafe. Carefully using the read-only @@ -198,8 +187,7 @@ pub fn setup_regs(vcpu: &kvm::Vcpu, boot_ip: u64, boot_sp: u64, boot_si: u64) -> ..Default::default() }; - vcpu.set_regs(®s) - .map_err(Error::SettingRegistersIoctl)?; + vcpu.set_regs(®s).map_err(Error::SettingRegistersIoctl)?; Ok(()) } @@ -219,9 +207,11 @@ const BOOT_GDT_MAX: usize = 4; fn write_gdt_table(table: &[u64], guest_mem: &GuestMemory) -> Result<()> { let boot_gdt_addr = GuestAddress(BOOT_GDT_OFFSET); for (index, entry) in table.iter().enumerate() { - let addr = guest_mem.checked_offset(boot_gdt_addr, (index * mem::size_of::<u64>()) as u64) + let addr = guest_mem + .checked_offset(boot_gdt_addr, (index * mem::size_of::<u64>()) as u64) .ok_or(Error::WriteGDTFailure)?; - guest_mem.write_obj_at_addr(*entry, addr) + guest_mem + .write_obj_at_addr(*entry, addr) .map_err(|_| Error::WriteGDTFailure)?; } Ok(()) @@ -236,7 +226,7 @@ fn write_idt_value(val: u64, guest_mem: &GuestMemory) -> Result<()> { fn configure_segments_and_sregs(mem: &GuestMemory, sregs: &mut kvm_sregs) -> Result<()> { let gdt_table: [u64; BOOT_GDT_MAX as usize] = [ - gdt::gdt_entry(0, 0, 0), // NULL + gdt::gdt_entry(0, 0, 0), // NULL gdt::gdt_entry(0xa09b, 0, 0xfffff), // CODE gdt::gdt_entry(0xc093, 0, 0xfffff), // DATA gdt::gdt_entry(0x808b, 0, 0xfffff), // TSS |