From 4b5775eda142a6ec8d0999751659d4ad2a8de792 Mon Sep 17 00:00:00 2001 From: Devin Watson Date: Tue, 17 Nov 2026 00:40:46 -0500 Subject: [PATCH 1/5] Challenge 22: Verify the safety of str iter functions with Kani --- library/core/src/array/iter/iter_inner.rs | 81 ++ library/core/src/slice/iter.rs | 10 + library/core/src/str/iter.rs | 1126 +++++++++++++++++++++ 3 files changed, 1217 insertions(+) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index d93cbf32c0162..c4f3932beffa8 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -324,3 +324,84 @@ impl PolymorphicIter<[MaybeUninit]> { }) } } + +#[cfg(kani)] +use crate::kani; + +// Loop-free sound over-approximation of `PolymorphicIter::fold` on `bool/u8` sum (total <= 32). +// Implemented as an inherent helper rather than an attached `PolymorphicIter::fold` contract +// (avoiding generic-method contract limits, cf. kani#4084), and paired with +// `check_kani_fold_bounded32_soundness` proving real `PolymorphicIter::fold` satisfies +// `res <= total && len == 0` for all 2^32 Boolean valuations. +#[cfg(kani)] +impl PolymorphicIter<[MaybeUninit]> { + pub(super) fn kani_fold_bounded32(&mut self, mut accum: B, f: F) -> B + where + F: FnMut(B, T) -> B, + { + assert!(crate::mem::size_of::() == 1); + assert!(crate::mem::size_of::() == 0); + assert!(kani::mem::can_dereference((&raw const accum).cast::())); + assert!(unsafe { *(&raw const accum).cast::() } == 0); + let total = self.len(); + assert!(total <= 32); + let _ = f; + let res_u8: u8 = kani::any(); + kani::assume(res_u8 <= total as u8); + self.alive = crate::ops::IndexRange::zero_to(0); + assert!(self.len() == 0, "bounded fold did not consume the iterator"); + kani::cover(total == 32, "bounded32 helper reached"); + unsafe { *(&raw mut accum).cast::() = res_u8 }; + accum + } +} + +#[cfg(kani)] +#[kani::proof] +pub fn check_kani_fold_bounded32_soundness() { + let values: [bool; 32] = [ + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + ]; + let mut iter = values.into_iter(); + let total = iter.len(); + assert_eq!(total, 32); + let res: u8 = iter.unsize_mut().fold(0u8, |accum, value| accum + value as u8); + assert!((res as usize) <= total); + assert_eq!(iter.len(), 0); + let sum_res: u8 = values.into_iter().map(|v| v as u8).sum(); + assert_eq!(sum_res, res); + kani::cover(res == 0, "all values false"); + kani::cover(res == 32, "all values true"); + kani::cover(res > 0 && res < 32, "mixed values"); +} diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 9e5a8338b8afc..e1b9fd6d9c791 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -3402,3 +3402,13 @@ mod verify { check_iter_with_ty!(verify_char, char, 50); check_iter_with_ty!(verify_tup, (char, u8), 50); } + +#[cfg(kani)] +impl<'a, T> Iter<'a, T> { + /// Exposes the raw cursor and end pointers for sibling `core::str::iter` Kani invariants. + pub(crate) fn kani_parts_for_ch22(&self) -> (*const T, *const T) { + // NonNull is transparent over its pointer; T is Sized here. + let cursor = unsafe { crate::mem::transmute::, *const T>(self.ptr) }; + (cursor, self.end_or_len) + } +} diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index cc7b0e6324fbc..1b75534c8d85f 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -54,11 +54,27 @@ impl<'a> Iterator for Chars<'a> { #[inline] fn advance_by(&mut self, mut remainder: usize) -> Result<(), NonZero> { const CHUNK_SIZE: usize = 32; + #[cfg(kani)] + let initial_remainder = remainder; + #[cfg(kani)] + let original = self.iter.as_slice(); + #[cfg(kani)] + let original_ptr = original.as_ptr(); + #[cfg(kani)] + let original_full = original.len() - original.len() % CHUNK_SIZE; if remainder >= CHUNK_SIZE { let mut chunks = self.iter.as_slice().as_chunks::().0.iter(); let mut bytes_skipped: usize = 0; + #[safety::loop_invariant({ + let (cp, ce) = chunks.kani_parts_for_ch22(); + let r0 = initial_remainder; + bytes_skipped % CHUNK_SIZE == 0 && bytes_skipped <= original_full + && (cp as *const u8) == (unsafe { crate::intrinsics::arith_offset(original_ptr, bytes_skipped as isize) }) + && (ce as *const u8) == (unsafe { crate::intrinsics::arith_offset(original_ptr, original_full as isize) }) + && remainder <= r0 && r0 - remainder <= bytes_skipped + })] while remainder > CHUNK_SIZE && let Some(chunk) = chunks.next() { @@ -66,6 +82,8 @@ impl<'a> Iterator for Chars<'a> { let mut start_bytes = [false; CHUNK_SIZE]; + #[cfg_attr(kani, kani::loop_modifies(&raw mut start_bytes))] + #[cfg_attr(kani, kani::loop_invariant(kani::index <= CHUNK_SIZE && (chunk as *const [u8; 32] as usize) != 0 && verify::bool32_valid(&raw const start_bytes)))] for i in 0..CHUNK_SIZE { start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); } @@ -78,6 +96,10 @@ impl<'a> Iterator for Chars<'a> { unsafe { self.iter.advance_by(bytes_skipped).unwrap_unchecked() }; // skip trailing continuation bytes + // Verification frame: advance_by changes the cursor pointer only. + // Keep the endpoint fixed so the original allocation stays identified. + #[cfg_attr(kani, kani::loop_modifies((&raw mut self.iter).cast::<*const u8>()))] + #[safety::loop_invariant(self.kani_cont_loop_inv(bytes_skipped, original))] while self.iter.len() > 0 { let b = self.iter.as_slice()[0]; if !super::validations::utf8_is_cont_byte(b) { @@ -85,9 +107,14 @@ impl<'a> Iterator for Chars<'a> { } // SAFETY: We just peeked at the byte, therefore it exists unsafe { self.iter.advance_by(1).unwrap_unchecked() }; + // verification-only: the byte just skipped is a continuation byte + #[cfg(kani)] + assert!(super::validations::utf8_is_cont_byte(b)); } } + #[cfg_attr(kani, kani::loop_modifies((&raw mut self.iter).cast::<*const u8>(), &raw mut remainder))] + #[safety::loop_invariant(self.kani_char_loop_inv(remainder, original, initial_remainder))] while (remainder > 0) && (self.iter.len() > 0) { remainder -= 1; let b = self.iter.as_slice()[0]; @@ -161,6 +188,60 @@ impl<'a> Chars<'a> { // SAFETY: `Chars` is only made from a str, which guarantees the iter is valid UTF-8. unsafe { from_utf8_unchecked(self.iter.as_slice()) } } + + #[cfg(kani)] + pub(super) fn raw_parts(&self) -> (*const u8, *const u8) { + self.iter.kani_parts_for_ch22() + } + + #[cfg(kani)] + pub(super) fn kani_cont_loop_inv(&self, skipped: usize, original: &[u8]) -> bool { + let (p, total_len) = (original as *const [u8] as *const u8, original.len()); + let (ptr, end) = self.raw_parts(); + let cur = crate::intrinsics::wrapping_sub(ptr as usize, p as usize); + // `cur >= skipped`: the byte offset never falls behind what the chunk loop skipped + cur <= total_len + && cur >= skipped + && ptr == unsafe { crate::intrinsics::arith_offset(p, cur as isize) } + && end == unsafe { crate::intrinsics::arith_offset(p, total_len as isize) } + } + + #[cfg(kani)] + pub(super) fn kani_char_loop_inv( + &self, + remainder: usize, + original: &[u8], + initial_remainder: usize, + ) -> bool { + let (p, total_len) = (original as *const [u8] as *const u8, original.len()); + let (ptr, end) = self.raw_parts(); + let cur = crate::intrinsics::wrapping_sub(ptr as usize, p as usize); + // Challenge Assumption (4) expanded in scalar form at boundary `cur`. + if cur <= total_len { + if cur < original.len() && !((original[cur] as i8) < -64) { + let width = match original[cur] { + 0x00..=0x7F => 1usize, + 0xC2..=0xDF => 2, + 0xE0..=0xEF => 3, + 0xF0..=0xF4 => 4, + _ => 0, + }; + kani::assume(width > 0 && width <= original.len() - cur); + let next = cur + width; + kani::assume(next == original.len() || !((original[next] as i8) < -64)); + } + } + // `remainder` chars still to skip out of the entry count: the chars skipped so far + // (`initial_remainder - remainder`) are at most the bytes consumed (a char has at least one byte). + // Entry of the loop checks this against the chunk loop's bookkeeping. + let r0 = initial_remainder; + cur <= total_len + && (cur == total_len || !((original[cur] as i8) < -64)) + && remainder <= r0 + && r0 - remainder <= cur + && ptr == unsafe { crate::intrinsics::arith_offset(p, cur as isize) } + && end == unsafe { crate::intrinsics::arith_offset(p, total_len as isize) } + } } /// An iterator over the [`char`]s of a string slice, and their positions. @@ -1663,3 +1744,1048 @@ macro_rules! escape_types_impls { } escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode); + +#[cfg(kani)] +pub(super) mod verify { + use super::*; + use crate::str::pattern::{self, SearchStep}; + use crate::str::validations; + + macro_rules! cover { + ($cond:expr) => { + kani::cover($cond, stringify!($cond)); + }; + } + + // Pointer-model allocation invariant: slices and raw pointers allocated under Kani's + // pointer offset model adhere to Rust memory layout constraints. + // Under Kani -Z c-ffi, malloc allocates a fresh symbolic buffer (nondet u8 bytes). + const MAX_ALLOCATION_BYTES: usize = (1 << 51) - 1; + + unsafe extern "C" { + fn malloc(size: usize) -> *mut u8; + fn __CPROVER_havoc_slice(pointer: *mut u8, size: usize); + } + + fn any_alloc(len: usize) -> *const u8 { + let p = unsafe { malloc(len) }; + kani::assume(!p.is_null()); + // Initialize before forming a reference. CBMC's existing havoc_slice + // primitive then writes independent arbitrary byte values. All u8 bit + // patterns are valid; no algorithm output or UTF-8 fact is assumed here. + // https://github.com/diffblue/cbmc/blob/develop/doc/cprover-manual/api.md + unsafe { crate::ptr::write_bytes(p, 0, len) }; + if len > 0 { + unsafe { __CPROVER_havoc_slice(p, len) }; + } + p + } + + #[kani::proof] + pub fn check_arbitrary_initialized_buffer() { + let len: usize = kani::any(); + kani::assume(len <= MAX_ALLOCATION_BYTES); + let p = any_alloc(len); + let bytes = unsafe { crate::slice::from_raw_parts(p, len) }; + cover!(len == 0); + if len > 0 { + let i: usize = kani::any(); + kani::assume(i < len); + cover!(bytes[i] == 0); + cover!(bytes[i] == 255); + cover!(len > 100 && bytes[i] == 195); + } + if len >= 2 { + cover!(bytes[0] != bytes[1]); + } + } + + // number of ModelSearcher::next_match_back calls (spec of the trailing-empty-piece skip) + pub(super) static mut NMB_CALLS: usize = 0; + // results (the reported match) of the first two ModelSearcher::next_match_back calls + pub(super) static mut NMB_RES: [Option<(usize, usize)>; 2] = [None, None]; + + // Challenge Assumption (4): valid UTF-8 strings. Generates an unbounded symbolic &str + // with symbolic length up to MAX_ALLOCATION_BYTES. + fn any_haystack() -> &'static str { + let len: usize = kani::any(); + kani::assume(len <= MAX_ALLOCATION_BYTES); + let p = any_alloc(len); + unsafe { crate::str::from_utf8_unchecked(crate::slice::from_raw_parts(p, len)) } + } + + #[inline] + fn raw_utf8_char_width(b: u8) -> usize { + match b { + 0x00..=0x7F => 1, + 0xC2..=0xDF => 2, + 0xE0..=0xEF => 3, + 0xF0..=0xF4 => 4, + _ => 0, + } + } + + // Pure table replacement, checked against the real table on all 256 inputs. + // No assumption about the calling algorithm or remaining buffer is made. + fn stub_utf8_char_width(b: u8) -> usize { + raw_utf8_char_width(b) + } + + // Explicit instance of Challenge Assumption (4), queried only against the + // captured original immutable input, never against the byte passed to width. + // The implication is true at EVERY offset of a valid UTF-8 string, including + // offsets chosen by an incorrect algorithm. It does not assume that the + // algorithm is at a boundary, advances correctly, or returns the right result. + pub(super) fn assume_original_utf8_at(original: &[u8], pos: usize) { + if pos < original.len() && !validations::utf8_is_cont_byte(original[pos]) { + let width = validations::utf8_char_width(original[pos]); + kani::assume(width > 0 && width <= original.len() - pos); + let next = pos + width; + kani::assume(next == original.len() || !validations::utf8_is_cont_byte(original[next])); + } + } + + // Loop-free RFC 3629 UTF-8 validation predicates for decoders + #[inline] + fn is_valid_first_utf8_char(b: &[u8]) -> bool { + if b.is_empty() { + return true; + } + match b[0] { + 0x00..=0x7F => true, + 0xC2..=0xDF => b.len() >= 2 && validations::utf8_is_cont_byte(b[1]), + 0xE0 => { + b.len() >= 3 + && (b[1] >= 0xA0 && b[1] <= 0xBF) + && validations::utf8_is_cont_byte(b[2]) + } + 0xE1..=0xEC | 0xEE..=0xEF => { + b.len() >= 3 + && validations::utf8_is_cont_byte(b[1]) + && validations::utf8_is_cont_byte(b[2]) + } + 0xED => { + b.len() >= 3 + && (b[1] >= 0x80 && b[1] <= 0x9F) + && validations::utf8_is_cont_byte(b[2]) + } + 0xF0 => { + b.len() >= 4 + && (b[1] >= 0x90 && b[1] <= 0xBF) + && validations::utf8_is_cont_byte(b[2]) + && validations::utf8_is_cont_byte(b[3]) + } + 0xF1..=0xF3 => { + b.len() >= 4 + && validations::utf8_is_cont_byte(b[1]) + && validations::utf8_is_cont_byte(b[2]) + && validations::utf8_is_cont_byte(b[3]) + } + 0xF4 => { + b.len() >= 4 + && (b[1] >= 0x80 && b[1] <= 0x8F) + && validations::utf8_is_cont_byte(b[2]) + && validations::utf8_is_cont_byte(b[3]) + } + _ => false, + } + } + + // The last char of `b` is complete and valid: the nearest non-continuation byte within the last + // four bytes is a valid lead byte whose char ends exactly at the end of `b`. + #[inline] + fn is_valid_last_utf8_char(b: &[u8]) -> bool { + let n = b.len(); + if n == 0 { + return true; + } + let k = last_char_len(b); + n >= k && is_valid_first_utf8_char(&b[n - k..]) && raw_utf8_char_width(b[n - k]) == k + } + + #[derive(Clone)] + pub struct ModelPattern; + + pub struct ModelSearcher<'a> { + pub haystack: &'a str, + pub front: usize, + pub back: usize, + pub last_match: Option<(usize, usize)>, + } + + // See verify-rust-std#753 (rust-lang/rust#165681): `Pattern` is still a safe trait on + // the pinned toolchain; update to `unsafe impl Pattern for ModelPattern` once synced past rust#165681. + impl Pattern for ModelPattern { + type Searcher<'a> = ModelSearcher<'a>; + fn into_searcher(self, haystack: &str) -> ModelSearcher<'_> { + ModelSearcher { haystack, front: 0, back: haystack.len(), last_match: None } + } + } + + // Challenge Assumption (2): pattern.rs is safe and correct. This is a + // nondeterministic over-approximation of its documented range guarantees, + // not an implementation of the matching semantics of one fixed pattern. + // Both Match and Reject may be empty (Searcher::next, ReverseSearcher::next_back). + fn assume_search_range(s: &str, lo: usize, hi: usize, a: usize, b: usize) { + // Adjacent, non-overlapping ranges remain in the unsearched interval. + kani::assume(lo <= a && a <= b && b <= hi); + // Searcher safety requirement: both endpoints are UTF-8 boundaries. + kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); + cover!(a == b); + cover!(a < b); + } + + unsafe impl<'a> Searcher<'a> for ModelSearcher<'a> { + fn haystack(&self) -> &'a str { + self.haystack + } + + fn next(&mut self) -> crate::str::pattern::SearchStep { + use crate::str::pattern::SearchStep; + // Done is allowed only after every byte has been visited. Equality + // alone does not force Done: an empty match/reject can still follow. + if self.front == self.back && kani::any() { + return SearchStep::Done; + } + let a = self.front; + let b = kani::any(); + assume_search_range(self.haystack, self.front, self.back, a, b); + self.front = b; + if kani::any() { SearchStep::Match(a, b) } else { SearchStep::Reject(a, b) } + } + + fn next_match(&mut self) -> Option<(usize, usize)> { + let result = if kani::any() { + // Abstract any sequence of rejects followed by Done. + self.front = self.back; + None + } else { + let a = kani::any(); + let b = kani::any(); + assume_search_range(self.haystack, self.front, self.back, a, b); + self.front = b; + Some((a, b)) + }; + self.last_match = result; + result + } + } + + unsafe impl<'a> ReverseSearcher<'a> for ModelSearcher<'a> { + fn next_back(&mut self) -> crate::str::pattern::SearchStep { + use crate::str::pattern::SearchStep; + if self.front == self.back && kani::any() { + return SearchStep::Done; + } + let a = kani::any(); + let b = self.back; + assume_search_range(self.haystack, self.front, self.back, a, b); + self.back = a; + if kani::any() { SearchStep::Match(a, b) } else { SearchStep::Reject(a, b) } + } + + fn next_match_back(&mut self) -> Option<(usize, usize)> { + let call = unsafe { NMB_CALLS }; + unsafe { NMB_CALLS += 1 }; + let result = if kani::any() { + self.back = self.front; + None + } else { + let a = kani::any(); + let b = kani::any(); + assume_search_range(self.haystack, self.front, self.back, a, b); + self.back = a; + Some((a, b)) + }; + self.last_match = result; + if call < 2 { + unsafe { NMB_RES[call] = result }; + } + result + } + } + + impl<'a> DoubleEndedSearcher<'a> for ModelSearcher<'a> {} + + fn searcher_invariant(m: &ModelSearcher<'_>) -> bool { + m.front <= m.back + && m.back <= m.haystack.len() + && m.haystack.is_char_boundary(m.front) + && m.haystack.is_char_boundary(m.back) + } + + // One arbitrary transition from an arbitrary valid state proves inductive + // preservation of the range invariant; no bound on the number of steps. + #[kani::proof] + pub fn check_model_searcher_step() { + use crate::str::pattern::SearchStep; + let s = any_haystack(); + let mut m = any_split(s).matcher; + let (lo, hi) = (m.front, m.back); + unsafe { NMB_CALLS = 0 }; + let direction: u8 = kani::any(); + let step = match direction % 4 { + 0 => m.next(), + 1 => m.next_back(), + 2 => m.next_match().map_or(SearchStep::Done, |(a, b)| SearchStep::Match(a, b)), + _ => m.next_match_back().map_or(SearchStep::Done, |(a, b)| SearchStep::Match(a, b)), + }; + assert!(searcher_invariant(&m)); + assert!(lo <= m.front && m.back <= hi); + assert_eq!(m.haystack.as_ptr(), s.as_ptr()); + assert_eq!(m.haystack.len(), s.len()); + match step { + SearchStep::Match(a, b) | SearchStep::Reject(a, b) => { + assert!(lo <= a && a <= b && b <= hi); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + if direction % 4 == 0 { + assert_eq!(a, lo); + } + if direction % 4 == 1 { + assert_eq!(b, hi); + } + cover!(lo == hi && a == b); + cover!(a < b); + } + SearchStep::Done => { + assert_eq!(m.front, m.back); + } + } + cover!(matches!(step, SearchStep::Done)); + cover!(matches!(step, SearchStep::Reject(_, _))); + cover!(matches!(step, SearchStep::Match(_, _))); + } + + fn split_invariant(it: &SplitInternal<'_, ModelPattern>) -> bool { + searcher_invariant(&it.matcher) + && it.start <= it.matcher.front + && it.matcher.back <= it.end + && it.end <= it.matcher.haystack.len() + && it.matcher.haystack.is_char_boundary(it.start) + && it.matcher.haystack.is_char_boundary(it.end) + } + + fn assert_valid_subslice(s: &str, sub: &str) { + let base = s.as_ptr() as usize; + let sub_ptr = sub.as_ptr() as usize; + let start = sub_ptr.wrapping_sub(base); + let end = start.wrapping_add(sub.len()); + assert!(start <= end && end <= s.len()); + assert!(sub.as_ptr() == unsafe { s.as_ptr().add(start) }); + assert!(s.is_char_boundary(start) && s.is_char_boundary(end)); + } + + // `sub` is exactly the piece s[lo..hi] (same pointer, same length). + fn assert_piece(s: &str, sub: &str, lo: usize, hi: usize) { + assert!(lo <= hi && hi <= s.len()); + assert!(sub.as_ptr() == unsafe { s.as_ptr().add(lo) }); + assert_eq!(sub.len(), hi - lo); + } + + // Exact spec of one next_back / next_back_inclusive call, from the matches the searcher + // reported (NMB_CALLS searches, NMB_RES results). Piece = s[b..end] and new end = a + // (exclusive) or b (inclusive); with !allow_trailing_empty the first search may only produce + // the (skipped) empty trailing piece, then a second search follows. + fn assert_next_back_spec( + s: &str, + split: &SplitInternal<'static, ModelPattern>, + res: Option<&str>, + so: usize, + eo: usize, + was_finished: bool, + skip: bool, + inclusive: bool, + ) { + let n = unsafe { NMB_CALLS }; + let r1 = unsafe { NMB_RES[0] }; + let r2 = unsafe { NMB_RES[1] }; + if was_finished { + assert!(res.is_none()); + assert_eq!(n, 0); + assert!(split.finished); + return; + } + assert!(split.allow_trailing_empty); + assert_eq!(split.start, so); + let new_end = |m: (usize, usize)| if inclusive { m.1 } else { m.0 }; + if !skip { + assert_eq!(n, 1); + match r1 { + Some(m) => { + assert_piece(s, res.unwrap(), m.1, eo); + assert_eq!(split.end, new_end(m)); + assert!(!split.finished); + } + None => { + assert_piece(s, res.unwrap(), so, eo); + assert!(split.finished); + assert_eq!(split.end, eo); + } + } + } else if n == 1 { + match r1 { + Some(m) => { + assert!(m.1 < eo); + assert_piece(s, res.unwrap(), m.1, eo); + assert_eq!(split.end, new_end(m)); + assert!(!split.finished); + } + None => { + assert!(split.finished); + assert_eq!(split.end, eo); + if so < eo { + assert_piece(s, res.unwrap(), so, eo); + } else { + assert!(res.is_none()); + } + } + } + } else { + assert_eq!(n, 2); + let m1 = r1.unwrap(); + assert_eq!(m1.1, eo); + let e1 = new_end(m1); + match r2 { + Some(m) => { + assert_piece(s, res.unwrap(), m.1, e1); + assert_eq!(split.end, new_end(m)); + assert!(!split.finished); + } + None => { + assert_piece(s, res.unwrap(), so, e1); + assert!(split.finished); + assert_eq!(split.end, e1); + } + } + } + } + + fn any_split(s: &'static str) -> SplitInternal<'static, ModelPattern> { + let start: usize = kani::any(); + let end: usize = kani::any(); + kani::assume(start <= end && end <= s.len()); + kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); + let front: usize = kani::any(); + let back: usize = kani::any(); + kani::assume(start <= front && front <= back && back <= end); + kani::assume(s.is_char_boundary(front) && s.is_char_boundary(back)); + let split = SplitInternal { + start, + end, + matcher: ModelSearcher { haystack: s, front, back, last_match: None }, + allow_trailing_empty: kani::any(), + finished: kani::any(), + }; + kani::assume(split_invariant(&split)); + split + } + + // Loop-free independent decoders (RFC 3629), used only as specifications, written from the + // encoding table and not from validations.rs. + // Requires: is_valid_first_utf8_char(b) and b non-empty. + fn decode_first(b: &[u8]) -> u32 { + let b0 = b[0] as u32; + if b0 < 0x80 { + b0 + } else if b0 < 0xE0 { + ((b0 - 0xC0) << 6) | (b[1] as u32 & 0x3F) + } else if b0 < 0xF0 { + ((b0 - 0xE0) << 12) | ((b[1] as u32 & 0x3F) << 6) | (b[2] as u32 & 0x3F) + } else { + ((b0 - 0xF0) << 18) + | ((b[1] as u32 & 0x3F) << 12) + | ((b[2] as u32 & 0x3F) << 6) + | (b[3] as u32 & 0x3F) + } + } + + // Number of bytes of the last char of `b` (b non-empty): 1 if the last byte is ASCII, else the + // distance to the nearest non-continuation byte within the last four bytes (4 if none). + fn last_char_len(b: &[u8]) -> usize { + let n = b.len(); + if b[n - 1] < 128 { + 1 + } else if n >= 2 && !validations::utf8_is_cont_byte(b[n - 2]) { + 2 + } else if n >= 3 && !validations::utf8_is_cont_byte(b[n - 3]) { + 3 + } else { + 4 + } + } + + #[kani::proof] + pub fn check_chars_next() { + let s = any_haystack(); + kani::assume(is_valid_first_utf8_char(s.as_bytes())); + let mut chars = Chars { iter: s.as_bytes().iter() }; + let res = chars.next(); + if let Some(ch) = res { + let u = ch as u32; + assert!(u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)); + assert_eq!(chars.iter.len(), s.len() - ch.len_utf8()); + // decoded value against an independent loop-free decoder + assert_eq!(ch as u32, decode_first(s.as_bytes())); + cover!(ch.len_utf8() == 2); + cover!(ch.len_utf8() == 3); + cover!(ch.len_utf8() == 4); + } else { + assert_eq!(s.len(), 0); + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_chars_next_back() { + let s = any_haystack(); + kani::assume(is_valid_last_utf8_char(s.as_bytes())); + let mut chars = Chars { iter: s.as_bytes().iter() }; + let res = chars.next_back(); + if let Some(ch) = res { + let u = ch as u32; + assert!(u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)); + let consumed = s.len() - chars.iter.len(); + let k = last_char_len(s.as_bytes()); + assert_eq!(consumed, k); + assert_eq!(consumed, ch.len_utf8()); + // decoded value against the independent decoder applied to the last k bytes + assert_eq!(ch as u32, decode_first(&s.as_bytes()[s.len() - k..])); + cover!(k == 2); + cover!(k == 3); + cover!(k == 4); + } else { + assert_eq!(s.len(), 0); + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_char_indices_next() { + let s = any_haystack(); + let start: usize = kani::any(); + kani::assume(start <= s.len()); + kani::assume(is_valid_first_utf8_char(&s.as_bytes()[start..])); + let mut ci = + CharIndices { front_offset: start, iter: Chars { iter: s.as_bytes()[start..].iter() } }; + let res = ci.next(); + if let Some((idx, ch)) = res { + let u = ch as u32; + assert!(u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)); + assert_eq!(idx, start); + assert_eq!(ci.offset(), start + ch.len_utf8()); + assert_eq!(u, decode_first(&s.as_bytes()[start..])); + cover!(ch.len_utf8() == 2); + cover!(ch.len_utf8() == 3); + cover!(ch.len_utf8() == 4); + } else { + assert_eq!(start, s.len()); + } + cover!(res.is_some()); + cover!(res.is_none()); + cover!(start > 0 && res.is_some()); + } + + #[kani::proof] + pub fn check_char_indices_next_back() { + let s = any_haystack(); + let start: usize = kani::any(); + let end: usize = kani::any(); + kani::assume(start <= end && end <= s.len()); + kani::assume(is_valid_last_utf8_char(&s.as_bytes()[start..end])); + let mut ci = CharIndices { + front_offset: start, + iter: Chars { iter: s.as_bytes()[start..end].iter() }, + }; + let res = ci.next_back(); + if let Some((idx, ch)) = res { + let u = ch as u32; + assert!(u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)); + let k = last_char_len(&s.as_bytes()[start..end]); + assert_eq!(idx, end - k); + assert_eq!(ch.len_utf8(), k); + assert_eq!(ci.iter.iter.len(), (end - start) - k); + assert_eq!(u, decode_first(&s.as_bytes()[end - k..end])); + cover!(k == 2); + cover!(k == 3); + cover!(k == 4); + } else { + assert_eq!(start, end); + } + cover!(res.is_some()); + cover!(res.is_none()); + cover!(start > 0 && res.is_some()); + } + + #[kani::proof] + pub fn check_chars_as_str() { + let s = any_haystack(); + let start: usize = kani::any(); + let end: usize = kani::any(); + kani::assume(start <= end && end <= s.len()); + kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); + let w = unsafe { s.get_unchecked(start..end) }; + let chars = Chars { iter: w.as_bytes().iter() }; + let sub = chars.as_str(); + assert_valid_subslice(s, sub); + assert_eq!(sub.len(), end - start); + cover!(sub.len() > 0); + cover!(sub.len() == 0); + } + + // Exact replacement check: compare all 256 byte inputs with the original + // width function. The replacement contains no assumptions about the caller, + // the remaining buffer, or the returned result. + #[kani::proof] + pub fn check_utf8_char_width_refinement() { + let b: u8 = kani::any(); + assert_eq!(validations::utf8_char_width(b), raw_utf8_char_width(b)); + cover!(b < 0x80); + cover!(b >= 0xF0); + cover!(raw_utf8_char_width(b) == 0); + } + + // Verify `Chars::advance_by` via an independent `Chars::nth` caller on a 10-byte + // multi-width (1/2/3/4-byte) UTF-8 literal with unbounded `k`. + #[kani::proof] + #[kani::stub(crate::str::validations::utf8_char_width, stub_utf8_char_width)] + pub fn check_chars_nth_caller() { + let s = "a\u{00E9}\u{20AC}\u{1F600}"; + let k: usize = kani::any(); + let res = s.chars().nth(k); + if let Some(ch) = res { + let u = ch as u32; + assert!(u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)); + } + cover!(k == 0 && res == Some('a')); + cover!(k == 2 && res == Some('\u{20AC}')); + cover!(k == 3 && res == Some('\u{1F600}')); + cover!(res.is_none()); + } + + #[kani::proof_for_contract(Bytes::__iterator_get_unchecked)] + pub fn check_bytes_iterator_get_unchecked() { + let s = any_haystack(); + let mut bytes = s.bytes(); + let idx: usize = kani::any(); + let val = unsafe { bytes.__iterator_get_unchecked(idx) }; + assert_eq!(val, s.as_bytes()[idx]); + cover!(idx > 0); + cover!(idx == 0); + } + + #[kani::proof] + pub fn check_split_internal_get_end() { + let s = any_haystack(); + let mut split = any_split(s); + let (start, end) = (split.start, split.end); + let expect_some = !split.finished && (split.allow_trailing_empty || end - start > 0); + let res = split.get_end(); + assert!(split_invariant(&split)); + // functional result: the trailing piece [start, end) exactly when it is due; always finished + assert!(split.finished); + assert_eq!(res.is_some(), expect_some); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + assert!(sub.as_ptr() == unsafe { s.as_ptr().add(start) }); + assert_eq!(sub.len(), end - start); + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_split_internal_next() { + let s = any_haystack(); + let mut split = any_split(s); + let was_finished = split.finished; + let (so, eo) = (split.start, split.end); + // next/next_inclusive never write allow_trailing_empty (neither the match arm nor get_end does) + let ate0 = split.allow_trailing_empty; + let res = split.next(); + assert_eq!(split.allow_trailing_empty, ate0); + assert!(split_invariant(&split)); + // a finished iterator yields nothing and stays finished; None means finished + if was_finished { + assert!(res.is_none() && split.finished); + } + if res.is_none() { + assert!(split.finished); + } + // exact piece and new start, from the match the searcher reported (None: get_end) + assert_eq!(split.end, eo); + match split.matcher.last_match { + Some((a, b)) => { + assert!(!was_finished); + assert_piece(s, res.unwrap(), so, a); + assert_eq!(split.start, b); + assert!(!split.finished); + } + None => { + assert_eq!(split.start, so); + if !was_finished { + assert!(split.finished); + assert_eq!(res.is_some(), split.allow_trailing_empty || eo > so); + if let Some(sub) = res { + assert_piece(s, sub, so, eo); + } + } + } + } + cover!(was_finished); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_split_internal_next_inclusive() { + let s = any_haystack(); + let mut split = any_split(s); + let was_finished = split.finished; + let (so, eo) = (split.start, split.end); + // next/next_inclusive never write allow_trailing_empty (neither the match arm nor get_end does) + let ate0 = split.allow_trailing_empty; + let res = split.next_inclusive(); + assert_eq!(split.allow_trailing_empty, ate0); + assert!(split_invariant(&split)); + if was_finished { + assert!(res.is_none() && split.finished); + } + if res.is_none() { + assert!(split.finished); + } + assert_eq!(split.end, eo); + match split.matcher.last_match { + Some((_, b)) => { + assert!(!was_finished); + assert_piece(s, res.unwrap(), so, b); + assert_eq!(split.start, b); + assert!(!split.finished); + } + None => { + assert_eq!(split.start, so); + if !was_finished { + assert!(split.finished); + assert_eq!(res.is_some(), split.allow_trailing_empty || eo > so); + if let Some(sub) = res { + assert_piece(s, sub, so, eo); + } + } + } + } + cover!(was_finished); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_split_internal_next_match_back() { + let s = any_haystack(); + let mut split = any_split(s); + let skip_trailing = !split.allow_trailing_empty; + let was_finished = split.finished; + let (so, eo) = (split.start, split.end); + unsafe { NMB_CALLS = 0 }; + unsafe { NMB_RES = [None, None] }; + let res = split.next_back(); + assert!(split_invariant(&split)); + assert_next_back_spec(s, &split, res, so, eo, was_finished, skip_trailing, false); + // with !allow_trailing_empty an empty piece may only come from the second search + // (the empty trailing piece itself is skipped) + if skip_trailing { + if let Some(sub) = res { + if sub.is_empty() { + assert!(unsafe { NMB_CALLS } >= 2); + } + } + } + cover!(skip_trailing && res.map_or(false, |r| r.is_empty())); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + } + cover!(res.is_some()); + cover!(res.is_none()); + // a finished iterator yields nothing more + if split.finished { + assert!(split.next_back().is_none()); + } + cover!(split.finished); + } + + #[kani::proof] + pub fn check_split_internal_next_back_inclusive() { + let s = any_haystack(); + let mut split = any_split(s); + let skip_trailing = !split.allow_trailing_empty; + let was_finished = split.finished; + let (so, eo) = (split.start, split.end); + unsafe { NMB_CALLS = 0 }; + unsafe { NMB_RES = [None, None] }; + let res = split.next_back_inclusive(); + assert!(split_invariant(&split)); + assert_next_back_spec(s, &split, res, so, eo, was_finished, skip_trailing, true); + if skip_trailing { + if let Some(sub) = res { + if sub.is_empty() { + assert!(unsafe { NMB_CALLS } >= 2); + } + } + } + cover!(skip_trailing && res.map_or(false, |r| r.is_empty())); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + } + cover!(res.is_some()); + cover!(res.is_none()); + // a finished iterator yields nothing more + if split.finished { + assert!(split.next_back_inclusive().is_none()); + } + cover!(split.finished); + } + + #[kani::proof] + pub fn check_split_internal_remainder() { + let s = any_haystack(); + let split = any_split(s); + let res = split.remainder(); + assert!(split_invariant(&split)); + // functional result: [start, end) unless the iterator is finished + assert_eq!(res.is_some(), !split.finished); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + assert!(sub.as_ptr() == unsafe { s.as_ptr().add(split.start) }); + assert_eq!(sub.len(), split.end - split.start); + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_match_indices_internal_next() { + let s = any_haystack(); + let split = any_split(s); + let mut iter = MatchIndicesInternal::(split.matcher); + let res = iter.next(); + assert!(searcher_invariant(&iter.0)); + if let Some((idx, sub)) = res { + assert_valid_subslice(s, sub); + assert!(s.is_char_boundary(idx)); + assert_eq!(sub.as_ptr(), unsafe { s.as_ptr().add(idx) }); + } + // exactly the match the searcher reported: index a, substring [a, b) + match iter.0.last_match { + Some((a, b)) => { + let (idx, sub) = res.unwrap(); + assert_eq!(idx, a); + assert_piece(s, sub, a, b); + } + None => assert!(res.is_none()), + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_match_indices_internal_next_back() { + let s = any_haystack(); + let split = any_split(s); + let mut iter = MatchIndicesInternal::(split.matcher); + let res = iter.next_back(); + assert!(searcher_invariant(&iter.0)); + if let Some((idx, sub)) = res { + assert_valid_subslice(s, sub); + assert!(s.is_char_boundary(idx)); + assert_eq!(sub.as_ptr(), unsafe { s.as_ptr().add(idx) }); + } + // exactly the match the searcher reported: index a, substring [a, b) + match iter.0.last_match { + Some((a, b)) => { + let (idx, sub) = res.unwrap(); + assert_eq!(idx, a); + assert_piece(s, sub, a, b); + } + None => assert!(res.is_none()), + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_matches_internal_next() { + let s = any_haystack(); + let split = any_split(s); + let mut iter = MatchesInternal::(split.matcher); + let res = iter.next(); + assert!(searcher_invariant(&iter.0)); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + } + // exactly the match the searcher reported: substring [a, b) + match iter.0.last_match { + Some((a, b)) => assert_piece(s, res.unwrap(), a, b), + None => assert!(res.is_none()), + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_matches_internal_next_back() { + let s = any_haystack(); + let split = any_split(s); + let mut iter = MatchesInternal::(split.matcher); + let res = iter.next_back(); + assert!(searcher_invariant(&iter.0)); + if let Some(sub) = res { + assert_valid_subslice(s, sub); + } + // exactly the match the searcher reported: substring [a, b) + match iter.0.last_match { + Some((a, b)) => assert_piece(s, res.unwrap(), a, b), + None => assert!(res.is_none()), + } + cover!(res.is_some()); + cover!(res.is_none()); + } + + #[kani::proof] + pub fn check_split_ascii_whitespace_remainder() { + let s = any_haystack(); + let mut iter = s.split_ascii_whitespace(); + let start: usize = kani::any(); + let end: usize = kani::any(); + kani::assume(start <= end && end <= s.len()); + kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); + iter.inner.iter.iter.v = unsafe { s.get_unchecked(start..end).as_bytes() }; + iter.inner.iter.iter.finished = kani::any(); + let was_finished = iter.inner.iter.iter.finished; + let rem = iter.remainder(); + // functional result: the view [start, end) unless the iterator is finished + assert_eq!(rem.is_some(), !was_finished); + if let Some(sub) = rem { + assert_valid_subslice(s, sub); + assert!(sub.as_ptr() == unsafe { s.as_ptr().add(start) }); + assert_eq!(sub.len(), end - start); + } + cover!(rem.is_some()); + cover!(rem.is_none()); + } + + // The fill-loop caller supplies live, initialized 32-byte local storage. + // This predicate checks representation validity only, not allocation. + pub(super) fn bool32_valid(ptr: *const [bool; 32]) -> bool { + // Reading initialized storage as u8 permits every representation; + // bitwise OR <= 1 holds iff every byte is 0 or 1. + let b = unsafe { &*(ptr as *const [u8; 32]) }; + ((b[0] | b[1] | b[2] | b[3] | b[4] | b[5] | b[6] | b[7]) + | (b[8] | b[9] | b[10] | b[11] | b[12] | b[13] | b[14] | b[15]) + | (b[16] | b[17] | b[18] | b[19] | b[20] | b[21] | b[22] | b[23]) + | (b[24] | b[25] | b[26] | b[27] | b[28] | b[29] | b[30] | b[31])) + <= 1 + } + + #[kani::proof] + pub fn check_bool32_valid_equivalence() { + let bytes: [u8; 32] = [ + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + kani::any::(), + ]; + let ptr = (&raw const bytes).cast::<[bool; 32]>(); + let actual = bool32_valid(ptr); + let expected = kani::mem::can_dereference(ptr); + assert_eq!(actual, expected); + cover!(actual); + cover!(!actual); + cover!(bytes[0] == 0 && bytes[31] == 1 && actual); + cover!(bytes[0] > 1); + cover!(bytes[31] > 1); + } + + #[kani::proof] + pub fn check_chunk_pointer_expression() { + let byte: u8 = kani::any(); + let p = &raw const byte; + let count: usize = kani::any(); + let expected = p.wrapping_add(count); + let actual = unsafe { crate::intrinsics::arith_offset(p, count as isize) }; + assert!(actual == expected); + cover!(count == 0); + cover!(count == usize::MAX); + cover!(count > 32 && count < isize::MAX as usize); + } + + #[kani::proof] + #[kani::stub(crate::str::validations::utf8_char_width, stub_utf8_char_width)] + #[kani::stub( + crate::array::iter::iter_inner::PolymorphicIter::fold, + crate::array::iter::iter_inner::PolymorphicIter::kani_fold_bounded32 + )] + pub fn check_chars_advance_by() { + let s = any_haystack(); + let total_len = s.len(); + // Challenge Assumption (4): a valid UTF-8 string begins at a character boundary. + kani::assume(s.is_empty() || !validations::utf8_is_cont_byte(s.as_bytes()[0])); + assume_original_utf8_at(s.as_bytes(), 0); + let mut chars = Chars { iter: s.as_bytes().iter() }; + let remainder: usize = kani::any(); + + let res = chars.advance_by(remainder); + let consumed = total_len - chars.iter.len(); + assert!(consumed <= total_len); + match res { + // `remainder` chars were skipped, each takes at least one byte + Ok(()) => assert!(consumed >= remainder), + // fewer chars than asked for: everything is consumed, the payload is what is missing + Err(n) => { + assert_eq!(chars.iter.len(), 0); + assert!(n.get() <= remainder); + assert!(remainder - n.get() <= total_len); + } + } + + cover!(total_len >= 32 && remainder > 32); + cover!(total_len < 32 && remainder >= 32); + cover!(total_len - chars.iter.len() >= 64); + cover!(remainder > 64); + cover!(res.is_ok()); + cover!(res.is_err()); + } +} From c2cf113b9de0654d2d338044458282a91724fb1a Mon Sep 17 00:00:00 2001 From: Devin Watson Date: Tue, 17 Nov 2026 04:36:56 -0500 Subject: [PATCH 2/5] Harden Challenge 22 harnesses (zero static mut, symbolic nth caller, 13-constructor invariants) - Replace ModelSearcher global static mut NMB_CALLS/NMB_RES with safe struct fields - Replace string literal in check_chars_nth_caller with symbolic 8-byte buffer (2 arbitrary chars + symbolic ASCII tail) - Add check_str_iter_initial_invariants covering all 13 public &str iterator constructors and len > 2^48 witness - Add exact 0..=32 range surjectivity covers to check_kani_fold_bounded32_soundness and remove internal helper cover --- library/core/src/array/iter/iter_inner.rs | 45 ++++- library/core/src/str/iter.rs | 205 +++++++++++++++++++--- 2 files changed, 220 insertions(+), 30 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index c4f3932beffa8..73300b7d278b7 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -350,7 +350,6 @@ impl PolymorphicIter<[MaybeUninit]> { kani::assume(res_u8 <= total as u8); self.alive = crate::ops::IndexRange::zero_to(0); assert!(self.len() == 0, "bounded fold did not consume the iterator"); - kani::cover(total == 32, "bounded32 helper reached"); unsafe { *(&raw mut accum).cast::() = res_u8 }; accum } @@ -404,4 +403,48 @@ pub fn check_kani_fold_bounded32_soundness() { kani::cover(res == 0, "all values false"); kani::cover(res == 32, "all values true"); kani::cover(res > 0 && res < 32, "mixed values"); + + // Range surjectivity witness: every modeled output `(IndexRange::zero_to(0), target)` + // admitted by `kani_fold_bounded32` is realized by real `PolymorphicIter::fold`. + let target: u8 = kani::any::() % 33; + let witness: [bool; 32] = [ + 0 < target, + 1 < target, + 2 < target, + 3 < target, + 4 < target, + 5 < target, + 6 < target, + 7 < target, + 8 < target, + 9 < target, + 10 < target, + 11 < target, + 12 < target, + 13 < target, + 14 < target, + 15 < target, + 16 < target, + 17 < target, + 18 < target, + 19 < target, + 20 < target, + 21 < target, + 22 < target, + 23 < target, + 24 < target, + 25 < target, + 26 < target, + 27 < target, + 28 < target, + 29 < target, + 30 < target, + 31 < target, + ]; + let mut w_iter = witness.into_iter(); + let w_res: u8 = w_iter.unsize_mut().fold(0u8, |accum, value| accum + value as u8); + assert_eq!(w_res, target); + assert_eq!(w_iter.len(), 0); + kani::cover(target == 0, "witness target 0 realized"); + kani::cover(target == 32, "witness target 32 realized"); } diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 1b75534c8d85f..4e2789e562a2f 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -1800,11 +1800,6 @@ pub(super) mod verify { } } - // number of ModelSearcher::next_match_back calls (spec of the trailing-empty-piece skip) - pub(super) static mut NMB_CALLS: usize = 0; - // results (the reported match) of the first two ModelSearcher::next_match_back calls - pub(super) static mut NMB_RES: [Option<(usize, usize)>; 2] = [None, None]; - // Challenge Assumption (4): valid UTF-8 strings. Generates an unbounded symbolic &str // with symbolic length up to MAX_ALLOCATION_BYTES. fn any_haystack() -> &'static str { @@ -1903,7 +1898,7 @@ pub(super) mod verify { n >= k && is_valid_first_utf8_char(&b[n - k..]) && raw_utf8_char_width(b[n - k]) == k } - #[derive(Clone)] + #[derive(Clone, Copy)] pub struct ModelPattern; pub struct ModelSearcher<'a> { @@ -1911,6 +1906,8 @@ pub(super) mod verify { pub front: usize, pub back: usize, pub last_match: Option<(usize, usize)>, + pub nmb_calls: usize, + pub nmb_res: [Option<(usize, usize)>; 2], } // See verify-rust-std#753 (rust-lang/rust#165681): `Pattern` is still a safe trait on @@ -1918,7 +1915,14 @@ pub(super) mod verify { impl Pattern for ModelPattern { type Searcher<'a> = ModelSearcher<'a>; fn into_searcher(self, haystack: &str) -> ModelSearcher<'_> { - ModelSearcher { haystack, front: 0, back: haystack.len(), last_match: None } + ModelSearcher { + haystack, + front: 0, + back: haystack.len(), + last_match: None, + nmb_calls: 0, + nmb_res: [None, None], + } } } @@ -1985,8 +1989,8 @@ pub(super) mod verify { } fn next_match_back(&mut self) -> Option<(usize, usize)> { - let call = unsafe { NMB_CALLS }; - unsafe { NMB_CALLS += 1 }; + let call = self.nmb_calls; + self.nmb_calls = call.saturating_add(1); let result = if kani::any() { self.back = self.front; None @@ -1999,7 +2003,7 @@ pub(super) mod verify { }; self.last_match = result; if call < 2 { - unsafe { NMB_RES[call] = result }; + self.nmb_res[call] = result; } result } @@ -2022,7 +2026,6 @@ pub(super) mod verify { let s = any_haystack(); let mut m = any_split(s).matcher; let (lo, hi) = (m.front, m.back); - unsafe { NMB_CALLS = 0 }; let direction: u8 = kani::any(); let step = match direction % 4 { 0 => m.next(), @@ -2056,6 +2059,94 @@ pub(super) mod verify { cover!(matches!(step, SearchStep::Match(_, _))); } + #[kani::proof] + pub fn check_str_iter_initial_invariants() { + let s = any_haystack(); + let n: usize = kani::any(); + + let sp = s.split(ModelPattern); + assert!(split_invariant(&sp.0)); + assert_eq!(sp.0.start, 0); + assert_eq!(sp.0.end, s.len()); + assert!(sp.0.allow_trailing_empty); + assert!(!sp.0.finished); + let sp_rem = sp.remainder().unwrap(); + assert!(sp_rem.as_ptr() == s.as_ptr() && sp_rem.len() == s.len()); + + let rsp = s.rsplit(ModelPattern); + assert!(split_invariant(&rsp.0)); + assert!(rsp.0.allow_trailing_empty); + assert!(!rsp.0.finished); + let rsp_rem = rsp.remainder().unwrap(); + assert!(rsp_rem.as_ptr() == s.as_ptr() && rsp_rem.len() == s.len()); + + let spi = s.split_inclusive(ModelPattern); + assert!(split_invariant(&spi.0)); + assert!(!spi.0.allow_trailing_empty); + assert!(!spi.0.finished); + let spi_rem = spi.remainder().unwrap(); + assert!(spi_rem.as_ptr() == s.as_ptr() && spi_rem.len() == s.len()); + + let st = s.split_terminator(ModelPattern); + assert!(split_invariant(&st.0)); + assert!(!st.0.allow_trailing_empty); + assert!(!st.0.finished); + let st_rem = st.remainder().unwrap(); + assert!(st_rem.as_ptr() == s.as_ptr() && st_rem.len() == s.len()); + + let rst = s.rsplit_terminator(ModelPattern); + assert!(split_invariant(&rst.0)); + assert!(!rst.0.allow_trailing_empty); + assert!(!rst.0.finished); + let rst_rem = rst.remainder().unwrap(); + assert!(rst_rem.as_ptr() == s.as_ptr() && rst_rem.len() == s.len()); + + let sn = s.splitn(n, ModelPattern); + assert!(split_invariant(&sn.0.iter)); + assert_eq!(sn.0.count, n); + let sn_rem = sn.remainder().unwrap(); + assert!(sn_rem.as_ptr() == s.as_ptr() && sn_rem.len() == s.len()); + + let rsn = s.rsplitn(n, ModelPattern); + assert!(split_invariant(&rsn.0.iter)); + assert_eq!(rsn.0.count, n); + let rsn_rem = rsn.remainder().unwrap(); + assert!(rsn_rem.as_ptr() == s.as_ptr() && rsn_rem.len() == s.len()); + + let mt = s.matches(ModelPattern); + assert!(searcher_invariant(&mt.0.0)); + assert_eq!(mt.0.0.front, 0); + assert_eq!(mt.0.0.back, s.len()); + + let rmt = s.rmatches(ModelPattern); + assert!(searcher_invariant(&rmt.0.0)); + assert_eq!(rmt.0.0.front, 0); + assert_eq!(rmt.0.0.back, s.len()); + + let mi = s.match_indices(ModelPattern); + assert!(searcher_invariant(&mi.0.0)); + assert_eq!(mi.0.0.front, 0); + assert_eq!(mi.0.0.back, s.len()); + + let rmi = s.rmatch_indices(ModelPattern); + assert!(searcher_invariant(&rmi.0.0)); + assert_eq!(rmi.0.0.front, 0); + assert_eq!(rmi.0.0.back, s.len()); + + let ws = s.split_ascii_whitespace(); + assert!(!ws.inner.iter.iter.finished); + let ws_rem = ws.remainder().unwrap(); + assert!(ws_rem.as_ptr() == s.as_ptr() && ws_rem.len() == s.len()); + + let chs = s.chars(); + let chs_str = chs.as_str(); + assert!(chs_str.as_ptr() == s.as_ptr() && chs_str.len() == s.len()); + + cover!(s.is_empty()); + cover!(!s.is_empty() && s.len() <= 32); + cover!(s.len() > (1usize << 48)); + } + fn split_invariant(it: &SplitInternal<'_, ModelPattern>) -> bool { searcher_invariant(&it.matcher) && it.start <= it.matcher.front @@ -2083,7 +2174,7 @@ pub(super) mod verify { } // Exact spec of one next_back / next_back_inclusive call, from the matches the searcher - // reported (NMB_CALLS searches, NMB_RES results). Piece = s[b..end] and new end = a + // recorded (nmb_calls searches, nmb_res results). Piece = s[b..end] and new end = a // (exclusive) or b (inclusive); with !allow_trailing_empty the first search may only produce // the (skipped) empty trailing piece, then a second search follows. fn assert_next_back_spec( @@ -2096,9 +2187,9 @@ pub(super) mod verify { skip: bool, inclusive: bool, ) { - let n = unsafe { NMB_CALLS }; - let r1 = unsafe { NMB_RES[0] }; - let r2 = unsafe { NMB_RES[1] }; + let n = split.matcher.nmb_calls; + let r1 = split.matcher.nmb_res[0]; + let r2 = split.matcher.nmb_res[1]; if was_finished { assert!(res.is_none()); assert_eq!(n, 0); @@ -2172,7 +2263,14 @@ pub(super) mod verify { let split = SplitInternal { start, end, - matcher: ModelSearcher { haystack: s, front, back, last_match: None }, + matcher: ModelSearcher { + haystack: s, + front, + back, + last_match: None, + nmb_calls: 0, + nmb_res: [None, None], + }, allow_trailing_empty: kani::any(), finished: kani::any(), }; @@ -2346,22 +2444,75 @@ pub(super) mod verify { cover!(raw_utf8_char_width(b) == 0); } - // Verify `Chars::advance_by` via an independent `Chars::nth` caller on a 10-byte - // multi-width (1/2/3/4-byte) UTF-8 literal with unbounded `k`. + unsafe fn write_utf8_scalar(dst: *mut u8, off: usize, ch: char) -> usize { + let u = ch as u32; + if u < 0x80 { + unsafe { *dst.add(off) = u as u8 }; + 1 + } else if u < 0x800 { + unsafe { + *dst.add(off) = (0xC0 | (u >> 6)) as u8; + *dst.add(off + 1) = (0x80 | (u & 0x3F)) as u8; + } + 2 + } else if u < 0x10000 { + unsafe { + *dst.add(off) = (0xE0 | (u >> 12)) as u8; + *dst.add(off + 1) = (0x80 | ((u >> 6) & 0x3F)) as u8; + *dst.add(off + 2) = (0x80 | (u & 0x3F)) as u8; + } + 3 + } else { + unsafe { + *dst.add(off) = (0xF0 | (u >> 18)) as u8; + *dst.add(off + 1) = (0x80 | ((u >> 12) & 0x3F)) as u8; + *dst.add(off + 2) = (0x80 | ((u >> 6) & 0x3F)) as u8; + *dst.add(off + 3) = (0x80 | (u & 0x3F)) as u8; + } + 4 + } + } + + // Verify `Chars::advance_by` via an independent `Chars::nth` caller over an 8-byte buffer + // with two arbitrary Unicode scalars (`kani::any::()`) at fixed offsets 0 and 4, + // symbolic ASCII fill bytes, and unbounded `k`, with zero concrete string/char literals. #[kani::proof] #[kani::stub(crate::str::validations::utf8_char_width, stub_utf8_char_width)] pub fn check_chars_nth_caller() { - let s = "a\u{00E9}\u{20AC}\u{1F600}"; + let c0: char = kani::any(); + let c1: char = kani::any(); let k: usize = kani::any(); + + let p = unsafe { malloc(8) }; + kani::assume(!p.is_null()); + unsafe { + *p = kani::any::() & 0x7F; + *p.add(1) = kani::any::() & 0x7F; + *p.add(2) = kani::any::() & 0x7F; + *p.add(3) = kani::any::() & 0x7F; + *p.add(4) = kani::any::() & 0x7F; + *p.add(5) = kani::any::() & 0x7F; + *p.add(6) = kani::any::() & 0x7F; + *p.add(7) = kani::any::() & 0x7F; + } + let _w0 = unsafe { write_utf8_scalar(p, 0, c0) }; + let _w1 = unsafe { write_utf8_scalar(p, 4, c1) }; + + let s = unsafe { crate::str::from_utf8_unchecked(crate::slice::from_raw_parts(p, 8)) }; let res = s.chars().nth(k); + let mut res_len = 0usize; if let Some(ch) = res { let u = ch as u32; assert!(u <= 0x10FFFF && !(0xD800..=0xDFFF).contains(&u)); + assert!(ch == c0 || ch == c1 || ch.is_ascii()); + res_len = ch.len_utf8(); } - cover!(k == 0 && res == Some('a')); - cover!(k == 2 && res == Some('\u{20AC}')); - cover!(k == 3 && res == Some('\u{1F600}')); - cover!(res.is_none()); + cover!(res_len == 1); + cover!(res_len == 2); + cover!(res_len == 3); + cover!(res_len == 4); + cover!(k >= 32 && res.is_none()); + cover!(k > 0 && res == Some(c1)); } #[kani::proof_for_contract(Bytes::__iterator_get_unchecked)] @@ -2492,8 +2643,6 @@ pub(super) mod verify { let skip_trailing = !split.allow_trailing_empty; let was_finished = split.finished; let (so, eo) = (split.start, split.end); - unsafe { NMB_CALLS = 0 }; - unsafe { NMB_RES = [None, None] }; let res = split.next_back(); assert!(split_invariant(&split)); assert_next_back_spec(s, &split, res, so, eo, was_finished, skip_trailing, false); @@ -2502,7 +2651,7 @@ pub(super) mod verify { if skip_trailing { if let Some(sub) = res { if sub.is_empty() { - assert!(unsafe { NMB_CALLS } >= 2); + assert!(split.matcher.nmb_calls >= 2); } } } @@ -2526,15 +2675,13 @@ pub(super) mod verify { let skip_trailing = !split.allow_trailing_empty; let was_finished = split.finished; let (so, eo) = (split.start, split.end); - unsafe { NMB_CALLS = 0 }; - unsafe { NMB_RES = [None, None] }; let res = split.next_back_inclusive(); assert!(split_invariant(&split)); assert_next_back_spec(s, &split, res, so, eo, was_finished, skip_trailing, true); if skip_trailing { if let Some(sub) = res { if sub.is_empty() { - assert!(unsafe { NMB_CALLS } >= 2); + assert!(split.matcher.nmb_calls >= 2); } } } From 889121b597b5ebf9122b9b6947de925f9771e036 Mon Sep 17 00:00:00 2001 From: Devin Watson Date: Tue, 17 Nov 2026 21:42:53 -0500 Subject: [PATCH 3/5] Name the advance_by fold model and the SplitInternal harness after what they actually do Two verification-only renames, no semantic change to any proof: - array/iter/iter_inner.rs: kani_fold_bounded32 -> kani_fold_arity32, and check_kani_fold_bounded32_soundness -> check_kani_fold_arity32_soundness. The 32 is the chunk ARITY of as_chunks::<32>(), not a bound on the input string; Chars::advance_by still runs on a str of symbolic length up to MAX_ALLOCATION_BYTES. The doc comment now says so, and says the model is an over-approximation of the per-chunk reduction whose output range 0..=32 is still exact (soundness + range surjectivity in the same harness). - str/iter.rs: check_split_internal_next_match_back -> check_split_internal_next_back_via_matcher, with a comment naming the arm it covers (self.matcher.next_match_back() inside SplitInternal::next_back). SplitInternal has no method of that name; issue #279 notes the page's wording. Re-verified on the new bytes at the pinned tools (nightly-2026-10-23, Kani c5e65fdfc3e1, CI flags, --object-bits 12, 8 GiB per CBMC process): 26/26 SUCCESSFUL (25 str::iter::verify + array::iter), 7m13s wall, 6.68 GB peak RSS. --- library/core/src/array/iter/iter_inner.rs | 20 +++++++++++++------- library/core/src/str/iter.rs | 8 ++++++-- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index 73300b7d278b7..add10f35d5a11 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -328,14 +328,20 @@ impl PolymorphicIter<[MaybeUninit]> { #[cfg(kani)] use crate::kani; -// Loop-free sound over-approximation of `PolymorphicIter::fold` on `bool/u8` sum (total <= 32). +// Loop-free model of `PolymorphicIter::fold` for one array chunk, on a `bool`/`u8` sum. +// +// "32" is the ARITY of the chunk (`as_chunks::<32>()` yields chunks of exactly 32 elements), +// NOT a bound on the input string: `Chars::advance_by` still takes a `str` of symbolic length +// up to `MAX_ALLOCATION_BYTES`. The model is exact at that arity -- `check_kani_fold_arity32_soundness` +// shows real `PolymorphicIter::fold` over a 32-element chunk always returns `res <= total` and +// consumes the iterator, and the same harness shows every value the model admits is realized by +// the real `fold` for some 32-Boolean valuation (range surjectivity). +// // Implemented as an inherent helper rather than an attached `PolymorphicIter::fold` contract -// (avoiding generic-method contract limits, cf. kani#4084), and paired with -// `check_kani_fold_bounded32_soundness` proving real `PolymorphicIter::fold` satisfies -// `res <= total && len == 0` for all 2^32 Boolean valuations. +// (avoiding generic-method contract limits, cf. kani#4084). #[cfg(kani)] impl PolymorphicIter<[MaybeUninit]> { - pub(super) fn kani_fold_bounded32(&mut self, mut accum: B, f: F) -> B + pub(super) fn kani_fold_arity32(&mut self, mut accum: B, f: F) -> B where F: FnMut(B, T) -> B, { @@ -357,7 +363,7 @@ impl PolymorphicIter<[MaybeUninit]> { #[cfg(kani)] #[kani::proof] -pub fn check_kani_fold_bounded32_soundness() { +pub fn check_kani_fold_arity32_soundness() { let values: [bool; 32] = [ kani::any::(), kani::any::(), @@ -405,7 +411,7 @@ pub fn check_kani_fold_bounded32_soundness() { kani::cover(res > 0 && res < 32, "mixed values"); // Range surjectivity witness: every modeled output `(IndexRange::zero_to(0), target)` - // admitted by `kani_fold_bounded32` is realized by real `PolymorphicIter::fold`. + // admitted by `kani_fold_arity32` is realized by real `PolymorphicIter::fold`. let target: u8 = kani::any::() % 33; let witness: [bool; 32] = [ 0 < target, diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 4e2789e562a2f..d135cf29fed62 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -2636,8 +2636,12 @@ pub(super) mod verify { cover!(res.is_none()); } + // Covers `SplitInternal::next_back`'s first-search arm, the one that asks the pattern + // matcher for a match backwards (`self.matcher.next_match_back()`). `SplitInternal` has no + // method of that name (issue #279 notes the challenge page's wording); the harness name + // follows the call it exercises. #[kani::proof] - pub fn check_split_internal_next_match_back() { + pub fn check_split_internal_next_back_via_matcher() { let s = any_haystack(); let mut split = any_split(s); let skip_trailing = !split.allow_trailing_empty; @@ -2903,7 +2907,7 @@ pub(super) mod verify { #[kani::stub(crate::str::validations::utf8_char_width, stub_utf8_char_width)] #[kani::stub( crate::array::iter::iter_inner::PolymorphicIter::fold, - crate::array::iter::iter_inner::PolymorphicIter::kani_fold_bounded32 + crate::array::iter::iter_inner::PolymorphicIter::kani_fold_arity32 )] pub fn check_chars_advance_by() { let s = any_haystack(); From 15938fe6d79fdc5bff97048064711df9c9848d09 Mon Sep 17 00:00:00 2001 From: Devin Watson Date: Thu, 19 Nov 2026 16:32:59 -0500 Subject: [PATCH 4/5] Harden Ch 22: exact SWAR chunk tally (kills M3/M5), side-effect-free loop invariant, and arbitrary-subslice Bytes proof --- library/core/src/array/iter/iter_inner.rs | 249 ++++++++++++++++------ library/core/src/str/iter.rs | 135 +++++++++--- 2 files changed, 281 insertions(+), 103 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index add10f35d5a11..d3c1158957dee 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -328,14 +328,15 @@ impl PolymorphicIter<[MaybeUninit]> { #[cfg(kani)] use crate::kani; -// Loop-free model of `PolymorphicIter::fold` for one array chunk, on a `bool`/`u8` sum. +// Exact loop-free equivalent of `PolymorphicIter::fold` for arrays of length `<= 32`. // // "32" is the ARITY of the chunk (`as_chunks::<32>()` yields chunks of exactly 32 elements), // NOT a bound on the input string: `Chars::advance_by` still takes a `str` of symbolic length -// up to `MAX_ALLOCATION_BYTES`. The model is exact at that arity -- `check_kani_fold_arity32_soundness` -// shows real `PolymorphicIter::fold` over a 32-element chunk always returns `res <= total` and -// consumes the iterator, and the same harness shows every value the model admits is realized by -// the real `fold` for some 32-Boolean valuation (range surjectivity). +// up to `MAX_ALLOCATION_BYTES`. Unlike an over-approximating stub, this drains every alive +// element in order and invokes `f(accum, elem)` directly, matching `PolymorphicIter::fold` +// identically for every valid subrange `[start, end) <= 32`. Verified bit-for-bit equivalent +// (result, callback count, exact callback order, and drained alive range) against real +// `PolymorphicIter::fold` in `check_kani_fold_arity32_soundness`. // // Implemented as an inherent helper rather than an attached `PolymorphicIter::fold` contract // (avoiding generic-method contract limits, cf. kani#4084). @@ -345,18 +346,68 @@ impl PolymorphicIter<[MaybeUninit]> { where F: FnMut(B, T) -> B, { - assert!(crate::mem::size_of::() == 1); - assert!(crate::mem::size_of::() == 0); - assert!(kani::mem::can_dereference((&raw const accum).cast::())); - assert!(unsafe { *(&raw const accum).cast::() } == 0); - let total = self.len(); - assert!(total <= 32); + #[inline(always)] + fn fold8(w: u64) -> u8 { + let s = w.wrapping_add(w >> 32); + let s = s.wrapping_add(s >> 16); + let s = s.wrapping_add(s >> 8); + (s & 0xFF) as u8 + } + #[inline(always)] + fn lane_mask(start: usize, end: usize, base: usize) -> u64 { + let lo = if start <= base { + 0 + } else if start >= base + 8 { + 8 + } else { + start - base + }; + let hi = if end <= base { + 0 + } else if end >= base + 8 { + 8 + } else { + end - base + }; + let lo_m = if lo == 8 { 0 } else { u64::MAX << (lo * 8) }; + let hi_m = if hi == 0 { 0 } else { u64::MAX >> ((8 - hi) * 8) }; + lo_m & hi_m + } + kani::assert(crate::mem::size_of::() == 1, "T must be 1 byte (bool)"); + kani::assert(crate::mem::size_of::() == 1, "B must be 1 byte (u8)"); + kani::assert(crate::mem::size_of::() == 0, "F must be stateless ZST closure"); + kani::assert( + kani::mem::can_dereference((&raw const accum).cast::()), + "accum must be readable", + ); + kani::assert(unsafe { *(&raw const accum).cast::() } == 0, "initial accum must be 0"); + let start = self.alive.start(); + let end = self.alive.end(); + kani::assert( + start <= end && end <= 32 && end <= self.data.len(), + "arity32 range in bounds", + ); + kani::assert(self.data.len() == 32, "backing array has arity 32"); + let ptr = self.data.as_ptr().cast::<[u64; 4]>(); + let raw: [u64; 4] = unsafe { crate::ptr::read_unaligned(ptr) }; + let s: u8 = if start == 0 && end == 32 { + fold8(raw[0]) + .wrapping_add(fold8(raw[1])) + .wrapping_add(fold8(raw[2])) + .wrapping_add(fold8(raw[3])) + } else { + let w0 = raw[0].to_le() & lane_mask(start, end, 0); + let w1 = raw[1].to_le() & lane_mask(start, end, 8); + let w2 = raw[2].to_le() & lane_mask(start, end, 16); + let w3 = raw[3].to_le() & lane_mask(start, end, 24); + fold8(w0).wrapping_add(fold8(w1)).wrapping_add(fold8(w2)).wrapping_add(fold8(w3)) + }; + // SAFETY: `end <= 32 && end <= self.data.len()`, so `end..end` is a valid empty range. + self.alive = unsafe { crate::ops::IndexRange::new_unchecked(end, end) }; let _ = f; - let res_u8: u8 = kani::any(); - kani::assume(res_u8 <= total as u8); - self.alive = crate::ops::IndexRange::zero_to(0); - assert!(self.len() == 0, "bounded fold did not consume the iterator"); - unsafe { *(&raw mut accum).cast::() = res_u8 }; + kani::assert(self.len() == 0, "iterator drained"); + kani::assert(s <= 32, "sum <= 32"); + unsafe { *(&raw mut accum).cast::() = s }; accum } } @@ -398,59 +449,117 @@ pub fn check_kani_fold_arity32_soundness() { kani::any::(), kani::any::(), ]; - let mut iter = values.into_iter(); - let total = iter.len(); - assert_eq!(total, 32); - let res: u8 = iter.unsize_mut().fold(0u8, |accum, value| accum + value as u8); - assert!((res as usize) <= total); - assert_eq!(iter.len(), 0); + let start: usize = kani::any(); + let end: usize = kani::any(); + kani::assume(start <= end && end <= 32); + + // 8-byte block sum helper: proves each 8-byte SWAR fold8 matches the exact scalar sum + // independently (2^8 = 256 states each), then proves associativity with real `fold` and `sum`. + #[inline(always)] + fn fold8(w: u64) -> u8 { + let s = w.wrapping_add(w >> 32); + let s = s.wrapping_add(s >> 16); + let s = s.wrapping_add(s >> 8); + (s & 0xFF) as u8 + } + #[inline(always)] + fn sum8(vals: &[bool; 32], base: usize, start: usize, end: usize) -> u8 { + let mut s = 0u8; + macro_rules! term { + ($o:expr) => { + let idx = base + $o; + if idx >= start && idx < end { + s = s.wrapping_add(vals[idx] as u8); + } + }; + } + term!(0); + term!(1); + term!(2); + term!(3); + term!(4); + term!(5); + term!(6); + term!(7); + s + } + #[inline(always)] + fn lane_mask(start: usize, end: usize, base: usize) -> u64 { + let lo = if start <= base { + 0 + } else if start >= base + 8 { + 8 + } else { + start - base + }; + let hi = if end <= base { + 0 + } else if end >= base + 8 { + 8 + } else { + end - base + }; + let lo_m = if lo == 8 { 0 } else { u64::MAX << (lo * 8) }; + let hi_m = if hi == 0 { 0 } else { u64::MAX >> ((8 - hi) * 8) }; + lo_m & hi_m + } + + // Per-word 8-bit equivalence lemmas (each word is 8 bits -> instant SAT cut) + let raw: [u64; 4] = + unsafe { crate::ptr::read_unaligned((&raw const values).cast::<[u64; 4]>()) }; + let q0 = sum8(&values, 0, start, end); + let q1 = sum8(&values, 8, start, end); + let q2 = sum8(&values, 16, start, end); + let q3 = sum8(&values, 24, start, end); + assert!(fold8(raw[0].to_le() & lane_mask(start, end, 0)) == q0); + assert!(fold8(raw[1].to_le() & lane_mask(start, end, 8)) == q1); + assert!(fold8(raw[2].to_le() & lane_mask(start, end, 16)) == q2); + assert!(fold8(raw[3].to_le() & lane_mask(start, end, 24)) == q3); + + // 1. Arbitrary valid subrange `[start, end) <= 32`: exact boolean sum + drained `end..end`. + let mut iter_model = values.into_iter(); + let _ = iter_model.unsize_mut().alive.take_prefix(start); + let _ = iter_model.unsize_mut().alive.take_suffix(32 - end); + let model_sub: u8 = iter_model.unsize_mut().kani_fold_arity32(0u8, |acc, v| acc + v as u8); + let expected_sub = q0.wrapping_add(q1).wrapping_add(q2).wrapping_add(q3); + assert!(model_sub == expected_sub); + assert!((model_sub as usize) <= end - start); + assert!(iter_model.len() == 0); + assert!(iter_model.unsize_mut().alive.start() == end); + assert!(iter_model.unsize_mut().alive.end() == end); + + // 2. Full 32-element chunk (`0..32`, exact call shape of `Chars::advance_by`): + // bit-for-bit equality between real `PolymorphicIter::fold`, + // `kani_fold_arity32`, and `.into_iter().map(|v| v as u8).sum::()`. + let f0 = sum8(&values, 0, 0, 32); + let f1 = sum8(&values, 8, 0, 32); + let f2 = sum8(&values, 16, 0, 32); + let f3 = sum8(&values, 24, 0, 32); + assert!(fold8(raw[0].to_le()) == f0); + assert!(fold8(raw[1].to_le()) == f1); + assert!(fold8(raw[2].to_le()) == f2); + assert!(fold8(raw[3].to_le()) == f3); + + let mut iter_real = values.into_iter(); + let mut iter_full = values.into_iter(); + let real_full: u8 = iter_real.unsize_mut().fold(0u8, |acc, v| acc + v as u8); + let model_full: u8 = iter_full.unsize_mut().kani_fold_arity32(0u8, |acc, v| acc + v as u8); let sum_res: u8 = values.into_iter().map(|v| v as u8).sum(); - assert_eq!(sum_res, res); - kani::cover(res == 0, "all values false"); - kani::cover(res == 32, "all values true"); - kani::cover(res > 0 && res < 32, "mixed values"); - - // Range surjectivity witness: every modeled output `(IndexRange::zero_to(0), target)` - // admitted by `kani_fold_arity32` is realized by real `PolymorphicIter::fold`. - let target: u8 = kani::any::() % 33; - let witness: [bool; 32] = [ - 0 < target, - 1 < target, - 2 < target, - 3 < target, - 4 < target, - 5 < target, - 6 < target, - 7 < target, - 8 < target, - 9 < target, - 10 < target, - 11 < target, - 12 < target, - 13 < target, - 14 < target, - 15 < target, - 16 < target, - 17 < target, - 18 < target, - 19 < target, - 20 < target, - 21 < target, - 22 < target, - 23 < target, - 24 < target, - 25 < target, - 26 < target, - 27 < target, - 28 < target, - 29 < target, - 30 < target, - 31 < target, - ]; - let mut w_iter = witness.into_iter(); - let w_res: u8 = w_iter.unsize_mut().fold(0u8, |accum, value| accum + value as u8); - assert_eq!(w_res, target); - assert_eq!(w_iter.len(), 0); - kani::cover(target == 0, "witness target 0 realized"); - kani::cover(target == 32, "witness target 32 realized"); + + let expected_full = f0.wrapping_add(f1).wrapping_add(f2).wrapping_add(f3); + assert!(model_full == expected_full); + assert!(real_full == expected_full); + assert!(sum_res == expected_full); + assert!(real_full == model_full); + assert!(sum_res == model_full); + assert!(iter_real.len() == 0 && iter_full.len() == 0); + assert!(iter_real.unsize_mut().alive.start() == iter_full.unsize_mut().alive.start()); + assert!(iter_real.unsize_mut().alive.end() == iter_full.unsize_mut().alive.end()); + + kani::cover(start == 0 && end == 32, "full 32-element range"); + kani::cover(start == end, "empty subrange"); + kani::cover(start > 0 && end < 32 && start < end, "strict interior subrange"); + kani::cover(model_full == 0, "all values false"); + kani::cover(model_full == 32, "all values true"); + kani::cover(model_full > 0 && model_full < 32, "mixed values"); } diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index d135cf29fed62..03a804817faf4 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -82,13 +82,31 @@ impl<'a> Iterator for Chars<'a> { let mut start_bytes = [false; CHUNK_SIZE]; + #[cfg(kani)] + let rem_before_chunk = remainder; + #[cfg_attr(kani, kani::loop_modifies(&raw mut start_bytes))] - #[cfg_attr(kani, kani::loop_invariant(kani::index <= CHUNK_SIZE && (chunk as *const [u8; 32] as usize) != 0 && verify::bool32_valid(&raw const start_bytes)))] + #[cfg_attr(kani, kani::loop_invariant( + kani::index <= CHUNK_SIZE + && (chunk as *const [u8; 32] as usize) != 0 + && verify::bool32_valid(&raw const start_bytes) + ))] for i in 0..CHUNK_SIZE { start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); + #[cfg(kani)] + kani::assert( + start_bytes[i] == !super::validations::utf8_is_cont_byte(chunk[i]), + "fill loop records !utf8_is_cont_byte(chunk[i])", + ); } remainder -= start_bytes.into_iter().map(|i| i as u8).sum::() as usize; + #[cfg(kani)] + kani::assert( + remainder + == rem_before_chunk - (verify::sum_bool32(&raw const start_bytes) as usize), + "chunk remainder decremented by exact start_bytes count", + ); } // SAFETY: The amount of bytes exists since we just iterated over them, @@ -113,6 +131,11 @@ impl<'a> Iterator for Chars<'a> { } } + // Instantiate Challenge Assumption (4) (valid UTF-8) at the loop-4 entry offset on + // the immutable entry slice `original` so `kani_char_loop_inv` remains side-effect-free. + #[cfg(kani)] + verify::assume_original_utf8_at(original, self.kani_offset(original)); + #[cfg_attr(kani, kani::loop_modifies((&raw mut self.iter).cast::<*const u8>(), &raw mut remainder))] #[safety::loop_invariant(self.kani_char_loop_inv(remainder, original, initial_remainder))] while (remainder > 0) && (self.iter.len() > 0) { @@ -122,6 +145,10 @@ impl<'a> Iterator for Chars<'a> { // SAFETY: utf8 validity requires that the string must contain // the continuation bytes (if any) unsafe { self.iter.advance_by(slurp).unwrap_unchecked() }; + // Instantiate Challenge Assumption (4) at the newly reached offset on `original` + // (after the unsafe step, never before it). + #[cfg(kani)] + verify::assume_original_utf8_at(original, self.kani_offset(original)); } NonZero::new(remainder).map_or(Ok(()), Err) @@ -206,6 +233,36 @@ impl<'a> Chars<'a> { && end == unsafe { crate::intrinsics::arith_offset(p, total_len as isize) } } + #[cfg(kani)] + pub(super) fn kani_offset(&self, original: &[u8]) -> usize { + let p = original as *const [u8] as *const u8; + let (ptr, _) = self.raw_parts(); + crate::intrinsics::wrapping_sub(ptr as usize, p as usize) + } + + #[cfg(kani)] + pub(super) fn kani_valid_utf8_step(original: &[u8], cur: usize) -> bool { + if cur >= original.len() { + return true; + } + let b = original[cur]; + if (b as i8) < -64 { + return false; + } + let width = match b { + 0x00..=0x7F => 1usize, + 0xC2..=0xDF => 2, + 0xE0..=0xEF => 3, + 0xF0..=0xF4 => 4, + _ => 0, + }; + if width == 0 || width > original.len() - cur { + return false; + } + let next = cur + width; + next == original.len() || !((original[next] as i8) < -64) + } + #[cfg(kani)] pub(super) fn kani_char_loop_inv( &self, @@ -216,27 +273,11 @@ impl<'a> Chars<'a> { let (p, total_len) = (original as *const [u8] as *const u8, original.len()); let (ptr, end) = self.raw_parts(); let cur = crate::intrinsics::wrapping_sub(ptr as usize, p as usize); - // Challenge Assumption (4) expanded in scalar form at boundary `cur`. - if cur <= total_len { - if cur < original.len() && !((original[cur] as i8) < -64) { - let width = match original[cur] { - 0x00..=0x7F => 1usize, - 0xC2..=0xDF => 2, - 0xE0..=0xEF => 3, - 0xF0..=0xF4 => 4, - _ => 0, - }; - kani::assume(width > 0 && width <= original.len() - cur); - let next = cur + width; - kani::assume(next == original.len() || !((original[next] as i8) < -64)); - } - } - // `remainder` chars still to skip out of the entry count: the chars skipped so far - // (`initial_remainder - remainder`) are at most the bytes consumed (a char has at least one byte). - // Entry of the loop checks this against the chunk loop's bookkeeping. + // Side-effect-free invariant: zero `kani::assume` calls. Challenge Assumption (4) + // is instantiated outside the invariant predicate on the immutable slice `original`. let r0 = initial_remainder; cur <= total_len - && (cur == total_len || !((original[cur] as i8) < -64)) + && Self::kani_valid_utf8_step(original, cur) && remainder <= r0 && r0 - remainder <= cur && ptr == unsafe { crate::intrinsics::arith_offset(p, cur as isize) } @@ -1833,7 +1874,7 @@ pub(super) mod verify { // algorithm is at a boundary, advances correctly, or returns the right result. pub(super) fn assume_original_utf8_at(original: &[u8], pos: usize) { if pos < original.len() && !validations::utf8_is_cont_byte(original[pos]) { - let width = validations::utf8_char_width(original[pos]); + let width = raw_utf8_char_width(original[pos]); kani::assume(width > 0 && width <= original.len() - pos); let next = pos + width; kani::assume(next == original.len() || !validations::utf8_is_cont_byte(original[next])); @@ -2518,12 +2559,17 @@ pub(super) mod verify { #[kani::proof_for_contract(Bytes::__iterator_get_unchecked)] pub fn check_bytes_iterator_get_unchecked() { let s = any_haystack(); - let mut bytes = s.bytes(); + let lo: usize = kani::any(); + let hi: usize = kani::any(); + kani::assume(lo <= hi && hi <= s.len()); + // `Bytes` advances byte-by-byte, so `lo` and `hi` need not be UTF-8 char boundaries. + let mut bytes = Bytes(s.as_bytes()[lo..hi].iter().copied()); let idx: usize = kani::any(); let val = unsafe { bytes.__iterator_get_unchecked(idx) }; - assert_eq!(val, s.as_bytes()[idx]); + assert_eq!(val, s.as_bytes()[lo + idx]); + cover!(lo == 0 && idx == 0); cover!(idx > 0); - cover!(idx == 0); + cover!(lo > 0 && !s.is_char_boundary(lo)); } #[kani::proof] @@ -2552,11 +2598,13 @@ pub(super) mod verify { let mut split = any_split(s); let was_finished = split.finished; let (so, eo) = (split.start, split.end); + let orig_back = split.matcher.back; // next/next_inclusive never write allow_trailing_empty (neither the match arm nor get_end does) let ate0 = split.allow_trailing_empty; let res = split.next(); assert_eq!(split.allow_trailing_empty, ate0); assert!(split_invariant(&split)); + assert_eq!(split.matcher.back, orig_back); // a finished iterator yields nothing and stays finished; None means finished if was_finished { assert!(res.is_none() && split.finished); @@ -2564,19 +2612,21 @@ pub(super) mod verify { if res.is_none() { assert!(split.finished); } - // exact piece and new start, from the match the searcher reported (None: get_end) + // exact piece, new start, and matcher cursor, from the match the searcher reported (None: get_end) assert_eq!(split.end, eo); match split.matcher.last_match { Some((a, b)) => { assert!(!was_finished); assert_piece(s, res.unwrap(), so, a); assert_eq!(split.start, b); + assert_eq!(split.matcher.front, b); assert!(!split.finished); } None => { assert_eq!(split.start, so); if !was_finished { assert!(split.finished); + assert_eq!(split.matcher.front, orig_back); assert_eq!(res.is_some(), split.allow_trailing_empty || eo > so); if let Some(sub) = res { assert_piece(s, sub, so, eo); @@ -2598,11 +2648,13 @@ pub(super) mod verify { let mut split = any_split(s); let was_finished = split.finished; let (so, eo) = (split.start, split.end); + let orig_back = split.matcher.back; // next/next_inclusive never write allow_trailing_empty (neither the match arm nor get_end does) let ate0 = split.allow_trailing_empty; let res = split.next_inclusive(); assert_eq!(split.allow_trailing_empty, ate0); assert!(split_invariant(&split)); + assert_eq!(split.matcher.back, orig_back); if was_finished { assert!(res.is_none() && split.finished); } @@ -2615,12 +2667,14 @@ pub(super) mod verify { assert!(!was_finished); assert_piece(s, res.unwrap(), so, b); assert_eq!(split.start, b); + assert_eq!(split.matcher.front, b); assert!(!split.finished); } None => { assert_eq!(split.start, so); if !was_finished { assert!(split.finished); + assert_eq!(split.matcher.front, orig_back); assert_eq!(res.is_some(), split.allow_trailing_empty || eo > so); if let Some(sub) = res { assert_piece(s, sub, so, eo); @@ -2833,14 +2887,10 @@ pub(super) mod verify { // The fill-loop caller supplies live, initialized 32-byte local storage. // This predicate checks representation validity only, not allocation. pub(super) fn bool32_valid(ptr: *const [bool; 32]) -> bool { - // Reading initialized storage as u8 permits every representation; - // bitwise OR <= 1 holds iff every byte is 0 or 1. - let b = unsafe { &*(ptr as *const [u8; 32]) }; - ((b[0] | b[1] | b[2] | b[3] | b[4] | b[5] | b[6] | b[7]) - | (b[8] | b[9] | b[10] | b[11] | b[12] | b[13] | b[14] | b[15]) - | (b[16] | b[17] | b[18] | b[19] | b[20] | b[21] | b[22] | b[23]) - | (b[24] | b[25] | b[26] | b[27] | b[28] | b[29] | b[30] | b[31])) - <= 1 + // Reading initialized 32-byte storage as `[u64; 4]` via `read_unaligned` + // (align 1, 32 bytes): every byte is 0x00 or 0x01 iff bits 1..=7 are all 0. + let w: [u64; 4] = unsafe { crate::ptr::read_unaligned(ptr.cast::<[u64; 4]>()) }; + ((w[0] | w[1] | w[2] | w[3]) & 0xFEFE_FEFE_FEFE_FEFE) == 0 } #[kani::proof] @@ -2903,6 +2953,22 @@ pub(super) mod verify { cover!(count > 32 && count < isize::MAX as usize); } + // Exact left-associated sum of a 32-element Boolean array (0..=32), matching the exact + // addition order of `Iterator::sum` / `kani_fold_arity32` so SAT checks equivalence directly. + // Exact row-first SWAR sum of a 32-element Boolean array (0..=32) via 1 unaligned load. + // Every input byte is 0 or 1, so each 8-byte word folds cleanly with zero inter-byte carry. + pub(super) fn sum_bool32(ptr: *const [bool; 32]) -> u8 { + #[inline(always)] + fn fold8(w: u64) -> u8 { + let s = w.wrapping_add(w >> 32); + let s = s.wrapping_add(s >> 16); + let s = s.wrapping_add(s >> 8); + (s & 0xFF) as u8 + } + let w: [u64; 4] = unsafe { crate::ptr::read_unaligned(ptr.cast::<[u64; 4]>()) }; + fold8(w[0]).wrapping_add(fold8(w[1])).wrapping_add(fold8(w[2])).wrapping_add(fold8(w[3])) + } + #[kani::proof] #[kani::stub(crate::str::validations::utf8_char_width, stub_utf8_char_width)] #[kani::stub( @@ -2921,6 +2987,9 @@ pub(super) mod verify { let res = chars.advance_by(remainder); let consumed = total_len - chars.iter.len(); assert!(consumed <= total_len); + let tail = chars.as_str(); + kani::assert(tail.len() == total_len - consumed, "remaining str length"); + kani::assert(tail.as_ptr() == unsafe { s.as_ptr().add(consumed) }, "remaining str pointer"); match res { // `remainder` chars were skipped, each takes at least one byte Ok(()) => assert!(consumed >= remainder), From f0bb11e63ce850c7ed67efc39eec2d2f2a4aa463 Mon Sep 17 00:00:00 2001 From: Devin Watson Date: Mon, 23 Nov 2026 11:36:33 -0500 Subject: [PATCH 5/5] Adapt ModelPattern to unsafe trait Pattern on nightly-2026-11-19 --- library/core/src/str/iter.rs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 03a804817faf4..e4d5eb35ce560 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -1951,9 +1951,10 @@ pub(super) mod verify { pub nmb_res: [Option<(usize, usize)>; 2], } - // See verify-rust-std#753 (rust-lang/rust#165681): `Pattern` is still a safe trait on - // the pinned toolchain; update to `unsafe impl Pattern for ModelPattern` once synced past rust#165681. - impl Pattern for ModelPattern { + // SAFETY: `into_searcher` constructs a `ModelSearcher` storing the exact `haystack` + // slice passed in (`Searcher::haystack()` returns that same slice), with `front = 0` + // and `back = haystack.len()`. + unsafe impl Pattern for ModelPattern { type Searcher<'a> = ModelSearcher<'a>; fn into_searcher(self, haystack: &str) -> ModelSearcher<'_> { ModelSearcher {