rust-lang / rust-lang/rust

Safety requirements in `core::ptr` disregard type invariants

Open
#161,948 6 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-docs C-bug T-libs T-opsem
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

The only parts of the safety docs of ptr::read that are relevant to references are in the section about ownership.

The exact wording is:

read creates a bitwise copy of T, regardless of whether T is Copy. If T is not Copy, using both the returned value and the value at *src can violate memory safety. Note that assigning to *src counts as a use because it will attempt to drop the value at *src.

Therefore, I believe the following (unsound) function satisfies all safety requirements of read:

fn violate_pin_guarantees<T>(x: std::pin::Pin<Box<T>>) {
    // SAFETY:
    // - The pointer validity requirements are trivially satisfied, as it's created from `&T`
    // - Only the value returned from `read` is used. The original is forgotten.
    let inner: T = unsafe { std::ptr::read(&*x) };
    std::mem::forget(x);
    drop(inner);
}

In general, I believe that the functions in core::ptr are underspecified with respect to type invariants. Raw pointers can be used to bypass privacy and transmute things, yet we don't treat them with the same care as e.g. mem::transmute(_copy) in the docs.

@rustbot label I-unsound T-libs A-docs T-opsem

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start with the linked std::ptr::read documentation, especially the “Ownership of the returned value” section, then compare its safety requirements with the Pin example and the broader concern about core::ptr. Done means the relevant type-invariant and safety requirements are clearly specified in the affected documentation, with the scope of any broader changes decided.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
documentation
Issue type
Documentation
Difficulty
5/5
Estimated time
Over a week
Activity status
Active
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.