rust: prefer NonNull::new to assertions

Do not use new_unchecked; the effect is the same, but the
code is easier to read and unsafe regions become smaller.
Likewise, NonNull::new can be used instead of assertion and
followed by as_ref() or as_mut() instead of dereferencing the
pointer.

Suggested-by: Zhao Liu <zhao1.liu@intel.com>
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
This commit is contained in:
Paolo Bonzini 2025-01-23 11:25:22 +01:00
parent 24f0e8d818
commit 7d0520398f
5 changed files with 35 additions and 47 deletions

View file

@ -593,11 +593,8 @@ pub const IRQMASK: [u32; 6] = [
/// the same size as [`PL011State`]. We also expect the device is /// the same size as [`PL011State`]. We also expect the device is
/// readable/writeable from one thread at any time. /// readable/writeable from one thread at any time.
pub unsafe extern "C" fn pl011_can_receive(opaque: *mut c_void) -> c_int { pub unsafe extern "C" fn pl011_can_receive(opaque: *mut c_void) -> c_int {
unsafe { let state = NonNull::new(opaque).unwrap().cast::<PL011State>();
debug_assert!(!opaque.is_null()); unsafe { state.as_ref().can_receive().into() }
let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
state.as_ref().can_receive().into()
}
} }
/// # Safety /// # Safety
@ -608,9 +605,8 @@ pub unsafe extern "C" fn pl011_can_receive(opaque: *mut c_void) -> c_int {
/// ///
/// The buffer and size arguments must also be valid. /// The buffer and size arguments must also be valid.
pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size: c_int) { pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size: c_int) {
let mut state = NonNull::new(opaque).unwrap().cast::<PL011State>();
unsafe { unsafe {
debug_assert!(!opaque.is_null());
let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
if state.as_ref().loopback_enabled() { if state.as_ref().loopback_enabled() {
return; return;
} }
@ -627,11 +623,8 @@ pub unsafe extern "C" fn pl011_receive(opaque: *mut c_void, buf: *const u8, size
/// the same size as [`PL011State`]. We also expect the device is /// the same size as [`PL011State`]. We also expect the device is
/// readable/writeable from one thread at any time. /// readable/writeable from one thread at any time.
pub unsafe extern "C" fn pl011_event(opaque: *mut c_void, event: QEMUChrEvent) { pub unsafe extern "C" fn pl011_event(opaque: *mut c_void, event: QEMUChrEvent) {
unsafe { let mut state = NonNull::new(opaque).unwrap().cast::<PL011State>();
debug_assert!(!opaque.is_null()); unsafe { state.as_mut().event(event) }
let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
state.as_mut().event(event)
}
} }
/// # Safety /// # Safety

View file

@ -12,12 +12,10 @@ use qemu_api::{
use crate::device::PL011State; use crate::device::PL011State;
#[allow(clippy::missing_const_for_fn)]
extern "C" fn pl011_clock_needed(opaque: *mut c_void) -> bool { extern "C" fn pl011_clock_needed(opaque: *mut c_void) -> bool {
unsafe { let state = NonNull::new(opaque).unwrap().cast::<PL011State>();
debug_assert!(!opaque.is_null()); unsafe { state.as_ref().migrate_clock }
let state = NonNull::new_unchecked(opaque.cast::<PL011State>());
state.as_ref().migrate_clock
}
} }
/// Migration subsection for [`PL011State`] clock. /// Migration subsection for [`PL011State`] clock.
@ -33,15 +31,12 @@ pub static VMSTATE_PL011_CLOCK: VMStateDescription = VMStateDescription {
}; };
extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int { extern "C" fn pl011_post_load(opaque: *mut c_void, version_id: c_int) -> c_int {
unsafe { let mut state = NonNull::new(opaque).unwrap().cast::<PL011State>();
debug_assert!(!opaque.is_null()); let result = unsafe { state.as_mut().post_load(version_id as u32) };
let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>()); if result.is_err() {
let result = state.as_mut().post_load(version_id as u32); -1
if result.is_err() { } else {
-1 0
} else {
0
}
} }
} }

View file

@ -25,7 +25,7 @@ pub static PL011_OPS: MemoryRegionOps = MemoryRegionOps {
unsafe extern "C" fn pl011_read(opaque: *mut c_void, addr: hwaddr, size: c_uint) -> u64 { unsafe extern "C" fn pl011_read(opaque: *mut c_void, addr: hwaddr, size: c_uint) -> u64 {
assert!(!opaque.is_null()); assert!(!opaque.is_null());
let mut state = unsafe { NonNull::new_unchecked(opaque.cast::<PL011State>()) }; let mut state = NonNull::new(opaque).unwrap().cast::<PL011State>();
let val = unsafe { state.as_mut().read(addr, size) }; let val = unsafe { state.as_mut().read(addr, size) };
match val { match val {
std::ops::ControlFlow::Break(val) => val, std::ops::ControlFlow::Break(val) => val,
@ -43,9 +43,6 @@ unsafe extern "C" fn pl011_read(opaque: *mut c_void, addr: hwaddr, size: c_uint)
} }
unsafe extern "C" fn pl011_write(opaque: *mut c_void, addr: hwaddr, data: u64, _size: c_uint) { unsafe extern "C" fn pl011_write(opaque: *mut c_void, addr: hwaddr, data: u64, _size: c_uint) {
unsafe { let mut state = NonNull::new(opaque).unwrap().cast::<PL011State>();
assert!(!opaque.is_null()); unsafe { state.as_mut().write(addr, data) }
let mut state = NonNull::new_unchecked(opaque.cast::<PL011State>());
state.as_mut().write(addr, data)
}
} }

View file

@ -4,7 +4,7 @@
//! Bindings to create devices and access device functionality from Rust. //! Bindings to create devices and access device functionality from Rust.
use std::ffi::CStr; use std::{ffi::CStr, ptr::NonNull};
pub use bindings::{DeviceClass, DeviceState, Property}; pub use bindings::{DeviceClass, DeviceState, Property};
@ -55,9 +55,8 @@ pub trait DeviceImpl {
/// can be downcasted to type `T`. We also expect the device is /// can be downcasted to type `T`. We also expect the device is
/// readable/writeable from one thread at any time. /// readable/writeable from one thread at any time.
unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(dev: *mut DeviceState, _errp: *mut *mut Error) { unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(dev: *mut DeviceState, _errp: *mut *mut Error) {
assert!(!dev.is_null()); let state = NonNull::new(dev).unwrap().cast::<T>();
let state = dev.cast::<T>(); T::REALIZE.unwrap()(unsafe { state.as_ref() });
T::REALIZE.unwrap()(unsafe { &mut *state });
} }
/// # Safety /// # Safety
@ -66,9 +65,8 @@ unsafe extern "C" fn rust_realize_fn<T: DeviceImpl>(dev: *mut DeviceState, _errp
/// can be downcasted to type `T`. We also expect the device is /// can be downcasted to type `T`. We also expect the device is
/// readable/writeable from one thread at any time. /// readable/writeable from one thread at any time.
unsafe extern "C" fn rust_reset_fn<T: DeviceImpl>(dev: *mut DeviceState) { unsafe extern "C" fn rust_reset_fn<T: DeviceImpl>(dev: *mut DeviceState) {
assert!(!dev.is_null()); let mut state = NonNull::new(dev).unwrap().cast::<T>();
let state = dev.cast::<T>(); T::RESET.unwrap()(unsafe { state.as_mut() });
T::RESET.unwrap()(unsafe { &mut *state });
} }
impl<T> ClassInitImpl<DeviceClass> for T impl<T> ClassInitImpl<DeviceClass> for T

View file

@ -58,6 +58,7 @@ use std::{
fmt, fmt,
ops::{Deref, DerefMut}, ops::{Deref, DerefMut},
os::raw::c_void, os::raw::c_void,
ptr::NonNull,
}; };
pub use bindings::{Object, ObjectClass}; pub use bindings::{Object, ObjectClass};
@ -153,27 +154,34 @@ impl<T: fmt::Display + ObjectType> fmt::Display for ParentField<T> {
} }
unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut Object) { unsafe extern "C" fn rust_instance_init<T: ObjectImpl>(obj: *mut Object) {
let mut state = NonNull::new(obj).unwrap().cast::<T>();
// SAFETY: obj is an instance of T, since rust_instance_init<T> // SAFETY: obj is an instance of T, since rust_instance_init<T>
// is called from QOM core as the instance_init function // is called from QOM core as the instance_init function
// for class T // for class T
unsafe { T::INSTANCE_INIT.unwrap()(&mut *obj.cast::<T>()) } unsafe {
T::INSTANCE_INIT.unwrap()(state.as_mut());
}
} }
unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut Object) { unsafe extern "C" fn rust_instance_post_init<T: ObjectImpl>(obj: *mut Object) {
let state = NonNull::new(obj).unwrap().cast::<T>();
// SAFETY: obj is an instance of T, since rust_instance_post_init<T> // SAFETY: obj is an instance of T, since rust_instance_post_init<T>
// is called from QOM core as the instance_post_init function // is called from QOM core as the instance_post_init function
// for class T // for class T
T::INSTANCE_POST_INIT.unwrap()(unsafe { &*obj.cast::<T>() }) T::INSTANCE_POST_INIT.unwrap()(unsafe { state.as_ref() });
} }
unsafe extern "C" fn rust_class_init<T: ObjectType + ClassInitImpl<T::Class>>( unsafe extern "C" fn rust_class_init<T: ObjectType + ClassInitImpl<T::Class>>(
klass: *mut ObjectClass, klass: *mut ObjectClass,
_data: *mut c_void, _data: *mut c_void,
) { ) {
let mut klass = NonNull::new(klass)
.unwrap()
.cast::<<T as ObjectType>::Class>();
// SAFETY: klass is a T::Class, since rust_class_init<T> // SAFETY: klass is a T::Class, since rust_class_init<T>
// is called from QOM core as the class_init function // is called from QOM core as the class_init function
// for class T // for class T
T::class_init(unsafe { &mut *klass.cast::<T::Class>() }) T::class_init(unsafe { klass.as_mut() })
} }
unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut Object) { unsafe extern "C" fn drop_object<T: ObjectImpl>(obj: *mut Object) {
@ -581,11 +589,8 @@ pub trait ClassInitImpl<T> {
/// can be downcasted to type `T`. We also expect the device is /// can be downcasted to type `T`. We also expect the device is
/// readable/writeable from one thread at any time. /// readable/writeable from one thread at any time.
unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) { unsafe extern "C" fn rust_unparent_fn<T: ObjectImpl>(dev: *mut Object) {
unsafe { let state = NonNull::new(dev).unwrap().cast::<T>();
assert!(!dev.is_null()); T::UNPARENT.unwrap()(unsafe { state.as_ref() });
let state = core::ptr::NonNull::new_unchecked(dev.cast::<T>());
T::UNPARENT.unwrap()(state.as_ref());
}
} }
impl<T> ClassInitImpl<ObjectClass> for T impl<T> ClassInitImpl<ObjectClass> for T