Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions library/alloc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,7 @@
#![feature(min_specialization)]
#![feature(multiple_supertrait_upcastable)]
#![feature(negative_impls)]
#![feature(proc_macro_hygiene)]
#![feature(rustc_attrs)]
#![feature(slice_internals)]
#![feature(staged_api)]
Expand Down
66 changes: 66 additions & 0 deletions library/alloc/src/vec/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,13 +104,17 @@ use core::cmp::Ordering;
use core::hash::{Hash, Hasher};
#[cfg(not(no_global_oom_handling))]
use core::iter;
#[cfg(kani)]
use core::kani;
use core::marker::{Destruct, Freeze, PhantomData};
use core::mem::{self, Assume, ManuallyDrop, MaybeUninit, SizedTypeProperties, TransmuteFrom};
use core::ops::{self, Index, IndexMut, Range, RangeBounds};
use core::ptr::{self, NonNull};
use core::slice::{self, SliceIndex};
use core::{cmp, fmt, hint, intrinsics, ub_checks};

use safety::{ensures, requires};

#[stable(feature = "extract_if", since = "1.87.0")]
pub use self::extract_if::ExtractIf;
use crate::alloc::{Allocator, AllocatorNightly, Global};
Expand Down Expand Up @@ -165,6 +169,38 @@ use self::spec_from_elem::SpecFromElem;
#[cfg(not(no_global_oom_handling))]
mod spec_from_elem;

#[cfg(all(kani, not(no_global_oom_handling)))]
#[unstable(feature = "kani", issue = "none")]
mod verify_ch23;

/// Kani-only: partial check of documented `Vec` raw-parts layout invariants (see module docs).
/// Checks `length <= capacity`, non-null and alignment of `ptr`, `Layout::array::<T>(capacity)`
/// fitting within `isize::MAX` bytes, `can_write`, base-offset-0 (rejecting interior pointers
/// via `!same_allocation(ptr, ptr - 1)`), and in-bounds byte extent of at least
/// `capacity * size_of::<T>()` (permitting legal over-allocated custom-allocator blocks).
/// Remaining caller safety obligations NOT machine-checked by this predicate (due to Kani/CBMC
/// limitations) remain documented caller preconditions: (1) `ptr` was allocated via the matching
/// `Allocator` instance, (2) `ptr` was allocated with `T`'s exact alignment and a fitting layout
/// (`requested_size <= capacity * size_of::<T>() <= actual_size`), and (3) the first `length`
/// elements are initialized to valid values of `T`.
#[cfg(kani)]
fn vec_parts_valid<T>(ptr: *mut T, length: usize, capacity: usize) -> bool {
length <= capacity
&& !ptr.is_null()
&& ptr.is_aligned()
&& (T::IS_ZST || crate::alloc::Layout::array::<T>(capacity).is_ok())
&& ub_checks::can_write(ptr::slice_from_raw_parts_mut(ptr, capacity))
&& (T::IS_ZST
|| capacity == 0
|| (kani::mem::is_inbounds(ptr::slice_from_raw_parts(
ptr as *const u8,
capacity * mem::size_of::<T>(),
)) && !kani::mem::same_allocation(
ptr as *const u8,
(ptr as *const u8).wrapping_byte_sub(1),
)))
}

#[cfg(not(no_global_oom_handling))]
use self::set_len_on_drop::SetLenOnDrop;

Expand Down Expand Up @@ -629,6 +665,8 @@ impl<T> Vec<T> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
#[requires(vec_parts_valid(ptr, length, capacity))]
#[ensures(|result| result.len() == length && result.as_ptr() == ptr as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })]
pub const unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Self {
// SAFETY: Upheld by caller.
unsafe { Self::from_raw_parts_in(ptr, length, capacity, Global) }
Expand Down Expand Up @@ -709,6 +747,8 @@ impl<T> Vec<T> {
#[inline]
#[stable(feature = "box_vec_non_null", since = "1.99.0")]
#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
#[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))]
#[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })]
pub const unsafe fn from_parts(ptr: NonNull<T>, length: usize, capacity: usize) -> Self {
// SAFETY: Upheld by caller.
unsafe { Self::from_parts_in(ptr, length, capacity, Global) }
Expand Down Expand Up @@ -1222,6 +1262,8 @@ impl<T, A: Allocator> Vec<T, A> {
#[inline]
#[stable(feature = "allocator_api", since = "1.100.0")]
#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
#[requires(vec_parts_valid(ptr.as_ptr(), length, capacity))]
#[ensures(|result| result.len() == length && result.as_ptr() == ptr.as_ptr() as *const T && result.capacity() == if T::IS_ZST { usize::MAX } else { capacity })]
pub const unsafe fn from_parts_in(
ptr: NonNull<T>,
length: usize,
Expand Down Expand Up @@ -2142,6 +2184,16 @@ impl<T, A: Allocator> Vec<T, A> {
#[inline]
#[stable(feature = "rust1", since = "1.0.0")]
#[rustc_const_unstable(feature = "const_heap", issue = "79597")]
#[requires(new_len <= self.capacity())]
#[requires(
new_len <= self.len
|| ub_checks::can_dereference(ptr::slice_from_raw_parts(
self.as_ptr().wrapping_add(self.len),
new_len - self.len,
))
)]
#[cfg_attr(kani, kani::modifies(&self.len))]
#[ensures(|_| self.len() == new_len)]
pub const unsafe fn set_len(&mut self, new_len: usize) {
ub_checks::assert_unsafe_precondition!(
check_library_ub,
Expand Down Expand Up @@ -3442,6 +3494,8 @@ impl<T, A: Allocator> Vec<T, A> {
/// Safety: changing returned .2 (&mut usize) is considered the same as calling `.set_len(_)`.
///
/// This method provides unique access to all vec parts at once in `extend_from_within`.
#[requires(self.len <= self.buf.capacity())]
#[ensures(|result| result.0.len() == *result.2 && result.0.len() + result.1.len() == old(self.capacity()))]
const unsafe fn split_at_spare_mut_with_len(
&mut self,
) -> (&mut [T], &mut [MaybeUninit<T>], &mut usize) {
Expand Down Expand Up @@ -4051,6 +4105,18 @@ impl<T: Clone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {

#[cfg(not(no_global_oom_handling))]
impl<T: TrivialClone, A: Allocator> ExtendFromWithinSpec for Vec<T, A> {
#[requires(src.start <= src.end && src.end <= self.len())]
#[requires(src.end - src.start <= self.capacity() - self.len())]
#[ensures(|_| self.len() == old(self.len()) + old(src.end - src.start))]
#[ensures(|_| self.capacity() == old(self.capacity()))]
#[ensures(|_| self.as_ptr() == old(self.as_ptr()))]
#[cfg_attr(
kani,
kani::modifies(
&self.len,
ptr::slice_from_raw_parts(self.as_ptr().wrapping_add(self.len()), src.end - src.start),
)
)]
unsafe fn spec_extend_from_within(&mut self, src: Range<usize>) {
let count = src.len();
{
Expand Down
12 changes: 12 additions & 0 deletions library/alloc/src/vec/set_len_on_drop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,18 @@ impl<'a> SetLenOnDrop<'a> {
pub(super) fn current_len(&self) -> usize {
self.local_len
}

#[cfg(all(kani, not(no_global_oom_handling)))]
pub(super) fn kani_trace_increment_len(&mut self, increment: usize) {
self.local_len += increment;
// SAFETY: Kani verification harnesses are single-threaded; record the
// stack address of `self.local_len` once on the peeled iteration so
// `extend_trusted`'s loop invariant can observe the closure's exact
// `SetLenOnDrop` counter without modifying shipped code.
unsafe {
crate::vec::verify_ch23::record_extend_trusted_len_ptr(&raw mut self.local_len);
}
}
}

impl Drop for SetLenOnDrop<'_> {
Expand Down
4 changes: 4 additions & 0 deletions library/alloc/src/vec/spec_extend_with.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use core::clone::TrivialClone;
#[cfg(kani)]
use core::kani;
use core::{mem, ptr};

use crate::alloc::Allocator;
Expand Down Expand Up @@ -83,6 +85,8 @@ impl<T: TrivialClone, A: Allocator> SpecExtendWith<T> for Vec<T, A> {
// We use an incrementing index here instead of incrementing pointer because the former
// has been observed to have less register pressure in the loop initialization.
// https://llvm.org/docs/Vectorizers.html#inductions
#[cfg_attr(kani, kani::loop_invariant(i <= n))]
#[cfg_attr(kani, kani::loop_modifies(&i, ptr::slice_from_raw_parts_mut(ptr, n)))]
while i < n {
// SAFETY: `TrivialClone` indicates that copying `value` is equivalent to
// calling `Clone::clone` for `T`. As per the safety comment for `ptr`, this pointer
Expand Down
Loading
Loading