You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
macro_rules! field_ptr {($base_ptr:ident.$field:ident) => {// The only valid pointer cast from &T is *const T, so this is always// a const pointer to the field type exactly.&(*$base_ptr).$field as*const _
};}
creates a temporary reference to the structure but offset_of doesn't initialize the structure, so this creates a temporary reference to uninitialized memory which is unsound. There's related discussion in rust-lang/rust-bindgen#1651.
This also means that this macro can't be used to get the offset of a field in a packed struct:
error[E0793]: reference to packed field is unaligned
--> src/main.rs:7:9
|
7 | &(*$base_ptr).$field as *const _
| ^^^^^^^^^^^^^^^^^^^^
...
21 | let _ptr = unsafe { field_ptr!(base_ptr.y) };
| ---------------------- in this macro invocation
The proper way to get a field offset of an uninitialized struct is with the std::ptr::addr_of macro.
Create a const raw pointer to a place, without creating an intermediate reference.
Creating a reference with &/&mut is only allowed if the pointer is properly aligned and points to initialized data. For cases where those requirements do not hold, raw pointers should be used instead. However, &expr as *const _ creates a reference before casting it to a raw pointer, and that reference is subject to the same rules as all other references. This macro can create a raw pointer without creating a reference first.
Note that, to use the ptr methods, you need to first obtain a raw pointer to the data you want to initialize. It is illegal to construct a reference to uninitialized data, which implies that you have to be careful when obtaining said raw pointer:
[...]
For a struct, however, in general we do not know how it is laid out, and we also cannot use &mut base_ptr.field as that would be creating a reference. So, you must carefully use the addr_of_mut macro. This creates a raw pointer to the field without creating an intermediate reference
The text was updated successfully, but these errors were encountered:
The
field_ptr
macrocreates a temporary reference to the structure but
offset_of
doesn't initialize the structure, so this creates a temporary reference to uninitialized memory which is unsound. There's related discussion in rust-lang/rust-bindgen#1651.This also means that this macro can't be used to get the offset of a field in a packed struct:
The proper way to get a field offset of an uninitialized struct is with the
std::ptr::addr_of
macro.nomicon:
The text was updated successfully, but these errors were encountered: