Skip to content
Open
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
107 changes: 90 additions & 17 deletions library/core/src/slice/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4500,6 +4500,10 @@ impl<T> [T] {
}
}

const fn align_to_gcd(a: usize, b: usize) -> usize {
if b == 0 { a } else { Self::align_to_gcd(b, a % b) }
}

/// Function to calculate lengths of the middle and trailing slice for `align_to{,_mut}`.
fn align_to_offsets<U>(&self) -> (usize, usize) {
// What we gonna do about `rest` is figure out what multiple of `U`s we can put in a
Expand All @@ -4520,13 +4524,9 @@ impl<T> [T] {
// Ts = size_of::<U> / gcd(size_of::<T>, size_of::<U>)
//
// Luckily since all this is constant-evaluated... performance here matters not!
const fn gcd(a: usize, b: usize) -> usize {
if b == 0 { a } else { gcd(b, a % b) }
}

// Explicitly wrap the function call in a const block so it gets
// constant-evaluated even in debug mode.
let gcd: usize = const { gcd(size_of::<T>(), size_of::<U>()) };
let gcd: usize = const { Self::align_to_gcd(size_of::<T>(), size_of::<U>()) };
let ts: usize = size_of::<U>() / gcd;
let us: usize = size_of::<T>() / gcd;

Expand All @@ -4537,6 +4537,37 @@ impl<T> [T] {
(us_len, ts_len)
}

#[cfg(kani)]
fn align_to_middle_is_maximal<U>(
addr: usize,
len: usize,
prefix: usize,
middle: usize,
suffix: usize,
) -> bool {
let unsplit = prefix == len && middle == 0 && suffix == 0;
if T::IS_ZST || U::IS_ZST {
return unsplit;
}

// Moving by whole T elements preserves the address modulo this gcd.
let alignment_gcd = const { Self::align_to_gcd(size_of::<T>(), align_of::<U>()) };
if addr % alignment_gcd != 0 {
return unsplit;
}

// Aligned starts repeat every alignment_period T elements. The contiguity
// postcondition and the middle slice's alignment make the first such start
// the only possible split within that period.
let alignment_period = align_of::<U>() / alignment_gcd;
let size_gcd = const { Self::align_to_gcd(size_of::<T>(), size_of::<U>()) };
let group_len = size_of::<U>() / size_gcd;
// A suffix shorter than one group cannot supply another whole group of U
// elements. Each group spans at least one alignment period, so an entire
// input shorter than the period cannot supply a group either.
prefix < alignment_period && suffix < group_len && (prefix < len || unsplit)
}

/// Transmutes the slice to a slice of another type, ensuring alignment of the types is
/// maintained.
///
Expand Down Expand Up @@ -4582,12 +4613,9 @@ impl<T> [T] {
}
}
)]
//The following clause guarantees that middle is of maximum size within self
//If U or T are ZSTs, then middle has size zero, so we adapt the check in that case
#[ensures(|(prefix, _, suffix): &(&[T], &[U], &[T])|
((U::IS_ZST || T::IS_ZST) && prefix.len() == self.len()) || (
(prefix.len() * size_of::<T>() < align_of::<U>()) &&
(suffix.len() * size_of::<T>() < size_of::<U>())
#[ensures(|(prefix, middle, suffix): &(&[T], &[U], &[T])|
Self::align_to_middle_is_maximal::<U>(
self.as_ptr().addr(), self.len(), prefix.len(), middle.len(), suffix.len(),
)
)]
//Either align_to just returns self in the prefix, or the 3 returned slices
Expand Down Expand Up @@ -4682,12 +4710,9 @@ impl<T> [T] {
}
}
)]
//The following clause guarantees that middle is of maximum size within self
//If U or T are ZSTs, then middle has size zero, so we adapt the check in that case
#[ensures(|(prefix, _, suffix): &(&mut [T], &mut [U], &mut [T])|
((U::IS_ZST || T::IS_ZST) && prefix.len() == old(self.len())) || (
(prefix.len() * size_of::<T>() < align_of::<U>()) &&
(suffix.len() * size_of::<T>() < size_of::<U>())
#[ensures(|(prefix, middle, suffix): &(&mut [T], &mut [U], &mut [T])|
Self::align_to_middle_is_maximal::<U>(
old(self.as_ptr().addr()), old(self.len()), prefix.len(), middle.len(), suffix.len(),
)
)]
//Either align_to just returns self in the prefix, or the 3 returned slices
Expand Down Expand Up @@ -6091,6 +6116,54 @@ mod verify {
gen_align_to_mut_harnesses!(align_to_mut_from_char, char);
gen_align_to_mut_harnesses!(align_to_mut_from_unit, ());

mod align_to_nontrivial_layouts {
use super::*;

proof_of_contract_for_align_to!(align_to_arr3_u16, [u8; 3], u16);
proof_of_contract_for_align_to_mut!(align_to_mut_arr3_u16, [u8; 3], u16);
proof_of_contract_for_align_to!(align_to_u32_u16x3, u32, [u16; 3]);
proof_of_contract_for_align_to_mut!(align_to_mut_u32_u16x3, u32, [u16; 3]);

#[repr(align(2))]
struct AlignedBytes([u8; 9]);

#[kani::proof_for_contract(<[[u8; 2]]>::align_to)]
fn align_to_arr2_u16() {
let bytes = AlignedBytes(kani::any());
let start = usize::from(kani::any::<bool>());
let len = kani::any_where(|len| *len <= 4);
// SAFETY: At most 8 initialized bytes remain in bounds at either offset, and
// [u8; 2] has byte alignment.
let src = unsafe { from_raw_parts(bytes.0.as_ptr().add(start).cast::<[u8; 2]>(), len) };
// SAFETY: Every initialized two-byte pattern is a valid u16.
let (prefix, middle, suffix) = unsafe { src.align_to::<u16>() };
kani::cover(start == 0 && !middle.is_empty(), "even offset produces a middle slice");
kani::cover(
start == 1 && !prefix.is_empty() && middle.is_empty() && suffix.is_empty(),
"odd offset cannot reach u16 alignment",
);
}

#[kani::proof_for_contract(<[[u8; 2]]>::align_to_mut)]
fn align_to_mut_arr2_u16() {
let mut bytes = AlignedBytes(kani::any());
let start = usize::from(kani::any::<bool>());
let len = kani::any_where(|len| *len <= 4);
// SAFETY: At most 8 initialized bytes remain in bounds at either offset, and
// [u8; 2] has byte alignment. The buffer is exclusively borrowed.
let src = unsafe {
from_raw_parts_mut(bytes.0.as_mut_ptr().add(start).cast::<[u8; 2]>(), len)
};
// SAFETY: The two types admit every initialized two-byte pattern, including writes.
let (prefix, middle, suffix) = unsafe { src.align_to_mut::<u16>() };
kani::cover(start == 0 && !middle.is_empty(), "even offset produces a middle slice");
kani::cover(
start == 1 && !prefix.is_empty() && middle.is_empty() && suffix.is_empty(),
"odd offset cannot reach u16 alignment",
);
}
}

#[kani::proof]
fn check_reverse() {
let mut a: [u8; 100] = kani::any();
Expand Down
Loading