Skip to content

core::ptr::replace implementation is unsound since Rust 1.80 #138351

Closed

Description

@orlp

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:

  • dst must be valid for both reads and writes.
  • dst must be properly aligned.
  • dst must point to a properly initialized value of type T.

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

  1. added
    C-bug
    on Mar 11, 2025
  2. added
    needs-triage
    on Mar 11, 2025
  3. changed the title [-]core::ptr::replace is unsound since Rust 1.80[/-] [+]core::ptr::replace implementation is unsound since Rust 1.80[/+] on Mar 11, 2025
  4. RalfJung commented on Mar 11, 2025

    @RalfJung
    Member

    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

  5. RalfJung commented on Mar 11, 2025

    @RalfJung
    Member

    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).

    To be fully precise, this is about the following two things not being equivalent any more:

    1. The pointer is valid for reads of size_of::<T>() many bytes, and it is aligned to align_of::<T>(), and reading those bytes produces a valid representation of T
    2. The pointer can be converted to a reference of type &T
  6. added
    T-lang
    I-unsound
    on Mar 12, 2025
  7. added
    I-prioritize
    on Mar 12, 2025
  8. removed
    I-prioritize
    on Mar 12, 2025
  9. added
    T-opsem
    and removed
    needs-triage
    on Apr 10, 2025
  10. zhi-ping commented on Nov 19, 2025

    @zhi-ping

    @rustbot claim

  11. RalfJung commented on Nov 19, 2025

    @RalfJung
    Member

    @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.

  12. RalfJung commented on Nov 19, 2025

    @RalfJung
    Member

    @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.

    1. 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:

      the entire motivation for the change was not "suddenly, it's a good idea to shove null ZST pointers everywhere!" but rather "we agreed that the blender should only turn on when it has something to actually blend, if you happen to put your foot in it and the blender does not automatically activate then you should consider yourself fortunate rather than continuing to find ways to tempt fate".

      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.

    2. If we don't change what is UB, this becomes more of a @rust-lang/libs-api question, though functions like ptr::read/write are 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 make null_ptr.read() be library UB even when it is not language UB.

    3. The third option is to keep the notion of "valid for reads" unchanged, and instead change ptr::replace to simply return early doing nothing when T is 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 *ptr is not.

  13. 9 remaining items

  14. RalfJung commented on Nov 21, 2025

    @RalfJung
    Member

    #149169 implements the proposed change in ptr::replace, to make it consistent with ptr::read and ptr::write.

  15. T-Dark0 commented on Nov 21, 2025

    @T-Dark0

    I am wondering if it makes sense to make zero-sized null pointer reads/writes into "erroneous behavior", and define them to either abort or do nothing.
    This seems like the worst possible outcome, to me. There is a lot of code out there that calls ptr::{read, write} on a pointer to a generic T, and this code can be perfectly sound, or at least isn't obviously unsound (consider for example replace_with, which can be implemented by reading a value out of the given &mut, then writeing the value the closure returns, if it doesn't panic).

    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() with if 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 does read not just do that internally, then" (and the equivalent question can be asked about write)

    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.

  16. RalfJung commented on Nov 21, 2025

    @RalfJung
    Member

    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.

  17. RalfJung commented on Nov 21, 2025

    @RalfJung
    Member

    I think I love that. So it would not be included in the "valid for reads" definition but instead be a note down below saying it's not UB but erroneous behavior, probably noting that reborrowing them is still instant UB? In that case there's no unnecessary undefined behavior, but also avoids this whole issue.

    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::replace in its current form makes this UB, not EB (I think we should fix that); in CloneToUninit::clone_to_uninit it will probably remain UB.

    Of course we could also just document this to be a NOP in those functions, instead of erroneous behavior.

  18. added a commit that references this issue on Feb 24, 2026
  19. added a commit that references this issue on Feb 25, 2026
  20. added a commit that references this issue on Feb 25, 2026
  21. added a commit that references this issue on Feb 28, 2026
  22. added a commit that references this issue on Feb 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugI-lang-radarI-unsoundT-langT-opsem

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions