Description
Summary
The implementation of addr_of!
is just:
pub macro addr_of($place:expr) {
&raw const $place
}
Then the documentation for ptr::addr_of!
says:
Creating a reference with &/&mut is only allowed if the pointer is properly aligned and points to initialized data.
...
This macro can create a raw pointer without creating a reference first.Note, however, that the
expr
inaddr_of!(expr)
is still subject to all the usual rules.
The first paragraph of the documentation suggests that addr_of!
is useful for creating misaligned pointers. Then the second paragraph warns about "all the usual rules", which are not defined anywhere. So reading this documentation, one can come away with either impression about whether this program is well-defined or not:
struct Misalignment {
a: u32,
}
fn main() {
let items: [Misalignment; 2] = [Misalignment { a: 0 }, Misalignment { a: 1 }];
unsafe {
let ptr: *const Misalignment = items.as_ptr().cast::<u8>().add(1).cast::<Misalignment>();
let _ptr = core::ptr::addr_of!((*ptr).a);
}
}
Do "the usual rules" forbid the misaligned dereference inside of addr_of!
? Or is addr_of!
exempted because that's the whole reason it exists?
The goal of this meeting is to decide if we are able to bless this use of addr_of!
, whether we probably need it to be UB, or if we wish to delay this decision. If we wish to delay this decision, then we also have the goal of deciding what guidance we should offer to our users in the meantime.
Reading
- Don't check for misaligned raw pointer derefs inside Rvalue::AddressOf rust#112026
- Should raw pointer deref/projections have to be in-bounds? unsafe-code-guidelines#319
HackMD: https://hackmd.io/YjSceBPISBiGwsiqt9cDdw
Comment policy
These issues are meant to be used as an "announcements channel" regarding the proposal, and not as a
place to discuss the technical details. Feel free to subscribe to updates. We'll post comments when
reviewing the proposal in meetings or making a scheduling decision. In the meantime, if you have
questions or ideas, ping the proposers on Zulip (or elsewhere).