edition: Use dyn syntax for trait objects

Found by running: `cargo rustc -- -D bare_trait_objects`

Bare trait objects like `&Trait` and `Box<Trait>` are soft-deprecated in
2018 edition and will start warning at some point.

As part of this, I replaced `Box<Trait + 'static>` with `Box<dyn Trait>`
because the 'static bound is implied for boxed trait objects.

TEST=cargo check --all-features
TEST=cargo check --target aarch64-unknown-linux-gnu
TEST=local kokoro

Change-Id: I41c4f13530bece8a34a8ed1c1afd7035b8f86f19
Reviewed-on: https://chromium-review.googlesource.com/1513059
Commit-Ready: ChromeOS CL Exonerator Bot <chromiumos-cl-exonerator@appspot.gserviceaccount.com>
Tested-by: David Tolnay <dtolnay@chromium.org>
Tested-by: kokoro <noreply+kokoro@google.com>
Reviewed-by: David Tolnay <dtolnay@chromium.org>
This commit is contained in:
David Tolnay 2019-03-08 16:56:14 -08:00 committed by chrome-bot
parent 98895ac05d
commit fdac5ede46
45 changed files with 142 additions and 130 deletions

View file

@ -201,7 +201,7 @@ impl arch::LinuxArch for AArch64 {
F: FnOnce(
&GuestMemory,
&EventFd,
) -> std::result::Result<Vec<(Box<PciDevice>, Option<Minijail>)>, E>,
) -> std::result::Result<Vec<(Box<dyn PciDevice>, Option<Minijail>)>, E>,
E: StdError + 'static,
{
let mut resources =

View file

@ -61,7 +61,7 @@ pub struct RunnableLinuxVm {
/// The device and optional jail.
pub struct VirtioDeviceStub {
pub dev: Box<VirtioDevice>,
pub dev: Box<dyn VirtioDevice>,
pub jail: Option<Minijail>,
}
@ -83,7 +83,7 @@ pub trait LinuxArch {
create_devices: F,
) -> Result<RunnableLinuxVm, Self::Error>
where
F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<(Box<PciDevice>, Option<Minijail>)>, E>,
F: FnOnce(&GuestMemory, &EventFd) -> Result<Vec<(Box<dyn PciDevice>, Option<Minijail>)>, E>,
E: StdError + 'static;
}
@ -144,7 +144,7 @@ impl Display for DeviceRegistrationError {
/// Creates a root PCI device for use by this Vm.
pub fn generate_pci_root(
devices: Vec<(Box<PciDevice>, Option<Minijail>)>,
devices: Vec<(Box<dyn PciDevice>, Option<Minijail>)>,
mmio_bus: &mut Bus,
resources: &mut SystemAllocator,
vm: &mut Vm,
@ -191,7 +191,7 @@ pub fn generate_pci_root(
.map_err(DeviceRegistrationError::RegisterIoevent)?;
keep_fds.push(event.as_raw_fd());
}
let arced_dev: Arc<Mutex<BusDevice>> = if let Some(jail) = jail {
let arced_dev: Arc<Mutex<dyn BusDevice>> = if let Some(jail) = jail {
let proxy = ProxyDevice::new(device, &jail, keep_fds)
.map_err(DeviceRegistrationError::ProxyDeviceCreation)?;
pid_labels.insert(proxy.pid() as u32, proxy.debug_label());

View file

@ -106,7 +106,7 @@ impl PartialOrd for BusRange {
/// only restriction is that no two devices can overlap in this address space.
#[derive(Clone)]
pub struct Bus {
devices: BTreeMap<BusRange, Arc<Mutex<BusDevice>>>,
devices: BTreeMap<BusRange, Arc<Mutex<dyn BusDevice>>>,
}
impl Bus {
@ -117,7 +117,7 @@ impl Bus {
}
}
fn first_before(&self, addr: u64) -> Option<(BusRange, &Mutex<BusDevice>)> {
fn first_before(&self, addr: u64) -> Option<(BusRange, &Mutex<dyn BusDevice>)> {
let (range, dev) = self
.devices
.range(
@ -132,7 +132,7 @@ impl Bus {
Some((*range, dev))
}
fn get_device(&self, addr: u64) -> Option<(u64, &Mutex<BusDevice>)> {
fn get_device(&self, addr: u64) -> Option<(u64, &Mutex<dyn BusDevice>)> {
if let Some((range, dev)) = self.first_before(addr) {
let offset = addr - range.base;
if offset < range.len {
@ -149,7 +149,7 @@ impl Bus {
/// Puts the given device at the given address space.
pub fn insert(
&mut self,
device: Arc<Mutex<BusDevice>>,
device: Arc<Mutex<dyn BusDevice>>,
base: u64,
len: u64,
full_addr: bool,

View file

@ -38,7 +38,7 @@ pub struct Ac97Dev {
impl Ac97Dev {
/// Creates an 'Ac97Dev' that uses the given `GuestMemory` and starts with all registers at
/// default values.
pub fn new(mem: GuestMemory, audio_server: Box<StreamSource>) -> Self {
pub fn new(mem: GuestMemory, audio_server: Box<dyn StreamSource>) -> Self {
let config_regs = PciConfiguration::new(
0x8086,
PCI_DEVICE_ID_INTEL_82801AA_5,

View file

@ -74,7 +74,7 @@ enum PlaybackError {
// Failure reading samples from guest memory.
ReadingGuestSamples(data_model::VolatileMemoryError),
// Failure to get an buffer from the stream.
StreamError(Box<Error>),
StreamError(Box<dyn Error>),
// Failure writing to the audio output.
WritingOutput(std::io::Error),
}
@ -406,7 +406,7 @@ impl Ac97BusMaster {
self.regs.lock().glob_cnt = new_glob_cnt;
}
fn start_audio(&mut self, func: Ac97Function, mixer: &Ac97Mixer) -> Result<(), Box<Error>> {
fn start_audio(&mut self, func: Ac97Function, mixer: &Ac97Mixer) -> Result<(), Box<dyn Error>> {
const AUDIO_THREAD_RTPRIO: u16 = 12; // Matches other cros audio clients.
match func {

View file

@ -239,8 +239,8 @@ impl PciConfiguration {
vendor_id: u16,
device_id: u16,
class_code: PciClassCode,
subclass: &PciSubclass,
programming_interface: Option<&PciProgrammingInterface>,
subclass: &dyn PciSubclass,
programming_interface: Option<&dyn PciProgrammingInterface>,
header_type: PciHeaderType,
subsystem_vendor_id: u16,
subsystem_id: u16,
@ -422,7 +422,7 @@ impl PciConfiguration {
/// `cap_data` should include the two-byte PCI capability header (type, next),
/// but not populate it. Correct values will be generated automatically based
/// on `cap_data.id()`.
pub fn add_capability(&mut self, cap_data: &PciCapability) -> Result<usize> {
pub fn add_capability(&mut self, cap_data: &dyn PciCapability) -> Result<usize> {
let total_len = cap_data.bytes().len();
// Check that the length is valid.
if cap_data.bytes().is_empty() {

View file

@ -44,7 +44,7 @@ pub struct PciRoot {
/// Bus configuration for the root device.
root_configuration: PciRootConfiguration,
/// Devices attached to this bridge.
devices: Vec<Arc<Mutex<BusDevice>>>,
devices: Vec<Arc<Mutex<dyn BusDevice>>>,
}
impl PciRoot {
@ -68,7 +68,7 @@ impl PciRoot {
}
/// Add a `device` to this root PCI bus.
pub fn add_device(&mut self, device: Arc<Mutex<BusDevice>>) {
pub fn add_device(&mut self, device: Arc<Mutex<dyn BusDevice>>) {
self.devices.push(device);
}

View file

@ -66,7 +66,7 @@ enum CommandResult {
ReadConfigResult(u32),
}
fn child_proc(sock: UnixSeqpacket, device: &mut BusDevice) {
fn child_proc(sock: UnixSeqpacket, device: &mut dyn BusDevice) {
let mut running = true;
let sock = MsgSocket::<CommandResult, Command>::new(sock);

View file

@ -197,7 +197,7 @@ pub struct RegisterSpec<T> {
struct RegisterInner<T: RegisterValue> {
spec: RegisterSpec<T>,
value: T,
write_cb: Option<Box<Fn(T) -> T + Send>>,
write_cb: Option<Box<dyn Fn(T) -> T + Send>>,
}
/// Register is a thread safe struct. It can be safely changed from any thread.

View file

@ -7,7 +7,7 @@ use std::collections::btree_map::BTreeMap;
/// Register space repesents a set of registers. It can handle read/write operations.
pub struct RegisterSpace {
regs: BTreeMap<RegisterRange, Box<RegisterInterface>>,
regs: BTreeMap<RegisterRange, Box<dyn RegisterInterface>>,
}
impl RegisterSpace {
@ -70,17 +70,17 @@ impl RegisterSpace {
}
/// Get first register before this addr.
fn first_before(&self, addr: RegisterOffset) -> Option<&Box<RegisterInterface>> {
fn first_before(&self, addr: RegisterOffset) -> Option<&dyn RegisterInterface> {
for (range, r) in self.regs.iter().rev() {
if range.from <= addr {
return Some(r);
return Some(r.as_ref());
}
}
None
}
/// Get register at this addr.
fn get_register(&self, addr: RegisterOffset) -> Option<&Box<RegisterInterface>> {
fn get_register(&self, addr: RegisterOffset) -> Option<&dyn RegisterInterface> {
let r = self.first_before(addr)?;
let range = r.range();
if addr <= range.to {

View file

@ -59,11 +59,11 @@ pub struct Serial {
scratch: u8,
baud_divisor: u16,
in_buffer: VecDeque<u8>,
out: Option<Box<io::Write + Send>>,
out: Option<Box<dyn io::Write + Send>>,
}
impl Serial {
fn new(interrupt_evt: EventFd, out: Option<Box<io::Write + Send>>) -> Serial {
fn new(interrupt_evt: EventFd, out: Option<Box<dyn io::Write + Send>>) -> Serial {
Serial {
interrupt_enable: 0,
interrupt_identification: DEFAULT_INTERRUPT_IDENTIFICATION,
@ -80,7 +80,7 @@ impl Serial {
}
/// Constructs a Serial port ready for output.
pub fn new_out(interrupt_evt: EventFd, out: Box<io::Write + Send>) -> Serial {
pub fn new_out(interrupt_evt: EventFd, out: Box<dyn io::Write + Send>) -> Serial {
Self::new(interrupt_evt, Some(out))
}

View file

@ -17,7 +17,7 @@ use vm_control::MaybeOwnedFd;
pub struct Context {
context: LibUsbContext,
event_loop: Arc<EventLoop>,
event_handler: Arc<EventHandler>,
event_handler: Arc<dyn EventHandler>,
}
impl Context {
@ -124,7 +124,7 @@ impl EventHandler for LibUsbEventHandler {
struct PollfdChangeHandler {
event_loop: Arc<EventLoop>,
event_handler: Weak<EventHandler>,
event_handler: Weak<dyn EventHandler>,
}
impl LibUsbPollfdChangeHandler for PollfdChangeHandler {

View file

@ -55,7 +55,7 @@ impl HostBackendDeviceProvider {
fn start_helper(
&mut self,
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
event_loop: Arc<EventLoop>,
hub: Arc<UsbHub>,
) -> Result<()> {
@ -67,7 +67,7 @@ impl HostBackendDeviceProvider {
let job_queue =
AsyncJobQueue::init(&event_loop).map_err(Error::StartAsyncJobQueue)?;
let inner = Arc::new(ProviderInner::new(fail_handle, job_queue, ctx, sock, hub));
let handler: Arc<EventHandler> = inner.clone();
let handler: Arc<dyn EventHandler> = inner.clone();
event_loop
.add_event(
&inner.sock,
@ -93,7 +93,7 @@ impl HostBackendDeviceProvider {
impl XhciBackendDeviceProvider for HostBackendDeviceProvider {
fn start(
&mut self,
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
event_loop: Arc<EventLoop>,
hub: Arc<UsbHub>,
) -> std::result::Result<(), ()> {
@ -119,7 +119,7 @@ impl XhciBackendDeviceProvider for HostBackendDeviceProvider {
/// ProviderInner listens to control socket.
pub struct ProviderInner {
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
ctx: Context,
sock: MsgSocket<UsbControlResult, UsbControlCommand>,
@ -128,7 +128,7 @@ pub struct ProviderInner {
impl ProviderInner {
fn new(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
ctx: Context,
sock: MsgSocket<UsbControlResult, UsbControlCommand>,

View file

@ -83,7 +83,7 @@ impl HostToDeviceControlRequest {
/// Host device is a device connected to host.
pub struct HostDevice {
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
// Endpoints only contains data endpoints (1 to 30). Control transfers are handled at device
// level.
endpoints: Vec<UsbEndpoint>,
@ -106,7 +106,7 @@ impl Drop for HostDevice {
impl HostDevice {
/// Create a new host device.
pub fn new(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
device: LibUsbDevice,
device_handle: DeviceHandle,

View file

@ -22,7 +22,7 @@ use utils::FailHandle;
/// Isochronous, Bulk or Interrupt endpoint.
pub struct UsbEndpoint {
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
device_handle: Arc<Mutex<DeviceHandle>>,
endpoint_number: u8,
@ -33,7 +33,7 @@ pub struct UsbEndpoint {
impl UsbEndpoint {
/// Create new endpoint. This function will panic if endpoint type is control.
pub fn new(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
job_queue: Arc<AsyncJobQueue>,
device_handle: Arc<Mutex<DeviceHandle>>,
endpoint_number: u8,

View file

@ -44,7 +44,7 @@ pub fn update_transfer_state<T: UsbTransferBuffer>(
/// Helper function to submit usb_transfer to device handle.
pub fn submit_transfer<T: UsbTransferBuffer>(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
job_queue: &Arc<AsyncJobQueue>,
xhci_transfer: Arc<XhciTransfer>,
device_handle: &Arc<Mutex<DeviceHandle>>,

View file

@ -77,14 +77,14 @@ fn valid_endpoint_id(endpoint_id: u8) -> bool {
#[derive(Clone)]
pub struct DeviceSlots {
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
hub: Arc<UsbHub>,
slots: Vec<Arc<DeviceSlot>>,
}
impl DeviceSlots {
pub fn new(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
dcbaap: Register<u64>,
hub: Arc<UsbHub>,
interrupter: Arc<Mutex<Interrupter>>,
@ -336,7 +336,7 @@ impl DeviceSlot {
/// Disable this device slot. If the slot is not enabled, callback will be invoked immediately
/// with error. Otherwise, callback will be invoked when all trc is stopped.
pub fn disable<C: FnMut(TrbCompletionCode) -> std::result::Result<(), ()> + 'static + Send>(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
slot: &Arc<DeviceSlot>,
mut callback: C,
) -> Result<()> {
@ -577,7 +577,7 @@ impl DeviceSlot {
pub fn reset_slot<
C: FnMut(TrbCompletionCode) -> std::result::Result<(), ()> + 'static + Send,
>(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
slot: &Arc<DeviceSlot>,
mut callback: C,
) -> Result<()> {
@ -621,7 +621,7 @@ impl DeviceSlot {
C: FnMut(TrbCompletionCode) -> std::result::Result<(), ()> + 'static + Send,
>(
&self,
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
endpoint_id: u8,
mut cb: C,
) -> Result<()> {

View file

@ -25,7 +25,7 @@ impl IntrResampleHandler {
interrupter,
resample_evt,
});
let tmp_handler: Arc<EventHandler> = handler.clone();
let tmp_handler: Arc<dyn EventHandler> = handler.clone();
if let Err(e) = event_loop.add_event(
&handler.resample_evt,
WatchingEvents::empty().set_read(),

View file

@ -106,7 +106,7 @@ where
event_loop: event_loop.clone(),
event: evt,
});
let event_handler: Arc<EventHandler> = controller.clone();
let event_handler: Arc<dyn EventHandler> = controller.clone();
event_loop
.add_event(
&controller.event,

View file

@ -26,7 +26,7 @@ impl RingBufferStopCallback {
}
struct RingBufferStopCallbackInner {
callback: Box<FnMut() + Send>,
callback: Box<dyn FnMut() + Send>,
}
impl Drop for RingBufferStopCallbackInner {
@ -38,7 +38,7 @@ impl Drop for RingBufferStopCallbackInner {
/// Helper function to wrap up a closure with fail handle. The fail handle will be triggered if the
/// closure returns an error.
pub fn fallible_closure<E: std::fmt::Display, C: FnMut() -> Result<(), E> + 'static + Send>(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
mut callback: C,
) -> impl FnMut() + 'static + Send {
move || match callback() {

View file

@ -74,7 +74,7 @@ pub struct UsbPort {
portsc: Register<u32>,
usbsts: Register<u32>,
interrupter: Arc<Mutex<Interrupter>>,
backend_device: Mutex<Option<Box<XhciBackendDevice>>>,
backend_device: Mutex<Option<Box<dyn XhciBackendDevice>>>,
}
impl UsbPort {
@ -116,7 +116,7 @@ impl UsbPort {
}
/// Get current connected backend.
pub fn get_backend_device(&self) -> MutexGuard<Option<Box<XhciBackendDevice>>> {
pub fn get_backend_device(&self) -> MutexGuard<Option<Box<dyn XhciBackendDevice>>> {
self.backend_device.lock()
}
@ -131,7 +131,10 @@ impl UsbPort {
Ok(())
}
fn attach(&self, device: Box<XhciBackendDevice>) -> std::result::Result<(), InterrupterError> {
fn attach(
&self,
device: Box<dyn XhciBackendDevice>,
) -> std::result::Result<(), InterrupterError> {
usb_debug!("A backend is connected to port {}", self.port_id);
let mut locked = self.backend_device.lock();
assert!(locked.is_none());
@ -250,7 +253,7 @@ impl UsbHub {
}
/// Connect backend to next empty port.
pub fn connect_backend(&self, backend: Box<XhciBackendDevice>) -> Result<u8> {
pub fn connect_backend(&self, backend: Box<dyn XhciBackendDevice>) -> Result<u8> {
usb_debug!("Trying to connect backend to hub");
for port in &self.ports {
if port.is_attached() {

View file

@ -58,7 +58,7 @@ impl Display for Error {
/// xHCI controller implementation.
pub struct Xhci {
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
regs: XhciRegs,
interrupter: Arc<Mutex<Interrupter>>,
command_ring_controller: Arc<CommandRingController>,
@ -75,7 +75,7 @@ pub struct Xhci {
impl Xhci {
/// Create a new xHCI controller.
pub fn new(
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
mem: GuestMemory,
device_provider: HostBackendDeviceProvider,
irq_evt: EventFd,

View file

@ -12,7 +12,7 @@ pub trait XhciBackendDeviceProvider: Send {
/// Start the provider on EventLoop.
fn start(
&mut self,
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
event_loop: Arc<EventLoop>,
hub: Arc<UsbHub>,
) -> std::result::Result<(), ()>;

View file

@ -87,7 +87,7 @@ enum XhciControllerState {
// Xhci init could fail.
#[allow(dead_code)]
xhci: Option<Arc<Xhci>>,
fail_handle: Arc<FailHandle>,
fail_handle: Arc<dyn FailHandle>,
},
}
@ -131,7 +131,7 @@ impl XhciController {
irq_resample_evt,
} => {
let (mmio, regs) = init_xhci_mmio_space_and_regs();
let fail_handle: Arc<FailHandle> = Arc::new(XhciFailHandle::new(&regs));
let fail_handle: Arc<dyn FailHandle> = Arc::new(XhciFailHandle::new(&regs));
let xhci = match Xhci::new(
fail_handle.clone(),
self.mem.clone(),

View file

@ -66,7 +66,7 @@ pub enum XhciTransferState {
/// When transfer is submitted, it will contain a transfer callback, which should be invoked
/// when the transfer is cancelled.
Submitted {
cancel_callback: Box<FnMut() + Send>,
cancel_callback: Box<dyn FnMut() + Send>,
},
Cancelling,
Cancelled,

View file

@ -11,7 +11,7 @@ use sys_util::{EventFd, WatchingEvents};
/// Async Job Queue can schedule async jobs.
pub struct AsyncJobQueue {
jobs: Mutex<Vec<Box<FnMut() + 'static + Send>>>,
jobs: Mutex<Vec<Box<dyn FnMut() + Send>>>,
evt: EventFd,
}
@ -23,7 +23,7 @@ impl AsyncJobQueue {
jobs: Mutex::new(Vec::new()),
evt,
});
let handler: Arc<EventHandler> = queue.clone();
let handler: Arc<dyn EventHandler> = queue.clone();
event_loop.add_event(
&queue.evt,
WatchingEvents::empty().set_read(),

View file

@ -19,7 +19,7 @@ pub trait FailHandle: Send + Sync {
fn failed(&self) -> bool;
}
impl FailHandle for Option<Arc<FailHandle>> {
impl FailHandle for Option<Arc<dyn FailHandle>> {
fn fail(&self) {
match *self {
Some(ref handle) => handle.fail(),
@ -57,9 +57,9 @@ impl PollToken for Fd {
/// EpollEventLoop is an event loop blocked on a set of fds. When a monitered events is triggered,
/// event loop will invoke the mapped handler.
pub struct EventLoop {
fail_handle: Option<Arc<FailHandle>>,
fail_handle: Option<Arc<dyn FailHandle>>,
poll_ctx: Arc<EpollContext<Fd>>,
handlers: Arc<Mutex<BTreeMap<RawFd, Weak<EventHandler>>>>,
handlers: Arc<Mutex<BTreeMap<RawFd, Weak<dyn EventHandler>>>>,
stop_evt: EventFd,
}
@ -71,13 +71,13 @@ pub trait EventHandler: Send + Sync {
impl EventLoop {
/// Start an event loop. An optional fail handle could be passed to the event loop.
pub fn start(
fail_handle: Option<Arc<FailHandle>>,
fail_handle: Option<Arc<dyn FailHandle>>,
) -> Result<(EventLoop, thread::JoinHandle<()>)> {
let (self_stop_evt, stop_evt) = EventFd::new()
.and_then(|e| Ok((e.try_clone()?, e)))
.map_err(Error::CreateEventFd)?;
let fd_callbacks: Arc<Mutex<BTreeMap<RawFd, Weak<EventHandler>>>> =
let fd_callbacks: Arc<Mutex<BTreeMap<RawFd, Weak<dyn EventHandler>>>> =
Arc::new(Mutex::new(BTreeMap::new()));
let poll_ctx: EpollContext<Fd> = EpollContext::new()
.and_then(|pc| pc.add(&stop_evt, Fd(stop_evt.as_raw_fd())).and(Ok(pc)))
@ -156,9 +156,9 @@ impl EventLoop {
/// the event will be removed.
pub fn add_event(
&self,
fd: &AsRawFd,
fd: &dyn AsRawFd,
events: WatchingEvents,
handler: Weak<EventHandler>,
handler: Weak<dyn EventHandler>,
) -> Result<()> {
if self.fail_handle.failed() {
return Err(Error::EventLoopAlreadyFailed);
@ -173,7 +173,7 @@ impl EventLoop {
/// Removes event for this `fd`. This function returns false if it fails.
///
/// EventLoop does not guarantee all events for `fd` is handled.
pub fn remove_event_for_fd(&self, fd: &AsRawFd) -> Result<()> {
pub fn remove_event_for_fd(&self, fd: &dyn AsRawFd) -> Result<()> {
if self.fail_handle.failed() {
return Err(Error::EventLoopAlreadyFailed);
}

View file

@ -312,7 +312,7 @@ pub struct Backend {
display: Rc<RefCell<GpuDisplay>>,
device: Device,
renderer: Renderer,
resources: Map<u32, Box<VirglResource>>,
resources: Map<u32, Box<dyn VirglResource>>,
contexts: Map<u32, RendererContext>,
scanout_surface: Option<u32>,
cursor_surface: Option<u32>,

View file

@ -82,7 +82,7 @@ pub trait VirtioDevice: Send {
}
/// Returns any additional capabiltiies required by the device.
fn get_device_caps(&self) -> Vec<Box<PciCapability>> {
fn get_device_caps(&self) -> Vec<Box<dyn PciCapability>> {
Vec::new()
}
}

View file

@ -43,7 +43,7 @@ impl VirtioPciCommonConfig {
offset: u64,
data: &mut [u8],
queues: &mut Vec<Queue>,
device: &mut Box<VirtioDevice>,
device: &mut dyn VirtioDevice,
) {
match data.len() {
1 => {
@ -71,7 +71,7 @@ impl VirtioPciCommonConfig {
offset: u64,
data: &[u8],
queues: &mut Vec<Queue>,
device: &mut Box<VirtioDevice>,
device: &mut dyn VirtioDevice,
) {
match data.len() {
1 => self.write_common_config_byte(offset, data[0]),
@ -133,7 +133,7 @@ impl VirtioPciCommonConfig {
}
}
fn read_common_config_dword(&self, offset: u64, device: &Box<VirtioDevice>) -> u32 {
fn read_common_config_dword(&self, offset: u64, device: &dyn VirtioDevice) -> u32 {
match offset {
0x00 => self.device_feature_select,
0x04 => {
@ -155,7 +155,7 @@ impl VirtioPciCommonConfig {
offset: u64,
value: u32,
queues: &mut Vec<Queue>,
device: &mut Box<VirtioDevice>,
device: &mut dyn VirtioDevice,
) {
fn hi(v: &mut GuestAddress, x: u32) {
*v = (*v & 0xffffffff) | ((x as u64) << 32)
@ -267,41 +267,41 @@ mod tests {
queue_select: 0xff,
};
let mut dev: Box<VirtioDevice> = Box::new(DummyDevice(0));
let dev = &mut DummyDevice(0) as &mut dyn VirtioDevice;
let mut queues = Vec::new();
// Can set all bits of driver_status.
regs.write(0x14, &[0x55], &mut queues, &mut dev);
regs.write(0x14, &[0x55], &mut queues, dev);
let mut read_back = vec![0x00];
regs.read(0x14, &mut read_back, &mut queues, &mut dev);
regs.read(0x14, &mut read_back, &mut queues, dev);
assert_eq!(read_back[0], 0x55);
// The config generation register is read only.
regs.write(0x15, &[0xaa], &mut queues, &mut dev);
regs.write(0x15, &[0xaa], &mut queues, dev);
let mut read_back = vec![0x00];
regs.read(0x15, &mut read_back, &mut queues, &mut dev);
regs.read(0x15, &mut read_back, &mut queues, dev);
assert_eq!(read_back[0], 0x55);
// Device features is read-only and passed through from the device.
regs.write(0x04, &[0, 0, 0, 0], &mut queues, &mut dev);
regs.write(0x04, &[0, 0, 0, 0], &mut queues, dev);
let mut read_back = vec![0, 0, 0, 0];
regs.read(0x04, &mut read_back, &mut queues, &mut dev);
regs.read(0x04, &mut read_back, &mut queues, dev);
assert_eq!(LittleEndian::read_u32(&read_back), DUMMY_FEATURES as u32);
// Feature select registers are read/write.
regs.write(0x00, &[1, 2, 3, 4], &mut queues, &mut dev);
regs.write(0x00, &[1, 2, 3, 4], &mut queues, dev);
let mut read_back = vec![0, 0, 0, 0];
regs.read(0x00, &mut read_back, &mut queues, &mut dev);
regs.read(0x00, &mut read_back, &mut queues, dev);
assert_eq!(LittleEndian::read_u32(&read_back), 0x0403_0201);
regs.write(0x08, &[1, 2, 3, 4], &mut queues, &mut dev);
regs.write(0x08, &[1, 2, 3, 4], &mut queues, dev);
let mut read_back = vec![0, 0, 0, 0];
regs.read(0x08, &mut read_back, &mut queues, &mut dev);
regs.read(0x08, &mut read_back, &mut queues, dev);
assert_eq!(LittleEndian::read_u32(&read_back), 0x0403_0201);
// 'queue_select' can be read and written.
regs.write(0x16, &[0xaa, 0x55], &mut queues, &mut dev);
regs.write(0x16, &[0xaa, 0x55], &mut queues, dev);
let mut read_back = vec![0x00, 0x00];
regs.read(0x16, &mut read_back, &mut queues, &mut dev);
regs.read(0x16, &mut read_back, &mut queues, dev);
assert_eq!(read_back[0], 0xaa);
assert_eq!(read_back[1], 0x55);
}

View file

@ -149,7 +149,7 @@ const VIRTIO_PCI_DEVICE_ID_BASE: u16 = 0x1040; // Add to device type to get devi
pub struct VirtioPciDevice {
config_regs: PciConfiguration,
device: Box<VirtioDevice>,
device: Box<dyn VirtioDevice>,
device_activated: bool,
interrupt_status: Arc<AtomicUsize>,
@ -165,7 +165,7 @@ pub struct VirtioPciDevice {
impl VirtioPciDevice {
/// Constructs a new PCI transport for the given virtio device.
pub fn new(mem: GuestMemory, device: Box<VirtioDevice>) -> Result<Self> {
pub fn new(mem: GuestMemory, device: Box<dyn VirtioDevice>) -> Result<Self> {
let mut queue_evts = Vec::new();
for _ in device.queue_max_sizes().iter() {
queue_evts.push(EventFd::new()?)
@ -414,7 +414,7 @@ impl PciDevice for VirtioPciDevice {
o - COMMON_CONFIG_BAR_OFFSET,
data,
&mut self.queues,
&mut self.device,
self.device.as_mut(),
)
}
o if ISR_CONFIG_BAR_OFFSET <= o && o < ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE => {
@ -448,7 +448,7 @@ impl PciDevice for VirtioPciDevice {
o - COMMON_CONFIG_BAR_OFFSET,
data,
&mut self.queues,
&mut self.device,
self.device.as_mut(),
)
}
o if ISR_CONFIG_BAR_OFFSET <= o && o < ISR_CONFIG_BAR_OFFSET + ISR_CONFIG_SIZE => {

View file

@ -32,6 +32,7 @@ use std::cell::RefCell;
use std::collections::btree_map::Entry;
use std::collections::{BTreeMap as Map, BTreeSet as Set, VecDeque};
use std::convert::From;
use std::error::Error as StdError;
use std::ffi::CStr;
use std::fmt::{self, Display};
use std::fs::File;
@ -645,7 +646,7 @@ enum WlResp<'a> {
VfdHup {
id: u32,
},
Err(Box<std::error::Error>),
Err(Box<dyn StdError>),
OutOfMemory,
InvalidId,
InvalidType,
@ -891,11 +892,11 @@ impl WlVfd {
}
// The FD that is used for polling for events on this VFD.
fn poll_fd(&self) -> Option<&AsRawFd> {
self.socket
fn poll_fd(&self) -> Option<&dyn AsRawFd> {
self.socket.as_ref().map(|s| s as &dyn AsRawFd).or(self
.local_pipe
.as_ref()
.map(|s| s as &AsRawFd)
.or(self.local_pipe.as_ref().map(|&(_, ref p)| p as &AsRawFd))
.map(|&(_, ref p)| p as &dyn AsRawFd))
}
// Sends data/files from the guest to the host over this VFD.

View file

@ -113,6 +113,7 @@ pub fn create_gpu_memory_allocator() -> Result<Option<Box<GpuMemoryAllocator>>,
}
#[cfg(not(feature = "wl-dmabuf"))]
pub fn create_gpu_memory_allocator() -> Result<Option<Box<GpuMemoryAllocator>>, GpuAllocatorError> {
pub fn create_gpu_memory_allocator(
) -> Result<Option<Box<dyn GpuMemoryAllocator>>, GpuAllocatorError> {
Ok(None)
}

View file

@ -27,7 +27,7 @@ pub struct SystemAllocator {
io_address_space: Option<AddressAllocator>,
device_address_space: AddressAllocator,
mmio_address_space: AddressAllocator,
gpu_allocator: Option<Box<GpuMemoryAllocator>>,
gpu_allocator: Option<Box<dyn GpuMemoryAllocator>>,
next_irq: u32,
}
@ -98,7 +98,7 @@ impl SystemAllocator {
}
/// Gets an allocator to be used for GPU memory.
pub fn gpu_memory_allocator(&self) -> Option<&GpuMemoryAllocator> {
pub fn gpu_memory_allocator(&self) -> Option<&dyn GpuMemoryAllocator> {
self.gpu_allocator.as_ref().map(|v| v.as_ref())
}
}

View file

@ -4,7 +4,7 @@
use std;
use std::cmp::min;
use std::error;
use std::error::Error as StdError;
use std::ffi::CStr;
use std::fmt::{self, Display};
use std::fs::{File, OpenOptions};
@ -92,7 +92,7 @@ pub enum Error {
InvalidFdPath,
InvalidWaylandPath,
IoJail(io_jail::Error),
LoadKernel(Box<error::Error>),
LoadKernel(Box<dyn StdError>),
NetDeviceNew(virtio::NetError),
OpenAndroidFstab(PathBuf, io::Error),
OpenInitrd(PathBuf, io::Error),
@ -302,14 +302,14 @@ fn create_block_device(
// Access as a raw block device.
let dev = virtio::Block::new(raw_image, disk.read_only, Some(disk_device_socket))
.map_err(Error::BlockDeviceNew)?;
Box::new(dev) as Box<VirtioDevice>
Box::new(dev) as Box<dyn VirtioDevice>
}
ImageType::Qcow2 => {
// Valid qcow header present
let qcow_image = QcowFile::from(raw_image).map_err(Error::QcowDeviceCreate)?;
let dev = virtio::Block::new(qcow_image, disk.read_only, Some(disk_device_socket))
.map_err(Error::BlockDeviceNew)?;
Box::new(dev) as Box<VirtioDevice>
Box::new(dev) as Box<dyn VirtioDevice>
}
};
@ -484,11 +484,11 @@ fn create_net_device(
let dev =
virtio::vhost::Net::<Tap, vhost::Net<Tap>>::new(host_ip, netmask, mac_address, mem)
.map_err(Error::VhostNetDeviceNew)?;
Box::new(dev) as Box<VirtioDevice>
Box::new(dev) as Box<dyn VirtioDevice>
} else {
let dev =
virtio::Net::<Tap>::new(host_ip, netmask, mac_address).map_err(Error::NetDeviceNew)?;
Box::new(dev) as Box<VirtioDevice>
Box::new(dev) as Box<dyn VirtioDevice>
};
let policy = if cfg.vhost_net {
@ -768,7 +768,7 @@ fn create_devices(
balloon_device_socket: UnixSeqpacket,
disk_device_sockets: &mut Vec<UnixSeqpacket>,
usb_provider: HostBackendDeviceProvider,
) -> DeviceResult<Vec<(Box<PciDevice>, Option<Minijail>)>> {
) -> DeviceResult<Vec<(Box<dyn PciDevice>, Option<Minijail>)>> {
let stubs = create_virtio_devices(
&cfg,
mem,
@ -782,7 +782,7 @@ fn create_devices(
for stub in stubs {
let dev = VirtioPciDevice::new(mem.clone(), stub.dev).map_err(Error::VirtioPciDev)?;
let dev = Box::new(dev) as Box<PciDevice>;
let dev = Box::new(dev) as Box<dyn PciDevice>;
pci_devices.push((dev, stub.jail));
}

View file

@ -50,10 +50,7 @@ fn restore_stderr(stderr: File) -> bool {
}
// Sends as much information about the panic as possible to syslog.
fn log_panic_info(
default_panic: &Box<dyn Fn(&PanicInfo) + Sync + Send + 'static>,
info: &PanicInfo,
) {
fn log_panic_info(default_panic: &(dyn Fn(&PanicInfo) + Sync + Send + 'static), info: &PanicInfo) {
// Grab a lock of stderr to prevent concurrent threads from trampling on our stderr capturing
// procedure. The default_panic procedure likely uses stderr.lock as well, but the mutex inside
// stderr is reentrant, so it will not dead-lock on this thread.
@ -98,7 +95,7 @@ fn log_panic_info(
pub fn set_panic_hook() {
let default_panic = panic::take_hook();
panic::set_hook(Box::new(move |info| {
log_panic_info(&default_panic, info);
log_panic_info(default_panic.as_ref(), info);
// Abort to trigger the crash reporter so that a minidump is generated.
abort();
}));

View file

@ -16,7 +16,7 @@ pub enum FileFlags {
}
impl FileFlags {
pub fn from_file(file: &AsRawFd) -> Result<FileFlags> {
pub fn from_file(file: &dyn AsRawFd) -> Result<FileFlags> {
// Trivially safe because fcntl with the F_GETFL command is totally safe and we check for
// error.
let flags = unsafe { fcntl(file.as_raw_fd(), F_GETFL) };

View file

@ -148,7 +148,7 @@ pub enum FlockOperation {
/// Safe wrapper for flock(2) with the operation `op` and optionally `nonblocking`. The lock will be
/// dropped automatically when `file` is dropped.
#[inline(always)]
pub fn flock(file: &AsRawFd, op: FlockOperation, nonblocking: bool) -> Result<()> {
pub fn flock(file: &dyn AsRawFd, op: FlockOperation, nonblocking: bool) -> Result<()> {
let mut operation = match op {
FlockOperation::LockShared => libc::LOCK_SH,
FlockOperation::LockExclusive => libc::LOCK_EX,
@ -177,7 +177,7 @@ pub enum FallocateMode {
/// Safe wrapper for `fallocate()`.
pub fn fallocate(
file: &AsRawFd,
file: &dyn AsRawFd,
mode: FallocateMode,
keep_size: bool,
offset: u64,

View file

@ -160,7 +160,7 @@ impl MemoryMapping {
/// # Arguments
/// * `fd` - File descriptor to mmap from.
/// * `size` - Size of memory region in bytes.
pub fn from_fd(fd: &AsRawFd, size: usize) -> Result<MemoryMapping> {
pub fn from_fd(fd: &dyn AsRawFd, size: usize) -> Result<MemoryMapping> {
MemoryMapping::from_fd_offset(fd, size, 0)
}
@ -170,7 +170,7 @@ impl MemoryMapping {
/// * `fd` - File descriptor to mmap from.
/// * `size` - Size of memory region in bytes.
/// * `offset` - Offset in bytes from the beginning of `fd` to start the mmap.
pub fn from_fd_offset(fd: &AsRawFd, size: usize, offset: usize) -> Result<MemoryMapping> {
pub fn from_fd_offset(fd: &dyn AsRawFd, size: usize, offset: usize) -> Result<MemoryMapping> {
if offset > libc::off_t::max_value() as usize {
return Err(Error::InvalidOffset);
}

View file

@ -293,7 +293,7 @@ impl<T: PollToken> EpollContext<T> {
/// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and
/// there were no duplicated file descriptors (i.e. adding the same descriptor with a different
/// FD number) added to this context, events will not be reported by `wait` anymore.
pub fn add(&self, fd: &AsRawFd, token: T) -> Result<()> {
pub fn add(&self, fd: &dyn AsRawFd, token: T) -> Result<()> {
self.add_fd_with_events(fd, WatchingEvents::empty().set_read(), token)
}
@ -303,7 +303,12 @@ impl<T: PollToken> EpollContext<T> {
/// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and
/// there were no duplicated file descriptors (i.e. adding the same descriptor with a different
/// FD number) added to this context, events will not be reported by `wait` anymore.
pub fn add_fd_with_events(&self, fd: &AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
pub fn add_fd_with_events(
&self,
fd: &dyn AsRawFd,
events: WatchingEvents,
token: T,
) -> Result<()> {
let mut evt = epoll_event {
events: events.get_raw(),
u64: token.as_raw_token(),
@ -326,7 +331,7 @@ impl<T: PollToken> EpollContext<T> {
/// If `fd` was previously added to this context, the watched events will be replaced with
/// `events` and the token associated with it will be replaced with the given `token`.
pub fn modify(&self, fd: &AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
pub fn modify(&self, fd: &dyn AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
let mut evt = epoll_event {
events: events.0,
u64: token.as_raw_token(),
@ -353,7 +358,7 @@ impl<T: PollToken> EpollContext<T> {
/// method or by closing/dropping (if and only if the fd was never dup()'d/fork()'d) the `fd`.
/// Failure to do so will cause the `wait` method to always return immediately, causing ~100%
/// CPU load.
pub fn delete(&self, fd: &AsRawFd) -> Result<()> {
pub fn delete(&self, fd: &dyn AsRawFd) -> Result<()> {
// Safe because we give a valid epoll FD and FD to stop watching. Then we check the return
// value.
let ret = unsafe {
@ -497,7 +502,7 @@ impl<T: PollToken> PollContext<T> {
/// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and
/// there were no duplicated file descriptors (i.e. adding the same descriptor with a different
/// FD number) added to this context, events will not be reported by `wait` anymore.
pub fn add(&self, fd: &AsRawFd, token: T) -> Result<()> {
pub fn add(&self, fd: &dyn AsRawFd, token: T) -> Result<()> {
self.add_fd_with_events(fd, WatchingEvents::empty().set_read(), token)
}
@ -507,7 +512,12 @@ impl<T: PollToken> PollContext<T> {
/// A `fd` can only be added once and does not need to be kept open. If the `fd` is dropped and
/// there were no duplicated file descriptors (i.e. adding the same descriptor with a different
/// FD number) added to this context, events will not be reported by `wait` anymore.
pub fn add_fd_with_events(&self, fd: &AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
pub fn add_fd_with_events(
&self,
fd: &dyn AsRawFd,
events: WatchingEvents,
token: T,
) -> Result<()> {
self.epoll_ctx.add_fd_with_events(fd, events, token)?;
self.hangups.set(0);
self.max_hangups.set(self.max_hangups.get() + 1);
@ -516,7 +526,7 @@ impl<T: PollToken> PollContext<T> {
/// If `fd` was previously added to this context, the watched events will be replaced with
/// `events` and the token associated with it will be replaced with the given `token`.
pub fn modify(&self, fd: &AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
pub fn modify(&self, fd: &dyn AsRawFd, events: WatchingEvents, token: T) -> Result<()> {
self.epoll_ctx.modify(fd, events, token)
}
@ -526,7 +536,7 @@ impl<T: PollToken> PollContext<T> {
/// method or by closing/dropping (if and only if the fd was never dup()'d/fork()'d) the `fd`.
/// Failure to do so will cause the `wait` method to always return immediately, causing ~100%
/// CPU load.
pub fn delete(&self, fd: &AsRawFd) -> Result<()> {
pub fn delete(&self, fd: &dyn AsRawFd) -> Result<()> {
self.epoll_ctx.delete(fd)?;
self.hangups.set(0);
self.max_hangups.set(self.max_hangups.get() - 1);

View file

@ -38,7 +38,7 @@ pub trait UsbHotplugHandler: Send + Sync + 'static {
/// user_data to libusb_hotplug_register_callback.
pub struct UsbHotplugHandlerHolder {
context: Arc<LibUsbContextInner>,
handler: Box<UsbHotplugHandler>,
handler: Box<dyn UsbHotplugHandler>,
}
impl UsbHotplugHandlerHolder {

View file

@ -139,7 +139,7 @@ impl LibUsbContext {
}
/// Set a handler that could handle pollfd change events.
pub fn set_pollfd_notifiers(&self, handler: Box<LibUsbPollfdChangeHandler>) {
pub fn set_pollfd_notifiers(&self, handler: Box<dyn LibUsbPollfdChangeHandler>) {
// LibUsbContext is alive when any libusb related function is called. It owns the handler,
// thus the handler memory is always valid when callback is invoked.
let holder = Box::new(PollfdChangeHandlerHolder { handler });
@ -262,7 +262,7 @@ pub trait LibUsbPollfdChangeHandler: Send + Sync + 'static {
// This struct owns LibUsbPollfdChangeHandler. We need it because it's not possible to cast void
// pointer to trait pointer.
struct PollfdChangeHandlerHolder {
handler: Box<LibUsbPollfdChangeHandler>,
handler: Box<dyn LibUsbPollfdChangeHandler>,
}
// This function is safe when user_data points to valid PollfdChangeHandlerHolder.

View file

@ -130,7 +130,7 @@ impl UsbTransferBuffer for BulkTransferBuffer {
}
}
type UsbTransferCompletionCallback<T> = Fn(UsbTransfer<T>) + Send + 'static;
type UsbTransferCompletionCallback<T> = dyn Fn(UsbTransfer<T>) + Send + 'static;
// This wraps libusb_transfer pointer.
struct LibUsbTransfer {

View file

@ -182,7 +182,7 @@ pub enum VmRequest {
fn register_memory(
vm: &mut Vm,
allocator: &mut SystemAllocator,
fd: &AsRawFd,
fd: &dyn AsRawFd,
size: usize,
) -> Result<(u64, u32)> {
let mmap = match MemoryMapping::from_fd(fd, size) {

View file

@ -305,7 +305,7 @@ impl arch::LinuxArch for X8664arch {
F: FnOnce(
&GuestMemory,
&EventFd,
) -> std::result::Result<Vec<(Box<PciDevice>, Option<Minijail>)>, E>,
) -> std::result::Result<Vec<(Box<dyn PciDevice>, Option<Minijail>)>, E>,
E: StdError + 'static,
{
let mut resources =