Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Contracts & Harnesses for non_null::new and non_null::new_unchecked #88

Merged
merged 13 commits into from
Sep 27, 2024
35 changes: 35 additions & 0 deletions library/core/src/ptr/non_null.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,15 @@ use crate::num::NonZero;
use crate::ops::{CoerceUnsized, DispatchFromDyn};
use crate::pin::PinCoerceUnsized;
use crate::ptr::Unique;
use crate::ptr::null_mut;
QinyuanWu marked this conversation as resolved.
Show resolved Hide resolved
use crate::slice::{self, SliceIndex};
use crate::ub_checks::assert_unsafe_precondition;
use crate::{fmt, hash, intrinsics, ptr};
use safety::{ensures, requires};


#[cfg(kani)]
use crate::kani;

/// `*mut T` but non-zero and [covariant].
///
Expand Down Expand Up @@ -192,6 +198,8 @@ impl<T: ?Sized> NonNull<T> {
#[stable(feature = "nonnull", since = "1.25.0")]
#[rustc_const_stable(feature = "const_nonnull_new_unchecked", since = "1.25.0")]
#[inline]
#[requires(!ptr.is_null())]
#[ensures(|result| result.as_ptr() == ptr)]
pub const unsafe fn new_unchecked(ptr: *mut T) -> Self {
// SAFETY: the caller must guarantee that `ptr` is non-null.
unsafe {
Expand Down Expand Up @@ -221,6 +229,8 @@ impl<T: ?Sized> NonNull<T> {
#[stable(feature = "nonnull", since = "1.25.0")]
#[rustc_const_unstable(feature = "const_nonnull_new", issue = "93235")]
#[inline]
#[ensures(|result| result.is_some() == !ptr.is_null())]
#[ensures(|result| result.is_none() || result.expect("ptr is null!").as_ptr() == ptr)]
pub const fn new(ptr: *mut T) -> Option<Self> {
if !ptr.is_null() {
// SAFETY: The pointer is already checked and is not null
Expand Down Expand Up @@ -1770,3 +1780,28 @@ impl<T: ?Sized> From<&T> for NonNull<T> {
unsafe { NonNull { pointer: reference as *const T } }
}
}

#[cfg(kani)]
#[unstable(feature="kani", issue="none")]
mod verify {
use super::*;

// pub const unsafe fn new_unchecked(ptr: *mut T) -> Self
#[kani::proof_for_contract(NonNull::new_unchecked)]
pub fn non_null_check_new_unchecked() {
let mut x: i32 = kani::any();
let xptr = &mut x;
unsafe {
let _ = NonNull::new_unchecked(xptr as *mut i32);
QinyuanWu marked this conversation as resolved.
Show resolved Hide resolved
}
}

// pub const unsafe fn new(ptr: *mut T) -> Option<Self>
#[kani::proof_for_contract(NonNull::new)]
pub fn non_null_check_new() {
let mut x: i32 = kani::any();
let xptr = &mut x;
let maybe_null_ptr = if kani::any() { xptr as *mut i32 } else { null_mut() };
feliperodri marked this conversation as resolved.
Show resolved Hide resolved
let _ = NonNull::new(maybe_null_ptr);
}
}
Loading