Skip to content

Safety requirements in core::ptr disregard type invariants #161948

Description

@maxdexh

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and toolsC-bugCategory: This is a bug.T-libsRelevant to the library team, which will review and decide on the PR/issue.T-opsemRelevant to the opsem teamneeds-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions