Repository navigation
Description
Consider the following program:
fn main() {
use core::ptr::*;
unsafe { dbg!(replace(null_mut(), ())); }
}This was made a legal program in Rust 1.80, the preconditions state:
dstmust be valid for both reads and writes.dstmust be properly aligned.dstmust point to a properly initialized value of typeT.
This is because in Rust 1.80 the following line was added to valid:
For operations of size zero, every pointer is valid, including the null pointer. The following points are only concerned with non-zero-sized accesses.
Nevertheless, running the above program results in undefined behavior:
error: Undefined Behavior: constructing invalid value: encountered a null reference
--> /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1227:22
|
1227 | mem::replace(&mut *dst, src)
| ^^^^^^^^^ constructing invalid value: encountered a null reference
|
= help: this indicates a bug in the program: it performed an invalid operation, and caused Undefined Behavior
= help: see https://doc.rust-lang.org/nightly/reference/behavior-considered-undefined.html for further information
= note: BACKTRACE:
= note: inside `std::ptr::replace::<()>` at /playground/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu/lib/rustlib/src/rust/library/core/src/ptr/mod.rs:1227:22: 1227:31
note: inside `main`
--> src/main.rs:3:19
|
3 | unsafe { dbg!(replace(null_mut(), ())); }
| ^^^^^^^^^^^^^^^^^^^^^^^Rather than changing the implementation of core::ptr::replace, or an isolated change to the requirements of core::ptr::replace, I would like to see the change to the definition of a valid pointer for ZSTs reverted, I've expanded more about my thoughts and provided more arguments in this T-opsem zulip thread. In short, I believe that unsoundness similar to the case here in core::ptr::replace will keep happening as long as "dereferencing a pointer" and "reborrowing a pointer" have different requirements (which they do since Rust 1.80).
Activity
[-]core::ptr::replace is unsound since Rust 1.80[/-][+]core::ptr::replace implementation is unsound since Rust 1.80[/+]RalfJung commentedon Mar 11, 2025
Good catch, thanks! That is indeed an unintended consequence of the decision to allow zero-sized reads/writes from the null pointer.
Cc @rust-lang/opsem @rust-lang/lang
RalfJung commentedon Mar 11, 2025
To be fully precise, this is about the following two things not being equivalent any more:
size_of::<T>()many bytes, and it is aligned toalign_of::<T>(), and reading those bytes produces a valid representation ofT&Tzhi-ping commentedon Nov 19, 2025
@rustbot claim
RalfJung commentedon Nov 19, 2025
@zhi-ping How did you pick this issue? I would strongly recommend that you follow the advice we give in the dev guide and start with am issue that's explicitly listed as being suitable for beginners. It's not a good idea to pick something at random. This issue here involves discussing potential changes to the language semantics, it's not suited for someone new to the project.
RalfJung commentedon Nov 19, 2025
@rust-lang/opsem so, what do we think about this? I entirely lost track of this issue and it seems the same goes for everyone else.
The discussion on Zulip was not fully conclusive.
Some people argued that "readable" and "convertible to a reference" should be the same property, i.e., we should make reading (and writing) a null pointer UB again even if the read has size zero. However, the team members that replied generally didn't agree: adding more UB is not, or at least not always, the right way to make Rust more teachable; we can also teach people a weaker "layer of the tower" where they avoid reading from null even though doing so would be "fine". Or, as Jubilee put it:
On top of that, while "readable" and "convertible to a reference" being different indicates a loss of symmetry, there is other symmetry we gained: "dereferenceable for N bytes" and "can be inbounds-offset for N bytes" are now the same thing.
If we don't change what is UB, this becomes more of a @rust-lang/libs-api question, though functions like
ptr::read/writeare so fundamental that we may want to keep the lang team in the loop as well. Specifically, we could resolve this by changing the definition that the library uses for "valid for reads" to again require "is not null" (and similar for writes, which I won't keep repeating). Doing so would makenull_ptr.read()be library UB even when it is not language UB.The third option is to keep the notion of "valid for reads" unchanged, and instead change
ptr::replaceto simply return early doing nothing whenTis a ZST -- that's known at compile-time, so it has no overhead. However, we should then audit all other functions that use "valid for reads/writes" as their precondition to ensure they behave correctly when used for ZST accesses on a null pointer.Personally I prefer option 3. I don't like the idea of
ptr.read()being UB when*ptris not.9 remaining items
RalfJung commentedon Nov 21, 2025
#149169 implements the proposed change in
ptr::replace, to make it consistent withptr::readandptr::write.T-Dark0 commentedon Nov 21, 2025
Such code being suddenly broken and needing to add a ZST branch seems more than a little disruptive. It also seems sort of unnecessary, given the fix is trivial (replace
ptr.read()withif size_of::<T>() != 0 { ptr.read() } else { transmute(()) }. As a user, being told "you can't do this basic operation in the obvious way, but you can always do it in this other way instead" would like lead to me wondering "why doesreadnot just do that internally, then" (and the equivalent question can be asked aboutwrite)I personally don't think it's much of a problem to say that "can access through a pointer" no longer implies "can access through a reference". There is already a widespread understanding, in the parts of the community I know of, that mixing pointers and references is dangerous and best avoided: "stick to pointers instead".
That said, this also seems like a very niche use case, so I'd be willing to accept losing the "null is valid for ZST accesses" guarantee.
RalfJung commentedon Nov 21, 2025
The standard library alone contains at least two independent examples of code that creates a reference from a pointer based just on the knowledge that the pointer is valid for reads/writes. To add insult to injury, that was actually an entirely correct argument when the code was written.
So... I don't quite buy your claim that in the rest of the ecosystem, people are consistently very careful about such arguments.
RalfJung commentedon Nov 21, 2025
Some operations could promise that ZST null ptr accesses are erroneous: raw pointer loads/stores,
ptr::{read,write}, and a few more. However, we can't universally promise this for all functions that use "valid for reads/writes" in the precondition. That would get us back to the start for this issue --ptr::replacein its current form makes this UB, not EB (I think we should fix that); inCloneToUninit::clone_to_uninitit will probably remain UB.Of course we could also just document this to be a NOP in those functions, instead of erroneous behavior.
Rollup merge of rust-lang#149169 - RalfJung:replace-zst-null-ptr, r=M…
Rollup merge of rust-lang#149169 - RalfJung:replace-zst-null-ptr, r=M…
Unrolled build for #149169
Rollup merge of rust-lang#152615 - RalfJung:null-not-valid-for-read-w…
Unrolled build for #152615
Rollup merge of #152615 - RalfJung:null-not-valid-for-read-write, r=M…
Rollup merge of #149169 - RalfJung:replace-zst-null-ptr, r=Mark-Simul…
Rollup merge of #149169 - RalfJung:replace-zst-null-ptr, r=Mark-Simul…
Rollup merge of #149169 - RalfJung:replace-zst-null-ptr, r=Mark-Simul…
Rollup merge of #152615 - RalfJung:null-not-valid-for-read-write, r=M…