Skip to content

Conversation

@DiuDiu777
Copy link
Contributor

@DiuDiu777 DiuDiu777 commented Mar 25, 2025

In this PR:

  1. The initialization precondition for ptr::{ as_mut, as_ref, as_mut_unchecked, as_ref_unchecked } and NonNull::{ as_mut, as_ref } have been moved under the safety contracts.
  2. Specified the potential aliasing risks of APIs that return a reference, including ptr::{ as_mut, as_ref, as_mut_unchecked, as_ref_unchecked, as_uninit_mut, as_uninit_ref } and NonNull::{ as_mut, as_ref, as_uninit_mut, as_uninit_ref }. The following code passes the compiler's exclusivity checks, but Miri reports undefined behavior.
fn main() {
    use std::ptr::NonNull;
    let mut x = 0u32;
    let mut ptr = NonNull::new(&mut x).expect("null pointer");
    let x_ref = unsafe { ptr.as_mut() };
    unsafe { 
        *ptr.as_ptr() += 2;  
    }
    *x_ref += 2;
    println!("Final value: {}", x_ref);
}

@rustbot
Copy link
Collaborator

rustbot commented Mar 25, 2025

r? @Noratrieb

rustbot has assigned @Noratrieb.
They will have a look at your PR within the next two weeks and either review your PR or reassign to another reviewer.

Use r? to explicitly pick a reviewer

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue. labels Mar 25, 2025
Copy link
Member

@Noratrieb Noratrieb left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

what's the motivation for the two changes? I think having a note about aliasing and uninitialized memory is useful, but I'm not sure if they should be part of the # Safety section like that.

@DiuDiu777
Copy link
Contributor Author

Thanks for reviewing!

  • For Init, it's an exact precondition of these APIs. We’re moving this note into # Safety because that’s where all preconditions should live – it helps devs see the rules in one place and aligns with how other unsafe APIs document their contracts. Plus, it’ll make community to build safety contracts more fully in the future (like supporting contract verification project).
  • For alias, these APIs quietly require exclusive access (&mut guarantees) to avoid UB, but it wasn’t written down. For example, pointer::as_uninit_slice explicitly says this, but these APIs didn’t. We spotted real UB in code that violates this (see above code), so we’re fixing the docs to match what the APIs actually require.

@DiuDiu777 DiuDiu777 closed this Apr 11, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-libs Relevant to the library team, which will review and decide on the PR/issue.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants