From f89fb8a6364416bfd9135afc15e7e8b1f3e74acd Mon Sep 17 00:00:00 2001 From: v3risec Date: Tue, 27 Oct 2026 17:01:06 +0800 Subject: [PATCH 1/8] challenge 22 proof --- library/core/src/str/iter.rs | 1914 +++++++++++++++++++++++++++++++ library/core/src/str/pattern.rs | 335 +++++- 2 files changed, 2245 insertions(+), 4 deletions(-) diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 472ce896a059f..79abd0d6ba92a 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -1641,3 +1641,1917 @@ macro_rules! escape_types_impls { } escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode); + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use super::super::pattern::verify::{ + verifier_assert_real_char_searcher, verifier_char_searcher_invariant, + verifier_stub_char_next_match, verifier_stub_char_next_match_back, + verifier_stub_char_slice_next_match, verifier_stub_char_slice_next_match_back, + verifier_stub_str_nonempty_next_match, verifier_stub_str_nonempty_next_match_back, + }; + use super::super::pattern::{CharSearcher, CharSliceSearcher, StrSearcher}; + use super::super::validations::{utf8_char_width, utf8_is_cont_byte}; + use super::*; + + // The backing array bounds CBMC's object model, not the number of + // iteration steps. Claims of arbitrary mathematical length require an + // additional argument beyond this finite allocation model. + const MAX_BYTES: usize = 256; + const UTF8_PAD: usize = 4; + const BUFFER_BYTES: usize = MAX_BYTES + UTF8_PAD; + + // The local UTF-8 predicate and original bounded advance checks follow + // the input-model approach in PR #557; the interval protocol below + // replaces its char-specific iterator proof architecture. + // A loop-free UTF-8 validity model. For every leading byte, validate + // the sequence width, continuation bytes, and exceptional second-byte + // rules (E0/ED/F0/F4). Every continuation byte must be within three + // positions after a leading byte. Combined, these are equivalent to + // validity of buf[..len], provided len <= N - UTF8_PAD. + // Do not use from_utf8 as a symbolic-input filter under loop-contract + // instrumentation: it can abstract away the validation algorithm. + fn verifier_utf8_valid(buf: &[u8; N], len: usize) -> bool { + let p = buf.as_ptr(); + let sequences = crate::forall!(|i in (0, N - UTF8_PAD)| unsafe { + let i: usize = i; + let x0 = *p.wrapping_add(i); + let x1 = *p.wrapping_add(i.wrapping_add(1)); + let x2 = *p.wrapping_add(i.wrapping_add(2)); + let x3 = *p.wrapping_add(i.wrapping_add(3)); + let continuation0 = (x0 as i8) < -64; + let continuation1 = (x1 as i8) < -64; + let continuation2 = (x2 as i8) < -64; + let continuation3 = (x3 as i8) < -64; + let width = (x0 < 0x80) as usize + + (((x0 >= 0xC2) & (x0 < 0xE0)) as usize) * 2 + + (((x0 >= 0xE0) & (x0 < 0xF0)) as usize) * 3 + + (((x0 >= 0xF0) & (x0 < 0xF5)) as usize) * 4; + let next_is_continuation = + (*p.wrapping_add(i.wrapping_add(width)) as i8) < -64; + let second_byte_ok = ((x0 != 0xE0) | (x1 >= 0xA0)) + & ((x0 != 0xED) | (x1 < 0xA0)) + & ((x0 != 0xF0) | (x1 >= 0x90)) + & ((x0 != 0xF4) | (x1 < 0x90)); + (i >= len) + | continuation0 + | ((width > 0) + & (i.wrapping_add(width) <= len) + & ((width < 2) | (continuation1 & second_byte_ok)) + & ((width < 3) | continuation2) + & ((width < 4) | continuation3) + & ((i.wrapping_add(width) == len) | !next_is_continuation)) + }); + let covered = crate::forall!(|i in (0, N - UTF8_PAD)| unsafe { + let i: usize = i; + (i >= len) + | ((*p.wrapping_add(i) as i8) >= -64) + | ((i >= 1) & ((*p.wrapping_add(i.saturating_sub(1)) as i8) >= -64)) + | ((i >= 2) & ((*p.wrapping_add(i.saturating_sub(2)) as i8) >= -64)) + | ((i >= 3) & ((*p.wrapping_add(i.saturating_sub(3)) as i8) >= -64)) + }); + sequences && covered + } + + fn verifier_nondet_utf8(buf: &[u8; N]) -> &str { + let len: usize = kani::any(); + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(len <= N - UTF8_PAD); + kani::cover(true, "C22-A01: verifier_nondet_utf8 assumption admitted"); + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(buf, len)); + kani::cover(true, "C22-A02: verifier_nondet_utf8 assumption admitted"); + // SAFETY: verifier_utf8_valid characterizes valid UTF-8 exactly. + unsafe { from_utf8_unchecked(&buf[..len]) } + } + + fn verifier_nondet_window(s: &str) -> (usize, usize) { + let start: usize = kani::any(); + let end: usize = kani::any(); + // INPUT STATE: an ordered UTF-8 boundary window. + kani::assume(start <= end && end <= s.len()); + kani::cover(true, "C22-A03: verifier_nondet_window assumption admitted"); + // INPUT STATE: an ordered UTF-8 boundary window. + kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); + kani::cover(true, "C22-A04: verifier_nondet_window assumption admitted"); + (start, end) + } + + fn verifier_same_slice(left: &str, right: &str) -> bool { + left.as_ptr() == right.as_ptr() && left.len() == right.len() + } + + fn verifier_slice_offset(s: &str, subslice: &str) -> usize { + let base = s.as_ptr().addr(); + let current = subslice.as_ptr().addr(); + assert!(base <= current); + current - base + } + + // Assert *both* physical range and UTF-8 boundaries. Kani's checking + // of str::get_unchecked alone is not a substitute for the latter. + fn verifier_assert_str_range(s: &str, result: &str, start: usize, end: usize) { + assert!( + start <= end && end <= s.len(), + "slice is within the haystack" + ); + assert!( + s.is_char_boundary(start) && s.is_char_boundary(end), + "slice endpoints are UTF-8 character boundaries" + ); + assert!( + result.as_ptr() == s.as_ptr().wrapping_add(start), + "slice base pointer" + ); + assert!(result.len() == end - start, "slice byte length"); + } + + // An arbitrary [start, end) window is exactly the type invariant of + // Chars: arbitrary interleavings of next/next_back preserve this set. + #[kani::proof] + pub fn harness_chars_next() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (start, end) = verifier_nondet_window(s); + let mut iter = s[start..end].chars(); + match iter.next() { + Some(ch) => { + let next_start = start + ch.len_utf8(); + verifier_assert_str_range(s, iter.as_str(), next_start, end); + kani::cover(ch.len_utf8() == 1, "chars::next: ASCII"); + kani::cover(ch.len_utf8() == 2, "chars::next: two-byte scalar"); + kani::cover(ch.len_utf8() == 3, "chars::next: three-byte scalar"); + kani::cover(ch.len_utf8() == 4, "chars::next: four-byte scalar"); + } + None => { + assert!(start == end); + kani::cover(true, "chars::next: exhausted"); + } + } + kani::cover(true, "C22-END: harness_chars_next completed"); + } + + #[kani::proof] + pub fn harness_chars_next_back() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (start, end) = verifier_nondet_window(s); + let mut iter = s[start..end].chars(); + match iter.next_back() { + Some(ch) => { + assert!(ch.len_utf8() <= end - start); + verifier_assert_str_range(s, iter.as_str(), start, end - ch.len_utf8()); + kani::cover(ch.len_utf8() == 1, "chars::next_back: ASCII"); + kani::cover(ch.len_utf8() == 4, "chars::next_back: four-byte scalar"); + } + None => { + assert!(start == end); + kani::cover(true, "chars::next_back: exhausted"); + } + } + kani::cover(true, "C22-END: harness_chars_next_back completed"); + } + + #[kani::proof] + pub fn harness_chars_as_str() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (start, end) = verifier_nondet_window(s); + let window = &s[start..end]; + let mut iter = window.chars(); + assert!(verifier_same_slice(iter.as_str(), window)); + let front = iter.next().map_or(0, char::len_utf8); + let back = iter.next_back().map_or(0, char::len_utf8); + verifier_assert_str_range(s, iter.as_str(), start + front, end - back); + kani::cover(front > 0 && back > 0, "chars::as_str: both ends consumed"); + kani::cover(true, "C22-END: harness_chars_as_str completed"); + } + + const ADVANCE_MAX: usize = 8; + const ADVANCE_BYTES: usize = 128; + const CHUNK_MIN: usize = 33; + const CHUNK_MAX: usize = 40; + const CHUNK_BYTES: usize = 48; + + // Independent scalar-by-scalar reference for the bounded regression + // checks. It uses the public decoder, not advance_by's chunk counting. + fn verifier_reference_advance(s: &str, start: usize, end: usize, n: usize) -> (usize, usize) { + let mut chars = s[start..end].chars(); + let mut consumed = 0; + let mut pos = start; + while consumed < n { + match chars.next() { + Some(ch) => { + pos += ch.len_utf8(); + consumed += 1; + } + None => break, + } + } + (pos, consumed) + } + + fn verifier_check_chars_advance(s: &str, start: usize, end: usize, n: usize) { + let (expected_end, consumed) = verifier_reference_advance(s, start, end, n); + let mut iter = s[start..end].chars(); + let result = iter.advance_by(n); // real production body + verifier_assert_str_range(s, iter.as_str(), expected_end, end); + match result { + Ok(()) => assert!(consumed == n), + Err(remaining) => { + assert!(consumed < n); + assert!(expected_end == end); + assert!(remaining.get() == n - consumed); + } + } + kani::cover( + result.is_ok() && n > 0, + "chars::advance_by: successful skip", + ); + kani::cover(result.is_err(), "chars::advance_by: not enough characters"); + } + + // Both the backing allocation and advance count are bounded. The + // unwind derives from n, not string length; this is a regression proof. + #[kani::proof] + #[kani::unwind(9)] + pub fn harness_chars_advance_by_small() { + let buf: [u8; ADVANCE_BYTES + UTF8_PAD] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (start, end) = verifier_nondet_window(s); + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(n <= ADVANCE_MAX); + kani::cover(true, "C22-A05: harness_chars_advance_by_small assumption admitted"); + verifier_check_chars_advance(s, start, end, n); + kani::cover( + n == ADVANCE_MAX && start < end, + "advance_by: maximum small count", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_small completed"); + } + + // Exercise the real chunk-skip loop (as well as its trailing-byte and + // character loops) on a symbolic 48-byte UTF-8 string. The 48-byte + // fixed length is a solver-budget limitation, not unbounded proof. + #[kani::proof] + // The scalar reference can take 40 steps; the chunk body has 32. + #[kani::unwind(42)] + pub fn harness_chars_advance_by_chunked() { + let buf: [u8; CHUNK_BYTES + UTF8_PAD] = kani::any(); + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(&buf, CHUNK_BYTES)); + kani::cover(true, "C22-A06: harness_chars_advance_by_chunked assumption admitted"); + // SAFETY: the encoded prefix satisfies the exact UTF-8 predicate. + let s = unsafe { from_utf8_unchecked(&buf[..CHUNK_BYTES]) }; + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(CHUNK_MIN <= n && n <= CHUNK_MAX); + kani::cover(true, "C22-A07: harness_chars_advance_by_chunked assumption admitted"); + verifier_check_chars_advance(s, 0, CHUNK_BYTES, n); + kani::cover( + utf8_is_cont_byte(buf[32]), + "advance_by: crosses UTF-8 chunk boundary", + ); + kani::cover(buf[0] < 0x80 && buf[31] < 0x80, "advance_by: ASCII chunk"); + kani::cover( + buf[0] >= 0xF0 + && buf[4] >= 0xF0 + && buf[8] >= 0xF0 + && buf[12] >= 0xF0 + && buf[16] >= 0xF0 + && buf[20] >= 0xF0 + && buf[24] >= 0xF0 + && buf[28] >= 0xF0, + "advance_by: chunk with eight four-byte scalars", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_chunked completed"); + } + + // Challenge 22 permits assuming pattern.rs (assumption 2). This is an + // interval-protocol abstraction, not a proof of any matching algorithm. + // Each call may skip Reject steps and return any boundary-valid Match, + // including a zero-width Match. Thus widths may vary between calls. + // The common residual interval suffices for directional safety; this + // model deliberately does NOT implement DoubleEndedSearcher. Concrete + // double-ended instances are checked separately below. + // Projection argument: for a forward-only concrete searcher, front/back + // describe the unreported suffix; every real next_match return is admitted + // here. The reverse-only argument uses the unreported prefix. Consumers + // observe only haystack() and returned indices. This simulation argument + // imports assumption 2; Kani does not quantify over all Rust Pattern types. + struct ModelPattern; + + struct ModelSearcher<'a> { + haystack: &'a str, + front: usize, + back: usize, + // Fresh per-operation observers; production iterators cannot inspect + // these fields. any_split resets them when projecting a logical state. + last_match: Option<(usize, usize)>, + previous_match: Option<(usize, usize)>, + calls: usize, + } + + 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, + previous_match: None, + calls: 0, + } + } + } + + fn type_invariant_searcher(s: &ModelSearcher<'_>) -> bool { + s.front <= s.back + && s.back <= s.haystack.len() + && s.haystack.is_char_boundary(s.front) + && s.haystack.is_char_boundary(s.back) + } + + fn any_match_range(s: &str, front: usize, back: usize) -> (usize, usize) { + let a: usize = kani::any(); + let b: usize = kani::any(); + // These are Searcher guarantees imported under assumption 2, not + // properties of SplitInternal assumed after its execution. + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(front <= a && a <= b && b <= back); + kani::cover(true, "C22-A08: any_match_range assumption admitted"); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); + kani::cover(true, "C22-A09: any_match_range assumption admitted"); + (a, b) + } + + // SAFETY: next emits adjacent, in-bounds UTF-8 ranges. The next_match + // override summarizes zero or more skipped Rejects and one Match (or + // exhaustion). Matching contents are intentionally over-approximated. + unsafe impl<'a> Searcher<'a> for ModelSearcher<'a> { + fn haystack(&self) -> &'a str { + self.haystack + } + + fn next(&mut self) -> super::super::pattern::SearchStep { + use super::super::pattern::SearchStep; + assert!(type_invariant_searcher(self)); + if kani::any() { + let old = self.front; + self.front = self.back; + if old == self.back { + SearchStep::Done + } else { + SearchStep::Reject(old, self.back) + } + } else { + let (_, b) = any_match_range(self.haystack, self.front, self.back); + let a = self.front; + self.front = b; + if kani::any() { + SearchStep::Match(a, b) + } else { + SearchStep::Reject(a, b) + } + } + } + + fn next_match(&mut self) -> Option<(usize, usize)> { + assert!(type_invariant_searcher(self)); + self.previous_match = self.last_match; + // Instrumentation must not introduce overflow on long histories. + self.calls = self.calls.saturating_add(1); + self.last_match = if kani::any() { + let range = any_match_range(self.haystack, self.front, self.back); + self.front = range.1; + Some(range) + } else { + self.front = self.back; + None + }; + self.last_match + } + } + + // SAFETY: same range protocol, consumed from the opposite end. No claim + // is made that independent nondeterministic choices define identical + // forward/reverse streams, hence there is no DoubleEndedSearcher impl. + unsafe impl<'a> ReverseSearcher<'a> for ModelSearcher<'a> { + fn next_back(&mut self) -> super::super::pattern::SearchStep { + use super::super::pattern::SearchStep; + assert!(type_invariant_searcher(self)); + if kani::any() { + let old = self.back; + self.back = self.front; + if old == self.front { + SearchStep::Done + } else { + SearchStep::Reject(self.front, old) + } + } else { + let (a, _) = any_match_range(self.haystack, self.front, self.back); + let b = self.back; + self.back = a; + if kani::any() { + SearchStep::Match(a, b) + } else { + SearchStep::Reject(a, b) + } + } + } + + fn next_match_back(&mut self) -> Option<(usize, usize)> { + assert!(type_invariant_searcher(self)); + self.previous_match = self.last_match; + // Instrumentation must not introduce overflow on long histories. + self.calls = self.calls.saturating_add(1); + self.last_match = if kani::any() { + let range = any_match_range(self.haystack, self.front, self.back); + self.back = range.0; + Some(range) + } else { + self.back = self.front; + None + }; + self.last_match + } + } + + #[derive(Clone, Copy)] + struct SplitState { + start: usize, + end: usize, + front: usize, + back: usize, + trailing: bool, + finished: bool, + } + + fn split_state(iter: &SplitInternal<'_, ModelPattern>) -> SplitState { + SplitState { + start: iter.start, + end: iter.end, + front: iter.matcher.front, + back: iter.matcher.back, + trailing: iter.allow_trailing_empty, + finished: iter.finished, + } + } + + fn type_invariant_split(iter: &SplitInternal<'_, ModelPattern>) -> bool { + type_invariant_searcher(&iter.matcher) + && iter.start <= iter.matcher.front + && iter.matcher.back <= iter.end + && iter.end <= iter.matcher.haystack.len() + && iter.matcher.haystack.is_char_boundary(iter.start) + && iter.matcher.haystack.is_char_boundary(iter.end) + } + + fn any_split(s: &str) -> SplitInternal<'_, ModelPattern> { + let (start, end) = verifier_nondet_window(s); + let (front, back) = any_match_range(s, start, end); + SplitInternal { + start, + end, + matcher: ModelSearcher { + haystack: s, + front, + back, + last_match: None, + previous_match: None, + calls: 0, + }, + allow_trailing_empty: kani::any(), + finished: kani::any(), + } + } + + fn assert_split_frame(s: &str, iter: &SplitInternal<'_, ModelPattern>) { + assert!(type_invariant_split(iter)); + assert!(verifier_same_slice(iter.matcher.haystack(), s)); + } + + fn assert_valid_split_forward_transition( + s: &str, + old: SplitState, + iter: &SplitInternal<'_, ModelPattern>, + result: Option<&str>, + inclusive: bool, + ) { + assert_split_frame(s, iter); + assert_eq!(iter.end, old.end); + assert_eq!(iter.matcher.back, old.back); + assert_eq!(iter.allow_trailing_empty, old.trailing); + if old.finished { + assert!(result.is_none()); + assert_eq!(iter.start, old.start); + assert_eq!(iter.matcher.calls, 0); + assert_eq!(iter.matcher.front, old.front); + assert!(iter.finished); + return; + } + assert_eq!(iter.matcher.calls, 1); + match iter.matcher.last_match { + Some((a, b)) => { + let part = result.unwrap(); + verifier_assert_str_range(s, part, old.start, if inclusive { b } else { a }); + assert_eq!(iter.start, b); + assert!(!iter.finished); + kani::cover(a == b, "split: zero-width match"); + kani::cover(b - a > 4, "split: multi-character match"); + } + None => { + assert!(iter.finished); + assert_eq!(iter.start, old.start); + if old.trailing || old.start < old.end { + verifier_assert_str_range(s, result.unwrap(), old.start, old.end); + } else { + assert!(result.is_none()); + } + kani::cover(true, "split: exhausted search"); + } + } + } + + fn assert_valid_split_reverse_transition( + s: &str, + old: SplitState, + iter: &SplitInternal<'_, ModelPattern>, + result: Option<&str>, + inclusive: bool, + ) { + assert_split_frame(s, iter); + assert_eq!(iter.start, old.start); + assert_eq!(iter.matcher.front, old.front); + if old.finished { + assert!(result.is_none()); + assert_eq!(iter.end, old.end); + assert_eq!(iter.matcher.back, old.back); + assert_eq!(iter.matcher.calls, 0); + assert_eq!(iter.allow_trailing_empty, old.trailing); + assert!(iter.finished); + return; + } + assert!(iter.allow_trailing_empty); + assert!(iter.matcher.calls >= 1 && iter.matcher.calls <= 2); + if iter.finished { + match result { + Some(part) => { + // A first empty tail may have been suppressed before + // returning the remaining prefix in the second search. + verifier_assert_str_range(s, part, old.start, iter.end); + assert!(iter.end <= old.end); + } + None => assert!(!old.trailing && iter.end == old.start), + } + } else { + let (a, b) = iter.matcher.last_match.unwrap(); + let part = result.unwrap(); + let output_end = if iter.matcher.calls == 2 { + assert!(!old.trailing); + let (first_a, first_b) = iter.matcher.previous_match.unwrap(); + assert_eq!(first_b, old.end); + if inclusive { first_b } else { first_a } + } else { + old.end + }; + verifier_assert_str_range(s, part, b, output_end); + assert_eq!(iter.end, if inclusive { b } else { a }); + kani::cover(a == b, "reverse split: zero-width match"); + kani::cover(b - a > 4, "reverse split: multi-character match"); + } + kani::cover( + iter.matcher.calls == 2, + "reverse split: suppress empty tail then search again", + ); + kani::cover(result.is_none(), "reverse split: no remaining part"); + } + + #[kani::proof] + fn harness_searcher_protocol() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let old = split_state(&iter); + let reverse: bool = kani::any(); + let result = if reverse { + iter.matcher.next_match_back() + } else { + iter.matcher.next_match() + }; + assert!(type_invariant_searcher(&iter.matcher)); + assert!(verifier_same_slice(iter.matcher.haystack(), s)); + match result { + Some((a, b)) => { + assert!(old.front <= a && a <= b && b <= old.back); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + if reverse { + assert_eq!(iter.matcher.back, a); + } else { + assert_eq!(iter.matcher.front, b); + } + kani::cover(a == b, "protocol: zero-width match"); + kani::cover(b - a > 4, "protocol: width larger than one scalar"); + } + None => assert_eq!(iter.matcher.front, iter.matcher.back), + } + if reverse { + assert_eq!(iter.matcher.front, old.front); + } else { + assert_eq!(iter.matcher.back, old.back); + } + kani::cover(true, "C22-END: harness_searcher_protocol completed"); + } + + fn assert_initial_split(s: &str, iter: &SplitInternal<'_, P>, trailing: bool) { + assert_eq!(iter.start, 0); + assert_eq!(iter.end, s.len()); + assert_eq!(iter.allow_trailing_empty, trailing); + assert!(!iter.finished); + assert!(verifier_same_slice(iter.matcher.haystack(), s)); + } + + #[kani::proof] + fn harness_split_constructors() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let needle: char = kani::any(); + assert_initial_split(s, &s.split(needle).0, true); + assert_initial_split(s, &s.split_terminator(needle).0, false); + assert_initial_split(s, &s.split_inclusive(needle).0, false); + assert!(verifier_char_searcher_invariant(&s.split(needle).0.matcher)); + assert_initial_split(s, &s.split("").0, true); + assert_initial_split(s, &s.split_terminator("").0, false); + assert_initial_split(s, &s.split_inclusive("").0, false); + let chars: [char; 2] = kani::any(); + assert_initial_split(s, &s.split(&chars[..]).0, true); + assert_initial_split(s, &s.split_terminator(chars).0, false); + assert_initial_split(s, &s.split_inclusive(&chars).0, false); + let model = s.split(ModelPattern).0; + assert_initial_split(s, &model, true); + assert!(type_invariant_split(&model)); + let terminator = s.split_terminator(ModelPattern).0; + let inclusive = s.split_inclusive(ModelPattern).0; + assert_initial_split(s, &terminator, false); + assert_initial_split(s, &inclusive, false); + assert!(type_invariant_split(&terminator)); + assert!(type_invariant_split(&inclusive)); + kani::cover(s.is_empty(), "constructors: empty haystack"); + kani::cover(!s.is_empty(), "constructors: nonempty haystack"); + kani::cover(true, "C22-END: harness_split_constructors completed"); + } + + #[kani::proof] + fn harness_split_get_end() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let old = split_state(&iter); + let result = iter.get_end(); + if !old.finished && (old.trailing || old.start < old.end) { + verifier_assert_str_range(s, result.unwrap(), old.start, old.end); + kani::cover(old.start == old.end, "get_end: allowed empty tail"); + kani::cover(old.start < old.end, "get_end: nonempty tail"); + } else { + assert!(result.is_none()); + kani::cover(old.finished, "get_end: already finished"); + kani::cover(!old.finished, "get_end: suppressed empty tail"); + } + assert!(iter.finished); + assert_eq!(iter.start, old.start); + assert_eq!(iter.end, old.end); + assert_eq!(iter.matcher.front, old.front); + assert_eq!(iter.matcher.back, old.back); + assert_eq!(iter.matcher.calls, 0); + assert_split_frame(s, &iter); + kani::cover(true, "C22-END: harness_split_get_end completed"); + } + + #[kani::proof] + fn harness_split_next() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let old = split_state(&iter); + let result = iter.next(); + assert_valid_split_forward_transition(s, old, &iter, result, false); + kani::cover(true, "C22-END: harness_split_next completed"); + } + + #[kani::proof] + fn harness_split_next_inclusive() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let old = split_state(&iter); + let result = iter.next_inclusive(); + assert_valid_split_forward_transition(s, old, &iter, result, true); + kani::cover(true, "C22-END: harness_split_next_inclusive completed"); + } + + #[kani::proof] + fn harness_split_next_back() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let old = split_state(&iter); + let result = iter.next_back(); + assert_valid_split_reverse_transition(s, old, &iter, result, false); + kani::cover(true, "C22-END: harness_split_next_back completed"); + } + + #[kani::proof] + fn harness_split_next_back_inclusive() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let old = split_state(&iter); + let result = iter.next_back_inclusive(); + assert_valid_split_reverse_transition(s, old, &iter, result, true); + kani::cover(true, "C22-END: harness_split_next_back_inclusive completed"); + } + + #[kani::proof] + fn harness_split_remainder() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let iter = any_split(s); + let old = split_state(&iter); + match iter.remainder() { + Some(part) => { + assert!(!old.finished); + verifier_assert_str_range(s, part, old.start, old.end); + } + None => assert!(old.finished), + } + assert_split_frame(s, &iter); + assert_eq!(iter.matcher.calls, 0); + kani::cover(old.finished, "remainder: finished"); + kani::cover( + !old.finished && old.start == old.end, + "remainder: empty active interval", + ); + kani::cover(true, "C22-END: harness_split_remainder completed"); + } + + fn assert_valid_match_transition( + s: &str, + old_front: usize, + old_back: usize, + searcher: &ModelSearcher<'_>, + result: Option<(usize, &str)>, + reverse: bool, + ) { + assert!(type_invariant_searcher(searcher)); + assert!(verifier_same_slice(searcher.haystack(), s)); + assert_eq!(searcher.calls, 1); + match searcher.last_match { + Some((a, b)) => { + let (index, part) = result.unwrap(); + assert_eq!(index, a); + verifier_assert_str_range(s, part, a, b); + assert!(old_front <= a && b <= old_back); + if reverse { + assert_eq!(searcher.back, a); + } else { + assert_eq!(searcher.front, b); + } + kani::cover(a == b, "matches: empty match"); + kani::cover(b - a > 4, "matches: multiple-character match"); + } + None => { + assert!(result.is_none()); + assert_eq!(searcher.front, searcher.back); + } + } + if reverse { + assert_eq!(searcher.front, old_front); + } else { + assert_eq!(searcher.back, old_back); + } + kani::cover(result.is_none(), "matches: exhausted"); + } + + #[kani::proof] + fn harness_match_indices_next() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let searcher = any_split(s).matcher; + let (front, back) = (searcher.front, searcher.back); + let mut iter = MatchIndicesInternal::(searcher); + let result = iter.next(); + assert_valid_match_transition(s, front, back, &iter.0, result, false); + kani::cover(true, "C22-END: harness_match_indices_next completed"); + } + + #[kani::proof] + fn harness_match_indices_next_back() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let searcher = any_split(s).matcher; + let (front, back) = (searcher.front, searcher.back); + let mut iter = MatchIndicesInternal::(searcher); + let result = iter.next_back(); + assert_valid_match_transition(s, front, back, &iter.0, result, true); + kani::cover(true, "C22-END: harness_match_indices_next_back completed"); + } + + #[kani::proof] + fn harness_matches_next() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let searcher = any_split(s).matcher; + let (front, back) = (searcher.front, searcher.back); + let mut iter = MatchesInternal::(searcher); + let result = iter + .next() + .map(|part| (verifier_slice_offset(s, part), part)); + assert_valid_match_transition(s, front, back, &iter.0, result, false); + kani::cover(true, "C22-END: harness_matches_next completed"); + } + + #[kani::proof] + fn harness_matches_next_back() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let searcher = any_split(s).matcher; + let (front, back) = (searcher.front, searcher.back); + let mut iter = MatchesInternal::(searcher); + let result = iter + .next_back() + .map(|part| (verifier_slice_offset(s, part), part)); + assert_valid_match_transition(s, front, back, &iter.0, result, true); + kani::cover(true, "C22-END: harness_matches_next_back completed"); + } + + // Prove the stronger relation to the exact pre-call remaining interval. + // For any past prefix_end <= old.start and suffix_start >= old.end, + // these assertions imply the old ownership relation by transitivity. + // No extra assumption on ghost history bounds is needed here. + #[kani::proof] + fn harness_split_history_step() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = any_split(s); + let reverse: bool = kani::any(); + let old = split_state(&iter); + let result = if reverse { + iter.next_back() + } else { + iter.next() + }; + if let Some(part) = result { + let a = verifier_slice_offset(s, part); + let b = a + part.len(); + verifier_assert_str_range(s, part, a, b); + assert!(old.start <= a && b <= old.end); + if !iter.finished { + if reverse { + assert!(iter.end <= a); + } else { + assert!(b <= iter.start); + } + } + } + if !iter.finished { + assert!(old.start <= iter.start && iter.end <= old.end); + } else { + assert!(iter.next().is_none()); + assert!(iter.next_back().is_none()); + } + assert_split_frame(s, &iter); + kani::cover( + reverse && !old.finished && result.is_some(), + "history: reverse step", + ); + kani::cover( + !reverse && !old.finished && result.is_some(), + "history: forward step", + ); + kani::cover(true, "C22-END: harness_split_history_step completed"); + } + + #[kani::proof] + pub fn harness_split_ascii_whitespace_remainder() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut iter = s.split_ascii_whitespace(); + assert!( + iter.remainder() + .is_some_and(|part| verifier_same_slice(part, s)) + ); + + // Every reachable inner slice is a UTF-8-boundary window. Cutting + // at ASCII whitespace cannot cut through a multibyte scalar. + let (start, end) = verifier_nondet_window(s); + iter.inner.iter.iter.v = s[start..end].as_bytes(); + iter.inner.iter.iter.finished = kani::any(); + let finished = iter.inner.iter.iter.finished; + match iter.remainder() { + Some(part) => { + assert!(!finished); + verifier_assert_str_range(s, part, start, end); + kani::cover(part.is_empty(), "ASCII whitespace remainder: empty window"); + kani::cover( + !part.is_empty(), + "ASCII whitespace remainder: nonempty window", + ); + } + None => { + assert!(finished); + kani::cover(true, "ASCII whitespace remainder: finished"); + } + } + kani::cover(true, "C22-END: harness_split_ascii_whitespace_remainder completed"); + } + + // Main already contains #[requires(idx < self.0.len())]. The contract + // is discharged against the original body, with Kani generating the + // precondition rather than the harness assuming the target's safety. + #[kani::proof_for_contract(Bytes::__iterator_get_unchecked)] + pub fn harness_bytes_iterator_get_unchecked() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (start, end) = verifier_nondet_window(s); + let window = &s[start..end]; + let mut iter = window.bytes(); + let index: usize = kani::any(); + let item = unsafe { iter.__iterator_get_unchecked(index) }; + assert!(item == window.as_bytes()[index]); + kani::cover(index > 0, "bytes::get_unchecked: index past first byte"); + kani::cover(true, "C22-END: harness_bytes_iterator_get_unchecked completed"); + } + fn assert_ordered_parts(s: &str, front: Option<&str>, back: Option<&str>) { + if let Some(front) = front { + let a = verifier_slice_offset(s, front); + verifier_assert_str_range(s, front, a, a + front.len()); + } + if let Some(back) = back { + let a = verifier_slice_offset(s, back); + verifier_assert_str_range(s, back, a, a + back.len()); + } + if let (Some(front), Some(back)) = (front, back) { + let a = verifier_slice_offset(s, front); + let b = verifier_slice_offset(s, back); + assert!(a + front.len() <= b, "opposite-end outputs do not overlap"); + } + } + + fn assert_public_split_pair<'a, P>(s: &'a str, pattern: P) + where + P: Pattern: DoubleEndedSearcher<'a>>, + { + let inclusive: bool = kani::any(); + let trailing: bool = kani::any(); + let mut iter = if inclusive { + s.split_inclusive(pattern).0 + } else if trailing { + s.split(pattern).0 + } else { + s.split_terminator(pattern).0 + }; + let front_first: bool = kani::any(); + let (front, back) = if front_first { + let front = if inclusive { + iter.next_inclusive() + } else { + iter.next() + }; + let back = if inclusive { + iter.next_back_inclusive() + } else { + iter.next_back() + }; + (front, back) + } else { + let back = if inclusive { + iter.next_back_inclusive() + } else { + iter.next_back() + }; + let front = if inclusive { + iter.next_inclusive() + } else { + iter.next() + }; + (front, back) + }; + assert_ordered_parts(s, front, back); + if let Some(rest) = iter.remainder() { + let a = verifier_slice_offset(s, rest); + verifier_assert_str_range(s, rest, a, iter.end); + if let Some(front) = front { + assert!(verifier_slice_offset(s, front) + front.len() <= a); + } + if let Some(back) = back { + assert!(iter.end <= verifier_slice_offset(s, back)); + } + } else { + assert!(iter.finished); + assert!(iter.next().is_none()); + assert!(iter.next_back().is_none()); + } + kani::cover( + front_first && front.is_some() && back.is_some(), + "mixed: front then back", + ); + kani::cover( + !front_first && front.is_some() && back.is_some(), + "mixed: back then front", + ); + kani::cover( + inclusive && front.is_some() && back.is_some(), + "mixed: inclusive parts", + ); + kani::cover( + !inclusive && !trailing && front.is_some(), + "mixed: terminator parts", + ); + } + + #[kani::proof] + #[kani::stub( as Searcher<'_>>::next_match, verifier_stub_char_next_match)] + #[kani::stub( as ReverseSearcher<'_>>::next_match_back, verifier_stub_char_next_match_back)] + fn harness_split_mixed_directions() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + assert_public_split_pair(s, kani::any::()); + kani::cover(true, "C22-END: harness_split_mixed_directions completed"); + } + + #[kani::proof] + #[kani::stub( as Searcher<'_>>::next_match, verifier_stub_char_slice_next_match)] + #[kani::stub( as ReverseSearcher<'_>>::next_match_back, verifier_stub_char_slice_next_match_back)] + fn harness_split_char_slice_mixed() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let chars: [char; 2] = kani::any(); + let len: usize = kani::any(); + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(len <= chars.len()); + kani::cover(true, "C22-A10: harness_split_char_slice_mixed assumption admitted"); + assert_public_split_pair(s, &chars[..len]); + kani::cover(len == 0, "character set: empty"); + kani::cover( + len == 2 && chars[0].len_utf8() != chars[1].len_utf8(), + "character set: different widths", + ); + kani::cover(true, "C22-END: harness_split_char_slice_mixed completed"); + } + + // Concrete &str instances deliberately keep the two directions separate. + // They are integration checks under assumption 2, not a proof that all + // Pattern implementations refine the abstract protocol above. + fn assert_str_pattern_direction(s: &str, needle: &str, reverse: bool) { + let inclusive: bool = kani::any(); + let mut iter = if inclusive { + s.split_inclusive(needle).0 + } else { + s.split_terminator(needle).0 + }; + let first = if reverse { + if inclusive { + iter.next_back_inclusive() + } else { + iter.next_back() + } + } else if inclusive { + iter.next_inclusive() + } else { + iter.next() + }; + let second = if reverse { + if inclusive { + iter.next_back_inclusive() + } else { + iter.next_back() + } + } else if inclusive { + iter.next_inclusive() + } else { + iter.next() + }; + if reverse { + assert_ordered_parts(s, second, first); + } else { + assert_ordered_parts(s, first, second); + } + if let Some(rest) = iter.remainder() { + verifier_assert_str_range(s, rest, iter.start, iter.end); + } else { + assert!(iter.finished); + let terminal = if reverse { + if inclusive { + iter.next_back_inclusive() + } else { + iter.next_back() + } + } else if inclusive { + iter.next_inclusive() + } else { + iter.next() + }; + assert!(terminal.is_none()); + } + let mut indices = if reverse { + s.rmatch_indices(needle).0 + } else { + s.match_indices(needle).0 + }; + let matched = if reverse { + indices.next_back() + } else { + indices.next() + }; + if let Some((a, part)) = matched { + verifier_assert_str_range(s, part, a, a + needle.len()); + } + // A fresh instance also exercises the MatchesInternal wrapper. + let mut matches = MatchesInternal::<&str>(needle.into_searcher(s)); + if let Some(part) = if reverse { + matches.next_back() + } else { + matches.next() + } { + let a = verifier_slice_offset(s, part); + verifier_assert_str_range(s, part, a, a + needle.len()); + } + kani::cover( + first.is_some() && second.is_some(), + "str pattern: two split parts", + ); + } + + #[kani::proof] + #[kani::unwind(5)] + fn harness_str_empty_forward() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + assert_str_pattern_direction(s, "", false); + kani::cover(s.is_empty(), "empty needle: empty haystack"); + kani::cover(true, "C22-END: harness_str_empty_forward completed"); + } + + #[kani::proof] + #[kani::unwind(5)] + fn harness_str_empty_reverse() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + assert_str_pattern_direction(s, "", true); + kani::cover(s.is_empty(), "empty needle reverse: empty haystack"); + kani::cover(true, "C22-END: harness_str_empty_reverse completed"); + } + + fn any_short_needle(buf: &mut [u8; 8]) -> &str { + let first: char = kani::any(); + let mut len = first.encode_utf8(buf).len(); + if kani::any() { + let second: char = kani::any(); + len += second.encode_utf8(&mut buf[len..]).len(); + } + // SAFETY: concatenation of one or two scalar UTF-8 encodings. + unsafe { from_utf8_unchecked(&buf[..len]) } + } + + #[kani::proof] + #[kani::unwind(20)] + #[kani::stub( as Searcher<'_>>::next_match, verifier_stub_str_nonempty_next_match)] + fn harness_str_nonempty_forward() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut needle_buf = [0u8; 8]; + let needle = any_short_needle(&mut needle_buf); + assert_str_pattern_direction(s, needle, false); + kani::cover(needle.len() == 1, "str pattern: byte searcher"); + kani::cover(needle.len() > 4, "str pattern: two multibyte scalars"); + kani::cover(true, "C22-END: harness_str_nonempty_forward completed"); + } + + #[kani::proof] + #[kani::unwind(20)] + #[kani::stub( as ReverseSearcher<'_>>::next_match_back, verifier_stub_str_nonempty_next_match_back)] + fn harness_str_nonempty_reverse() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let mut needle_buf = [0u8; 8]; + let needle = any_short_needle(&mut needle_buf); + assert_str_pattern_direction(s, needle, true); + kani::cover(needle.len() == 1, "str pattern reverse: byte searcher"); + kani::cover( + needle.len() > 4, + "str pattern reverse: two multibyte scalars", + ); + kani::cover(true, "C22-END: harness_str_nonempty_reverse completed"); + } + + // Independent streaming decoder for checking the local input predicate. + // Its state is the expected continuation count and permitted next byte; + // unlike the local predicate it does not inspect overlapping windows. + fn reference_utf8_valid(bytes: &[u8]) -> bool { + let mut pending = 0usize; + let mut low = 0x80; + let mut high = 0xBF; + // Index traversal keeps this reference independent of slice iterator + // pointer models. No encoding constraint is assumed in this loop. + let mut index = 0usize; + while index < bytes.len() { + let byte = bytes[index]; + index += 1; + if pending > 0 { + if byte < low || byte > high { + return false; + } + pending -= 1; + low = 0x80; + high = 0xBF; + } else { + match byte { + 0..=0x7F => {} + 0xC2..=0xDF => pending = 1, + 0xE0 => { + pending = 2; + low = 0xA0; + } + 0xE1..=0xEC | 0xEE..=0xEF => pending = 2, + 0xED => { + pending = 2; + high = 0x9F; + } + 0xF0 => { + pending = 3; + low = 0x90; + } + 0xF1..=0xF3 => pending = 3, + 0xF4 => { + pending = 3; + high = 0x8F; + } + _ => return false, + } + } + } + pending == 0 + } + + // No UTF-8 validity filter: raw bytes include all invalid encodings. + // This checks both soundness and completeness of the local predicate + // against an independent streaming decoder throughout the largest + // allocation used by these proofs. It is not an arbitrary-N theorem. + #[kani::proof] + #[kani::unwind(257)] + fn harness_utf8_input_model() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let len: usize = kani::any(); + // INPUT-LENGTH: selecting a prefix within this allocation, not + // assuming any encoding property or expected comparison result. + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(len <= MAX_BYTES); + kani::cover(true, "C22-A11: harness_utf8_input_model assumption admitted"); + let local = verifier_utf8_valid(&buf, len); + let reference = reference_utf8_valid(&buf[..len]); + assert_eq!(local, reference); + kani::cover(local && len == MAX_BYTES, "UTF-8 model: full valid input"); + kani::cover( + !local && len == MAX_BYTES, + "UTF-8 model: rejects invalid input", + ); + kani::cover(local && len == 0, "UTF-8 model: empty input"); + kani::cover( + !local && len == 1 && buf[0] == 0xF0, + "UTF-8 model: truncated scalar", + ); + kani::cover( + local && len == 4 && buf[0] == 0xF4, + "UTF-8 model: largest scalar block", + ); + kani::cover(true, "C22-END: harness_utf8_input_model completed"); + } + + // Local safety lemmas for advance_by. These establish the obligations + // of one loop step only; the production loops are not contracted or + // replaced, so these are NOT an unbounded proof of advance_by. + #[kani::proof] + #[kani::unwind(33)] + fn harness_advance_chunk_step() { + let chunk: [u8; 32] = kani::any(); + let total_len: usize = kani::any(); + let skipped: usize = kani::any(); + let remainder: usize = kani::any(); + // LOCAL LEMMA: input precondition, not a proved production invariant. + kani::assume(skipped <= total_len && 32 <= total_len - skipped); + kani::cover(true, "C22-A12: harness_advance_chunk_step assumption admitted"); + // LOCAL LEMMA: input precondition, not a proved production invariant. + kani::assume(remainder > 32); + kani::cover(true, "C22-A13: harness_advance_chunk_step assumption admitted"); + let mut starts = [false; 32]; + for i in 0..32 { + starts[i] = !utf8_is_cont_byte(chunk[i]); + } + let count = starts.into_iter().map(|x| x as u8).sum::() as usize; + assert!(count <= 32); + assert!(count < remainder); + assert!(skipped + 32 <= total_len); + assert!(remainder - count > 0); + kani::cover(count == 32, "chunk step: all start bytes"); + kani::cover( + count == 0, + "chunk step: conservative invalid-byte over-approximation", + ); + kani::cover(true, "C22-END: harness_advance_chunk_step completed"); + } + + #[kani::proof] + fn harness_advance_character_step() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (start, end) = verifier_nondet_window(s); + // LOCAL LEMMA: input precondition, not a proved production invariant. + kani::assume(start < end); + kani::cover(true, "C22-A14: harness_advance_character_step assumption admitted"); + let width = utf8_char_width(s.as_bytes()[start]); + assert!(1 <= width && width <= 4); + assert!(width <= end - start); + assert!(s.is_char_boundary(start + width)); + let mut bytes = s.as_bytes()[start..end].iter(); + assert!(bytes.advance_by(width).is_ok()); + assert_eq!(bytes.len(), end - start - width); + kani::cover(width == 4, "character step: four-byte scalar"); + kani::cover(true, "C22-END: harness_advance_character_step completed"); + } + + #[kani::proof] + #[kani::unwind(4)] + fn harness_advance_boundary_restore() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let pos: usize = kani::any(); + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(pos <= s.len()); + kani::cover(true, "C22-A15: harness_advance_boundary_restore assumption admitted"); + let mut iter = s.as_bytes()[pos..].iter(); + let mut skipped = 0usize; + while let Some(&byte) = iter.as_slice().first() { + if !utf8_is_cont_byte(byte) { + break; + } + assert!(iter.advance_by(1).is_ok()); + skipped += 1; + } + assert!(skipped <= 3); + assert!(s.is_char_boundary(pos + skipped)); + kani::cover(skipped == 3, "boundary restore: three continuation bytes"); + kani::cover(skipped == 0, "boundary restore: already aligned"); + kani::cover(true, "C22-END: harness_advance_boundary_restore completed"); + } + // Count-gap regression on a fixed chunk or an empty string. A symbolic + // window made CBMC duplicate the unreachable chunk loop and exceeded the + // 480-second budget. This does not cover every length/window for n=9..32. + #[kani::proof] + #[kani::unwind(34)] + fn harness_chars_advance_by_medium() { + const BYTES: usize = 32; + let buf: [u8; BYTES + UTF8_PAD] = kani::any(); + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(&buf, BYTES)); + kani::cover(true, "C22-A16: harness_chars_advance_by_medium assumption admitted"); + // SAFETY: the local predicate establishes this fixed prefix's UTF-8. + let s = unsafe { from_utf8_unchecked(&buf[..BYTES]) }; + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(9 <= n && n <= 32); + kani::cover(true, "C22-A17: harness_chars_advance_by_medium assumption admitted"); + let empty: bool = kani::any(); + if empty { + verifier_check_chars_advance("", 0, 0, n); + } else { + verifier_check_chars_advance(s, 0, BYTES, n); + } + kani::cover(n == 32 && !empty, "advance_by: threshold count"); + kani::cover(empty, "advance_by: large count on empty input"); + kani::cover(true, "C22-END: harness_chars_advance_by_medium completed"); + } + + // Exhaust two full chunks for any request larger than their byte count, + // including usize::MAX. Only the allocation length is fixed here. The + // reference counts UTF-8 leading bytes, independently of chunk grouping; + // there is no character-decoding reference loop proportional to n. + // Requests 41..=64 have a separate fixed-size rank-reference proof below. + // Arbitrary allocation lengths are not covered here. + #[kani::proof] + #[kani::unwind(66)] + fn harness_chars_advance_by_multichunk() { + const BYTES: usize = 64; + let buf: [u8; BYTES + UTF8_PAD] = kani::any(); + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(&buf, BYTES)); + kani::cover(true, "C22-A18: harness_chars_advance_by_multichunk assumption admitted"); + // SAFETY: the local predicate establishes this fixed prefix's UTF-8. + let s = unsafe { from_utf8_unchecked(&buf[..BYTES]) }; + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(n > BYTES); + kani::cover(true, "C22-A19: harness_chars_advance_by_multichunk assumption admitted"); + let mut iter = s.chars(); + let result = iter.advance_by(n); + verifier_assert_str_range(s, iter.as_str(), BYTES, BYTES); + let mut chars = 0usize; + for i in 0..BYTES { + chars += (!utf8_is_cont_byte(buf[i])) as usize; + } + assert!(16 <= chars && chars <= BYTES); + let remaining = result.unwrap_err().get(); + assert_eq!(remaining, n - chars); + kani::cover(n == usize::MAX, "advance_by: maximum request"); + kani::cover(chars == 64, "advance_by: two ASCII chunks"); + kani::cover(chars == 16, "advance_by: two chunks of four-byte scalars"); + kani::cover( + utf8_is_cont_byte(buf[32]), + "advance_by: second chunk starts inside a scalar", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_multichunk completed"); + } + + // A byte-rank oracle, independent of advance_by's chunk grouping and + // continuation-restoration loop. On valid UTF-8, leading-byte rank is + // scalar rank. Locate the first boundary whose rank equals the request; + // if there is none, the expected residual string is empty. This oracle + // has a fixed allocation bound, even when n ranges over all usize values. + fn assert_advance_by_rank(buf: &[u8; N], n: usize) -> (usize, usize, usize) { + let len = N - UTF8_PAD; + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(buf, len)); + kani::cover(true, "C22-A20: assert_advance_by_rank assumption admitted"); + // SAFETY: the exact local predicate constrains the whole prefix. + let s = unsafe { from_utf8_unchecked(&buf[..len]) }; + let mut rank = 0usize; + let mut expected = len; + let mut first_chunk = 0usize; + let mut first_two_chunks = 0usize; + // Six verification blocks of 16 suffice for the largest input. + // This visits every byte once; it does not summarize counts per + // production chunk. A short inner loop allows a common unwind of + // 34, instead of expanding the target's scalar tail 98 times. + for block in 0..len.div_ceil(16) { + for offset in 0..16 { + let i = block * 16 + offset; + if i >= len { + break; + } + if i == 32 { + first_chunk = rank; + } + if i == 64 { + first_two_chunks = rank; + } + if !utf8_is_cont_byte(buf[i]) { + if rank == n { + expected = i; + } + rank += 1; + } + } + } + let mut iter = s.chars(); + let result = iter.advance_by(n); // real production body, no stubs + verifier_assert_str_range(s, iter.as_str(), expected, len); + if n <= rank { + assert!(result.is_ok()); + } else { + assert_eq!(result.unwrap_err().get(), n - rank); + } + kani::cover(result.is_ok(), "rank oracle: successful skip"); + kani::cover(result.is_err(), "rank oracle: exact missing scalar count"); + (expected, first_chunk, first_two_chunks) + } + + // Fill the request-count gap with an arbitrary valid 64-byte prefix. + // Both success and shortage are checked, rather than constraining the + // needle/request by an assumed postcondition on the production iterator. + #[kani::proof] + #[kani::unwind(34)] + fn harness_chars_advance_by_count_gap() { + let buf: [u8; 64 + UTF8_PAD] = kani::any(); + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(41 <= n && n <= 64); + kani::cover(true, "C22-A21: harness_chars_advance_by_count_gap assumption admitted"); + let (end, _, _) = assert_advance_by_rank(&buf, n); + kani::cover(n == 41 && end < 64, "count gap: lower request retains tail"); + kani::cover(n == 64, "count gap: upper request"); + kani::cover( + utf8_is_cont_byte(buf[32]), + "count gap: restore chunk boundary", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_count_gap completed"); + } + + // n > 64 forces at least two 32-byte scans: a chunk contains at most + // 32 leading bytes. Unlike the exhaustion regression, this input also + // permits a successful skip with a nonempty residual string. The rank + // covers establish that the chunk loop exits after exactly two scans, + // then restores a boundary and consumes a positive scalar remainder. + #[kani::proof] + // The real tail has at most 32 bytes after two scans. Keep unwinding + // assertions enabled to check this bound as well as the reference loops. + #[kani::unwind(34)] + fn harness_chars_advance_by_multichunk_tail() { + let buf: [u8; 96 + UTF8_PAD] = kani::any(); + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(65 <= n && n <= 96); + kani::cover(true, "C22-A22: harness_chars_advance_by_multichunk_tail assumption admitted"); + let (end, first, first_two) = assert_advance_by_rank(&buf, n); + let two_scans = n - first > 32 && n - first_two <= 32; + kani::cover(two_scans && end < 96, "multi chunk: two scans retain tail"); + kani::cover( + two_scans && end < 96 && utf8_is_cont_byte(buf[64]), + "multi chunk: restore boundary then retain tail", + ); + kani::cover( + n - first_two > 32 && end == 96, + "multi chunk: third scan exhausts input", + ); + kani::cover(n == 96, "multi chunk: upper request"); + kani::cover(true, "C22-END: harness_chars_advance_by_multichunk_tail completed"); + } + + // Check the state generator separately. This asserts consequences of + // its input bounds; no invariant or post-target property is assumed. + #[kani::proof] + fn harness_split_state_generator() { + let buf: [u8; BUFFER_BYTES] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let iter = any_split(s); + assert!(type_invariant_split(&iter)); + assert!(verifier_same_slice(s, iter.matcher.haystack())); + assert_eq!(iter.matcher.calls, 0); + assert!(iter.matcher.last_match.is_none()); + assert!(iter.matcher.previous_match.is_none()); + kani::cover( + iter.finished && iter.start < iter.end, + "state generator: finished nonempty interval", + ); + kani::cover( + !iter.finished && iter.start == iter.end, + "state generator: active empty interval", + ); + kani::cover(true, "C22-END: harness_split_state_generator completed"); + } + + // Challenge assumption 1 supplies the functional correctness of slice + // byte search. This deterministic model implements its exact last-match + // definition, not a nondeterministic return-range assumption. In particular + // None is returned only after every byte has been checked. + fn verifier_last_byte(needle: u8, bytes: &[u8]) -> Option { + let mut index = bytes.len(); + while index > 0 { + index -= 1; + if bytes[index] == needle { + return Some(index); + } + } + None + } + + // Check the leaf model against the complete last-index specification on + // arbitrary raw prefixes, including non-UTF-8 data and the empty slice. + #[kani::proof] + #[kani::unwind(20)] + fn harness_reverse_byte_model() { + let bytes: [u8; 16] = kani::any(); + let len: usize = kani::any(); + // INPUT-LENGTH: only prefixes of this initialized array are inputs. + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(len <= bytes.len()); + kani::cover(true, "C22-A23: harness_reverse_byte_model assumption admitted"); + let needle: u8 = kani::any(); + let result = verifier_last_byte(needle, &bytes[..len]); + if let Some(index) = result { + assert!(index < len); + assert_eq!(bytes[index], needle); + } + for index in 0..len { + if result.is_none_or(|last| last < index) { + assert_ne!(bytes[index], needle); + } + } + kani::cover(result.is_some(), "byte model: matching byte"); + kani::cover(result.is_none(), "byte model: no match"); + kani::cover( + len > 0 && result == Some(len - 1), + "byte model: final byte matches", + ); + kani::cover(len == 0 && result.is_none(), "byte model: empty prefix"); + kani::cover(true, "C22-END: harness_reverse_byte_model completed"); + } + + // Bounded inclusion evidence for the hand-written char adapters. Keep + // the directions separate to avoid combining both search circuits; their + // union covers the original arbitrary-direction input domain. + fn assert_char_searcher_direction(reverse: bool) { + let buf: [u8; 16 + UTF8_PAD] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (front, back) = verifier_nondet_window(s); + let needle: char = kani::any(); + let result = verifier_assert_real_char_searcher(s, needle, front, back, reverse); + kani::cover(result.is_some(), "real char search: matching scalar"); + kani::cover(result.is_none(), "real char search: exhausted window"); + kani::cover( + result.is_some() && needle.len_utf8() == 4, + "real char search: four-byte match", + ); + kani::cover( + front == back && result.is_none(), + "real char search: empty window", + ); + } + + // The byte window has at most 16 bytes. Every failed candidate consumes + // a byte, so 18 includes the final exhaustion call and loop-exit check. + #[kani::proof] + #[kani::unwind(18)] + fn harness_char_searcher_forward_refinement() { + assert_char_searcher_direction(false); + kani::cover(true, "C22-END: harness_char_searcher_forward_refinement completed"); + } + + // Neither CharSearcher method is stubbed. Only the reverse slice byte + // leaf uses the exact deterministic model under challenge assumption 1. + #[kani::proof] + #[kani::unwind(18)] + #[kani::stub(crate::slice::memchr::memrchr, verifier_last_byte)] + fn harness_char_searcher_reverse_refinement() { + assert_char_searcher_direction(true); + kani::cover(true, "C22-END: harness_char_searcher_reverse_refinement completed"); + } + + // Independent rank check for any caller-supplied UTF-8 window. The + // caller's allocation bound is asserted, not silently assumed here. + // A u16 counter covers all 256 bytes without truncating character counts. + // No search, advance, or result property is assumed in this reference. + fn assert_advance_by_window_rank( + s: &str, + start: usize, + end: usize, + n: usize, + ) -> (usize, usize) { + assert!(s.len() <= MAX_BYTES); + assert!(start <= end && end <= s.len()); + assert!(s.is_char_boundary(start) && s.is_char_boundary(end)); + let mut iter = s[start..end].chars(); + let result = iter.advance_by(n); // real target, no stubs + let remaining = iter.as_str(); + let position = verifier_slice_offset(s, remaining); + assert!(start <= position && position <= end); + verifier_assert_str_range(s, remaining, position, end); + + // Independently rank the returned boundary. Every UTF-8 boundary + // has a unique scalar rank, so this characterizes the exact suffix + // without selecting an expected pointer once for every input byte. + let mut total = 0u16; + let mut consumed = 0u16; + let len = end - start; + for block in 0..len.div_ceil(16) { + for offset in 0..16 { + let local = block * 16 + offset; + if local >= len { + break; + } + let index = start + local; + if !utf8_is_cont_byte(s.as_bytes()[index]) { + total += 1; + if index < position { + consumed += 1; + } + } + } + } + let count = usize::from(total); + assert!(count <= len); + assert_eq!(usize::from(consumed), n.min(count)); + if n <= count { + assert!(result.is_ok()); + } else { + assert_eq!(result.unwrap_err().get(), n - count); + } + (position, count) + } + + // Full usize request domain, including zero and usize::MAX. Only the + // initialized backing object and valid UTF-8 origin bound the input. + // After chunk scanning the real scalar tail needs at most 32 iterations; + // the reference's 16-byte blocks do not force a byte-length global bound. + #[kani::proof] + #[kani::unwind(34)] + fn harness_chars_advance_by_all_counts() { + const BYTES: usize = 40; + let buf: [u8; BYTES + UTF8_PAD] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let n: usize = kani::any(); + let (position, _) = assert_advance_by_window_rank(s, 0, s.len(), n); + kani::cover(n == 0 && !s.is_empty(), "all counts: zero request"); + kani::cover( + n == 32 && position < s.len(), + "all counts: threshold retains tail", + ); + kani::cover( + n == 33 && s.len() >= 36 + && !s.is_char_boundary(32) + && !s.is_char_boundary(33) + && !s.is_char_boundary(34) + && position < s.len(), + "all counts: three continuation bytes then scalar tail", + ); + kani::cover( + n == usize::MAX && s.len() == BYTES, + "all counts: maximum usize nonempty input", + ); + kani::cover( + s.len() == BYTES && n == BYTES + 1 && position == s.len(), + "all counts: byte capacity plus one shortage", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_all_counts completed"); + } + + // A distinct large-allocation domain: every 256-byte UTF-8 string and + // every request above 256. This explicit request range is not a + // postcondition assumption or a claim about requests 0..=256. + #[kani::proof] + #[kani::unwind(34)] + fn harness_chars_advance_by_eight_chunks() { + const BYTES: usize = 256; + let buf: [u8; BYTES + UTF8_PAD] = kani::any(); + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(&buf, BYTES)); + kani::cover(true, "C22-A24: harness_chars_advance_by_eight_chunks assumption admitted"); + // SAFETY: the input predicate specifies a valid UTF-8 origin. + let s = unsafe { from_utf8_unchecked(&buf[..BYTES]) }; + let n: usize = kani::any(); + // INPUT DOMAIN: this bounded request partition only. + kani::assume(n > BYTES); + kani::cover(true, "C22-A25: harness_chars_advance_by_eight_chunks assumption admitted"); + // Independent 16-byte counting blocks keep the reference's adder + // chains smaller than a 256-step sum. The real target scans 32-byte + // chunks. Every local upper bound below is checked, never assumed. + let mut rank = 0u16; + for block in 0..BYTES / 16 { + let mut in_block = 0u8; + for offset in 0..16 { + let index = block * 16 + offset; + in_block += u8::from(!utf8_is_cont_byte(s.as_bytes()[index])); + assert!(usize::from(in_block) <= offset + 1); + } + rank += u16::from(in_block); + assert!(usize::from(rank) <= (block + 1) * 16); + } + let count = usize::from(rank); + let mut iter = s.chars(); + let result = iter.advance_by(n); // real target, no stubs + verifier_assert_str_range(s, iter.as_str(), BYTES, BYTES); + assert!(result.is_err()); + assert_eq!(result.unwrap_err().get(), n - count); + kani::cover(n == BYTES + 1, "eight chunks: minimum request"); + kani::cover(n == usize::MAX, "eight chunks: maximum usize request"); + kani::cover(count == BYTES, "eight chunks: 256 ASCII scalars"); + kani::cover(count == BYTES / 4, "eight chunks: all four-byte scalars"); + kani::cover(true, "C22-END: harness_chars_advance_by_eight_chunks completed"); + } + + // An independently computed byte-prefix rank table. Checked local + // UTF-8 step facts expose the relation between a boundary and its next + // scalar before the real target runs; they are not assumptions or stubs. + fn assert_advance_by_block_rank(s: &str, n: usize) -> (usize, usize) { + assert!(CAP <= MAX_BYTES && s.len() <= CAP); + let mut ranks = [0u16; MAX_BYTES + 1]; + for block in 0..CAP.div_ceil(16) { + for offset in 0..16 { + let index = block * 16 + offset; + if index >= s.len() { + break; + } + ranks[index + 1] = ranks[index] + + u16::from(!utf8_is_cont_byte(s.as_bytes()[index])); + assert!(usize::from(ranks[index + 1]) <= index + 1); + } + } + for block in 0..CAP.div_ceil(16) { + for offset in 0..16 { + let index = block * 16 + offset; + if index >= s.len() { + break; + } + if s.is_char_boundary(index) { + let width = utf8_char_width(s.as_bytes()[index]) as usize; + assert!(width > 0 && width <= 4 && width <= s.len() - index); + assert!(s.is_char_boundary(index + width)); + assert_eq!(ranks[index + width], ranks[index] + 1); + } + } + } + + let count = usize::from(ranks[s.len()]); + let mut iter = s.chars(); + let result = iter.advance_by(n); // real target, no stubs + let remaining = iter.as_str(); + let position = verifier_slice_offset(s, remaining); + assert!(position <= s.len()); + verifier_assert_str_range(s, remaining, position, s.len()); + assert_eq!(usize::from(ranks[position]), n.min(count)); + if n <= count { + assert!(result.is_ok()); + } else { + assert_eq!(result.unwrap_err().get(), n - count); + } + (position, count) + } + + // Complement the retained 0..=40-byte complete-request proof with + // explicitly new extents. The guard selects an input length domain; + // no request or target-output condition is used as a filter. + #[kani::proof] + #[kani::unwind(34)] + fn harness_chars_advance_by_extended_counts() { + const BYTES: usize = 48; + let buf: [u8; BYTES + UTF8_PAD] = kani::any(); + let s = verifier_nondet_utf8(&buf); + if s.len() <= 40 { + return; + } + let n: usize = kani::any(); + let (position, _) = assert_advance_by_window_rank(s, 0, s.len(), n); + kani::cover( + n == 41 && s.len() == BYTES - 1 && position < s.len(), + "extended counts: new length and request retain tail", + ); + kani::cover( + n == 33 && s.len() == BYTES + && !s.is_char_boundary(32) + && !s.is_char_boundary(33) + && !s.is_char_boundary(34) + && position < s.len(), + "extended counts: three continuation bytes then scalar tail", + ); + kani::cover( + n == BYTES + 1 && s.len() == BYTES && position == s.len(), + "extended counts: exact shortage beyond byte capacity", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_extended_counts completed"); + } + + // A bounded view constructor, not a filter on iterator outputs. Any + // desired boundary window of at most LIMIT bytes is represented by + // choosing that same window before this constructor (it is unchanged). + fn verifier_utf8_prefix(s: &str) -> &str { + let mut end = s.len().min(LIMIT); + for _ in 0..3 { + if s.is_char_boundary(end) { + break; + } + assert!(end > 0); + end -= 1; + } + assert!(end <= LIMIT && end <= s.len()); + assert!(s.is_char_boundary(end)); + &s[..end] + } + + #[kani::proof] + #[kani::unwind(34)] + fn harness_chars_advance_by_window_rank() { + const BYTES: usize = 256; + const WINDOW_BYTES: usize = 8; + let buf: [u8; BYTES + UTF8_PAD] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (front, back) = verifier_nondet_window(s); + let selected = &s[front..back]; + let view = verifier_utf8_prefix::(selected); + verifier_assert_str_range(s, view, front, front + view.len()); + let n: usize = kani::any(); + let (position, _) = assert_advance_by_block_rank::(view, n); + assert!(front + position <= back); + kani::cover( + s.len() == BYTES && front > 0 && back < s.len() + && n == 7 && position < view.len(), + "window rank: interior large-allocation success", + ); + kani::cover( + s.len() == BYTES && front > 0 && front + view.len() < s.len() + && !view.is_empty() && n == usize::MAX, + "window rank: maximum request ends inside parent allocation", + ); + kani::cover( + view.is_empty() && front > 0 && front < s.len() && n > 0, + "window rank: empty interior shortage", + ); + kani::cover( + selected.len() > WINDOW_BYTES && view.len() + 3 == WINDOW_BYTES, + "window rank: view limit crosses three continuation bytes", + ); + kani::cover(true, "C22-END: harness_chars_advance_by_window_rank completed"); + } +} diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index ee6fd26ca0bfe..505bc32dbac3c 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -2116,20 +2116,34 @@ pub mod verify { let y: [u8; ARR_SIZE] = kani::any(); let xs = kani::slice::any_slice_of_array(&x); let ys = kani::slice::any_slice_of_array(&y); + // UNSAFE PRECONDITION: required by the operation under test. kani::assume(xs.len() == ys.len()); + kani::cover(true, "C22-A26: check_small_slice_eq assumption admitted"); unsafe { small_slice_eq(xs, ys); } + kani::cover(true, "C22-END: check_small_slice_eq completed"); } #[cfg(all(kani, target_arch = "x86_64"))] // only called on x86 #[kani::proof] #[kani::unwind(4)] pub fn check_small_slice_eq_empty() { - let ptr_x = kani::any_where::(|val| *val != 0) as *const u8; - let ptr_y = kani::any_where::(|val| *val != 0) as *const u8; - kani::assume(ptr_x.is_aligned()); - kani::assume(ptr_y.is_aligned()); + // Zero-length raw slices still require non-null pointers. Make the + // former any_where filters explicit so each has a coverage witness. + let address_x: usize = kani::any(); + // UNSAFE PRECONDITION: required by the operation under test. + kani::assume(address_x != 0); + kani::cover(true, "C22-A27: check_small_slice_eq_empty assumption admitted"); + let address_y: usize = kani::any(); + // UNSAFE PRECONDITION: required by the operation under test. + kani::assume(address_y != 0); + kani::cover(true, "C22-A28: check_small_slice_eq_empty assumption admitted"); + let ptr_x = address_x as *const u8; + let ptr_y = address_y as *const u8; + // u8 has alignment one; prove this instead of filtering inputs. + assert!(ptr_x.is_aligned()); + assert!(ptr_y.is_aligned()); assert_eq!( unsafe { small_slice_eq( @@ -2139,5 +2153,318 @@ pub mod verify { }, true ); + kani::cover(true, "C22-END: check_small_slice_eq_empty completed"); + } + + // Challenge 22: specifications for the permitted `str::pattern` assumption. + // These helpers are inside `str::pattern::verify`, not production code. + // Iterator harnesses stub only the explicitly annotated directional search + // operations; all real production bodies remain unchanged. These are + // manual safety abstractions under assumption 2, not stub_verified proofs. + // The simulation relation is observational: iter.rs reads haystack and + // match intervals, not search-algorithm preprocessing or equality state. + // See doc/src/verification/challenge-22-coverage.md for each adapter's + // admitted returns, frame conditions, progress, and proof obligations. + + pub fn verifier_char_searcher_invariant(searcher: &CharSearcher<'_>) -> bool { + let haystack = searcher.haystack; + let mut encoded = [0u8; 4]; + let width = searcher.needle.encode_utf8(&mut encoded).len(); + searcher.finger <= searcher.finger_back + && searcher.finger_back <= haystack.len() + && haystack.is_char_boundary(searcher.finger) + && haystack.is_char_boundary(searcher.finger_back) + && searcher.utf8_size() == width + && searcher.utf8_encoded[0] == encoded[0] + && (width < 2 || searcher.utf8_encoded[1] == encoded[1]) + && (width < 3 || searcher.utf8_encoded[2] == encoded[2]) + && (width < 4 || searcher.utf8_encoded[3] == encoded[3]) + } + + // A real call is checked against the return/frame relation imported by + // the char stubs below. The caller selects a valid input window; assert + // that precondition instead of silently filtering it with kani::assume. + // The dedicated harness preserves both real CharSearcher methods; its + // reverse slice byte-search leaf uses an exact model under assumption 1. + pub fn verifier_assert_real_char_searcher( + haystack: &str, + needle: char, + front: usize, + back: usize, + reverse: bool, + ) -> Option<(usize, usize)> { + assert!(front <= back && back <= haystack.len()); + assert!(haystack.is_char_boundary(front) && haystack.is_char_boundary(back)); + let mut searcher = needle.into_searcher(haystack); + searcher.finger = front; + searcher.finger_back = back; + assert!(verifier_char_searcher_invariant(&searcher)); + let encoding = searcher.utf8_encoded; + let width = searcher.utf8_size; + let result = if reverse { + searcher.next_match_back() + } else { + searcher.next_match() + }; + assert!(verifier_char_searcher_invariant(&searcher)); + assert_eq!(searcher.haystack.as_ptr(), haystack.as_ptr()); + assert_eq!(searcher.haystack.len(), haystack.len()); + assert_eq!(searcher.needle, needle); + assert_eq!(searcher.utf8_size, width); + for i in 0..4 { + assert_eq!(searcher.utf8_encoded[i], encoding[i]); + } + if reverse { + assert_eq!(searcher.finger, front); + } else { + assert_eq!(searcher.finger_back, back); + } + match result { + Some((a, b)) => { + assert!(front <= a && a < b && b <= back); + assert_eq!(b - a, needle.len_utf8()); + assert!(haystack.is_char_boundary(a) && haystack.is_char_boundary(b)); + let mut matched = haystack[a..b].chars(); + assert_eq!(matched.next(), Some(needle)); + assert!(matched.next().is_none()); + if reverse { + assert_eq!(searcher.finger_back, a); + } else { + assert_eq!(searcher.finger, b); + } + } + None => assert_eq!(searcher.finger, searcher.finger_back), + } + result + } + + // This over-approximates Searcher::next_match under Challenge 22 + // assumption 2: either no match remains, or a needle-width boundary + // range lies between the current search frontiers. This may admit a + // sequence of shorter scalars, an intentional safety over-approximation. + // We do not assume the match actually equals the needle, so the model + // admits at least the real searcher's possible returns. + pub fn verifier_stub_char_next_match<'a: 'a>( + searcher: &mut CharSearcher<'a>, + ) -> Option<(usize, usize)> { + assert!(verifier_char_searcher_invariant(searcher)); + let found: bool = kani::any(); + if !found { + searcher.finger = searcher.finger_back; + return None; + } + let start: usize = kani::any(); + let width = searcher.needle.len_utf8(); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(searcher.finger <= start && start <= searcher.finger_back); + kani::cover(true, "C22-A29: verifier_stub_char_next_match assumption admitted"); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(width <= searcher.finger_back - start); + kani::cover(true, "C22-A30: verifier_stub_char_next_match assumption admitted"); + let end = start + width; + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume( + searcher.haystack.is_char_boundary(start) && searcher.haystack.is_char_boundary(end), + ); + kani::cover(true, "C22-A31: verifier_stub_char_next_match assumption admitted"); + searcher.finger = end; + assert!(verifier_char_searcher_invariant(searcher)); + Some((start, end)) + } + + // ReverseSearcher::next_match_back: same permitted abstraction, with + // the opposite search frontier moved to the beginning of the match. + pub fn verifier_stub_char_next_match_back<'a: 'a>( + searcher: &mut CharSearcher<'a>, + ) -> Option<(usize, usize)> { + assert!(verifier_char_searcher_invariant(searcher)); + let found: bool = kani::any(); + if !found { + searcher.finger_back = searcher.finger; + return None; + } + let start: usize = kani::any(); + let width = searcher.needle.len_utf8(); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(searcher.finger <= start && start <= searcher.finger_back); + kani::cover(true, "C22-A32: verifier_stub_char_next_match_back assumption admitted"); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(width <= searcher.finger_back - start); + kani::cover(true, "C22-A33: verifier_stub_char_next_match_back assumption admitted"); + let end = start + width; + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume( + searcher.haystack.is_char_boundary(start) && searcher.haystack.is_char_boundary(end), + ); + kani::cover(true, "C22-A34: verifier_stub_char_next_match_back assumption admitted"); + searcher.finger_back = start; + assert!(verifier_char_searcher_invariant(searcher)); + Some((start, end)) + } + // Directional adapters for Challenge 22 assumption 2. They constrain + // returned ranges and the state consumed by iter.rs, not match contents. + // In particular StrSearcher has independent forward/reverse cursors: + // it must not inherit CharSearcher's shared-finger ordering invariant. + // None normalizes a cursor to an exhausted representative. Algorithm + // metadata is unobserved by iter.rs; these are not verified contracts for + // the real search bodies. Explicit self-bounded lifetimes match the + // early-bound generic parameters required by Kani's stub checker. + pub fn verifier_stub_str_next_match<'a: 'a, 'b: 'b>( + s: &mut StrSearcher<'a, 'b>, + ) -> Option<(usize, usize)> { + if s.needle.is_empty() { + // Empty-needle Match/Reject alternation needs at most two real + // steps. Retain its actual phase, UTF-8 decoding and exhaustion. + return match s.next() { + SearchStep::Match(a, b) => Some((a, b)), + SearchStep::Done => None, + SearchStep::Reject(..) => match s.next() { + SearchStep::Match(a, b) => Some((a, b)), + SearchStep::Done => None, + SearchStep::Reject(..) => unreachable!("empty needle alternates"), + }, + }; + } + verifier_stub_str_nonempty_next_match(s) + } + + pub fn verifier_stub_str_next_match_back<'a: 'a, 'b: 'b>( + s: &mut StrSearcher<'a, 'b>, + ) -> Option<(usize, usize)> { + if s.needle.is_empty() { + return match s.next_back() { + SearchStep::Match(a, b) => Some((a, b)), + SearchStep::Done => None, + SearchStep::Reject(..) => match s.next_back() { + SearchStep::Match(a, b) => Some((a, b)), + SearchStep::Done => None, + SearchStep::Reject(..) => unreachable!("empty needle alternates"), + }, + }; + } + verifier_stub_str_nonempty_next_match_back(s) + } + + // Nonempty-only entry keeps the Empty branch's real next() out of + // this harness call graph; pattern algorithms remain assumed correct. + pub fn verifier_stub_str_nonempty_next_match<'a: 'a, 'b: 'b>( + s: &mut StrSearcher<'a, 'b>, + ) -> Option<(usize, usize)> { + assert!(!s.needle.is_empty()); + let front = match &s.searcher { + StrSearcherImpl::Byte(x) => x.position, + StrSearcherImpl::TwoWay(x) => x.position, + StrSearcherImpl::Empty(_) => unreachable!(), + }; + assert!(front <= s.haystack.len() && s.haystack.is_char_boundary(front)); + let result = + verifier_directional_match(s.haystack, front, s.haystack.len(), s.needle.len()); + let next = result.map_or(s.haystack.len(), |(_, b)| b); + match &mut s.searcher { + StrSearcherImpl::Byte(x) => x.position = next, + StrSearcherImpl::TwoWay(x) => x.position = next, + StrSearcherImpl::Empty(_) => unreachable!(), + } + result + } + + // Nonempty-only entry keeps the Empty branch's real next() out of + // this harness call graph; pattern algorithms remain assumed correct. + pub fn verifier_stub_str_nonempty_next_match_back<'a: 'a, 'b: 'b>( + s: &mut StrSearcher<'a, 'b>, + ) -> Option<(usize, usize)> { + assert!(!s.needle.is_empty()); + let back = match &s.searcher { + StrSearcherImpl::Byte(x) => x.end, + StrSearcherImpl::TwoWay(x) => x.end, + StrSearcherImpl::Empty(_) => unreachable!(), + }; + assert!(back <= s.haystack.len() && s.haystack.is_char_boundary(back)); + let result = verifier_directional_match(s.haystack, 0, back, s.needle.len()); + let next = result.map_or(0, |(a, _)| a); + match &mut s.searcher { + StrSearcherImpl::Byte(x) => x.end = next, + StrSearcherImpl::TwoWay(x) => x.end = next, + StrSearcherImpl::Empty(_) => unreachable!(), + } + result + } + + fn verifier_directional_match( + s: &str, + front: usize, + back: usize, + width: usize, + ) -> Option<(usize, usize)> { + if !kani::any::() { + return None; + } + let a: usize = kani::any(); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(front <= a && a <= back); + kani::cover(true, "C22-A35: verifier_directional_match assumption admitted"); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(width <= back - a); + kani::cover(true, "C22-A36: verifier_directional_match assumption admitted"); + let b = a + width; + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); + kani::cover(true, "C22-A37: verifier_directional_match assumption admitted"); + Some((a, b)) + } + + pub fn verifier_char_slice_position(s: &CharSliceSearcher<'_, '_>) -> (usize, usize) { + let front = s.0.char_indices.front_offset; + (front, front + s.0.char_indices.iter.iter.len()) + } + + fn verifier_stub_char_slice_match( + s: &mut CharSliceSearcher<'_, '_>, + reverse: bool, + ) -> Option<(usize, usize)> { + let (front, back) = verifier_char_slice_position(s); + let haystack = s.0.haystack; + assert!(front <= back && back <= haystack.len()); + assert!(haystack.is_char_boundary(front) && haystack.is_char_boundary(back)); + let result = if s.0.char_eq.is_empty() || !kani::any::() { + None + } else { + let a: usize = kani::any(); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(front <= a && a < back); + kani::cover(true, "C22-A38: verifier_stub_char_slice_match assumption admitted"); + // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. + kani::assume(haystack.is_char_boundary(a)); + kani::cover(true, "C22-A39: verifier_stub_char_slice_match assumption admitted"); + // The real character width makes each result exactly one scalar, + // while the selected set element and equality are abstracted. + let width = super::super::validations::utf8_char_width(haystack.as_bytes()[a]); + assert!(width > 0 && width <= back - a); + let b = a + width; + assert!(haystack.is_char_boundary(b)); + Some((a, b)) + }; + let (new_front, new_back) = if reverse { + (front, result.map_or(front, |(a, _)| a)) + } else { + (result.map_or(back, |(_, b)| b), back) + }; + s.0.char_indices = super::super::CharIndices { + front_offset: new_front, + iter: haystack[new_front..new_back].chars(), + }; + result + } + + pub fn verifier_stub_char_slice_next_match<'a: 'a, 'b: 'b>( + s: &mut CharSliceSearcher<'a, 'b>, + ) -> Option<(usize, usize)> { + verifier_stub_char_slice_match(s, false) + } + + pub fn verifier_stub_char_slice_next_match_back<'a: 'a, 'b: 'b>( + s: &mut CharSliceSearcher<'a, 'b>, + ) -> Option<(usize, usize)> { + verifier_stub_char_slice_match(s, true) } } From 8166f4a4cbb76ea6c7e7c090395231efc92536d1 Mon Sep 17 00:00:00 2001 From: v3risec Date: Mon, 16 Nov 2026 19:35:15 +0800 Subject: [PATCH 2/8] Strengthen Challenge 22 verification with unbounded symbolic-length safety proofs --- library/core/src/array/iter/iter_inner.rs | 125 ++ library/core/src/slice/iter.rs | 38 + library/core/src/str/iter.rs | 2402 +++++++-------------- 3 files changed, 967 insertions(+), 1598 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index d93cbf32c0162..cfa8434efc0de 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -167,7 +167,88 @@ impl SpecPolymorphicIterClone for T { } } +// Fail closed if the harness-wide fold stub reaches an unproved element +// instantiation. The actual advance_by pipeline and refinement proofs use bool. +#[cfg(kani)] +trait Challenge22FoldElement { + fn admitted() -> bool; +} + +#[cfg(kani)] +impl Challenge22FoldElement for T { + default fn admitted() -> bool { false } +} + +#[cfg(kani)] +impl Challenge22FoldElement for bool { + fn admitted() -> bool { true } +} + impl PolymorphicIter<[MaybeUninit]> { + /// Loop-free replacement used only by the Challenge 22 harnesses. + /// + /// Unlike a non-consuming sum oracle, this advances `alive` before each + /// callback, just as `try_fold` does. Ordinary drop therefore sees exactly + /// the same remaining elements, including if a callback panics. + /// The assertions make uses outside the proved, fixed-size domain fail. + #[cfg(kani)] + pub(crate) fn kani_fold_at_most_32(&mut self, init: B, mut f: impl FnMut(B, T) -> B) -> B { + assert!(::admitted()); + assert!(self.alive.start() <= self.alive.end()); + assert!(self.alive.end() <= self.data.len()); + assert!(self.data.len() == 32); + let start = self.alive.start(); + let end = self.alive.end(); + let data = self.data.as_ptr().cast::(); + let mut accum = init; + macro_rules! step { + ($k:expr) => { + if start + $k < end { + let idx = start + $k; + let _ = self.alive.take_prefix(1); + // SAFETY: take_prefix removed an initialized element from the + // alive range, transferring its ownership to the callback. + let ptr = data.wrapping_add(idx); + let elem = unsafe { crate::intrinsics::read_via_copy(ptr) }; + accum = f(accum, elem); + } + }; + } + step!(0); + step!(1); + step!(2); + step!(3); + step!(4); + step!(5); + step!(6); + step!(7); + step!(8); + step!(9); + step!(10); + step!(11); + step!(12); + step!(13); + step!(14); + step!(15); + step!(16); + step!(17); + step!(18); + step!(19); + step!(20); + step!(21); + step!(22); + step!(23); + step!(24); + step!(25); + step!(26); + step!(27); + step!(28); + step!(29); + step!(30); + step!(31); + accum + } + #[inline] pub(super) fn as_slice(&self) -> &[T] { // SAFETY: We know that all elements within `alive` are properly initialized. @@ -324,3 +405,47 @@ impl PolymorphicIter<[MaybeUninit]> { }) } } + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + use super::*; + use crate::kani; + + // In addition to the sum used by advance_by, record the entire sequence + // (at most 32 bits) and the callback count. Compare the actual implementation + // directly with the model; neither implementation is stubbed in this proof. + #[kani::proof] + #[kani::unwind(33)] + fn check_consuming_fold_model() { + let flags: [bool; 32] = kani::any(); + let start: usize = kani::any(); + let end: usize = kani::any(); + kani::assume(start <= end && end <= 32); + // Same representation conversion as IntoIterator for arrays, without + // array::map's unrelated construction and draining machinery. + let data: [MaybeUninit; 32] = unsafe { crate::mem::transmute(flags) }; + let mut actual = unsafe { + PolymorphicIter::new_unchecked(IndexRange::new_unchecked(start, end), data) + }; + let mut model = unsafe { + PolymorphicIter::new_unchecked(IndexRange::new_unchecked(start, end), data) + }; + let actual: &mut PolymorphicIter<[MaybeUninit]> = &mut actual; + let model: &mut PolymorphicIter<[MaybeUninit]> = &mut model; + let observe = |(sum, trace, calls): (u8, u64, u8), flag: bool| { + (sum + flag as u8, (trace << 1) | flag as u64, calls + 1) + }; + let expected = actual.fold((0, 0, 0), observe); + let result = model.kani_fold_at_most_32((0, 0, 0), observe); + assert!(result == expected); + assert!(actual.alive == model.alive); + assert!(model.alive.start() == end && model.alive.end() == end); + assert!(result.2 as usize == end - start); + assert!(model.next().is_none() && actual.next().is_none()); + kani::cover(start == 0 && end == 32, "all 32 independent flags consumed"); + kani::cover(start == end, "empty alive range"); + kani::cover(0 < start && start < end && end < 32, "interior alive range"); + // Both ordinary destructors run; bool has no destructor of its own. + } +} diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 9e5a8338b8afc..1c088c550addc 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -168,6 +168,44 @@ impl AsRef<[T]> for Iter<'_, T> { } } +#[cfg(kani)] +impl Iter<'_, T> { + /// Verification-only access to the representation, avoiding contracted + /// NonNull methods inside loop clauses (see Kani issue #4796). + pub(crate) fn kani_raw_parts(&self) -> (*const T, *const T) { + (unsafe { mem::transmute::, *const T>(self.ptr) }, self.end_or_len) + } + + /// Clause-only copy: CBMC adds a write-set parameter to ordinary calls, + /// whereas calls from loop clauses have a different calling convention. + /// + /// # Safety + /// `this` must point to readable iterator storage. The pointer fields are + /// read as raw pointer representations, so a havoc candidate need not yet + /// satisfy the NonNull or iterator range invariants. + pub(crate) unsafe fn kani_loop_raw_parts(this: *const Self) -> (*const T, *const T) { + // Read the representation before requiring NonNull's validity. Havoc + // can produce invalid candidates, which the invariant must exclude. + let ptr = unsafe { (&raw const (*this).ptr).cast::<*const T>() }; + let end = unsafe { &raw const (*this).end_or_len }; + unsafe { (crate::intrinsics::read_via_copy(ptr), crate::intrinsics::read_via_copy(end)) } + } + + /// # Safety + /// These must be the fields of a valid iterator over a slice living for + /// `'a`, including the special end/length representation for a ZST. + pub(crate) unsafe fn kani_from_raw_parts<'a>( + ptr: *const T, + end_or_len: *const T, + ) -> Iter<'a, T> { + Iter { + ptr: unsafe { mem::transmute::<*const T, NonNull>(ptr) }, + end_or_len, + _marker: PhantomData, + } + } +} + #[unstable(feature = "ub_checks", issue = "none")] impl Invariant for Iter<'_, T> { /// An iterator can be safely used if its pointer can be read for its current length. diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 5ad12373112be..54405880b0000 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -59,6 +59,10 @@ impl<'a> Iterator for Chars<'a> { let mut chunks = self.iter.as_slice().as_chunks::().0.iter(); let mut bytes_skipped: usize = 0; + #[safety::loop_invariant(verify::chunks_inv( + &raw const chunks, bytes_skipped, on_entry(chunks.kani_raw_parts()), + ))] + #[cfg_attr(kani, kani::loop_modifies(&chunks, &bytes_skipped, &remainder))] while remainder > CHUNK_SIZE && let Some(chunk) = chunks.next() { @@ -66,6 +70,7 @@ impl<'a> Iterator for Chars<'a> { let mut start_bytes = [false; CHUNK_SIZE]; + #[safety::loop_invariant(verify::flags_valid(&raw const start_bytes))] for i in 0..CHUNK_SIZE { start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); } @@ -78,6 +83,10 @@ impl<'a> Iterator for Chars<'a> { unsafe { self.iter.advance_by(bytes_skipped).unwrap_unchecked() }; // skip trailing continuation bytes + #[safety::loop_invariant(verify::bytes_inv( + &raw const self.iter, on_entry(self.iter.kani_raw_parts()), + ))] + #[cfg_attr(kani, kani::loop_modifies(&self.iter))] while self.iter.len() > 0 { let b = self.iter.as_slice()[0]; if !super::validations::utf8_is_cont_byte(b) { @@ -88,6 +97,11 @@ impl<'a> Iterator for Chars<'a> { } } + #[safety::loop_invariant( + verify::bytes_inv(&raw const self.iter, on_entry(self.iter.kani_raw_parts())) + && verify::loop_on_char_boundary(&raw const self.iter) + )] + #[cfg_attr(kani, kani::loop_modifies(&self.iter, &remainder))] while (remainder > 0) && (self.iter.len() > 0) { remainder -= 1; let b = self.iter.as_slice()[0]; @@ -1645,288 +1659,488 @@ escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode); #[cfg(kani)] #[unstable(feature = "kani", issue = "none")] mod verify { - use super::super::pattern::verify::{ - verifier_assert_real_char_searcher, verifier_char_searcher_invariant, - verifier_stub_char_next_match, verifier_stub_char_next_match_back, - verifier_stub_char_slice_next_match, verifier_stub_char_slice_next_match_back, - verifier_stub_str_nonempty_next_match, verifier_stub_str_nonempty_next_match_back, - }; - use super::super::pattern::{CharSearcher, CharSliceSearcher, StrSearcher}; - use super::super::validations::{utf8_char_width, utf8_is_cont_byte}; + //! Symbolic-length safety harnesses for Challenge 22. + //! + //! Slice and Pattern behavior and UTF-8 validation semantics are the explicit + //! dependency assumptions allowed by doc/src/challenges/0022-str-iter.md. + //! Local UTF-8 facts constrain the original input; cursor bounds and character + //! boundaries after the actual target calls are checked, not assumed. + //! Fixed-size fold models have independent refinement and pipeline harnesses. + + use super::super::validations::utf8_is_cont_byte; use super::*; + use crate::mem; - // The backing array bounds CBMC's object model, not the number of - // iteration steps. Claims of arbitrary mathematical length require an - // additional argument beyond this finite allocation model. - const MAX_BYTES: usize = 256; - const UTF8_PAD: usize = 4; - const BUFFER_BYTES: usize = MAX_BYTES + UTF8_PAD; - - // The local UTF-8 predicate and original bounded advance checks follow - // the input-model approach in PR #557; the interval protocol below - // replaces its char-specific iterator proof architecture. - // A loop-free UTF-8 validity model. For every leading byte, validate - // the sequence width, continuation bytes, and exceptional second-byte - // rules (E0/ED/F0/F4). Every continuation byte must be within three - // positions after a leading byte. Combined, these are equivalent to - // validity of buf[..len], provided len <= N - UTF8_PAD. - // Do not use from_utf8 as a symbolic-input filter under loop-contract - // instrumentation: it can abstract away the validation algorithm. - fn verifier_utf8_valid(buf: &[u8; N], len: usize) -> bool { - let p = buf.as_ptr(); - let sequences = crate::forall!(|i in (0, N - UTF8_PAD)| unsafe { - let i: usize = i; - let x0 = *p.wrapping_add(i); - let x1 = *p.wrapping_add(i.wrapping_add(1)); - let x2 = *p.wrapping_add(i.wrapping_add(2)); - let x3 = *p.wrapping_add(i.wrapping_add(3)); - let continuation0 = (x0 as i8) < -64; - let continuation1 = (x1 as i8) < -64; - let continuation2 = (x2 as i8) < -64; - let continuation3 = (x3 as i8) < -64; - let width = (x0 < 0x80) as usize - + (((x0 >= 0xC2) & (x0 < 0xE0)) as usize) * 2 - + (((x0 >= 0xE0) & (x0 < 0xF0)) as usize) * 3 - + (((x0 >= 0xF0) & (x0 < 0xF5)) as usize) * 4; - let next_is_continuation = - (*p.wrapping_add(i.wrapping_add(width)) as i8) < -64; - let second_byte_ok = ((x0 != 0xE0) | (x1 >= 0xA0)) - & ((x0 != 0xED) | (x1 < 0xA0)) - & ((x0 != 0xF0) | (x1 >= 0x90)) - & ((x0 != 0xF4) | (x1 < 0x90)); - (i >= len) - | continuation0 - | ((width > 0) - & (i.wrapping_add(width) <= len) - & ((width < 2) | (continuation1 & second_byte_ok)) - & ((width < 3) | continuation2) - & ((width < 4) | continuation3) - & ((i.wrapping_add(width) == len) | !next_is_continuation)) - }); - let covered = crate::forall!(|i in (0, N - UTF8_PAD)| unsafe { - let i: usize = i; - (i >= len) - | ((*p.wrapping_add(i) as i8) >= -64) - | ((i >= 1) & ((*p.wrapping_add(i.saturating_sub(1)) as i8) >= -64)) - | ((i >= 2) & ((*p.wrapping_add(i.saturating_sub(2)) as i8) >= -64)) - | ((i >= 3) & ((*p.wrapping_add(i.saturating_sub(3)) as i8) >= -64)) - }); - sequences && covered - } - - fn verifier_nondet_utf8(buf: &[u8; N]) -> &str { - let len: usize = kani::any(); - // INPUT DOMAIN: allocated prefix or index extent. - kani::assume(len <= N - UTF8_PAD); - kani::cover(true, "C22-A01: verifier_nondet_utf8 assumption admitted"); - // CHALLENGE 22 assumption 4: valid UTF-8 input. - kani::assume(verifier_utf8_valid(buf, len)); - kani::cover(true, "C22-A02: verifier_nondet_utf8 assumption admitted"); - // SAFETY: verifier_utf8_valid characterizes valid UTF-8 exactly. - unsafe { from_utf8_unchecked(&buf[..len]) } - } - - fn verifier_nondet_window(s: &str) -> (usize, usize) { - let start: usize = kani::any(); - let end: usize = kani::any(); - // INPUT STATE: an ordered UTF-8 boundary window. - kani::assume(start <= end && end <= s.len()); - kani::cover(true, "C22-A03: verifier_nondet_window assumption admitted"); - // INPUT STATE: an ordered UTF-8 boundary window. - kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); - kani::cover(true, "C22-A04: verifier_nondet_window assumption admitted"); - (start, end) + // CI uses --object-bits 12 on a 64-bit target. This is the largest positive + // one-past offset, not a small input bound chosen for loop unwinding. + const MAX_ALLOCATION_BYTES: usize = (1usize << 51) - 1; + + unsafe extern "C" { + fn malloc(size: usize) -> *mut u8; + fn __CPROVER_havoc_object(p: *mut crate::ffi::c_void); } - fn verifier_same_slice(left: &str, right: &str) -> bool { - left.as_ptr() == right.as_ptr() && left.len() == right.len() + // Immutable input extent used to reconstruct pointers after loop havoc. + // Only harness input construction writes this ghost state. + static mut INPUT: (*const u8, usize) = (crate::ptr::null(), 0); + + fn symbolic_text() -> &'static str { + let len: usize = kani::any(); + kani::assume(len <= MAX_ALLOCATION_BYTES); + let p = if len == 0 { + // An aligned nonnull dangling pointer is sufficient for an empty str. + 1usize as *mut u8 + } else { + let p = unsafe { malloc(len) }; + kani::assume(!p.is_null()); + // Initialize the shadow-memory state, then give every byte an + // independent arbitrary initialized value. Neither builtin unwinds + // a Rust loop over the symbolic length. + unsafe { + p.write_bytes(0, len); + __CPROVER_havoc_object(p.cast()); + } + p + }; + unsafe { INPUT = (p, len) }; + // A valid nonempty input begins at a lead byte. This also justifies + // str indexing's optimized check when both endpoints are zero. + kani::assume(utf8_ok_at(0)); + // The C allocation supplies symbolic bytes. UTF-8 is assumed locally + // where bytes are consumed; this overapproximates all valid strings. + unsafe { from_utf8_unchecked(slice::from_raw_parts(p, len)) } + } + + // At harness exit these goals follow ALL input assumptions and target checks. + // Keeping them out of allocation and loop models avoids repeated cover goals + // inside induction. Covers check feasibility, not the truth of an assumption. + fn cover_completed_text(s: &str) { + kani::cover(s.is_empty(), "completed on empty input"); + kani::cover(s.len() > 4096, "completed beyond former input bounds"); + } + + fn lead_width(b: u8) -> usize { + match b { + 0..=0x7f => 1, + 0xc2..=0xdf => 2, + 0xe0..=0xef => 3, + 0xf0..=0xf4 => 4, + _ => 0, + } + } + + fn second_ok(lead: u8, b: u8) -> bool { + match lead { + 0xe0 => b >= 0xa0 && b <= 0xbf, + 0xed => b >= 0x80 && b <= 0x9f, + 0xf0 => b >= 0x90 && b <= 0xbf, + 0xf4 => b >= 0x80 && b <= 0x8f, + _ => utf8_is_cont_byte(b), + } + } + + unsafe fn byte(i: usize) -> u8 { + let (p, len) = unsafe { INPUT }; + assert!(i < len); + unsafe { *p.add(i) } + } + + /// A necessary rule at any position of a valid UTF-8 input. The lookbehind + /// case permits a continuation byte; it does not assume cursor alignment. + fn utf8_ok_at(i: usize) -> bool { + let len = unsafe { INPUT.1 }; + if i >= len { + return true; + } + unsafe { + let b = byte(i); + let w = lead_width(b); + if w != 0 { + w <= len - i + && (w < 2 || second_ok(b, byte(i + 1))) + && (w < 3 || utf8_is_cont_byte(byte(i + 2))) + && (w < 4 || utf8_is_cont_byte(byte(i + 3))) + && (i + w == len || !utf8_is_cont_byte(byte(i + w))) + } else if utf8_is_cont_byte(b) { + (i >= 1 && lead_width(byte(i - 1)) >= 2) + || (i >= 2 && utf8_is_cont_byte(byte(i - 1)) && lead_width(byte(i - 2)) >= 3) + || (i >= 3 + && utf8_is_cont_byte(byte(i - 1)) + && utf8_is_cont_byte(byte(i - 2)) + && lead_width(byte(i - 3)) == 4) + } else { + false + } + } } - fn verifier_slice_offset(s: &str, subslice: &str) -> usize { - let base = s.as_ptr().addr(); - let current = subslice.as_ptr().addr(); - assert!(base <= current); - current - base + // Loop clauses of the real advance_by body. None of these invokes a method + // with a function contract or assumes the invariant it is checking. + pub(super) fn bytes_inv( + iter: *const slice::Iter<'_, u8>, + entry: (*const u8, *const u8), + ) -> bool { + let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; + end == entry.1 + && crate::intrinsics::wrapping_sub(ptr as usize, entry.0 as usize) + <= crate::intrinsics::wrapping_sub(entry.1 as usize, entry.0 as usize) + } + + pub(super) fn chunks_inv( + iter: *const slice::Iter<'_, [u8; 32]>, + skipped: usize, + entry: (*const [u8; 32], *const [u8; 32]), + ) -> bool { + let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; + end == entry.1 + && skipped % 32 == 0 + && skipped <= crate::intrinsics::wrapping_sub(entry.1 as usize, entry.0 as usize) + && crate::intrinsics::wrapping_sub(ptr as usize, entry.0 as usize) == skipped + } + + fn on_char_boundary(iter: &slice::Iter<'_, u8>) -> bool { + let (ptr, end) = iter.kani_raw_parts(); + let (base, len) = unsafe { INPUT }; + let start = (ptr as usize).wrapping_sub(base as usize); + ptr == end || (start < len && !utf8_is_cont_byte(unsafe { *base.wrapping_add(start) })) + } + + // Do not call ordinary helpers from a loop clause (CBMC/Kani issue #4796). + // This is intentionally separate from the postcondition's ordinary check. + pub(super) fn loop_on_char_boundary(iter: *const slice::Iter<'_, u8>) -> bool { + let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; + let (base, len) = unsafe { INPUT }; + let start = crate::intrinsics::wrapping_sub(ptr as usize, base as usize); + ptr == end + || (start < len + && unsafe { *crate::intrinsics::arith_offset(base, start as isize) } & 0xc0 != 0x80) + } + + // Read the representation as integers before requiring any typed bool value. + // In particular this does not form a &[bool; 32] to the havoced loop state. + pub(super) fn flags_valid(flags: *const [bool; 32]) -> bool { + let ptr = flags.cast::<[u8; 32]>(); + let b = unsafe { crate::intrinsics::read_via_copy(ptr) }; + (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 + == 0 + } + + // The only slice model instantiations admitted by this proof. Unsupported + // instantiations fail rather than silently changing the modeled domain. + trait AdvanceElement { + fn width() -> usize; + } + + impl AdvanceElement for T { + default fn width() -> usize { + panic!("advance_by slice model only supports u8 and [u8; 32]") + } + } + impl AdvanceElement for u8 { + fn width() -> usize { + 1 + } + } + impl AdvanceElement for [u8; 32] { + fn width() -> usize { + 32 + } + } + + // Loop havoc loses CBMC's points-to set (Kani #4993). Check the represented + // interval, then reconstruct access pointers from the immutable input base. + // The comparisons also check allocation identity, not only numeric bounds. + fn advance_window(iter: &slice::Iter<'_, T>) -> (usize, usize) { + let (ptr, end) = iter.kani_raw_parts(); + let (base, len) = unsafe { INPUT }; + let start = (ptr as usize).wrapping_sub(base as usize); + let stop = (end as usize).wrapping_sub(base as usize); + assert!(start <= stop && stop <= len); + assert!(ptr.cast::() == base.wrapping_add(start)); + assert!(end.cast::() == base.wrapping_add(stop)); + assert!((stop - start) % T::width() == 0); + (start, stop) + } + + fn advance_slice<'a, T>(start: usize, stop: usize) -> &'a [T] { + let base = unsafe { INPUT.0 }; + let ptr = base.wrapping_add(start).cast::(); + unsafe { &*crate::ptr::slice_from_raw_parts(ptr, (stop - start) / T::width()) } + } + + fn advance_iter<'a, T>(start: usize, stop: usize) -> slice::Iter<'a, T> { + let base = unsafe { INPUT.0 }; + unsafe { + slice::Iter::kani_from_raw_parts( + base.wrapping_add(start).cast::(), + base.wrapping_add(stop).cast::(), + ) + } + } + + fn advance_len<'a, T>(iter: &slice::Iter<'a, T>) -> usize + where + 'a: 'a, + { + let (start, stop) = advance_window(iter); + (stop - start) / T::width() } - // Assert *both* physical range and UTF-8 boundaries. Kani's checking - // of str::get_unchecked alone is not a substitute for the latter. - fn verifier_assert_str_range(s: &str, result: &str, start: usize, end: usize) { - assert!( - start <= end && end <= s.len(), - "slice is within the haystack" - ); - assert!( - s.is_char_boundary(start) && s.is_char_boundary(end), - "slice endpoints are UTF-8 character boundaries" - ); - assert!( - result.as_ptr() == s.as_ptr().wrapping_add(start), - "slice base pointer" - ); - assert!(result.len() == end - start, "slice byte length"); + fn advance_as_slice_plain<'a, T>(iter: &slice::Iter<'a, T>) -> &'a [T] { + let (start, stop) = advance_window(iter); + advance_slice(start, stop) } - // An arbitrary [start, end) window is exactly the type invariant of - // Chars: arbitrary interleavings of next/next_back preserve this set. - #[kani::proof] - pub fn harness_chars_next() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (start, end) = verifier_nondet_window(s); - let mut iter = s[start..end].chars(); - match iter.next() { - Some(ch) => { - let next_start = start + ch.len_utf8(); - verifier_assert_str_range(s, iter.as_str(), next_start, end); - kani::cover(ch.len_utf8() == 1, "chars::next: ASCII"); - kani::cover(ch.len_utf8() == 2, "chars::next: two-byte scalar"); - kani::cover(ch.len_utf8() == 3, "chars::next: three-byte scalar"); - kani::cover(ch.len_utf8() == 4, "chars::next: four-byte scalar"); - } - None => { - assert!(start == end); - kani::cover(true, "chars::next: exhausted"); + fn advance_as_slice<'a, T>(iter: &slice::Iter<'a, T>) -> &'a [T] + where + 'a: 'a, + { + let (start, stop) = advance_window(iter); + if T::width() == 1 { + // Every byte iterator used by this harness ends at the original + // string end. This is checked, not assumed after an operation. + assert!(stop == unsafe { INPUT.1 }); + if start < stop { + // Necessary facts at ANY position of the original valid string: + // a lead byte's sequence fits and ends at a boundary. In + // particular continuation bytes (width 0) are allowed here. + // Full scalar decoding constraints are unnecessary for advance_by. + let base = unsafe { INPUT.0 }; + let first = unsafe { *base.wrapping_add(start) }; + let width = super::super::validations::utf8_char_width(first); + kani::assume(width <= stop - start); + kani::assume( + width == 0 + || start + width == stop + || !utf8_is_cont_byte(unsafe { *base.wrapping_add(start + width) }), + ); } } - kani::cover(true, "C22-END: harness_chars_next completed"); + advance_slice(start, stop) } - #[kani::proof] - pub fn harness_chars_next_back() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (start, end) = verifier_nondet_window(s); - let mut iter = s[start..end].chars(); - match iter.next_back() { - Some(ch) => { - assert!(ch.len_utf8() <= end - start); - verifier_assert_str_range(s, iter.as_str(), start, end - ch.len_utf8()); - kani::cover(ch.len_utf8() == 1, "chars::next_back: ASCII"); - kani::cover(ch.len_utf8() == 4, "chars::next_back: four-byte scalar"); - } - None => { - assert!(start == end); - kani::cover(true, "chars::next_back: exhausted"); - } + fn advance_bytes<'a, T>(iter: &mut slice::Iter<'a, T>, n: usize) -> Result<(), NonZero> + where + 'a: 'a, + { + let (start, stop) = advance_window(iter); + let count = crate::cmp::min(n, (stop - start) / T::width()); + *iter = advance_iter(start + count * T::width(), stop); + NonZero::new(n - count).map_or(Ok(()), Err) + } + + fn advance_next<'a, T>(iter: &mut slice::Iter<'a, T>) -> Option<&'a T> + where + 'a: 'a, + { + let (start, stop) = advance_window(iter); + if start == stop { + return None; } - kani::cover(true, "C22-END: harness_chars_next_back completed"); + let part: &'a [T] = advance_slice(start, stop); + *iter = advance_iter(start + T::width(), stop); + Some(&part[0]) } #[kani::proof] - pub fn harness_chars_as_str() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (start, end) = verifier_nondet_window(s); - let window = &s[start..end]; - let mut iter = window.chars(); - assert!(verifier_same_slice(iter.as_str(), window)); - let front = iter.next().map_or(0, char::len_utf8); - let back = iter.next_back().map_or(0, char::len_utf8); - verifier_assert_str_range(s, iter.as_str(), start + front, end - back); - kani::cover(front > 0 && back > 0, "chars::as_str: both ends consumed"); - kani::cover(true, "C22-END: harness_chars_as_str completed"); - } - - const ADVANCE_MAX: usize = 8; - const ADVANCE_BYTES: usize = 128; - const CHUNK_MIN: usize = 33; - const CHUNK_MAX: usize = 40; - const CHUNK_BYTES: usize = 48; - - // Independent scalar-by-scalar reference for the bounded regression - // checks. It uses the public decoder, not advance_by's chunk counting. - fn verifier_reference_advance(s: &str, start: usize, end: usize, n: usize) -> (usize, usize) { - let mut chars = s[start..end].chars(); - let mut consumed = 0; - let mut pos = start; - while consumed < n { - match chars.next() { - Some(ch) => { - pos += ch.len_utf8(); - consumed += 1; - } - None => break, - } - } - (pos, consumed) + #[kani::stub( as crate::iter::ExactSizeIterator>::len, advance_len)] + #[kani::stub(crate::slice::Iter::as_slice, advance_as_slice)] + #[kani::stub( as crate::iter::Iterator>::advance_by, advance_bytes)] + #[kani::stub( as crate::iter::Iterator>::next, advance_next)] + #[kani::stub( + crate::array::iter::iter_inner::PolymorphicIter::fold, + crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 + )] + fn harness_chars_advance_by() { + // Every valid Chars state is a fresh iterator over its remaining valid + // string. Both the length and requested character count are symbolic. + let text = symbolic_text(); + let mut chars = text.chars(); + let n: usize = kani::any(); // No request/count bound. + let result = chars.advance_by(n); + let _ = advance_window(&chars.iter); + assert!(on_char_boundary(&chars.iter)); + kani::cover( + result.is_ok() && n > 64 && text.len() == MAX_ALLOCATION_BYTES, + "maximum representable string and chunk path", + ); + kani::cover(result.is_err() && n > 64, "insufficient characters"); + kani::cover(result.is_ok() && n > 0 && n < 32, "scalar path"); + kani::cover( + n == usize::MAX && text.len() > 4096 && result.is_err(), + "maximum request remains admitted after UTF-8 assumptions", + ); + kani::cover( + text.len() == 4 && n == 1 && result.is_ok() && lead_width(unsafe { byte(0) }) == 4, + "four-byte input remains admitted after scalar-loop checks", + ); } - fn verifier_check_chars_advance(s: &str, start: usize, end: usize, n: usize) { - let (expected_end, consumed) = verifier_reference_advance(s, start, end, n); - let mut iter = s[start..end].chars(); - let result = iter.advance_by(n); // real production body - verifier_assert_str_range(s, iter.as_str(), expected_end, end); - match result { - Ok(()) => assert!(consumed == n), - Err(remaining) => { - assert!(consumed < n); - assert!(expected_end == end); - assert!(remaining.get() == n - consumed); - } - } + // Empty slices can have arbitrary nonnull aligned addresses, not only the + // dangling address used by symbolic_text's zero-length allocation case. + #[kani::proof] + #[kani::stub( as crate::iter::ExactSizeIterator>::len, advance_len)] + #[kani::stub(crate::slice::Iter::as_slice, advance_as_slice)] + #[kani::stub( as crate::iter::Iterator>::advance_by, advance_bytes)] + #[kani::stub( as crate::iter::Iterator>::next, advance_next)] + #[kani::stub( + crate::array::iter::iter_inner::PolymorphicIter::fold, + crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 + )] + fn harness_chars_advance_by_empty() { + let ptr = kani::any::() as *const u8; + kani::assume(!ptr.is_null()); + unsafe { INPUT = (ptr, 0) }; + // SAFETY: any nonnull address is aligned for u8; no bytes are accessed. + let text = unsafe { from_utf8_unchecked(slice::from_raw_parts(ptr, 0)) }; + let mut chars = text.chars(); + let result = chars.advance_by(kani::any()); + assert!(chars.iter.kani_raw_parts() == (ptr, ptr)); + kani::cover(result.is_ok(), "zero request on arbitrary empty pointer"); kani::cover( - result.is_ok() && n > 0, - "chars::advance_by: successful skip", + result.is_err(), + "positive request on arbitrary empty pointer", ); - kani::cover(result.is_err(), "chars::advance_by: not enough characters"); } - // Both the backing allocation and advance count are bounded. The - // unwind derives from n, not string length; this is a regression proof. + fn any_window(s: &str) -> (usize, usize) { + let (a, b): (usize, usize) = (kani::any(), kani::any()); + kani::assume(a <= b && b <= s.len()); + kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); + kani::cover(true, "a boundary window exists"); + (a, b) + } + + // Input-state construction: these are checked premises, not target outputs. + // Avoid pulling panic-message string searching into every proof's call graph. + fn window(s: &str, a: usize, b: usize) -> &str { + assert!(a <= b && b <= s.len()); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + unsafe { s.get_unchecked(a..b) } + } + + fn same_slice(a: &str, b: &str) -> bool { + a.as_ptr() == b.as_ptr() && a.len() == b.len() + } + + // Check bounds and provenance before using an offset in the postcondition. + fn checked_offset(s: &str, part: &str) -> usize { + let offset = (part.as_ptr() as usize).wrapping_sub(s.as_ptr() as usize); + assert!(offset <= s.len() && part.len() <= s.len() - offset); + assert!(part.as_ptr() == s.as_ptr().wrapping_add(offset)); + offset + } + + fn check_range(s: &str, part: &str, a: usize, b: usize) { + assert!(a <= b && b <= s.len()); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + assert!(part.as_ptr() == s.as_ptr().wrapping_add(a)); + assert!(part.len() == b - a); + } + #[kani::proof] - #[kani::unwind(9)] - pub fn harness_chars_advance_by_small() { - let buf: [u8; ADVANCE_BYTES + UTF8_PAD] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (start, end) = verifier_nondet_window(s); - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(n <= ADVANCE_MAX); - kani::cover(true, "C22-A05: harness_chars_advance_by_small assumption admitted"); - verifier_check_chars_advance(s, start, end, n); + fn harness_chars_next() { + let s = symbolic_text(); + let (a, b) = any_window(s); + if a < b { + // Input facts at the first sequence of this valid boundary window. + // The decoder and its unsafe reads are executed without a stub. + kani::assume(utf8_ok_at(a)); + let width = lead_width(unsafe { byte(a) }); + kani::assume(width > 0 && width <= b - a); + } + let mut chars = window(s, a, b).chars(); + if let Some(ch) = chars.next() { + assert!(char::from_u32(ch as u32).is_some()); + check_range(s, chars.as_str(), a + ch.len_utf8(), b); + kani::cover(ch.len_utf8() == 1, "one-byte scalar"); + kani::cover(ch.len_utf8() == 2, "two-byte scalar"); + kani::cover(ch.len_utf8() == 3, "three-byte scalar"); + kani::cover(ch.len_utf8() == 4, "four-byte scalar"); + } else { + assert!(a == b); + } + cover_completed_text(s); kani::cover( - n == ADVANCE_MAX && start < end, - "advance_by: maximum small count", + a > 4096 && b - a > 4096, + "completed on a large interior window", ); - kani::cover(true, "C22-END: harness_chars_advance_by_small completed"); } - // Exercise the real chunk-skip loop (as well as its trailing-byte and - // character loops) on a symbolic 48-byte UTF-8 string. The 48-byte - // fixed length is a solver-budget limitation, not unbounded proof. #[kani::proof] - // The scalar reference can take 40 steps; the chunk body has 32. - #[kani::unwind(42)] - pub fn harness_chars_advance_by_chunked() { - let buf: [u8; CHUNK_BYTES + UTF8_PAD] = kani::any(); - // CHALLENGE 22 assumption 4: valid UTF-8 input. - kani::assume(verifier_utf8_valid(&buf, CHUNK_BYTES)); - kani::cover(true, "C22-A06: harness_chars_advance_by_chunked assumption admitted"); - // SAFETY: the encoded prefix satisfies the exact UTF-8 predicate. - let s = unsafe { from_utf8_unchecked(&buf[..CHUNK_BYTES]) }; - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(CHUNK_MIN <= n && n <= CHUNK_MAX); - kani::cover(true, "C22-A07: harness_chars_advance_by_chunked assumption admitted"); - verifier_check_chars_advance(s, 0, CHUNK_BYTES, n); + fn harness_chars_next_back() { + let s = symbolic_text(); + let (a, b) = any_window(s); + if a < b { + // A valid nonempty UTF-8 window has one final complete sequence. + // This symbolic width is an input witness, not a decoder result. + let width: usize = kani::any(); + kani::assume(1 <= width && width <= 4 && width <= b - a); + let lead = b - width; + kani::assume(utf8_ok_at(lead) && lead_width(unsafe { byte(lead) }) == width); + } + let mut chars = window(s, a, b).chars(); + if let Some(ch) = chars.next_back() { + assert!(char::from_u32(ch as u32).is_some()); + assert!(ch.len_utf8() <= b - a); + check_range(s, chars.as_str(), a, b - ch.len_utf8()); + kani::cover(ch.len_utf8() == 1, "one-byte scalar"); + kani::cover(ch.len_utf8() == 2, "two-byte scalar"); + kani::cover(ch.len_utf8() == 3, "three-byte scalar"); + kani::cover(ch.len_utf8() == 4, "four-byte scalar"); + } else { + assert!(a == b); + } + cover_completed_text(s); kani::cover( - utf8_is_cont_byte(buf[32]), - "advance_by: crosses UTF-8 chunk boundary", + a > 4096 && b - a > 4096, + "completed on a large interior window", ); - kani::cover(buf[0] < 0x80 && buf[31] < 0x80, "advance_by: ASCII chunk"); + } + + #[kani::proof] + fn harness_chars_as_str() { + let s = symbolic_text(); + let (a, b) = any_window(s); + let chars = window(s, a, b).chars(); + check_range(s, chars.as_str(), a, b); + cover_completed_text(s); kani::cover( - buf[0] >= 0xF0 - && buf[4] >= 0xF0 - && buf[8] >= 0xF0 - && buf[12] >= 0xF0 - && buf[16] >= 0xF0 - && buf[20] >= 0xF0 - && buf[24] >= 0xF0 - && buf[28] >= 0xF0, - "advance_by: chunk with eight four-byte scalars", + a > 4096 && b - a > 4096, + "completed on a large interior window", ); - kani::cover(true, "C22-END: harness_chars_advance_by_chunked completed"); } // Challenge 22 permits assuming pattern.rs (assumption 2). This is an @@ -1934,8 +2148,8 @@ mod verify { // Each call may skip Reject steps and return any boundary-valid Match, // including a zero-width Match. Thus widths may vary between calls. // The common residual interval suffices for directional safety; this - // model deliberately does NOT implement DoubleEndedSearcher. Concrete - // double-ended instances are checked separately below. + // model deliberately does NOT implement DoubleEndedSearcher; consumers are + // checked one operation at a time under the interval protocol. // Projection argument: for a forward-only concrete searcher, front/back // describe the unreported suffix; every real next_match return is admitted // here. The reverse-only argument uses the unreported prefix. Consumers @@ -1947,13 +2161,12 @@ mod verify { haystack: &'a str, front: usize, back: usize, - // Fresh per-operation observers; production iterators cannot inspect - // these fields. any_split resets them when projecting a logical state. - last_match: Option<(usize, usize)>, - previous_match: Option<(usize, usize)>, - calls: usize, } + // Issue #753: into_searcher must preserve the passed haystack by pointer AND + // length. The model and constructor proof uphold that requirement. Pattern is + // still a safe trait in this repository's pinned std, so this is a safe impl; + // change it to unsafe impl only when the upstream trait change is imported. impl Pattern for ModelPattern { type Searcher<'a> = ModelSearcher<'a>; @@ -1962,9 +2175,6 @@ mod verify { haystack, front: 0, back: haystack.len(), - last_match: None, - previous_match: None, - calls: 0, } } } @@ -2023,18 +2233,14 @@ mod verify { fn next_match(&mut self) -> Option<(usize, usize)> { assert!(type_invariant_searcher(self)); - self.previous_match = self.last_match; - // Instrumentation must not introduce overflow on long histories. - self.calls = self.calls.saturating_add(1); - self.last_match = if kani::any() { + if kani::any() { let range = any_match_range(self.haystack, self.front, self.back); self.front = range.1; Some(range) } else { self.front = self.back; None - }; - self.last_match + } } } @@ -2067,39 +2273,14 @@ mod verify { fn next_match_back(&mut self) -> Option<(usize, usize)> { assert!(type_invariant_searcher(self)); - self.previous_match = self.last_match; - // Instrumentation must not introduce overflow on long histories. - self.calls = self.calls.saturating_add(1); - self.last_match = if kani::any() { + if kani::any() { let range = any_match_range(self.haystack, self.front, self.back); self.back = range.0; Some(range) } else { self.back = self.front; None - }; - self.last_match - } - } - - #[derive(Clone, Copy)] - struct SplitState { - start: usize, - end: usize, - front: usize, - back: usize, - trailing: bool, - finished: bool, - } - - fn split_state(iter: &SplitInternal<'_, ModelPattern>) -> SplitState { - SplitState { - start: iter.start, - end: iter.end, - front: iter.matcher.front, - back: iter.matcher.back, - trailing: iter.allow_trailing_empty, - finished: iter.finished, + } } } @@ -2113,7 +2294,7 @@ mod verify { } fn any_split(s: &str) -> SplitInternal<'_, ModelPattern> { - let (start, end) = verifier_nondet_window(s); + let (start, end) = any_window(s); let (front, back) = any_match_range(s, start, end); SplitInternal { start, @@ -2122,440 +2303,209 @@ mod verify { haystack: s, front, back, - last_match: None, - previous_match: None, - calls: 0, }, allow_trailing_empty: kani::any(), finished: kani::any(), } } - fn assert_split_frame(s: &str, iter: &SplitInternal<'_, ModelPattern>) { + fn check_searcher(s: &str, searcher: &ModelSearcher<'_>) { + assert!(type_invariant_searcher(searcher)); + assert!(same_slice(searcher.haystack(), s)); + } + + fn check_split_frame(s: &str, iter: &SplitInternal<'_, ModelPattern>) { assert!(type_invariant_split(iter)); - assert!(verifier_same_slice(iter.matcher.haystack(), s)); - } - - fn assert_valid_split_forward_transition( - s: &str, - old: SplitState, - iter: &SplitInternal<'_, ModelPattern>, - result: Option<&str>, - inclusive: bool, - ) { - assert_split_frame(s, iter); - assert_eq!(iter.end, old.end); - assert_eq!(iter.matcher.back, old.back); - assert_eq!(iter.allow_trailing_empty, old.trailing); - if old.finished { - assert!(result.is_none()); - assert_eq!(iter.start, old.start); - assert_eq!(iter.matcher.calls, 0); - assert_eq!(iter.matcher.front, old.front); - assert!(iter.finished); - return; - } - assert_eq!(iter.matcher.calls, 1); - match iter.matcher.last_match { - Some((a, b)) => { - let part = result.unwrap(); - verifier_assert_str_range(s, part, old.start, if inclusive { b } else { a }); - assert_eq!(iter.start, b); - assert!(!iter.finished); - kani::cover(a == b, "split: zero-width match"); - kani::cover(b - a > 4, "split: multi-character match"); - } - None => { - assert!(iter.finished); - assert_eq!(iter.start, old.start); - if old.trailing || old.start < old.end { - verifier_assert_str_range(s, result.unwrap(), old.start, old.end); - } else { - assert!(result.is_none()); - } - kani::cover(true, "split: exhausted search"); - } + assert!(same_slice(iter.matcher.haystack(), s)); + } + + fn check_piece(s: &str, piece: &str) -> usize { + let start = checked_offset(s, piece); + check_range(s, piece, start, start + piece.len()); + start + } + + // Closure of the safety invariant supports arbitrarily long iterator histories; + // exact matching contents, call counts and character ranks are not required. + fn check_split(s: &str, iter: &SplitInternal<'_, ModelPattern>, result: Option<&str>) { + check_split_frame(s, iter); + if let Some(part) = result { + check_piece(s, part); } + kani::cover(result.is_none(), "split: no remaining piece"); + kani::cover(result.is_some_and(str::is_empty), "split: empty piece"); + kani::cover( + result.is_some_and(|part| part.len() > 4096), + "split: large piece", + ); + cover_completed_text(s); } - fn assert_valid_split_reverse_transition( - s: &str, - old: SplitState, - iter: &SplitInternal<'_, ModelPattern>, - result: Option<&str>, - inclusive: bool, - ) { - assert_split_frame(s, iter); - assert_eq!(iter.start, old.start); - assert_eq!(iter.matcher.front, old.front); - if old.finished { - assert!(result.is_none()); - assert_eq!(iter.end, old.end); - assert_eq!(iter.matcher.back, old.back); - assert_eq!(iter.matcher.calls, 0); - assert_eq!(iter.allow_trailing_empty, old.trailing); - assert!(iter.finished); - return; - } - assert!(iter.allow_trailing_empty); - assert!(iter.matcher.calls >= 1 && iter.matcher.calls <= 2); - if iter.finished { - match result { - Some(part) => { - // A first empty tail may have been suppressed before - // returning the remaining prefix in the second search. - verifier_assert_str_range(s, part, old.start, iter.end); - assert!(iter.end <= old.end); - } - None => assert!(!old.trailing && iter.end == old.start), - } - } else { - let (a, b) = iter.matcher.last_match.unwrap(); - let part = result.unwrap(); - let output_end = if iter.matcher.calls == 2 { - assert!(!old.trailing); - let (first_a, first_b) = iter.matcher.previous_match.unwrap(); - assert_eq!(first_b, old.end); - if inclusive { first_b } else { first_a } - } else { - old.end - }; - verifier_assert_str_range(s, part, b, output_end); - assert_eq!(iter.end, if inclusive { b } else { a }); - kani::cover(a == b, "reverse split: zero-width match"); - kani::cover(b - a > 4, "reverse split: multi-character match"); + fn check_match(s: &str, searcher: &ModelSearcher<'_>, result: Option<(usize, &str)>) { + check_searcher(s, searcher); + if let Some((index, part)) = result { + assert!(index == check_piece(s, part)); } + kani::cover(result.is_none(), "matches: exhausted"); + kani::cover( + result.is_some_and(|(_, part)| part.is_empty()), + "matches: empty match", + ); kani::cover( - iter.matcher.calls == 2, - "reverse split: suppress empty tail then search again", + result.is_some_and(|(_, part)| part.len() > 4096), + "matches: large match", ); - kani::cover(result.is_none(), "reverse split: no remaining part"); + cover_completed_text(s); } #[kani::proof] fn harness_searcher_protocol() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let mut iter = any_split(s); - let old = split_state(&iter); + let s = symbolic_text(); + let (front, back) = any_window(s); + let mut searcher = ModelSearcher { + haystack: s, + front, + back, + }; let reverse: bool = kani::any(); let result = if reverse { - iter.matcher.next_match_back() + searcher.next_match_back() } else { - iter.matcher.next_match() + searcher.next_match() }; - assert!(type_invariant_searcher(&iter.matcher)); - assert!(verifier_same_slice(iter.matcher.haystack(), s)); - match result { - Some((a, b)) => { - assert!(old.front <= a && a <= b && b <= old.back); - assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); - if reverse { - assert_eq!(iter.matcher.back, a); - } else { - assert_eq!(iter.matcher.front, b); - } - kani::cover(a == b, "protocol: zero-width match"); - kani::cover(b - a > 4, "protocol: width larger than one scalar"); + check_searcher(s, &searcher); + if let Some((a, b)) = result { + assert!(front <= a && a <= b && b <= back); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + if reverse { + assert!(searcher.back == a); + } else { + assert!(searcher.front == b); } - None => assert_eq!(iter.matcher.front, iter.matcher.back), + kani::cover(a == b, "protocol: zero-width match"); + kani::cover(b - a > 4, "protocol: multiple-character match"); + } else { + assert!(searcher.front == searcher.back); } if reverse { - assert_eq!(iter.matcher.front, old.front); + assert!(searcher.front == front); } else { - assert_eq!(iter.matcher.back, old.back); + assert!(searcher.back == back); } - kani::cover(true, "C22-END: harness_searcher_protocol completed"); - } - - fn assert_initial_split(s: &str, iter: &SplitInternal<'_, P>, trailing: bool) { - assert_eq!(iter.start, 0); - assert_eq!(iter.end, s.len()); - assert_eq!(iter.allow_trailing_empty, trailing); - assert!(!iter.finished); - assert!(verifier_same_slice(iter.matcher.haystack(), s)); + cover_completed_text(s); } #[kani::proof] fn harness_split_constructors() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let needle: char = kani::any(); - assert_initial_split(s, &s.split(needle).0, true); - assert_initial_split(s, &s.split_terminator(needle).0, false); - assert_initial_split(s, &s.split_inclusive(needle).0, false); - assert!(verifier_char_searcher_invariant(&s.split(needle).0.matcher)); - assert_initial_split(s, &s.split("").0, true); - assert_initial_split(s, &s.split_terminator("").0, false); - assert_initial_split(s, &s.split_inclusive("").0, false); - let chars: [char; 2] = kani::any(); - assert_initial_split(s, &s.split(&chars[..]).0, true); - assert_initial_split(s, &s.split_terminator(chars).0, false); - assert_initial_split(s, &s.split_inclusive(&chars).0, false); - let model = s.split(ModelPattern).0; - assert_initial_split(s, &model, true); - assert!(type_invariant_split(&model)); - let terminator = s.split_terminator(ModelPattern).0; - let inclusive = s.split_inclusive(ModelPattern).0; - assert_initial_split(s, &terminator, false); - assert_initial_split(s, &inclusive, false); - assert!(type_invariant_split(&terminator)); - assert!(type_invariant_split(&inclusive)); - kani::cover(s.is_empty(), "constructors: empty haystack"); - kani::cover(!s.is_empty(), "constructors: nonempty haystack"); - kani::cover(true, "C22-END: harness_split_constructors completed"); + let s = symbolic_text(); + let searcher = ModelPattern.into_searcher(s); + check_searcher(s, &searcher); + check_split_frame(s, &s.split(ModelPattern).0); + check_split_frame(s, &s.split_terminator(ModelPattern).0); + check_split_frame(s, &s.split_inclusive(ModelPattern).0); + cover_completed_text(s); } #[kani::proof] fn harness_split_get_end() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + let s = symbolic_text(); let mut iter = any_split(s); - let old = split_state(&iter); let result = iter.get_end(); - if !old.finished && (old.trailing || old.start < old.end) { - verifier_assert_str_range(s, result.unwrap(), old.start, old.end); - kani::cover(old.start == old.end, "get_end: allowed empty tail"); - kani::cover(old.start < old.end, "get_end: nonempty tail"); - } else { - assert!(result.is_none()); - kani::cover(old.finished, "get_end: already finished"); - kani::cover(!old.finished, "get_end: suppressed empty tail"); - } - assert!(iter.finished); - assert_eq!(iter.start, old.start); - assert_eq!(iter.end, old.end); - assert_eq!(iter.matcher.front, old.front); - assert_eq!(iter.matcher.back, old.back); - assert_eq!(iter.matcher.calls, 0); - assert_split_frame(s, &iter); - kani::cover(true, "C22-END: harness_split_get_end completed"); + check_split(s, &iter, result); } #[kani::proof] fn harness_split_next() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + let s = symbolic_text(); let mut iter = any_split(s); - let old = split_state(&iter); let result = iter.next(); - assert_valid_split_forward_transition(s, old, &iter, result, false); - kani::cover(true, "C22-END: harness_split_next completed"); + check_split(s, &iter, result); } #[kani::proof] fn harness_split_next_inclusive() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + let s = symbolic_text(); let mut iter = any_split(s); - let old = split_state(&iter); let result = iter.next_inclusive(); - assert_valid_split_forward_transition(s, old, &iter, result, true); - kani::cover(true, "C22-END: harness_split_next_inclusive completed"); + check_split(s, &iter, result); } #[kani::proof] fn harness_split_next_back() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + let s = symbolic_text(); let mut iter = any_split(s); - let old = split_state(&iter); let result = iter.next_back(); - assert_valid_split_reverse_transition(s, old, &iter, result, false); - kani::cover(true, "C22-END: harness_split_next_back completed"); + check_split(s, &iter, result); } #[kani::proof] fn harness_split_next_back_inclusive() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + let s = symbolic_text(); let mut iter = any_split(s); - let old = split_state(&iter); let result = iter.next_back_inclusive(); - assert_valid_split_reverse_transition(s, old, &iter, result, true); - kani::cover(true, "C22-END: harness_split_next_back_inclusive completed"); + check_split(s, &iter, result); } #[kani::proof] fn harness_split_remainder() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + let s = symbolic_text(); let iter = any_split(s); - let old = split_state(&iter); - match iter.remainder() { - Some(part) => { - assert!(!old.finished); - verifier_assert_str_range(s, part, old.start, old.end); - } - None => assert!(old.finished), - } - assert_split_frame(s, &iter); - assert_eq!(iter.matcher.calls, 0); - kani::cover(old.finished, "remainder: finished"); - kani::cover( - !old.finished && old.start == old.end, - "remainder: empty active interval", - ); - kani::cover(true, "C22-END: harness_split_remainder completed"); - } - - fn assert_valid_match_transition( - s: &str, - old_front: usize, - old_back: usize, - searcher: &ModelSearcher<'_>, - result: Option<(usize, &str)>, - reverse: bool, - ) { - assert!(type_invariant_searcher(searcher)); - assert!(verifier_same_slice(searcher.haystack(), s)); - assert_eq!(searcher.calls, 1); - match searcher.last_match { - Some((a, b)) => { - let (index, part) = result.unwrap(); - assert_eq!(index, a); - verifier_assert_str_range(s, part, a, b); - assert!(old_front <= a && b <= old_back); - if reverse { - assert_eq!(searcher.back, a); - } else { - assert_eq!(searcher.front, b); - } - kani::cover(a == b, "matches: empty match"); - kani::cover(b - a > 4, "matches: multiple-character match"); - } - None => { - assert!(result.is_none()); - assert_eq!(searcher.front, searcher.back); - } - } - if reverse { - assert_eq!(searcher.front, old_front); - } else { - assert_eq!(searcher.back, old_back); - } - kani::cover(result.is_none(), "matches: exhausted"); + let result = iter.remainder(); + check_split(s, &iter, result); } #[kani::proof] fn harness_match_indices_next() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let searcher = any_split(s).matcher; - let (front, back) = (searcher.front, searcher.back); - let mut iter = MatchIndicesInternal::(searcher); + let s = symbolic_text(); + let mut iter = MatchIndicesInternal::(any_split(s).matcher); let result = iter.next(); - assert_valid_match_transition(s, front, back, &iter.0, result, false); - kani::cover(true, "C22-END: harness_match_indices_next completed"); + check_match(s, &iter.0, result); } #[kani::proof] fn harness_match_indices_next_back() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let searcher = any_split(s).matcher; - let (front, back) = (searcher.front, searcher.back); - let mut iter = MatchIndicesInternal::(searcher); + let s = symbolic_text(); + let mut iter = MatchIndicesInternal::(any_split(s).matcher); let result = iter.next_back(); - assert_valid_match_transition(s, front, back, &iter.0, result, true); - kani::cover(true, "C22-END: harness_match_indices_next_back completed"); + check_match(s, &iter.0, result); } #[kani::proof] fn harness_matches_next() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let searcher = any_split(s).matcher; - let (front, back) = (searcher.front, searcher.back); - let mut iter = MatchesInternal::(searcher); - let result = iter - .next() - .map(|part| (verifier_slice_offset(s, part), part)); - assert_valid_match_transition(s, front, back, &iter.0, result, false); - kani::cover(true, "C22-END: harness_matches_next completed"); + let s = symbolic_text(); + let mut iter = MatchesInternal::(any_split(s).matcher); + let result = iter.next().map(|part| (checked_offset(s, part), part)); + check_match(s, &iter.0, result); } #[kani::proof] fn harness_matches_next_back() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let searcher = any_split(s).matcher; - let (front, back) = (searcher.front, searcher.back); - let mut iter = MatchesInternal::(searcher); - let result = iter - .next_back() - .map(|part| (verifier_slice_offset(s, part), part)); - assert_valid_match_transition(s, front, back, &iter.0, result, true); - kani::cover(true, "C22-END: harness_matches_next_back completed"); - } - - // Prove the stronger relation to the exact pre-call remaining interval. - // For any past prefix_end <= old.start and suffix_start >= old.end, - // these assertions imply the old ownership relation by transitivity. - // No extra assumption on ghost history bounds is needed here. - #[kani::proof] - fn harness_split_history_step() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let mut iter = any_split(s); - let reverse: bool = kani::any(); - let old = split_state(&iter); - let result = if reverse { - iter.next_back() - } else { - iter.next() - }; - if let Some(part) = result { - let a = verifier_slice_offset(s, part); - let b = a + part.len(); - verifier_assert_str_range(s, part, a, b); - assert!(old.start <= a && b <= old.end); - if !iter.finished { - if reverse { - assert!(iter.end <= a); - } else { - assert!(b <= iter.start); - } - } - } - if !iter.finished { - assert!(old.start <= iter.start && iter.end <= old.end); - } else { - assert!(iter.next().is_none()); - assert!(iter.next_back().is_none()); - } - assert_split_frame(s, &iter); - kani::cover( - reverse && !old.finished && result.is_some(), - "history: reverse step", - ); - kani::cover( - !reverse && !old.finished && result.is_some(), - "history: forward step", - ); - kani::cover(true, "C22-END: harness_split_history_step completed"); + let s = symbolic_text(); + let mut iter = MatchesInternal::(any_split(s).matcher); + let result = iter.next_back().map(|part| (checked_offset(s, part), part)); + check_match(s, &iter.0, result); } #[kani::proof] - pub fn harness_split_ascii_whitespace_remainder() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); + fn harness_split_ascii_whitespace_remainder() { + let s = symbolic_text(); let mut iter = s.split_ascii_whitespace(); - assert!( - iter.remainder() - .is_some_and(|part| verifier_same_slice(part, s)) - ); + assert!(iter.remainder().is_some_and(|part| same_slice(part, s))); // Every reachable inner slice is a UTF-8-boundary window. Cutting // at ASCII whitespace cannot cut through a multibyte scalar. - let (start, end) = verifier_nondet_window(s); - iter.inner.iter.iter.v = s[start..end].as_bytes(); + let (start, end) = any_window(s); + iter.inner.iter.iter.v = window(s, start, end).as_bytes(); iter.inner.iter.iter.finished = kani::any(); let finished = iter.inner.iter.iter.finished; match iter.remainder() { Some(part) => { assert!(!finished); - verifier_assert_str_range(s, part, start, end); + check_range(s, part, start, end); + kani::cover( + part.len() > 4096, + "returned a large remainder after range checks", + ); kani::cover(part.is_empty(), "ASCII whitespace remainder: empty window"); kani::cover( !part.is_empty(), @@ -2567,991 +2517,247 @@ mod verify { kani::cover(true, "ASCII whitespace remainder: finished"); } } - kani::cover(true, "C22-END: harness_split_ascii_whitespace_remainder completed"); + cover_completed_text(s); } // Main already contains #[requires(idx < self.0.len())]. The contract // is discharged against the original body, with Kani generating the // precondition rather than the harness assuming the target's safety. #[kani::proof_for_contract(Bytes::__iterator_get_unchecked)] - pub fn harness_bytes_iterator_get_unchecked() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (start, end) = verifier_nondet_window(s); - let window = &s[start..end]; - let mut iter = window.bytes(); + fn harness_bytes_iterator_get_unchecked() { + let s = symbolic_text(); + // Bytes consumes individual bytes, so a reachable cursor may lie + // inside a scalar. No character-boundary premise belongs here. + let (start, end): (usize, usize) = (kani::any(), kani::any()); + kani::assume(start <= end && end <= s.len()); + let window = unsafe { s.as_bytes().get_unchecked(start..end) }; + let mut iter = Bytes(window.iter().copied()); let index: usize = kani::any(); let item = unsafe { iter.__iterator_get_unchecked(index) }; - assert!(item == window.as_bytes()[index]); + assert!(item == window[index]); kani::cover(index > 0, "bytes::get_unchecked: index past first byte"); - kani::cover(true, "C22-END: harness_bytes_iterator_get_unchecked completed"); - } - fn assert_ordered_parts(s: &str, front: Option<&str>, back: Option<&str>) { - if let Some(front) = front { - let a = verifier_slice_offset(s, front); - verifier_assert_str_range(s, front, a, a + front.len()); - } - if let Some(back) = back { - let a = verifier_slice_offset(s, back); - verifier_assert_str_range(s, back, a, a + back.len()); - } - if let (Some(front), Some(back)) = (front, back) { - let a = verifier_slice_offset(s, front); - let b = verifier_slice_offset(s, back); - assert!(a + front.len() <= b, "opposite-end outputs do not overlap"); - } - } - - fn assert_public_split_pair<'a, P>(s: &'a str, pattern: P) - where - P: Pattern: DoubleEndedSearcher<'a>>, - { - let inclusive: bool = kani::any(); - let trailing: bool = kani::any(); - let mut iter = if inclusive { - s.split_inclusive(pattern).0 - } else if trailing { - s.split(pattern).0 - } else { - s.split_terminator(pattern).0 - }; - let front_first: bool = kani::any(); - let (front, back) = if front_first { - let front = if inclusive { - iter.next_inclusive() - } else { - iter.next() - }; - let back = if inclusive { - iter.next_back_inclusive() - } else { - iter.next_back() - }; - (front, back) - } else { - let back = if inclusive { - iter.next_back_inclusive() - } else { - iter.next_back() - }; - let front = if inclusive { - iter.next_inclusive() - } else { - iter.next() - }; - (front, back) - }; - assert_ordered_parts(s, front, back); - if let Some(rest) = iter.remainder() { - let a = verifier_slice_offset(s, rest); - verifier_assert_str_range(s, rest, a, iter.end); - if let Some(front) = front { - assert!(verifier_slice_offset(s, front) + front.len() <= a); - } - if let Some(back) = back { - assert!(iter.end <= verifier_slice_offset(s, back)); - } - } else { - assert!(iter.finished); - assert!(iter.next().is_none()); - assert!(iter.next_back().is_none()); - } - kani::cover( - front_first && front.is_some() && back.is_some(), - "mixed: front then back", - ); - kani::cover( - !front_first && front.is_some() && back.is_some(), - "mixed: back then front", - ); - kani::cover( - inclusive && front.is_some() && back.is_some(), - "mixed: inclusive parts", - ); - kani::cover( - !inclusive && !trailing && front.is_some(), - "mixed: terminator parts", - ); - } - - #[kani::proof] - #[kani::stub( as Searcher<'_>>::next_match, verifier_stub_char_next_match)] - #[kani::stub( as ReverseSearcher<'_>>::next_match_back, verifier_stub_char_next_match_back)] - fn harness_split_mixed_directions() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - assert_public_split_pair(s, kani::any::()); - kani::cover(true, "C22-END: harness_split_mixed_directions completed"); - } - - #[kani::proof] - #[kani::stub( as Searcher<'_>>::next_match, verifier_stub_char_slice_next_match)] - #[kani::stub( as ReverseSearcher<'_>>::next_match_back, verifier_stub_char_slice_next_match_back)] - fn harness_split_char_slice_mixed() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let chars: [char; 2] = kani::any(); - let len: usize = kani::any(); - // INPUT DOMAIN: allocated prefix or index extent. - kani::assume(len <= chars.len()); - kani::cover(true, "C22-A10: harness_split_char_slice_mixed assumption admitted"); - assert_public_split_pair(s, &chars[..len]); - kani::cover(len == 0, "character set: empty"); - kani::cover( - len == 2 && chars[0].len_utf8() != chars[1].len_utf8(), - "character set: different widths", - ); - kani::cover(true, "C22-END: harness_split_char_slice_mixed completed"); - } - - // Concrete &str instances deliberately keep the two directions separate. - // They are integration checks under assumption 2, not a proof that all - // Pattern implementations refine the abstract protocol above. - fn assert_str_pattern_direction(s: &str, needle: &str, reverse: bool) { - let inclusive: bool = kani::any(); - let mut iter = if inclusive { - s.split_inclusive(needle).0 - } else { - s.split_terminator(needle).0 - }; - let first = if reverse { - if inclusive { - iter.next_back_inclusive() - } else { - iter.next_back() - } - } else if inclusive { - iter.next_inclusive() - } else { - iter.next() - }; - let second = if reverse { - if inclusive { - iter.next_back_inclusive() - } else { - iter.next_back() - } - } else if inclusive { - iter.next_inclusive() - } else { - iter.next() - }; - if reverse { - assert_ordered_parts(s, second, first); - } else { - assert_ordered_parts(s, first, second); - } - if let Some(rest) = iter.remainder() { - verifier_assert_str_range(s, rest, iter.start, iter.end); - } else { - assert!(iter.finished); - let terminal = if reverse { - if inclusive { - iter.next_back_inclusive() - } else { - iter.next_back() - } - } else if inclusive { - iter.next_inclusive() - } else { - iter.next() - }; - assert!(terminal.is_none()); - } - let mut indices = if reverse { - s.rmatch_indices(needle).0 - } else { - s.match_indices(needle).0 - }; - let matched = if reverse { - indices.next_back() - } else { - indices.next() - }; - if let Some((a, part)) = matched { - verifier_assert_str_range(s, part, a, a + needle.len()); - } - // A fresh instance also exercises the MatchesInternal wrapper. - let mut matches = MatchesInternal::<&str>(needle.into_searcher(s)); - if let Some(part) = if reverse { - matches.next_back() - } else { - matches.next() - } { - let a = verifier_slice_offset(s, part); - verifier_assert_str_range(s, part, a, a + needle.len()); - } - kani::cover( - first.is_some() && second.is_some(), - "str pattern: two split parts", - ); - } - - #[kani::proof] - #[kani::unwind(5)] - fn harness_str_empty_forward() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - assert_str_pattern_direction(s, "", false); - kani::cover(s.is_empty(), "empty needle: empty haystack"); - kani::cover(true, "C22-END: harness_str_empty_forward completed"); - } - - #[kani::proof] - #[kani::unwind(5)] - fn harness_str_empty_reverse() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - assert_str_pattern_direction(s, "", true); - kani::cover(s.is_empty(), "empty needle reverse: empty haystack"); - kani::cover(true, "C22-END: harness_str_empty_reverse completed"); - } - - fn any_short_needle(buf: &mut [u8; 8]) -> &str { - let first: char = kani::any(); - let mut len = first.encode_utf8(buf).len(); - if kani::any() { - let second: char = kani::any(); - len += second.encode_utf8(&mut buf[len..]).len(); - } - // SAFETY: concatenation of one or two scalar UTF-8 encodings. - unsafe { from_utf8_unchecked(&buf[..len]) } - } - - #[kani::proof] - #[kani::unwind(20)] - #[kani::stub( as Searcher<'_>>::next_match, verifier_stub_str_nonempty_next_match)] - fn harness_str_nonempty_forward() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let mut needle_buf = [0u8; 8]; - let needle = any_short_needle(&mut needle_buf); - assert_str_pattern_direction(s, needle, false); - kani::cover(needle.len() == 1, "str pattern: byte searcher"); - kani::cover(needle.len() > 4, "str pattern: two multibyte scalars"); - kani::cover(true, "C22-END: harness_str_nonempty_forward completed"); - } - - #[kani::proof] - #[kani::unwind(20)] - #[kani::stub( as ReverseSearcher<'_>>::next_match_back, verifier_stub_str_nonempty_next_match_back)] - fn harness_str_nonempty_reverse() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let mut needle_buf = [0u8; 8]; - let needle = any_short_needle(&mut needle_buf); - assert_str_pattern_direction(s, needle, true); - kani::cover(needle.len() == 1, "str pattern reverse: byte searcher"); - kani::cover( - needle.len() > 4, - "str pattern reverse: two multibyte scalars", - ); - kani::cover(true, "C22-END: harness_str_nonempty_reverse completed"); - } - - // Independent streaming decoder for checking the local input predicate. - // Its state is the expected continuation count and permitted next byte; - // unlike the local predicate it does not inspect overlapping windows. - fn reference_utf8_valid(bytes: &[u8]) -> bool { - let mut pending = 0usize; - let mut low = 0x80; - let mut high = 0xBF; - // Index traversal keeps this reference independent of slice iterator - // pointer models. No encoding constraint is assumed in this loop. - let mut index = 0usize; - while index < bytes.len() { - let byte = bytes[index]; - index += 1; - if pending > 0 { - if byte < low || byte > high { - return false; - } - pending -= 1; - low = 0x80; - high = 0xBF; - } else { - match byte { - 0..=0x7F => {} - 0xC2..=0xDF => pending = 1, - 0xE0 => { - pending = 2; - low = 0xA0; - } - 0xE1..=0xEC | 0xEE..=0xEF => pending = 2, - 0xED => { - pending = 2; - high = 0x9F; - } - 0xF0 => { - pending = 3; - low = 0x90; - } - 0xF1..=0xF3 => pending = 3, - 0xF4 => { - pending = 3; - high = 0x8F; - } - _ => return false, - } - } - } - pending == 0 - } - - // No UTF-8 validity filter: raw bytes include all invalid encodings. - // This checks both soundness and completeness of the local predicate - // against an independent streaming decoder throughout the largest - // allocation used by these proofs. It is not an arbitrary-N theorem. - #[kani::proof] - #[kani::unwind(257)] - fn harness_utf8_input_model() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let len: usize = kani::any(); - // INPUT-LENGTH: selecting a prefix within this allocation, not - // assuming any encoding property or expected comparison result. - // INPUT DOMAIN: allocated prefix or index extent. - kani::assume(len <= MAX_BYTES); - kani::cover(true, "C22-A11: harness_utf8_input_model assumption admitted"); - let local = verifier_utf8_valid(&buf, len); - let reference = reference_utf8_valid(&buf[..len]); - assert_eq!(local, reference); - kani::cover(local && len == MAX_BYTES, "UTF-8 model: full valid input"); - kani::cover( - !local && len == MAX_BYTES, - "UTF-8 model: rejects invalid input", - ); - kani::cover(local && len == 0, "UTF-8 model: empty input"); - kani::cover( - !local && len == 1 && buf[0] == 0xF0, - "UTF-8 model: truncated scalar", - ); - kani::cover( - local && len == 4 && buf[0] == 0xF4, - "UTF-8 model: largest scalar block", - ); - kani::cover(true, "C22-END: harness_utf8_input_model completed"); - } - - // Local safety lemmas for advance_by. These establish the obligations - // of one loop step only; the production loops are not contracted or - // replaced, so these are NOT an unbounded proof of advance_by. - #[kani::proof] - #[kani::unwind(33)] - fn harness_advance_chunk_step() { - let chunk: [u8; 32] = kani::any(); - let total_len: usize = kani::any(); - let skipped: usize = kani::any(); - let remainder: usize = kani::any(); - // LOCAL LEMMA: input precondition, not a proved production invariant. - kani::assume(skipped <= total_len && 32 <= total_len - skipped); - kani::cover(true, "C22-A12: harness_advance_chunk_step assumption admitted"); - // LOCAL LEMMA: input precondition, not a proved production invariant. - kani::assume(remainder > 32); - kani::cover(true, "C22-A13: harness_advance_chunk_step assumption admitted"); - let mut starts = [false; 32]; - for i in 0..32 { - starts[i] = !utf8_is_cont_byte(chunk[i]); - } - let count = starts.into_iter().map(|x| x as u8).sum::() as usize; - assert!(count <= 32); - assert!(count < remainder); - assert!(skipped + 32 <= total_len); - assert!(remainder - count > 0); - kani::cover(count == 32, "chunk step: all start bytes"); - kani::cover( - count == 0, - "chunk step: conservative invalid-byte over-approximation", - ); - kani::cover(true, "C22-END: harness_advance_chunk_step completed"); - } - - #[kani::proof] - fn harness_advance_character_step() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (start, end) = verifier_nondet_window(s); - // LOCAL LEMMA: input precondition, not a proved production invariant. - kani::assume(start < end); - kani::cover(true, "C22-A14: harness_advance_character_step assumption admitted"); - let width = utf8_char_width(s.as_bytes()[start]); - assert!(1 <= width && width <= 4); - assert!(width <= end - start); - assert!(s.is_char_boundary(start + width)); - let mut bytes = s.as_bytes()[start..end].iter(); - assert!(bytes.advance_by(width).is_ok()); - assert_eq!(bytes.len(), end - start - width); - kani::cover(width == 4, "character step: four-byte scalar"); - kani::cover(true, "C22-END: harness_advance_character_step completed"); - } - - #[kani::proof] - #[kani::unwind(4)] - fn harness_advance_boundary_restore() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let pos: usize = kani::any(); - // INPUT DOMAIN: allocated prefix or index extent. - kani::assume(pos <= s.len()); - kani::cover(true, "C22-A15: harness_advance_boundary_restore assumption admitted"); - let mut iter = s.as_bytes()[pos..].iter(); - let mut skipped = 0usize; - while let Some(&byte) = iter.as_slice().first() { - if !utf8_is_cont_byte(byte) { - break; - } - assert!(iter.advance_by(1).is_ok()); - skipped += 1; - } - assert!(skipped <= 3); - assert!(s.is_char_boundary(pos + skipped)); - kani::cover(skipped == 3, "boundary restore: three continuation bytes"); - kani::cover(skipped == 0, "boundary restore: already aligned"); - kani::cover(true, "C22-END: harness_advance_boundary_restore completed"); - } - // Count-gap regression on a fixed chunk or an empty string. A symbolic - // window made CBMC duplicate the unreachable chunk loop and exceeded the - // 480-second budget. This does not cover every length/window for n=9..32. - #[kani::proof] - #[kani::unwind(34)] - fn harness_chars_advance_by_medium() { - const BYTES: usize = 32; - let buf: [u8; BYTES + UTF8_PAD] = kani::any(); - // CHALLENGE 22 assumption 4: valid UTF-8 input. - kani::assume(verifier_utf8_valid(&buf, BYTES)); - kani::cover(true, "C22-A16: harness_chars_advance_by_medium assumption admitted"); - // SAFETY: the local predicate establishes this fixed prefix's UTF-8. - let s = unsafe { from_utf8_unchecked(&buf[..BYTES]) }; - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(9 <= n && n <= 32); - kani::cover(true, "C22-A17: harness_chars_advance_by_medium assumption admitted"); - let empty: bool = kani::any(); - if empty { - verifier_check_chars_advance("", 0, 0, n); - } else { - verifier_check_chars_advance(s, 0, BYTES, n); - } - kani::cover(n == 32 && !empty, "advance_by: threshold count"); - kani::cover(empty, "advance_by: large count on empty input"); - kani::cover(true, "C22-END: harness_chars_advance_by_medium completed"); - } - - // Exhaust two full chunks for any request larger than their byte count, - // including usize::MAX. Only the allocation length is fixed here. The - // reference counts UTF-8 leading bytes, independently of chunk grouping; - // there is no character-decoding reference loop proportional to n. - // Requests 41..=64 have a separate fixed-size rank-reference proof below. - // Arbitrary allocation lengths are not covered here. - #[kani::proof] - #[kani::unwind(66)] - fn harness_chars_advance_by_multichunk() { - const BYTES: usize = 64; - let buf: [u8; BYTES + UTF8_PAD] = kani::any(); - // CHALLENGE 22 assumption 4: valid UTF-8 input. - kani::assume(verifier_utf8_valid(&buf, BYTES)); - kani::cover(true, "C22-A18: harness_chars_advance_by_multichunk assumption admitted"); - // SAFETY: the local predicate establishes this fixed prefix's UTF-8. - let s = unsafe { from_utf8_unchecked(&buf[..BYTES]) }; - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(n > BYTES); - kani::cover(true, "C22-A19: harness_chars_advance_by_multichunk assumption admitted"); - let mut iter = s.chars(); - let result = iter.advance_by(n); - verifier_assert_str_range(s, iter.as_str(), BYTES, BYTES); - let mut chars = 0usize; - for i in 0..BYTES { - chars += (!utf8_is_cont_byte(buf[i])) as usize; - } - assert!(16 <= chars && chars <= BYTES); - let remaining = result.unwrap_err().get(); - assert_eq!(remaining, n - chars); - kani::cover(n == usize::MAX, "advance_by: maximum request"); - kani::cover(chars == 64, "advance_by: two ASCII chunks"); - kani::cover(chars == 16, "advance_by: two chunks of four-byte scalars"); - kani::cover( - utf8_is_cont_byte(buf[32]), - "advance_by: second chunk starts inside a scalar", - ); - kani::cover(true, "C22-END: harness_chars_advance_by_multichunk completed"); - } - - // A byte-rank oracle, independent of advance_by's chunk grouping and - // continuation-restoration loop. On valid UTF-8, leading-byte rank is - // scalar rank. Locate the first boundary whose rank equals the request; - // if there is none, the expected residual string is empty. This oracle - // has a fixed allocation bound, even when n ranges over all usize values. - fn assert_advance_by_rank(buf: &[u8; N], n: usize) -> (usize, usize, usize) { - let len = N - UTF8_PAD; - // CHALLENGE 22 assumption 4: valid UTF-8 input. - kani::assume(verifier_utf8_valid(buf, len)); - kani::cover(true, "C22-A20: assert_advance_by_rank assumption admitted"); - // SAFETY: the exact local predicate constrains the whole prefix. - let s = unsafe { from_utf8_unchecked(&buf[..len]) }; - let mut rank = 0usize; - let mut expected = len; - let mut first_chunk = 0usize; - let mut first_two_chunks = 0usize; - // Six verification blocks of 16 suffice for the largest input. - // This visits every byte once; it does not summarize counts per - // production chunk. A short inner loop allows a common unwind of - // 34, instead of expanding the target's scalar tail 98 times. - for block in 0..len.div_ceil(16) { - for offset in 0..16 { - let i = block * 16 + offset; - if i >= len { - break; - } - if i == 32 { - first_chunk = rank; - } - if i == 64 { - first_two_chunks = rank; - } - if !utf8_is_cont_byte(buf[i]) { - if rank == n { - expected = i; - } - rank += 1; - } - } - } - let mut iter = s.chars(); - let result = iter.advance_by(n); // real production body, no stubs - verifier_assert_str_range(s, iter.as_str(), expected, len); - if n <= rank { - assert!(result.is_ok()); - } else { - assert_eq!(result.unwrap_err().get(), n - rank); - } - kani::cover(result.is_ok(), "rank oracle: successful skip"); - kani::cover(result.is_err(), "rank oracle: exact missing scalar count"); - (expected, first_chunk, first_two_chunks) - } - - // Fill the request-count gap with an arbitrary valid 64-byte prefix. - // Both success and shortage are checked, rather than constraining the - // needle/request by an assumed postcondition on the production iterator. - #[kani::proof] - #[kani::unwind(34)] - fn harness_chars_advance_by_count_gap() { - let buf: [u8; 64 + UTF8_PAD] = kani::any(); - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(41 <= n && n <= 64); - kani::cover(true, "C22-A21: harness_chars_advance_by_count_gap assumption admitted"); - let (end, _, _) = assert_advance_by_rank(&buf, n); - kani::cover(n == 41 && end < 64, "count gap: lower request retains tail"); - kani::cover(n == 64, "count gap: upper request"); - kani::cover( - utf8_is_cont_byte(buf[32]), - "count gap: restore chunk boundary", - ); - kani::cover(true, "C22-END: harness_chars_advance_by_count_gap completed"); - } - - // n > 64 forces at least two 32-byte scans: a chunk contains at most - // 32 leading bytes. Unlike the exhaustion regression, this input also - // permits a successful skip with a nonempty residual string. The rank - // covers establish that the chunk loop exits after exactly two scans, - // then restores a boundary and consumes a positive scalar remainder. - #[kani::proof] - // The real tail has at most 32 bytes after two scans. Keep unwinding - // assertions enabled to check this bound as well as the reference loops. - #[kani::unwind(34)] - fn harness_chars_advance_by_multichunk_tail() { - let buf: [u8; 96 + UTF8_PAD] = kani::any(); - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(65 <= n && n <= 96); - kani::cover(true, "C22-A22: harness_chars_advance_by_multichunk_tail assumption admitted"); - let (end, first, first_two) = assert_advance_by_rank(&buf, n); - let two_scans = n - first > 32 && n - first_two <= 32; - kani::cover(two_scans && end < 96, "multi chunk: two scans retain tail"); - kani::cover( - two_scans && end < 96 && utf8_is_cont_byte(buf[64]), - "multi chunk: restore boundary then retain tail", - ); - kani::cover( - n - first_two > 32 && end == 96, - "multi chunk: third scan exhausts input", - ); - kani::cover(n == 96, "multi chunk: upper request"); - kani::cover(true, "C22-END: harness_chars_advance_by_multichunk_tail completed"); - } - - // Check the state generator separately. This asserts consequences of - // its input bounds; no invariant or post-target property is assumed. - #[kani::proof] - fn harness_split_state_generator() { - let buf: [u8; BUFFER_BYTES] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let iter = any_split(s); - assert!(type_invariant_split(&iter)); - assert!(verifier_same_slice(s, iter.matcher.haystack())); - assert_eq!(iter.matcher.calls, 0); - assert!(iter.matcher.last_match.is_none()); - assert!(iter.matcher.previous_match.is_none()); - kani::cover( - iter.finished && iter.start < iter.end, - "state generator: finished nonempty interval", - ); + kani::cover(!s.is_char_boundary(start), "byte cursor inside a scalar"); + // idx < len excludes empty byte windows; cover the admissible domain. kani::cover( - !iter.finished && iter.start == iter.end, - "state generator: active empty interval", + end - start > 4096 && index > 4096, + "completed contract on a large byte window and index", ); - kani::cover(true, "C22-END: harness_split_state_generator completed"); - } - - // Challenge assumption 1 supplies the functional correctness of slice - // byte search. This deterministic model implements its exact last-match - // definition, not a nondeterministic return-range assumption. In particular - // None is returned only after every byte has been checked. - fn verifier_last_byte(needle: u8, bytes: &[u8]) -> Option { - let mut index = bytes.len(); - while index > 0 { - index -= 1; - if bytes[index] == needle { - return Some(index); - } - } - None } - // Check the leaf model against the complete last-index specification on - // arbitrary raw prefixes, including non-UTF-8 data and the empty slice. - #[kani::proof] - #[kani::unwind(20)] - fn harness_reverse_byte_model() { - let bytes: [u8; 16] = kani::any(); - let len: usize = kani::any(); - // INPUT-LENGTH: only prefixes of this initialized array are inputs. - // INPUT DOMAIN: allocated prefix or index extent. - kani::assume(len <= bytes.len()); - kani::cover(true, "C22-A23: harness_reverse_byte_model assumption admitted"); - let needle: u8 = kani::any(); - let result = verifier_last_byte(needle, &bytes[..len]); - if let Some(index) = result { - assert!(index < len); - assert_eq!(bytes[index], needle); - } - for index in 0..len { - if result.is_none_or(|last| last < index) { - assert_ne!(bytes[index], needle); - } - } - kani::cover(result.is_some(), "byte model: matching byte"); - kani::cover(result.is_none(), "byte model: no match"); - kani::cover( - len > 0 && result == Some(len - 1), - "byte model: final byte matches", - ); - kani::cover(len == 0 && result.is_none(), "byte model: empty prefix"); - kani::cover(true, "C22-END: harness_reverse_byte_model completed"); - } - - // Bounded inclusion evidence for the hand-written char adapters. Keep - // the directions separate to avoid combining both search circuits; their - // union covers the original arbitrary-direction input domain. - fn assert_char_searcher_direction(reverse: bool) { - let buf: [u8; 16 + UTF8_PAD] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (front, back) = verifier_nondet_window(s); - let needle: char = kani::any(); - let result = verifier_assert_real_char_searcher(s, needle, front, back, reverse); - kani::cover(result.is_some(), "real char search: matching scalar"); - kani::cover(result.is_none(), "real char search: exhausted window"); - kani::cover( - result.is_some() && needle.len_utf8() == 4, - "real char search: four-byte match", - ); - kani::cover( - front == back && result.is_none(), - "real char search: empty window", - ); - } - - // The byte window has at most 16 bytes. Every failed candidate consumes - // a byte, so 18 includes the final exhaustion call and loop-exit check. - #[kani::proof] - #[kani::unwind(18)] - fn harness_char_searcher_forward_refinement() { - assert_char_searcher_direction(false); - kani::cover(true, "C22-END: harness_char_searcher_forward_refinement completed"); - } - - // Neither CharSearcher method is stubbed. Only the reverse slice byte - // leaf uses the exact deterministic model under challenge assumption 1. - #[kani::proof] - #[kani::unwind(18)] - #[kani::stub(crate::slice::memchr::memrchr, verifier_last_byte)] - fn harness_char_searcher_reverse_refinement() { - assert_char_searcher_direction(true); - kani::cover(true, "C22-END: harness_char_searcher_reverse_refinement completed"); - } - - // Independent rank check for any caller-supplied UTF-8 window. The - // caller's allocation bound is asserted, not silently assumed here. - // A u16 counter covers all 256 bytes without truncating character counts. - // No search, advance, or result property is assumed in this reference. - fn assert_advance_by_window_rank( - s: &str, - start: usize, - end: usize, - n: usize, - ) -> (usize, usize) { - assert!(s.len() <= MAX_BYTES); - assert!(start <= end && end <= s.len()); - assert!(s.is_char_boundary(start) && s.is_char_boundary(end)); - let mut iter = s[start..end].chars(); - let result = iter.advance_by(n); // real target, no stubs - let remaining = iter.as_str(); - let position = verifier_slice_offset(s, remaining); - assert!(start <= position && position <= end); - verifier_assert_str_range(s, remaining, position, end); - - // Independently rank the returned boundary. Every UTF-8 boundary - // has a unique scalar rank, so this characterizes the exact suffix - // without selecting an expected pointer once for every input byte. - let mut total = 0u16; - let mut consumed = 0u16; - let len = end - start; - for block in 0..len.div_ceil(16) { - for offset in 0..16 { - let local = block * 16 + offset; - if local >= len { - break; - } - let index = start + local; - if !utf8_is_cont_byte(s.as_bytes()[index]) { - total += 1; - if index < position { - consumed += 1; - } + // Component/refinement checks do not discharge any required target. The + // fixed unwinds here concern 32 flags or the optional real-searcher inputs, + // never the symbolic string length of a required iterator harness. + mod auxiliary { + //! Dependency models and fixed-size component proofs. Only the + //! real-searcher regressions below have a bounded string input. + + use super::super::super::pattern::verify::verifier_assert_real_char_searcher; + use super::*; + + fn sum_flags(flags: [bool; 32]) -> u8 { + flags.into_iter().map(|flag| flag as u8).sum::() + } + + #[kani::proof] + fn check_slice_models() { + let bytes = symbolic_text().as_bytes(); + let (a, b): (usize, usize) = (kani::any(), kani::any()); + kani::assume(a <= b && b <= bytes.len()); + let part = &bytes[a..b]; + let mut real = part.iter(); + let mut model = part.iter(); + assert!(advance_len(&model) == real.len()); + let modeled = advance_as_slice_plain(&model); + assert!(modeled.as_ptr() == real.as_slice().as_ptr() && modeled.len() == real.len()); + let n = kani::any(); + assert!(advance_bytes(&mut model, n) == real.advance_by(n)); + assert!(model.kani_raw_parts() == real.kani_raw_parts()); + let chunks = part.as_chunks::<32>().0; + let (mut real, mut model) = (chunks.iter(), chunks.iter()); + assert!( + advance_next(&mut model).map(|x| x as *const [u8; 32]) + == real.next().map(|x| x as *const [u8; 32]) + ); + assert!(model.kani_raw_parts() == real.kani_raw_parts()); + kani::cover( + part.len() > 4096 && n > 32, + "large symbolic window and request", + ); + kani::cover(part.is_empty(), "empty slice models completed"); + } + + #[kani::proof] + #[kani::unwind(33)] + fn check_sum_32_real() { + let flags: [bool; 32] = kani::any(); + let words: [u128; 2] = unsafe { mem::transmute(flags) }; + let result = sum_flags(flags); + assert!(result as u32 == words[0].count_ones() + words[1].count_ones()); + kani::cover(result == 32, "all flags consumed after sum assertion"); + } + + #[kani::proof] + #[kani::stub( + crate::array::iter::iter_inner::PolymorphicIter::fold, + crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 + )] + fn check_sum_32_model() { + let flags: [bool; 32] = kani::any(); + let words: [u128; 2] = unsafe { mem::transmute(flags) }; + let result = sum_flags(flags); + assert!(result as u32 == words[0].count_ones() + words[1].count_ones()); + kani::cover(result == 32, "all flags consumed after sum assertion"); + } + + const UTF8_PAD: usize = 4; + + fn verifier_utf8_valid(buf: &[u8; N], len: usize) -> bool { + let p = buf.as_ptr(); + let sequences = crate::forall!(|i in (0, N - UTF8_PAD)| unsafe { + let i: usize = i; + let x0 = *p.wrapping_add(i); + let x1 = *p.wrapping_add(i.wrapping_add(1)); + let x2 = *p.wrapping_add(i.wrapping_add(2)); + let x3 = *p.wrapping_add(i.wrapping_add(3)); + let continuation0 = (x0 as i8) < -64; + let continuation1 = (x1 as i8) < -64; + let continuation2 = (x2 as i8) < -64; + let continuation3 = (x3 as i8) < -64; + let width = (x0 < 0x80) as usize + + (((x0 >= 0xC2) & (x0 < 0xE0)) as usize) * 2 + + (((x0 >= 0xE0) & (x0 < 0xF0)) as usize) * 3 + + (((x0 >= 0xF0) & (x0 < 0xF5)) as usize) * 4; + let next_is_continuation = + (*p.wrapping_add(i.wrapping_add(width)) as i8) < -64; + let second_byte_ok = ((x0 != 0xE0) | (x1 >= 0xA0)) + & ((x0 != 0xED) | (x1 < 0xA0)) + & ((x0 != 0xF0) | (x1 >= 0x90)) + & ((x0 != 0xF4) | (x1 < 0x90)); + (i >= len) + | continuation0 + | ((width > 0) + & (i.wrapping_add(width) <= len) + & ((width < 2) | (continuation1 & second_byte_ok)) + & ((width < 3) | continuation2) + & ((width < 4) | continuation3) + & ((i.wrapping_add(width) == len) | !next_is_continuation)) + }); + let covered = crate::forall!(|i in (0, N - UTF8_PAD)| unsafe { + let i: usize = i; + (i >= len) + | ((*p.wrapping_add(i) as i8) >= -64) + | ((i >= 1) & ((*p.wrapping_add(i.saturating_sub(1)) as i8) >= -64)) + | ((i >= 2) & ((*p.wrapping_add(i.saturating_sub(2)) as i8) >= -64)) + | ((i >= 3) & ((*p.wrapping_add(i.saturating_sub(3)) as i8) >= -64)) + }); + sequences && covered + } + + fn verifier_nondet_utf8(buf: &[u8; N]) -> &str { + let len: usize = kani::any(); + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(len <= N - UTF8_PAD); + kani::cover(true, "C22-A01: verifier_nondet_utf8 assumption admitted"); + // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::assume(verifier_utf8_valid(buf, len)); + kani::cover(true, "C22-A02: verifier_nondet_utf8 assumption admitted"); + // SAFETY: verifier_utf8_valid characterizes valid UTF-8 exactly. + unsafe { from_utf8_unchecked(&buf[..len]) } + } + + fn verifier_nondet_window(s: &str) -> (usize, usize) { + let start: usize = kani::any(); + let end: usize = kani::any(); + // INPUT STATE: an ordered UTF-8 boundary window. + kani::assume(start <= end && end <= s.len()); + kani::cover(true, "C22-A03: verifier_nondet_window assumption admitted"); + // INPUT STATE: an ordered UTF-8 boundary window. + kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); + kani::cover(true, "C22-A04: verifier_nondet_window assumption admitted"); + (start, end) + } + + fn verifier_last_byte(needle: u8, bytes: &[u8]) -> Option { + let mut index = bytes.len(); + while index > 0 { + index -= 1; + if bytes[index] == needle { + return Some(index); } } - } - let count = usize::from(total); - assert!(count <= len); - assert_eq!(usize::from(consumed), n.min(count)); - if n <= count { - assert!(result.is_ok()); - } else { - assert_eq!(result.unwrap_err().get(), n - count); - } - (position, count) - } - - // Full usize request domain, including zero and usize::MAX. Only the - // initialized backing object and valid UTF-8 origin bound the input. - // After chunk scanning the real scalar tail needs at most 32 iterations; - // the reference's 16-byte blocks do not force a byte-length global bound. - #[kani::proof] - #[kani::unwind(34)] - fn harness_chars_advance_by_all_counts() { - const BYTES: usize = 40; - let buf: [u8; BYTES + UTF8_PAD] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let n: usize = kani::any(); - let (position, _) = assert_advance_by_window_rank(s, 0, s.len(), n); - kani::cover(n == 0 && !s.is_empty(), "all counts: zero request"); - kani::cover( - n == 32 && position < s.len(), - "all counts: threshold retains tail", - ); - kani::cover( - n == 33 && s.len() >= 36 - && !s.is_char_boundary(32) - && !s.is_char_boundary(33) - && !s.is_char_boundary(34) - && position < s.len(), - "all counts: three continuation bytes then scalar tail", - ); - kani::cover( - n == usize::MAX && s.len() == BYTES, - "all counts: maximum usize nonempty input", - ); - kani::cover( - s.len() == BYTES && n == BYTES + 1 && position == s.len(), - "all counts: byte capacity plus one shortage", - ); - kani::cover(true, "C22-END: harness_chars_advance_by_all_counts completed"); - } - - // A distinct large-allocation domain: every 256-byte UTF-8 string and - // every request above 256. This explicit request range is not a - // postcondition assumption or a claim about requests 0..=256. - #[kani::proof] - #[kani::unwind(34)] - fn harness_chars_advance_by_eight_chunks() { - const BYTES: usize = 256; - let buf: [u8; BYTES + UTF8_PAD] = kani::any(); - // CHALLENGE 22 assumption 4: valid UTF-8 input. - kani::assume(verifier_utf8_valid(&buf, BYTES)); - kani::cover(true, "C22-A24: harness_chars_advance_by_eight_chunks assumption admitted"); - // SAFETY: the input predicate specifies a valid UTF-8 origin. - let s = unsafe { from_utf8_unchecked(&buf[..BYTES]) }; - let n: usize = kani::any(); - // INPUT DOMAIN: this bounded request partition only. - kani::assume(n > BYTES); - kani::cover(true, "C22-A25: harness_chars_advance_by_eight_chunks assumption admitted"); - // Independent 16-byte counting blocks keep the reference's adder - // chains smaller than a 256-step sum. The real target scans 32-byte - // chunks. Every local upper bound below is checked, never assumed. - let mut rank = 0u16; - for block in 0..BYTES / 16 { - let mut in_block = 0u8; - for offset in 0..16 { - let index = block * 16 + offset; - in_block += u8::from(!utf8_is_cont_byte(s.as_bytes()[index])); - assert!(usize::from(in_block) <= offset + 1); - } - rank += u16::from(in_block); - assert!(usize::from(rank) <= (block + 1) * 16); - } - let count = usize::from(rank); - let mut iter = s.chars(); - let result = iter.advance_by(n); // real target, no stubs - verifier_assert_str_range(s, iter.as_str(), BYTES, BYTES); - assert!(result.is_err()); - assert_eq!(result.unwrap_err().get(), n - count); - kani::cover(n == BYTES + 1, "eight chunks: minimum request"); - kani::cover(n == usize::MAX, "eight chunks: maximum usize request"); - kani::cover(count == BYTES, "eight chunks: 256 ASCII scalars"); - kani::cover(count == BYTES / 4, "eight chunks: all four-byte scalars"); - kani::cover(true, "C22-END: harness_chars_advance_by_eight_chunks completed"); - } - - // An independently computed byte-prefix rank table. Checked local - // UTF-8 step facts expose the relation between a boundary and its next - // scalar before the real target runs; they are not assumptions or stubs. - fn assert_advance_by_block_rank(s: &str, n: usize) -> (usize, usize) { - assert!(CAP <= MAX_BYTES && s.len() <= CAP); - let mut ranks = [0u16; MAX_BYTES + 1]; - for block in 0..CAP.div_ceil(16) { - for offset in 0..16 { - let index = block * 16 + offset; - if index >= s.len() { - break; - } - ranks[index + 1] = ranks[index] - + u16::from(!utf8_is_cont_byte(s.as_bytes()[index])); - assert!(usize::from(ranks[index + 1]) <= index + 1); + None + } + + #[kani::proof] + #[kani::unwind(20)] + fn harness_reverse_byte_model() { + let bytes: [u8; 16] = kani::any(); + let len: usize = kani::any(); + // INPUT-LENGTH: only prefixes of this initialized array are inputs. + // INPUT DOMAIN: allocated prefix or index extent. + kani::assume(len <= bytes.len()); + kani::cover( + true, + "C22-A23: harness_reverse_byte_model assumption admitted", + ); + let needle: u8 = kani::any(); + let result = verifier_last_byte(needle, &bytes[..len]); + if let Some(index) = result { + assert!(index < len); + assert_eq!(bytes[index], needle); } - } - for block in 0..CAP.div_ceil(16) { - for offset in 0..16 { - let index = block * 16 + offset; - if index >= s.len() { - break; + for index in 0..len { + if result.is_none_or(|last| last < index) { + assert_ne!(bytes[index], needle); } - if s.is_char_boundary(index) { - let width = utf8_char_width(s.as_bytes()[index]) as usize; - assert!(width > 0 && width <= 4 && width <= s.len() - index); - assert!(s.is_char_boundary(index + width)); - assert_eq!(ranks[index + width], ranks[index] + 1); - } - } - } - - let count = usize::from(ranks[s.len()]); - let mut iter = s.chars(); - let result = iter.advance_by(n); // real target, no stubs - let remaining = iter.as_str(); - let position = verifier_slice_offset(s, remaining); - assert!(position <= s.len()); - verifier_assert_str_range(s, remaining, position, s.len()); - assert_eq!(usize::from(ranks[position]), n.min(count)); - if n <= count { - assert!(result.is_ok()); - } else { - assert_eq!(result.unwrap_err().get(), n - count); - } - (position, count) - } - - // Complement the retained 0..=40-byte complete-request proof with - // explicitly new extents. The guard selects an input length domain; - // no request or target-output condition is used as a filter. - #[kani::proof] - #[kani::unwind(34)] - fn harness_chars_advance_by_extended_counts() { - const BYTES: usize = 48; - let buf: [u8; BYTES + UTF8_PAD] = kani::any(); - let s = verifier_nondet_utf8(&buf); - if s.len() <= 40 { - return; - } - let n: usize = kani::any(); - let (position, _) = assert_advance_by_window_rank(s, 0, s.len(), n); - kani::cover( - n == 41 && s.len() == BYTES - 1 && position < s.len(), - "extended counts: new length and request retain tail", - ); - kani::cover( - n == 33 && s.len() == BYTES - && !s.is_char_boundary(32) - && !s.is_char_boundary(33) - && !s.is_char_boundary(34) - && position < s.len(), - "extended counts: three continuation bytes then scalar tail", - ); - kani::cover( - n == BYTES + 1 && s.len() == BYTES && position == s.len(), - "extended counts: exact shortage beyond byte capacity", - ); - kani::cover(true, "C22-END: harness_chars_advance_by_extended_counts completed"); - } - - // A bounded view constructor, not a filter on iterator outputs. Any - // desired boundary window of at most LIMIT bytes is represented by - // choosing that same window before this constructor (it is unchanged). - fn verifier_utf8_prefix(s: &str) -> &str { - let mut end = s.len().min(LIMIT); - for _ in 0..3 { - if s.is_char_boundary(end) { - break; } - assert!(end > 0); - end -= 1; + kani::cover(result.is_some(), "byte model: matching byte"); + kani::cover(result.is_none(), "byte model: no match"); + kani::cover( + len > 0 && result == Some(len - 1), + "byte model: final byte matches", + ); + kani::cover(len == 0 && result.is_none(), "byte model: empty prefix"); + kani::cover(true, "C22-END: harness_reverse_byte_model completed"); + } + + fn assert_char_searcher_direction(reverse: bool) { + let buf: [u8; 16 + UTF8_PAD] = kani::any(); + let s = verifier_nondet_utf8(&buf); + let (front, back) = verifier_nondet_window(s); + let needle: char = kani::any(); + let result = verifier_assert_real_char_searcher(s, needle, front, back, reverse); + kani::cover(result.is_some(), "real char search: matching scalar"); + kani::cover(result.is_none(), "real char search: exhausted window"); + kani::cover( + result.is_some() && needle.len_utf8() == 4, + "real char search: four-byte match", + ); + kani::cover( + front == back && result.is_none(), + "real char search: empty window", + ); + } + + #[kani::proof] + #[kani::unwind(18)] + fn harness_char_searcher_forward_refinement() { + assert_char_searcher_direction(false); + kani::cover( + true, + "C22-END: harness_char_searcher_forward_refinement completed", + ); + } + + #[kani::proof] + #[kani::unwind(18)] + #[kani::stub(crate::slice::memchr::memrchr, verifier_last_byte)] + fn harness_char_searcher_reverse_refinement() { + assert_char_searcher_direction(true); + kani::cover( + true, + "C22-END: harness_char_searcher_reverse_refinement completed", + ); } - assert!(end <= LIMIT && end <= s.len()); - assert!(s.is_char_boundary(end)); - &s[..end] - } - - #[kani::proof] - #[kani::unwind(34)] - fn harness_chars_advance_by_window_rank() { - const BYTES: usize = 256; - const WINDOW_BYTES: usize = 8; - let buf: [u8; BYTES + UTF8_PAD] = kani::any(); - let s = verifier_nondet_utf8(&buf); - let (front, back) = verifier_nondet_window(s); - let selected = &s[front..back]; - let view = verifier_utf8_prefix::(selected); - verifier_assert_str_range(s, view, front, front + view.len()); - let n: usize = kani::any(); - let (position, _) = assert_advance_by_block_rank::(view, n); - assert!(front + position <= back); - kani::cover( - s.len() == BYTES && front > 0 && back < s.len() - && n == 7 && position < view.len(), - "window rank: interior large-allocation success", - ); - kani::cover( - s.len() == BYTES && front > 0 && front + view.len() < s.len() - && !view.is_empty() && n == usize::MAX, - "window rank: maximum request ends inside parent allocation", - ); - kani::cover( - view.is_empty() && front > 0 && front < s.len() && n > 0, - "window rank: empty interior shortage", - ); - kani::cover( - selected.len() > WINDOW_BYTES && view.len() + 3 == WINDOW_BYTES, - "window rank: view limit crosses three continuation bytes", - ); - kani::cover(true, "C22-END: harness_chars_advance_by_window_rank completed"); } } From 81ead6a99895734f20d3897bccba16ef9a7fad24 Mon Sep 17 00:00:00 2001 From: v3risec Date: Mon, 16 Nov 2026 19:53:49 +0800 Subject: [PATCH 3/8] fix upstream test error --- library/core/src/array/iter/iter_inner.rs | 18 ++-- library/core/src/str/iter.rs | 117 ++++------------------ library/core/src/str/pattern.rs | 6 +- 3 files changed, 33 insertions(+), 108 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index cfa8434efc0de..f32c046f20030 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -176,12 +176,16 @@ trait Challenge22FoldElement { #[cfg(kani)] impl Challenge22FoldElement for T { - default fn admitted() -> bool { false } + default fn admitted() -> bool { + false + } } #[cfg(kani)] impl Challenge22FoldElement for bool { - fn admitted() -> bool { true } + fn admitted() -> bool { + true + } } impl PolymorphicIter<[MaybeUninit]> { @@ -425,12 +429,10 @@ mod verify { // Same representation conversion as IntoIterator for arrays, without // array::map's unrelated construction and draining machinery. let data: [MaybeUninit; 32] = unsafe { crate::mem::transmute(flags) }; - let mut actual = unsafe { - PolymorphicIter::new_unchecked(IndexRange::new_unchecked(start, end), data) - }; - let mut model = unsafe { - PolymorphicIter::new_unchecked(IndexRange::new_unchecked(start, end), data) - }; + let mut actual = + unsafe { PolymorphicIter::new_unchecked(IndexRange::new_unchecked(start, end), data) }; + let mut model = + unsafe { PolymorphicIter::new_unchecked(IndexRange::new_unchecked(start, end), data) }; let actual: &mut PolymorphicIter<[MaybeUninit]> = &mut actual; let model: &mut PolymorphicIter<[MaybeUninit]> = &mut model; let observe = |(sum, trace, calls): (u8, u64, u8), flag: bool| { diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 54405880b0000..d9809592178b3 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -2029,10 +2029,7 @@ mod verify { let result = chars.advance_by(kani::any()); assert!(chars.iter.kani_raw_parts() == (ptr, ptr)); kani::cover(result.is_ok(), "zero request on arbitrary empty pointer"); - kani::cover( - result.is_err(), - "positive request on arbitrary empty pointer", - ); + kani::cover(result.is_err(), "positive request on arbitrary empty pointer"); } fn any_window(s: &str) -> (usize, usize) { @@ -2093,10 +2090,7 @@ mod verify { assert!(a == b); } cover_completed_text(s); - kani::cover( - a > 4096 && b - a > 4096, - "completed on a large interior window", - ); + kani::cover(a > 4096 && b - a > 4096, "completed on a large interior window"); } #[kani::proof] @@ -2124,10 +2118,7 @@ mod verify { assert!(a == b); } cover_completed_text(s); - kani::cover( - a > 4096 && b - a > 4096, - "completed on a large interior window", - ); + kani::cover(a > 4096 && b - a > 4096, "completed on a large interior window"); } #[kani::proof] @@ -2137,10 +2128,7 @@ mod verify { let chars = window(s, a, b).chars(); check_range(s, chars.as_str(), a, b); cover_completed_text(s); - kani::cover( - a > 4096 && b - a > 4096, - "completed on a large interior window", - ); + kani::cover(a > 4096 && b - a > 4096, "completed on a large interior window"); } // Challenge 22 permits assuming pattern.rs (assumption 2). This is an @@ -2171,11 +2159,7 @@ mod verify { type Searcher<'a> = ModelSearcher<'a>; fn into_searcher(self, haystack: &str) -> ModelSearcher<'_> { - ModelSearcher { - haystack, - front: 0, - back: haystack.len(), - } + ModelSearcher { haystack, front: 0, back: haystack.len() } } } @@ -2214,20 +2198,12 @@ mod verify { if kani::any() { let old = self.front; self.front = self.back; - if old == self.back { - SearchStep::Done - } else { - SearchStep::Reject(old, self.back) - } + if old == self.back { SearchStep::Done } else { SearchStep::Reject(old, self.back) } } else { let (_, b) = any_match_range(self.haystack, self.front, self.back); let a = self.front; self.front = b; - if kani::any() { - SearchStep::Match(a, b) - } else { - SearchStep::Reject(a, b) - } + if kani::any() { SearchStep::Match(a, b) } else { SearchStep::Reject(a, b) } } } @@ -2263,11 +2239,7 @@ mod verify { let (a, _) = any_match_range(self.haystack, self.front, self.back); let b = self.back; self.back = a; - if kani::any() { - SearchStep::Match(a, b) - } else { - SearchStep::Reject(a, b) - } + if kani::any() { SearchStep::Match(a, b) } else { SearchStep::Reject(a, b) } } } @@ -2299,11 +2271,7 @@ mod verify { SplitInternal { start, end, - matcher: ModelSearcher { - haystack: s, - front, - back, - }, + matcher: ModelSearcher { haystack: s, front, back }, allow_trailing_empty: kani::any(), finished: kani::any(), } @@ -2334,10 +2302,7 @@ mod verify { } kani::cover(result.is_none(), "split: no remaining piece"); kani::cover(result.is_some_and(str::is_empty), "split: empty piece"); - kani::cover( - result.is_some_and(|part| part.len() > 4096), - "split: large piece", - ); + kani::cover(result.is_some_and(|part| part.len() > 4096), "split: large piece"); cover_completed_text(s); } @@ -2347,14 +2312,8 @@ mod verify { assert!(index == check_piece(s, part)); } kani::cover(result.is_none(), "matches: exhausted"); - kani::cover( - result.is_some_and(|(_, part)| part.is_empty()), - "matches: empty match", - ); - kani::cover( - result.is_some_and(|(_, part)| part.len() > 4096), - "matches: large match", - ); + kani::cover(result.is_some_and(|(_, part)| part.is_empty()), "matches: empty match"); + kani::cover(result.is_some_and(|(_, part)| part.len() > 4096), "matches: large match"); cover_completed_text(s); } @@ -2362,17 +2321,9 @@ mod verify { fn harness_searcher_protocol() { let s = symbolic_text(); let (front, back) = any_window(s); - let mut searcher = ModelSearcher { - haystack: s, - front, - back, - }; + let mut searcher = ModelSearcher { haystack: s, front, back }; let reverse: bool = kani::any(); - let result = if reverse { - searcher.next_match_back() - } else { - searcher.next_match() - }; + let result = if reverse { searcher.next_match_back() } else { searcher.next_match() }; check_searcher(s, &searcher); if let Some((a, b)) = result { assert!(front <= a && a <= b && b <= back); @@ -2502,15 +2453,9 @@ mod verify { Some(part) => { assert!(!finished); check_range(s, part, start, end); - kani::cover( - part.len() > 4096, - "returned a large remainder after range checks", - ); + kani::cover(part.len() > 4096, "returned a large remainder after range checks"); kani::cover(part.is_empty(), "ASCII whitespace remainder: empty window"); - kani::cover( - !part.is_empty(), - "ASCII whitespace remainder: nonempty window", - ); + kani::cover(!part.is_empty(), "ASCII whitespace remainder: nonempty window"); } None => { assert!(finished); @@ -2579,10 +2524,7 @@ mod verify { == real.next().map(|x| x as *const [u8; 32]) ); assert!(model.kani_raw_parts() == real.kani_raw_parts()); - kani::cover( - part.len() > 4096 && n > 32, - "large symbolic window and request", - ); + kani::cover(part.len() > 4096 && n > 32, "large symbolic window and request"); kani::cover(part.is_empty(), "empty slice models completed"); } @@ -2696,10 +2638,7 @@ mod verify { // INPUT-LENGTH: only prefixes of this initialized array are inputs. // INPUT DOMAIN: allocated prefix or index extent. kani::assume(len <= bytes.len()); - kani::cover( - true, - "C22-A23: harness_reverse_byte_model assumption admitted", - ); + kani::cover(true, "C22-A23: harness_reverse_byte_model assumption admitted"); let needle: u8 = kani::any(); let result = verifier_last_byte(needle, &bytes[..len]); if let Some(index) = result { @@ -2713,10 +2652,7 @@ mod verify { } kani::cover(result.is_some(), "byte model: matching byte"); kani::cover(result.is_none(), "byte model: no match"); - kani::cover( - len > 0 && result == Some(len - 1), - "byte model: final byte matches", - ); + kani::cover(len > 0 && result == Some(len - 1), "byte model: final byte matches"); kani::cover(len == 0 && result.is_none(), "byte model: empty prefix"); kani::cover(true, "C22-END: harness_reverse_byte_model completed"); } @@ -2733,20 +2669,14 @@ mod verify { result.is_some() && needle.len_utf8() == 4, "real char search: four-byte match", ); - kani::cover( - front == back && result.is_none(), - "real char search: empty window", - ); + kani::cover(front == back && result.is_none(), "real char search: empty window"); } #[kani::proof] #[kani::unwind(18)] fn harness_char_searcher_forward_refinement() { assert_char_searcher_direction(false); - kani::cover( - true, - "C22-END: harness_char_searcher_forward_refinement completed", - ); + kani::cover(true, "C22-END: harness_char_searcher_forward_refinement completed"); } #[kani::proof] @@ -2754,10 +2684,7 @@ mod verify { #[kani::stub(crate::slice::memchr::memrchr, verifier_last_byte)] fn harness_char_searcher_reverse_refinement() { assert_char_searcher_direction(true); - kani::cover( - true, - "C22-END: harness_char_searcher_reverse_refinement completed", - ); + kani::cover(true, "C22-END: harness_char_searcher_reverse_refinement completed"); } } } diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 505bc32dbac3c..f75a80119f51b 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -2201,11 +2201,7 @@ pub mod verify { assert!(verifier_char_searcher_invariant(&searcher)); let encoding = searcher.utf8_encoded; let width = searcher.utf8_size; - let result = if reverse { - searcher.next_match_back() - } else { - searcher.next_match() - }; + let result = if reverse { searcher.next_match_back() } else { searcher.next_match() }; assert!(verifier_char_searcher_invariant(&searcher)); assert_eq!(searcher.haystack.as_ptr(), haystack.as_ptr()); assert_eq!(searcher.haystack.len(), haystack.len()); From 0e79f5bd0bde2d87ab570f4238b7c09511e95990 Mon Sep 17 00:00:00 2001 From: v3risec Date: Wed, 18 Nov 2026 14:05:24 +0800 Subject: [PATCH 4/8] Run Challenge 22 proofs on pinned Kani Infer the chunk loop write set while preserving exact fold consumption. Capture iterator state locally and remove obsolete searcher stubs. --- library/core/src/array/iter/iter_inner.rs | 8 +- library/core/src/ops/index_range.rs | 7 + library/core/src/slice/iter.rs | 36 +- library/core/src/str/iter.rs | 598 +++++++++------------- library/core/src/str/pattern.rs | 255 +-------- 5 files changed, 272 insertions(+), 632 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index f32c046f20030..ef4f3f3642fbb 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -209,9 +209,11 @@ impl PolymorphicIter<[MaybeUninit]> { ($k:expr) => { if start + $k < end { let idx = start + $k; - let _ = self.alive.take_prefix(1); - // SAFETY: take_prefix removed an initialized element from the - // alive range, transferring its ownership to the callback. + // A direct range assignment keeps the model's write target + // visible to CBMC's loop-frame inference. + self.alive = IndexRange::kani_from_bounds(idx + 1, end); + // SAFETY: The range update transfers the initialized + // element's ownership to the callback. let ptr = data.wrapping_add(idx); let elem = unsafe { crate::intrinsics::read_via_copy(ptr) }; accum = f(accum, elem); diff --git a/library/core/src/ops/index_range.rs b/library/core/src/ops/index_range.rs index 1fc721b3a9e2e..b7f4781598c6b 100644 --- a/library/core/src/ops/index_range.rs +++ b/library/core/src/ops/index_range.rs @@ -40,6 +40,13 @@ impl IndexRange { IndexRange { start: 0, end } } + // The fold model uses this constructor inside a contracted loop. + #[cfg(kani)] + pub(crate) fn kani_from_bounds(start: usize, end: usize) -> Self { + assert!(start <= end); + Self { start, end } + } + #[inline] pub(crate) const fn start(&self) -> usize { self.start diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 1c088c550addc..211ad0144e8fb 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -169,11 +169,11 @@ impl AsRef<[T]> for Iter<'_, T> { } #[cfg(kani)] -impl Iter<'_, T> { - /// Verification-only access to the representation, avoiding contracted - /// NonNull methods inside loop clauses (see Kani issue #4796). - pub(crate) fn kani_raw_parts(&self) -> (*const T, *const T) { - (unsafe { mem::transmute::, *const T>(self.ptr) }, self.end_or_len) +impl<'a, T> Iter<'a, T> { + /// The field updated by forward iteration of non-ZSTs. Exposing its address + /// lets a loop contract name it without relying on the layout of `Iter`. + pub(crate) fn kani_cursor_slot(&mut self) -> *mut NonNull { + &raw mut self.ptr } /// Clause-only copy: CBMC adds a write-set parameter to ordinary calls, @@ -186,23 +186,23 @@ impl Iter<'_, T> { pub(crate) unsafe fn kani_loop_raw_parts(this: *const Self) -> (*const T, *const T) { // Read the representation before requiring NonNull's validity. Havoc // can produce invalid candidates, which the invariant must exclude. - let ptr = unsafe { (&raw const (*this).ptr).cast::<*const T>() }; + let ptr = unsafe { &raw const (*this).ptr } as *const *const T; let end = unsafe { &raw const (*this).end_or_len }; unsafe { (crate::intrinsics::read_via_copy(ptr), crate::intrinsics::read_via_copy(end)) } } - /// # Safety - /// These must be the fields of a valid iterator over a slice living for - /// `'a`, including the special end/length representation for a ZST. - pub(crate) unsafe fn kani_from_raw_parts<'a>( - ptr: *const T, - end_or_len: *const T, - ) -> Iter<'a, T> { - Iter { - ptr: unsafe { mem::transmute::<*const T, NonNull>(ptr) }, - end_or_len, - _marker: PhantomData, - } + /// A model of `as_slice` for byte-sized elements in a loop that havocs the + /// cursor. Rebuild it from the endpoint, which retains its points-to set. + pub(crate) fn kani_as_slice_from_end(&self) -> &'a [T] { + assert!(size_of::() == 1); + let ptr = unsafe { mem::transmute::, *const T>(self.ptr) }; + let end = self.end_or_len; + let len = (end as usize).wrapping_sub(ptr as usize); + assert!(len <= isize::MAX as usize); + let start = end.wrapping_sub(len); + assert!(start == ptr); + // SAFETY: The iterator's live range has the same pointer and length. + unsafe { &*crate::ptr::slice_from_raw_parts(start, len) } } } diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index d9809592178b3..98beb9a03d84b 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -54,15 +54,21 @@ 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 input = self.iter.as_slice(); + #[cfg(kani)] + let cursor = self.iter.kani_cursor_slot(); + #[cfg(kani)] + let requested = remainder; if remainder >= CHUNK_SIZE { let mut chunks = self.iter.as_slice().as_chunks::().0.iter(); let mut bytes_skipped: usize = 0; + // Infer the write set so it includes the temporary for `chunks.next()`. #[safety::loop_invariant(verify::chunks_inv( - &raw const chunks, bytes_skipped, on_entry(chunks.kani_raw_parts()), + &raw const chunks, bytes_skipped, input, requested, remainder, ))] - #[cfg_attr(kani, kani::loop_modifies(&chunks, &bytes_skipped, &remainder))] while remainder > CHUNK_SIZE && let Some(chunk) = chunks.next() { @@ -71,6 +77,7 @@ impl<'a> Iterator for Chars<'a> { let mut start_bytes = [false; CHUNK_SIZE]; #[safety::loop_invariant(verify::flags_valid(&raw const start_bytes))] + #[cfg_attr(kani, kani::loop_modifies(&raw mut start_bytes))] for i in 0..CHUNK_SIZE { start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); } @@ -84,9 +91,9 @@ impl<'a> Iterator for Chars<'a> { // skip trailing continuation bytes #[safety::loop_invariant(verify::bytes_inv( - &raw const self.iter, on_entry(self.iter.kani_raw_parts()), + &raw const self.iter, input, bytes_skipped, false, ))] - #[cfg_attr(kani, kani::loop_modifies(&self.iter))] + #[cfg_attr(kani, kani::loop_modifies(cursor))] while self.iter.len() > 0 { let b = self.iter.as_slice()[0]; if !super::validations::utf8_is_cont_byte(b) { @@ -98,13 +105,15 @@ impl<'a> Iterator for Chars<'a> { } #[safety::loop_invariant( - verify::bytes_inv(&raw const self.iter, on_entry(self.iter.kani_raw_parts())) - && verify::loop_on_char_boundary(&raw const self.iter) + remainder <= requested + && verify::bytes_inv(&raw const self.iter, input, requested - remainder, true) )] - #[cfg_attr(kani, kani::loop_modifies(&self.iter, &remainder))] + #[cfg_attr(kani, kani::loop_modifies(cursor, &raw mut remainder))] while (remainder > 0) && (self.iter.len() > 0) { remainder -= 1; let b = self.iter.as_slice()[0]; + #[cfg(kani)] + verify::assume_utf8_step(input, input.len() - self.iter.len(), b); let slurp = super::validations::utf8_char_width(b); // SAFETY: utf8 validity requires that the string must contain // the continuation bytes (if any) @@ -1669,7 +1678,6 @@ mod verify { use super::super::validations::utf8_is_cont_byte; use super::*; - use crate::mem; // CI uses --object-bits 12 on a 64-bit target. This is the largest positive // one-past offset, not a small input bound chosen for loop unwinding. @@ -1680,10 +1688,6 @@ mod verify { fn __CPROVER_havoc_object(p: *mut crate::ffi::c_void); } - // Immutable input extent used to reconstruct pointers after loop havoc. - // Only harness input construction writes this ghost state. - static mut INPUT: (*const u8, usize) = (crate::ptr::null(), 0); - fn symbolic_text() -> &'static str { let len: usize = kani::any(); kani::assume(len <= MAX_ALLOCATION_BYTES); @@ -1702,13 +1706,13 @@ mod verify { } p }; - unsafe { INPUT = (p, len) }; + let bytes = unsafe { slice::from_raw_parts(p, len) }; // A valid nonempty input begins at a lead byte. This also justifies // str indexing's optimized check when both endpoints are zero. - kani::assume(utf8_ok_at(0)); + kani::assume(bytes.is_empty() || utf8_sequence_width(bytes, 0) > 0); // The C allocation supplies symbolic bytes. UTF-8 is assumed locally // where bytes are consumed; this overapproximates all valid strings. - unsafe { from_utf8_unchecked(slice::from_raw_parts(p, len)) } + unsafe { from_utf8_unchecked(bytes) } } // At harness exit these goals follow ALL input assumptions and target checks. @@ -1719,8 +1723,8 @@ mod verify { kani::cover(s.len() > 4096, "completed beyond former input bounds"); } - fn lead_width(b: u8) -> usize { - match b { + fn modeled_utf8_width(byte: u8) -> usize { + match byte { 0..=0x7f => 1, 0xc2..=0xdf => 2, 0xe0..=0xef => 3, @@ -1739,250 +1743,147 @@ mod verify { } } - unsafe fn byte(i: usize) -> u8 { - let (p, len) = unsafe { INPUT }; - assert!(i < len); - unsafe { *p.add(i) } - } - - /// A necessary rule at any position of a valid UTF-8 input. The lookbehind - /// case permits a continuation byte; it does not assume cursor alignment. - fn utf8_ok_at(i: usize) -> bool { - let len = unsafe { INPUT.1 }; - if i >= len { - return true; - } - unsafe { - let b = byte(i); - let w = lead_width(b); - if w != 0 { - w <= len - i - && (w < 2 || second_ok(b, byte(i + 1))) - && (w < 3 || utf8_is_cont_byte(byte(i + 2))) - && (w < 4 || utf8_is_cont_byte(byte(i + 3))) - && (i + w == len || !utf8_is_cont_byte(byte(i + w))) - } else if utf8_is_cont_byte(b) { - (i >= 1 && lead_width(byte(i - 1)) >= 2) - || (i >= 2 && utf8_is_cont_byte(byte(i - 1)) && lead_width(byte(i - 2)) >= 3) - || (i >= 3 - && utf8_is_cont_byte(byte(i - 1)) - && utf8_is_cont_byte(byte(i - 2)) - && lead_width(byte(i - 3)) == 4) - } else { - false - } + // Width of a complete UTF-8 scalar starting at a character boundary. + fn utf8_sequence_width(bytes: &[u8], start: usize) -> usize { + let lead = bytes[start]; + let width = modeled_utf8_width(lead); + if width > 0 + && width <= bytes.len() - start + && (width < 2 || second_ok(lead, bytes[start + 1])) + && (width < 3 || utf8_is_cont_byte(bytes[start + 2])) + && (width < 4 || utf8_is_cont_byte(bytes[start + 3])) + && (start + width == bytes.len() || !utf8_is_cont_byte(bytes[start + width])) + { + width + } else { + 0 } } - // Loop clauses of the real advance_by body. None of these invokes a method - // with a function contract or assumes the invariant it is checking. - pub(super) fn bytes_inv( - iter: *const slice::Iter<'_, u8>, - entry: (*const u8, *const u8), - ) -> bool { - let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; - end == entry.1 - && crate::intrinsics::wrapping_sub(ptr as usize, entry.0 as usize) - <= crate::intrinsics::wrapping_sub(entry.1 as usize, entry.0 as usize) + fn any_window(s: &str) -> (usize, usize) { + let (a, b): (usize, usize) = (kani::any(), kani::any()); + kani::assume(a <= b && b <= s.len()); + kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); + kani::cover(true, "a boundary window exists"); + (a, b) } - pub(super) fn chunks_inv( - iter: *const slice::Iter<'_, [u8; 32]>, - skipped: usize, - entry: (*const [u8; 32], *const [u8; 32]), - ) -> bool { - let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; - end == entry.1 - && skipped % 32 == 0 - && skipped <= crate::intrinsics::wrapping_sub(entry.1 as usize, entry.0 as usize) - && crate::intrinsics::wrapping_sub(ptr as usize, entry.0 as usize) == skipped + // Input-state construction: these are checked premises, not target outputs. + // Avoid pulling panic-message string searching into every proof's call graph. + fn window(s: &str, a: usize, b: usize) -> &str { + assert!(a <= b && b <= s.len()); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + unsafe { s.get_unchecked(a..b) } } - fn on_char_boundary(iter: &slice::Iter<'_, u8>) -> bool { - let (ptr, end) = iter.kani_raw_parts(); - let (base, len) = unsafe { INPUT }; - let start = (ptr as usize).wrapping_sub(base as usize); - ptr == end || (start < len && !utf8_is_cont_byte(unsafe { *base.wrapping_add(start) })) + fn same_slice(a: &str, b: &str) -> bool { + a.as_ptr() == b.as_ptr() && a.len() == b.len() } - // Do not call ordinary helpers from a loop clause (CBMC/Kani issue #4796). - // This is intentionally separate from the postcondition's ordinary check. - pub(super) fn loop_on_char_boundary(iter: *const slice::Iter<'_, u8>) -> bool { - let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; - let (base, len) = unsafe { INPUT }; - let start = crate::intrinsics::wrapping_sub(ptr as usize, base as usize); - ptr == end - || (start < len - && unsafe { *crate::intrinsics::arith_offset(base, start as isize) } & 0xc0 != 0x80) + // Check bounds and provenance before using an offset in the postcondition. + fn checked_offset(s: &str, part: &str) -> usize { + let offset = (part.as_ptr() as usize).wrapping_sub(s.as_ptr() as usize); + assert!(offset <= s.len() && part.len() <= s.len() - offset); + assert!(part.as_ptr() == s.as_ptr().wrapping_add(offset)); + offset } - // Read the representation as integers before requiring any typed bool value. - // In particular this does not form a &[bool; 32] to the havoced loop state. - pub(super) fn flags_valid(flags: *const [bool; 32]) -> bool { - let ptr = flags.cast::<[u8; 32]>(); - let b = unsafe { crate::intrinsics::read_via_copy(ptr) }; - (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 - == 0 - } - - // The only slice model instantiations admitted by this proof. Unsupported - // instantiations fail rather than silently changing the modeled domain. - trait AdvanceElement { - fn width() -> usize; - } - - impl AdvanceElement for T { - default fn width() -> usize { - panic!("advance_by slice model only supports u8 and [u8; 32]") - } - } - impl AdvanceElement for u8 { - fn width() -> usize { - 1 - } - } - impl AdvanceElement for [u8; 32] { - fn width() -> usize { - 32 - } + fn check_range(s: &str, part: &str, a: usize, b: usize) { + assert!(a <= b && b <= s.len()); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + assert!(part.as_ptr() == s.as_ptr().wrapping_add(a)); + assert!(part.len() == b - a); } - // Loop havoc loses CBMC's points-to set (Kani #4993). Check the represented - // interval, then reconstruct access pointers from the immutable input base. - // The comparisons also check allocation identity, not only numeric bounds. - fn advance_window(iter: &slice::Iter<'_, T>) -> (usize, usize) { - let (ptr, end) = iter.kani_raw_parts(); - let (base, len) = unsafe { INPUT }; - let start = (ptr as usize).wrapping_sub(base as usize); - let stop = (end as usize).wrapping_sub(base as usize); - assert!(start <= stop && stop <= len); - assert!(ptr.cast::() == base.wrapping_add(start)); - assert!(end.cast::() == base.wrapping_add(stop)); - assert!((stop - start) % T::width() == 0); - (start, stop) - } - - fn advance_slice<'a, T>(start: usize, stop: usize) -> &'a [T] { - let base = unsafe { INPUT.0 }; - let ptr = base.wrapping_add(start).cast::(); - unsafe { &*crate::ptr::slice_from_raw_parts(ptr, (stop - start) / T::width()) } - } - - fn advance_iter<'a, T>(start: usize, stop: usize) -> slice::Iter<'a, T> { - let base = unsafe { INPUT.0 }; - unsafe { - slice::Iter::kani_from_raw_parts( - base.wrapping_add(start).cast::(), - base.wrapping_add(stop).cast::(), - ) - } - } + // Loop invariants and dependency models for Chars::advance_by. - fn advance_len<'a, T>(iter: &slice::Iter<'a, T>) -> usize - where - 'a: 'a, - { - let (start, stop) = advance_window(iter); - (stop - start) / T::width() + pub(super) fn chunks_inv( + iter: *const slice::Iter<'_, [u8; 32]>, + skipped: usize, + input: &[u8], + requested: usize, + remainder: usize, + ) -> bool { + let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; + let base = input as *const [u8] as *const u8; + let full = input.len() & !31; + skipped <= full + && skipped % 32 == 0 + && ptr as *const u8 + == unsafe { crate::intrinsics::arith_offset(base, skipped as isize) } + && end as *const u8 == unsafe { crate::intrinsics::arith_offset(base, full as isize) } + && remainder <= requested + && requested - remainder <= skipped } - fn advance_as_slice_plain<'a, T>(iter: &slice::Iter<'a, T>) -> &'a [T] { - let (start, stop) = advance_window(iter); - advance_slice(start, stop) + // A loop may havoc the cursor. Keep it in the original allocation and + // check that the scalar loop starts each iteration at a character boundary. + pub(super) fn bytes_inv( + iter: *const slice::Iter<'_, u8>, + input: &[u8], + skipped: usize, + at_char_boundary: bool, + ) -> bool { + let (ptr, end) = unsafe { slice::Iter::kani_loop_raw_parts(iter) }; + let base = input as *const [u8] as *const u8; + let len = input.len(); + let offset = crate::intrinsics::wrapping_sub(ptr as usize, base as usize); + skipped <= offset + && offset <= len + && ptr == unsafe { crate::intrinsics::arith_offset(base, offset as isize) } + && end == unsafe { crate::intrinsics::arith_offset(base, len as isize) } + && (!at_char_boundary || offset == len || (input[offset] as i8) >= -64) + } + + pub(super) fn assume_utf8_step(input: &[u8], offset: usize, lead: u8) { + assert!(offset < input.len() && lead == input[offset]); + if !utf8_is_cont_byte(lead) { + // On valid UTF-8, any non-continuation byte begins a complete + // scalar. This fact concerns the original bytes, even if the + // algorithm supplies an unexpected offset. + let width = modeled_utf8_width(lead); + kani::assume(width > 0 && width <= input.len() - offset); + let next = offset + width; + kani::assume(next == input.len() || !utf8_is_cont_byte(input[next])); + } + } + + // Check the branch-based model for every input to the real width table. + #[kani::proof] + fn check_utf8_width_model() { + let byte: u8 = kani::any(); + assert!(modeled_utf8_width(byte) == super::super::validations::utf8_char_width(byte)); } - fn advance_as_slice<'a, T>(iter: &slice::Iter<'a, T>) -> &'a [T] - where - 'a: 'a, - { - let (start, stop) = advance_window(iter); - if T::width() == 1 { - // Every byte iterator used by this harness ends at the original - // string end. This is checked, not assumed after an operation. - assert!(stop == unsafe { INPUT.1 }); - if start < stop { - // Necessary facts at ANY position of the original valid string: - // a lead byte's sequence fits and ends at a boundary. In - // particular continuation bytes (width 0) are allowed here. - // Full scalar decoding constraints are unnecessary for advance_by. - let base = unsafe { INPUT.0 }; - let first = unsafe { *base.wrapping_add(start) }; - let width = super::super::validations::utf8_char_width(first); - kani::assume(width <= stop - start); - kani::assume( - width == 0 - || start + width == stop - || !utf8_is_cont_byte(unsafe { *base.wrapping_add(start + width) }), - ); - } + #[kani::proof] + fn check_slice_view_model() { + let bytes = symbolic_text().as_bytes(); + let (start, end): (usize, usize) = kani::any(); + kani::assume(start <= end && end <= bytes.len()); + let iter = bytes[start..end].iter(); + let (actual, model) = (iter.as_slice(), iter.kani_as_slice_from_end()); + assert!(actual.as_ptr() == model.as_ptr() && actual.len() == model.len()); + let index: usize = kani::any(); + if index < actual.len() { + assert!(actual[index] == model[index]); } - advance_slice(start, stop) + kani::cover(start < end && bytes.len() == MAX_ALLOCATION_BYTES, "largest input"); } - fn advance_bytes<'a, T>(iter: &mut slice::Iter<'a, T>, n: usize) -> Result<(), NonZero> - where - 'a: 'a, - { - let (start, stop) = advance_window(iter); - let count = crate::cmp::min(n, (stop - start) / T::width()); - *iter = advance_iter(start + count * T::width(), stop); - NonZero::new(n - count).map_or(Ok(()), Err) - } - - fn advance_next<'a, T>(iter: &mut slice::Iter<'a, T>) -> Option<&'a T> - where - 'a: 'a, - { - let (start, stop) = advance_window(iter); - if start == stop { - return None; - } - let part: &'a [T] = advance_slice(start, stop); - *iter = advance_iter(start + T::width(), stop); - Some(&part[0]) + // Read the representation as integers before requiring any typed bool value. + pub(super) fn flags_valid(flags: *const [bool; 32]) -> bool { + let bytes = unsafe { crate::intrinsics::read_via_copy(flags as *const [u8; 32]) }; + let [lo, hi]: [u128; 2] = unsafe { crate::intrinsics::transmute(bytes) }; + (lo | hi) & !0x0101_0101_0101_0101_0101_0101_0101_0101 == 0 } #[kani::proof] - #[kani::stub( as crate::iter::ExactSizeIterator>::len, advance_len)] - #[kani::stub(crate::slice::Iter::as_slice, advance_as_slice)] - #[kani::stub( as crate::iter::Iterator>::advance_by, advance_bytes)] - #[kani::stub( as crate::iter::Iterator>::next, advance_next)] #[kani::stub( crate::array::iter::iter_inner::PolymorphicIter::fold, crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 )] + #[kani::stub(crate::str::validations::utf8_char_width, modeled_utf8_width)] + #[kani::stub(crate::slice::Iter::as_slice, crate::slice::Iter::kani_as_slice_from_end)] fn harness_chars_advance_by() { // Every valid Chars state is a fresh iterator over its remaining valid // string. Both the length and requested character count are symbolic. @@ -1990,8 +1891,17 @@ mod verify { let mut chars = text.chars(); let n: usize = kani::any(); // No request/count bound. let result = chars.advance_by(n); - let _ = advance_window(&chars.iter); - assert!(on_char_boundary(&chars.iter)); + let rest = chars.as_str(); + let skipped = checked_offset(text, rest); + assert!(rest.len() == text.len() - skipped); + assert!(text.is_char_boundary(skipped)); + match result { + Ok(()) => assert!(n <= skipped), + Err(missing) => { + assert!(rest.is_empty()); + assert!(missing.get() <= n && n - missing.get() <= skipped); + } + } kani::cover( result.is_ok() && n > 64 && text.len() == MAX_ALLOCATION_BYTES, "maximum representable string and chunk path", @@ -2003,7 +1913,10 @@ mod verify { "maximum request remains admitted after UTF-8 assumptions", ); kani::cover( - text.len() == 4 && n == 1 && result.is_ok() && lead_width(unsafe { byte(0) }) == 4, + text.len() == 4 + && n == 1 + && result.is_ok() + && modeled_utf8_width(text.as_bytes()[0]) == 4, "four-byte input remains admitted after scalar-loop checks", ); } @@ -2011,77 +1924,60 @@ mod verify { // Empty slices can have arbitrary nonnull aligned addresses, not only the // dangling address used by symbolic_text's zero-length allocation case. #[kani::proof] - #[kani::stub( as crate::iter::ExactSizeIterator>::len, advance_len)] - #[kani::stub(crate::slice::Iter::as_slice, advance_as_slice)] - #[kani::stub( as crate::iter::Iterator>::advance_by, advance_bytes)] - #[kani::stub( as crate::iter::Iterator>::next, advance_next)] #[kani::stub( crate::array::iter::iter_inner::PolymorphicIter::fold, crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 )] + #[kani::stub(crate::str::validations::utf8_char_width, modeled_utf8_width)] + #[kani::stub(crate::slice::Iter::as_slice, crate::slice::Iter::kani_as_slice_from_end)] fn harness_chars_advance_by_empty() { - let ptr = kani::any::() as *const u8; - kani::assume(!ptr.is_null()); - unsafe { INPUT = (ptr, 0) }; - // SAFETY: any nonnull address is aligned for u8; no bytes are accessed. + let address: NonZero = kani::any(); + let ptr = crate::ptr::without_provenance(address.get()); + // SAFETY: the address is nonnull and aligned for u8, and the input is empty. let text = unsafe { from_utf8_unchecked(slice::from_raw_parts(ptr, 0)) }; let mut chars = text.chars(); let result = chars.advance_by(kani::any()); - assert!(chars.iter.kani_raw_parts() == (ptr, ptr)); + let rest = chars.as_str(); + assert!(rest.is_empty() && rest.as_ptr() == ptr); kani::cover(result.is_ok(), "zero request on arbitrary empty pointer"); kani::cover(result.is_err(), "positive request on arbitrary empty pointer"); } - fn any_window(s: &str) -> (usize, usize) { - let (a, b): (usize, usize) = (kani::any(), kani::any()); - kani::assume(a <= b && b <= s.len()); - kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); - kani::cover(true, "a boundary window exists"); - (a, b) - } - - // Input-state construction: these are checked premises, not target outputs. - // Avoid pulling panic-message string searching into every proof's call graph. - fn window(s: &str, a: usize, b: usize) -> &str { - assert!(a <= b && b <= s.len()); - assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); - unsafe { s.get_unchecked(a..b) } - } - - fn same_slice(a: &str, b: &str) -> bool { - a.as_ptr() == b.as_ptr() && a.len() == b.len() - } - - // Check bounds and provenance before using an offset in the postcondition. - fn checked_offset(s: &str, part: &str) -> usize { - let offset = (part.as_ptr() as usize).wrapping_sub(s.as_ptr() as usize); - assert!(offset <= s.len() && part.len() <= s.len() - offset); - assert!(part.as_ptr() == s.as_ptr().wrapping_add(offset)); - offset - } + // Chars decoding and view proofs. - fn check_range(s: &str, part: &str, a: usize, b: usize) { - assert!(a <= b && b <= s.len()); - assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); - assert!(part.as_ptr() == s.as_ptr().wrapping_add(a)); - assert!(part.len() == b - a); + // Reference scalar from the payload bits of a previously validated sequence. + fn scalar_bits(bytes: &[u8], start: usize, width: usize) -> u32 { + let lead = u32::from(bytes[start]); + let tail = |i| u32::from(bytes[start + i] & 0x3f); + match width { + 1 => lead, + 2 => ((lead & 0x1f) << 6) | tail(1), + 3 => ((lead & 0x0f) << 12) | (tail(1) << 6) | tail(2), + 4 => ((lead & 0x07) << 18) | (tail(1) << 12) | (tail(2) << 6) | tail(3), + _ => unreachable!(), + } } #[kani::proof] fn harness_chars_next() { let s = symbolic_text(); let (a, b) = any_window(s); - if a < b { + let bytes = s.as_bytes(); + let width = if a < b { // Input facts at the first sequence of this valid boundary window. // The decoder and its unsafe reads are executed without a stub. - kani::assume(utf8_ok_at(a)); - let width = lead_width(unsafe { byte(a) }); + let width = utf8_sequence_width(bytes, a); kani::assume(width > 0 && width <= b - a); - } + width + } else { + 0 + }; let mut chars = window(s, a, b).chars(); if let Some(ch) = chars.next() { + assert!(width > 0 && ch as u32 == scalar_bits(bytes, a, width)); assert!(char::from_u32(ch as u32).is_some()); - check_range(s, chars.as_str(), a + ch.len_utf8(), b); + assert!(ch.len_utf8() == width); + check_range(s, chars.as_str(), a + width, b); kani::cover(ch.len_utf8() == 1, "one-byte scalar"); kani::cover(ch.len_utf8() == 2, "two-byte scalar"); kani::cover(ch.len_utf8() == 3, "three-byte scalar"); @@ -2097,19 +1993,24 @@ mod verify { fn harness_chars_next_back() { let s = symbolic_text(); let (a, b) = any_window(s); - if a < b { + let bytes = s.as_bytes(); + let width = if a < b { // A valid nonempty UTF-8 window has one final complete sequence. // This symbolic width is an input witness, not a decoder result. let width: usize = kani::any(); kani::assume(1 <= width && width <= 4 && width <= b - a); let lead = b - width; - kani::assume(utf8_ok_at(lead) && lead_width(unsafe { byte(lead) }) == width); - } + kani::assume(utf8_sequence_width(bytes, lead) == width); + width + } else { + 0 + }; let mut chars = window(s, a, b).chars(); if let Some(ch) = chars.next_back() { + assert!(width > 0 && ch as u32 == scalar_bits(bytes, b - width, width)); assert!(char::from_u32(ch as u32).is_some()); - assert!(ch.len_utf8() <= b - a); - check_range(s, chars.as_str(), a, b - ch.len_utf8()); + assert!(ch.len_utf8() == width); + check_range(s, chars.as_str(), a, b - width); kani::cover(ch.len_utf8() == 1, "one-byte scalar"); kani::cover(ch.len_utf8() == 2, "two-byte scalar"); kani::cover(ch.len_utf8() == 3, "three-byte scalar"); @@ -2131,18 +2032,11 @@ mod verify { kani::cover(a > 4096 && b - a > 4096, "completed on a large interior window"); } - // Challenge 22 permits assuming pattern.rs (assumption 2). This is an - // interval-protocol abstraction, not a proof of any matching algorithm. - // Each call may skip Reject steps and return any boundary-valid Match, - // including a zero-width Match. Thus widths may vary between calls. - // The common residual interval suffices for directional safety; this - // model deliberately does NOT implement DoubleEndedSearcher; consumers are - // checked one operation at a time under the interval protocol. - // Projection argument: for a forward-only concrete searcher, front/back - // describe the unreported suffix; every real next_match return is admitted - // here. The reverse-only argument uses the unreported prefix. Consumers - // observe only haystack() and returned indices. This simulation argument - // imports assumption 2; Kani does not quantify over all Rust Pattern types. + // Under the challenge's Pattern assumption, directional consumers observe + // only the haystack and ordered match ranges on UTF-8 boundaries. The model + // allows any such range, including empty matches and skipped rejects. + // Forward-only and reverse-only searchers project onto a suffix and a + // prefix respectively. No double-ended matching semantics are required. struct ModelPattern; struct ModelSearcher<'a> { @@ -2346,14 +2240,38 @@ mod verify { cover_completed_text(s); } + fn check_initial_searcher(s: &str, searcher: &ModelSearcher<'_>) { + check_searcher(s, searcher); + assert!(searcher.front == 0 && searcher.back == s.len()); + } + + fn check_initial_split(s: &str, split: &SplitInternal<'_, ModelPattern>, trailing: bool) { + check_initial_searcher(s, &split.matcher); + assert!(split.start == 0 && split.end == s.len()); + assert!(split.allow_trailing_empty == trailing && !split.finished); + assert!(type_invariant_split(split)); + } + #[kani::proof] - fn harness_split_constructors() { + fn harness_iterator_constructors() { let s = symbolic_text(); - let searcher = ModelPattern.into_searcher(s); - check_searcher(s, &searcher); - check_split_frame(s, &s.split(ModelPattern).0); - check_split_frame(s, &s.split_terminator(ModelPattern).0); - check_split_frame(s, &s.split_inclusive(ModelPattern).0); + let n = kani::any(); + let splitn = s.splitn(n, ModelPattern).0; + let rsplitn = s.rsplitn(n, ModelPattern).0; + check_initial_split(s, &s.split(ModelPattern).0, true); + check_initial_split(s, &s.rsplit(ModelPattern).0, true); + check_initial_split(s, &s.split_inclusive(ModelPattern).0, false); + check_initial_split(s, &s.split_terminator(ModelPattern).0, false); + check_initial_split(s, &s.rsplit_terminator(ModelPattern).0, false); + check_initial_split(s, &splitn.iter, true); + check_initial_split(s, &rsplitn.iter, true); + assert!(splitn.count == n && rsplitn.count == n); + check_initial_searcher(s, &s.matches(ModelPattern).0.0); + check_initial_searcher(s, &s.rmatches(ModelPattern).0.0); + check_initial_searcher(s, &s.match_indices(ModelPattern).0.0); + check_initial_searcher(s, &s.rmatch_indices(ModelPattern).0.0); + assert!(s.split_ascii_whitespace().remainder().is_some_and(|part| same_slice(s, part))); + assert!(same_slice(s, s.chars().as_str())); cover_completed_text(s); } @@ -2489,53 +2407,25 @@ mod verify { ); } - // Component/refinement checks do not discharge any required target. The - // fixed unwinds here concern 32 flags or the optional real-searcher inputs, - // never the symbolic string length of a required iterator harness. mod auxiliary { - //! Dependency models and fixed-size component proofs. Only the - //! real-searcher regressions below have a bounded string input. + //! Fixed-size fold checks and bounded real-searcher regressions. - use super::super::super::pattern::verify::verifier_assert_real_char_searcher; + use super::super::super::pattern::verify::assert_char_searcher_step; use super::*; + use crate::mem; - fn sum_flags(flags: [bool; 32]) -> u8 { - flags.into_iter().map(|flag| flag as u8).sum::() - } - - #[kani::proof] - fn check_slice_models() { - let bytes = symbolic_text().as_bytes(); - let (a, b): (usize, usize) = (kani::any(), kani::any()); - kani::assume(a <= b && b <= bytes.len()); - let part = &bytes[a..b]; - let mut real = part.iter(); - let mut model = part.iter(); - assert!(advance_len(&model) == real.len()); - let modeled = advance_as_slice_plain(&model); - assert!(modeled.as_ptr() == real.as_slice().as_ptr() && modeled.len() == real.len()); - let n = kani::any(); - assert!(advance_bytes(&mut model, n) == real.advance_by(n)); - assert!(model.kani_raw_parts() == real.kani_raw_parts()); - let chunks = part.as_chunks::<32>().0; - let (mut real, mut model) = (chunks.iter(), chunks.iter()); - assert!( - advance_next(&mut model).map(|x| x as *const [u8; 32]) - == real.next().map(|x| x as *const [u8; 32]) - ); - assert!(model.kani_raw_parts() == real.kani_raw_parts()); - kani::cover(part.len() > 4096 && n > 32, "large symbolic window and request"); - kani::cover(part.is_empty(), "empty slice models completed"); + fn check_sum_flags() { + let flags: [bool; 32] = kani::any(); + let words: [u128; 2] = unsafe { mem::transmute(flags) }; + let result = flags.into_iter().map(|flag| flag as u8).sum::(); + assert!(result as u32 == words[0].count_ones() + words[1].count_ones()); + kani::cover(result == 32, "all flags consumed after sum assertion"); } #[kani::proof] #[kani::unwind(33)] fn check_sum_32_real() { - let flags: [bool; 32] = kani::any(); - let words: [u128; 2] = unsafe { mem::transmute(flags) }; - let result = sum_flags(flags); - assert!(result as u32 == words[0].count_ones() + words[1].count_ones()); - kani::cover(result == 32, "all flags consumed after sum assertion"); + check_sum_flags(); } #[kani::proof] @@ -2544,11 +2434,7 @@ mod verify { crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 )] fn check_sum_32_model() { - let flags: [bool; 32] = kani::any(); - let words: [u128; 2] = unsafe { mem::transmute(flags) }; - let result = sum_flags(flags); - assert!(result as u32 == words[0].count_ones() + words[1].count_ones()); - kani::cover(result == 32, "all flags consumed after sum assertion"); + check_sum_flags(); } const UTF8_PAD: usize = 4; @@ -2607,18 +2493,6 @@ mod verify { unsafe { from_utf8_unchecked(&buf[..len]) } } - fn verifier_nondet_window(s: &str) -> (usize, usize) { - let start: usize = kani::any(); - let end: usize = kani::any(); - // INPUT STATE: an ordered UTF-8 boundary window. - kani::assume(start <= end && end <= s.len()); - kani::cover(true, "C22-A03: verifier_nondet_window assumption admitted"); - // INPUT STATE: an ordered UTF-8 boundary window. - kani::assume(s.is_char_boundary(start) && s.is_char_boundary(end)); - kani::cover(true, "C22-A04: verifier_nondet_window assumption admitted"); - (start, end) - } - fn verifier_last_byte(needle: u8, bytes: &[u8]) -> Option { let mut index = bytes.len(); while index > 0 { @@ -2660,9 +2534,9 @@ mod verify { fn assert_char_searcher_direction(reverse: bool) { let buf: [u8; 16 + UTF8_PAD] = kani::any(); let s = verifier_nondet_utf8(&buf); - let (front, back) = verifier_nondet_window(s); + let (front, back) = any_window(s); let needle: char = kani::any(); - let result = verifier_assert_real_char_searcher(s, needle, front, back, reverse); + let result = assert_char_searcher_step(s, needle, front, back, reverse); kani::cover(result.is_some(), "real char search: matching scalar"); kani::cover(result.is_none(), "real char search: exhausted window"); kani::cover( diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index f75a80119f51b..00a083087f34b 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -2156,17 +2156,7 @@ pub mod verify { kani::cover(true, "C22-END: check_small_slice_eq_empty completed"); } - // Challenge 22: specifications for the permitted `str::pattern` assumption. - // These helpers are inside `str::pattern::verify`, not production code. - // Iterator harnesses stub only the explicitly annotated directional search - // operations; all real production bodies remain unchanged. These are - // manual safety abstractions under assumption 2, not stub_verified proofs. - // The simulation relation is observational: iter.rs reads haystack and - // match intervals, not search-algorithm preprocessing or equality state. - // See doc/src/verification/challenge-22-coverage.md for each adapter's - // admitted returns, frame conditions, progress, and proof obligations. - - pub fn verifier_char_searcher_invariant(searcher: &CharSearcher<'_>) -> bool { + fn char_searcher_invariant(searcher: &CharSearcher<'_>) -> bool { let haystack = searcher.haystack; let mut encoded = [0u8; 4]; let width = searcher.needle.encode_utf8(&mut encoded).len(); @@ -2181,12 +2171,9 @@ pub mod verify { && (width < 4 || searcher.utf8_encoded[3] == encoded[3]) } - // A real call is checked against the return/frame relation imported by - // the char stubs below. The caller selects a valid input window; assert - // that precondition instead of silently filtering it with kani::assume. - // The dedicated harness preserves both real CharSearcher methods; its - // reverse slice byte-search leaf uses an exact model under assumption 1. - pub fn verifier_assert_real_char_searcher( + // Check the concrete searcher's result and iterator state against the + // range guarantees used by Challenge 22's symbolic searcher model. + pub(in crate::str) fn assert_char_searcher_step( haystack: &str, needle: char, front: usize, @@ -2198,11 +2185,11 @@ pub mod verify { let mut searcher = needle.into_searcher(haystack); searcher.finger = front; searcher.finger_back = back; - assert!(verifier_char_searcher_invariant(&searcher)); + assert!(char_searcher_invariant(&searcher)); let encoding = searcher.utf8_encoded; let width = searcher.utf8_size; let result = if reverse { searcher.next_match_back() } else { searcher.next_match() }; - assert!(verifier_char_searcher_invariant(&searcher)); + assert!(char_searcher_invariant(&searcher)); assert_eq!(searcher.haystack.as_ptr(), haystack.as_ptr()); assert_eq!(searcher.haystack.len(), haystack.len()); assert_eq!(searcher.needle, needle); @@ -2233,234 +2220,4 @@ pub mod verify { } result } - - // This over-approximates Searcher::next_match under Challenge 22 - // assumption 2: either no match remains, or a needle-width boundary - // range lies between the current search frontiers. This may admit a - // sequence of shorter scalars, an intentional safety over-approximation. - // We do not assume the match actually equals the needle, so the model - // admits at least the real searcher's possible returns. - pub fn verifier_stub_char_next_match<'a: 'a>( - searcher: &mut CharSearcher<'a>, - ) -> Option<(usize, usize)> { - assert!(verifier_char_searcher_invariant(searcher)); - let found: bool = kani::any(); - if !found { - searcher.finger = searcher.finger_back; - return None; - } - let start: usize = kani::any(); - let width = searcher.needle.len_utf8(); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(searcher.finger <= start && start <= searcher.finger_back); - kani::cover(true, "C22-A29: verifier_stub_char_next_match assumption admitted"); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(width <= searcher.finger_back - start); - kani::cover(true, "C22-A30: verifier_stub_char_next_match assumption admitted"); - let end = start + width; - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume( - searcher.haystack.is_char_boundary(start) && searcher.haystack.is_char_boundary(end), - ); - kani::cover(true, "C22-A31: verifier_stub_char_next_match assumption admitted"); - searcher.finger = end; - assert!(verifier_char_searcher_invariant(searcher)); - Some((start, end)) - } - - // ReverseSearcher::next_match_back: same permitted abstraction, with - // the opposite search frontier moved to the beginning of the match. - pub fn verifier_stub_char_next_match_back<'a: 'a>( - searcher: &mut CharSearcher<'a>, - ) -> Option<(usize, usize)> { - assert!(verifier_char_searcher_invariant(searcher)); - let found: bool = kani::any(); - if !found { - searcher.finger_back = searcher.finger; - return None; - } - let start: usize = kani::any(); - let width = searcher.needle.len_utf8(); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(searcher.finger <= start && start <= searcher.finger_back); - kani::cover(true, "C22-A32: verifier_stub_char_next_match_back assumption admitted"); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(width <= searcher.finger_back - start); - kani::cover(true, "C22-A33: verifier_stub_char_next_match_back assumption admitted"); - let end = start + width; - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume( - searcher.haystack.is_char_boundary(start) && searcher.haystack.is_char_boundary(end), - ); - kani::cover(true, "C22-A34: verifier_stub_char_next_match_back assumption admitted"); - searcher.finger_back = start; - assert!(verifier_char_searcher_invariant(searcher)); - Some((start, end)) - } - // Directional adapters for Challenge 22 assumption 2. They constrain - // returned ranges and the state consumed by iter.rs, not match contents. - // In particular StrSearcher has independent forward/reverse cursors: - // it must not inherit CharSearcher's shared-finger ordering invariant. - // None normalizes a cursor to an exhausted representative. Algorithm - // metadata is unobserved by iter.rs; these are not verified contracts for - // the real search bodies. Explicit self-bounded lifetimes match the - // early-bound generic parameters required by Kani's stub checker. - pub fn verifier_stub_str_next_match<'a: 'a, 'b: 'b>( - s: &mut StrSearcher<'a, 'b>, - ) -> Option<(usize, usize)> { - if s.needle.is_empty() { - // Empty-needle Match/Reject alternation needs at most two real - // steps. Retain its actual phase, UTF-8 decoding and exhaustion. - return match s.next() { - SearchStep::Match(a, b) => Some((a, b)), - SearchStep::Done => None, - SearchStep::Reject(..) => match s.next() { - SearchStep::Match(a, b) => Some((a, b)), - SearchStep::Done => None, - SearchStep::Reject(..) => unreachable!("empty needle alternates"), - }, - }; - } - verifier_stub_str_nonempty_next_match(s) - } - - pub fn verifier_stub_str_next_match_back<'a: 'a, 'b: 'b>( - s: &mut StrSearcher<'a, 'b>, - ) -> Option<(usize, usize)> { - if s.needle.is_empty() { - return match s.next_back() { - SearchStep::Match(a, b) => Some((a, b)), - SearchStep::Done => None, - SearchStep::Reject(..) => match s.next_back() { - SearchStep::Match(a, b) => Some((a, b)), - SearchStep::Done => None, - SearchStep::Reject(..) => unreachable!("empty needle alternates"), - }, - }; - } - verifier_stub_str_nonempty_next_match_back(s) - } - - // Nonempty-only entry keeps the Empty branch's real next() out of - // this harness call graph; pattern algorithms remain assumed correct. - pub fn verifier_stub_str_nonempty_next_match<'a: 'a, 'b: 'b>( - s: &mut StrSearcher<'a, 'b>, - ) -> Option<(usize, usize)> { - assert!(!s.needle.is_empty()); - let front = match &s.searcher { - StrSearcherImpl::Byte(x) => x.position, - StrSearcherImpl::TwoWay(x) => x.position, - StrSearcherImpl::Empty(_) => unreachable!(), - }; - assert!(front <= s.haystack.len() && s.haystack.is_char_boundary(front)); - let result = - verifier_directional_match(s.haystack, front, s.haystack.len(), s.needle.len()); - let next = result.map_or(s.haystack.len(), |(_, b)| b); - match &mut s.searcher { - StrSearcherImpl::Byte(x) => x.position = next, - StrSearcherImpl::TwoWay(x) => x.position = next, - StrSearcherImpl::Empty(_) => unreachable!(), - } - result - } - - // Nonempty-only entry keeps the Empty branch's real next() out of - // this harness call graph; pattern algorithms remain assumed correct. - pub fn verifier_stub_str_nonempty_next_match_back<'a: 'a, 'b: 'b>( - s: &mut StrSearcher<'a, 'b>, - ) -> Option<(usize, usize)> { - assert!(!s.needle.is_empty()); - let back = match &s.searcher { - StrSearcherImpl::Byte(x) => x.end, - StrSearcherImpl::TwoWay(x) => x.end, - StrSearcherImpl::Empty(_) => unreachable!(), - }; - assert!(back <= s.haystack.len() && s.haystack.is_char_boundary(back)); - let result = verifier_directional_match(s.haystack, 0, back, s.needle.len()); - let next = result.map_or(0, |(a, _)| a); - match &mut s.searcher { - StrSearcherImpl::Byte(x) => x.end = next, - StrSearcherImpl::TwoWay(x) => x.end = next, - StrSearcherImpl::Empty(_) => unreachable!(), - } - result - } - - fn verifier_directional_match( - s: &str, - front: usize, - back: usize, - width: usize, - ) -> Option<(usize, usize)> { - if !kani::any::() { - return None; - } - let a: usize = kani::any(); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(front <= a && a <= back); - kani::cover(true, "C22-A35: verifier_directional_match assumption admitted"); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(width <= back - a); - kani::cover(true, "C22-A36: verifier_directional_match assumption admitted"); - let b = a + width; - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); - kani::cover(true, "C22-A37: verifier_directional_match assumption admitted"); - Some((a, b)) - } - - pub fn verifier_char_slice_position(s: &CharSliceSearcher<'_, '_>) -> (usize, usize) { - let front = s.0.char_indices.front_offset; - (front, front + s.0.char_indices.iter.iter.len()) - } - - fn verifier_stub_char_slice_match( - s: &mut CharSliceSearcher<'_, '_>, - reverse: bool, - ) -> Option<(usize, usize)> { - let (front, back) = verifier_char_slice_position(s); - let haystack = s.0.haystack; - assert!(front <= back && back <= haystack.len()); - assert!(haystack.is_char_boundary(front) && haystack.is_char_boundary(back)); - let result = if s.0.char_eq.is_empty() || !kani::any::() { - None - } else { - let a: usize = kani::any(); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(front <= a && a < back); - kani::cover(true, "C22-A38: verifier_stub_char_slice_match assumption admitted"); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(haystack.is_char_boundary(a)); - kani::cover(true, "C22-A39: verifier_stub_char_slice_match assumption admitted"); - // The real character width makes each result exactly one scalar, - // while the selected set element and equality are abstracted. - let width = super::super::validations::utf8_char_width(haystack.as_bytes()[a]); - assert!(width > 0 && width <= back - a); - let b = a + width; - assert!(haystack.is_char_boundary(b)); - Some((a, b)) - }; - let (new_front, new_back) = if reverse { - (front, result.map_or(front, |(a, _)| a)) - } else { - (result.map_or(back, |(_, b)| b), back) - }; - s.0.char_indices = super::super::CharIndices { - front_offset: new_front, - iter: haystack[new_front..new_back].chars(), - }; - result - } - - pub fn verifier_stub_char_slice_next_match<'a: 'a, 'b: 'b>( - s: &mut CharSliceSearcher<'a, 'b>, - ) -> Option<(usize, usize)> { - verifier_stub_char_slice_match(s, false) - } - - pub fn verifier_stub_char_slice_next_match_back<'a: 'a, 'b: 'b>( - s: &mut CharSliceSearcher<'a, 'b>, - ) -> Option<(usize, usize)> { - verifier_stub_char_slice_match(s, true) - } } From 4f6b418a1e258a0ca20e7f63bc943ac16093abdd Mon Sep 17 00:00:00 2001 From: v3risec Date: Wed, 18 Nov 2026 21:51:21 +0800 Subject: [PATCH 5/8] Remove Challenge 22 unwind annotations and as_slice stub --- library/core/src/array/iter/iter_inner.rs | 2 +- library/core/src/slice/iter.rs | 22 +--- library/core/src/str/iter.rs | 122 +++++++++++++++------- library/core/src/str/pattern.rs | 21 ++++ 4 files changed, 112 insertions(+), 55 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index ef4f3f3642fbb..3223aeeb56c2c 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -422,7 +422,6 @@ mod verify { // (at most 32 bits) and the callback count. Compare the actual implementation // directly with the model; neither implementation is stubbed in this proof. #[kani::proof] - #[kani::unwind(33)] fn check_consuming_fold_model() { let flags: [bool; 32] = kani::any(); let start: usize = kani::any(); @@ -438,6 +437,7 @@ mod verify { let actual: &mut PolymorphicIter<[MaybeUninit]> = &mut actual; let model: &mut PolymorphicIter<[MaybeUninit]> = &mut model; let observe = |(sum, trace, calls): (u8, u64, u8), flag: bool| { + assert!(calls < 32, "fold called the callback more than 32 times"); (sum + flag as u8, (trace << 1) | flag as u64, calls + 1) }; let expected = actual.fold((0, 0, 0), observe); diff --git a/library/core/src/slice/iter.rs b/library/core/src/slice/iter.rs index 211ad0144e8fb..1eca942a3c4ff 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -170,10 +170,10 @@ impl AsRef<[T]> for Iter<'_, T> { #[cfg(kani)] impl<'a, T> Iter<'a, T> { - /// The field updated by forward iteration of non-ZSTs. Exposing its address - /// lets a loop contract name it without relying on the layout of `Iter`. - pub(crate) fn kani_cursor_slot(&mut self) -> *mut NonNull { - &raw mut self.ptr + /// Expose the updated cursor as a raw pointer for Kani's loop write set. + pub(crate) fn kani_cursor_slot(&mut self) -> *mut *const T { + // NonNull is transparent over its pointer. + (&raw mut self.ptr).cast() } /// Clause-only copy: CBMC adds a write-set parameter to ordinary calls, @@ -190,20 +190,6 @@ impl<'a, T> Iter<'a, T> { let end = unsafe { &raw const (*this).end_or_len }; unsafe { (crate::intrinsics::read_via_copy(ptr), crate::intrinsics::read_via_copy(end)) } } - - /// A model of `as_slice` for byte-sized elements in a loop that havocs the - /// cursor. Rebuild it from the endpoint, which retains its points-to set. - pub(crate) fn kani_as_slice_from_end(&self) -> &'a [T] { - assert!(size_of::() == 1); - let ptr = unsafe { mem::transmute::, *const T>(self.ptr) }; - let end = self.end_or_len; - let len = (end as usize).wrapping_sub(ptr as usize); - assert!(len <= isize::MAX as usize); - let start = end.wrapping_sub(len); - assert!(start == ptr); - // SAFETY: The iterator's live range has the same pointer and length. - unsafe { &*crate::ptr::slice_from_raw_parts(start, len) } - } } #[unstable(feature = "ub_checks", issue = "none")] diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 98beb9a03d84b..b2bb38052cc5b 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -1686,23 +1686,33 @@ mod verify { unsafe extern "C" { fn malloc(size: usize) -> *mut u8; fn __CPROVER_havoc_object(p: *mut crate::ffi::c_void); + fn __CPROVER_havoc_slice(p: *mut u8, len: usize); } fn symbolic_text() -> &'static str { + symbolic_text_with_storage::() + } + + fn symbolic_text_with_storage() -> &'static str { let len: usize = kani::any(); kani::assume(len <= MAX_ALLOCATION_BYTES); - let p = if len == 0 { + let p = if len == 0 && !ALLOCATE_EMPTY { // An aligned nonnull dangling pointer is sufficient for an empty str. 1usize as *mut u8 } else { - let p = unsafe { malloc(len) }; + let storage_len = if ALLOCATE_EMPTY { len.max(1) } else { len }; + let p = unsafe { malloc(storage_len) }; kani::assume(!p.is_null()); // Initialize the shadow-memory state, then give every byte an // independent arbitrary initialized value. Neither builtin unwinds // a Rust loop over the symbolic length. unsafe { - p.write_bytes(0, len); - __CPROVER_havoc_object(p.cast()); + p.write_bytes(0, storage_len); + if ALLOCATE_EMPTY { + __CPROVER_havoc_slice(p, storage_len); + } else { + __CPROVER_havoc_object(p.cast()); + } } p }; @@ -1855,21 +1865,6 @@ mod verify { assert!(modeled_utf8_width(byte) == super::super::validations::utf8_char_width(byte)); } - #[kani::proof] - fn check_slice_view_model() { - let bytes = symbolic_text().as_bytes(); - let (start, end): (usize, usize) = kani::any(); - kani::assume(start <= end && end <= bytes.len()); - let iter = bytes[start..end].iter(); - let (actual, model) = (iter.as_slice(), iter.kani_as_slice_from_end()); - assert!(actual.as_ptr() == model.as_ptr() && actual.len() == model.len()); - let index: usize = kani::any(); - if index < actual.len() { - assert!(actual[index] == model[index]); - } - kani::cover(start < end && bytes.len() == MAX_ALLOCATION_BYTES, "largest input"); - } - // Read the representation as integers before requiring any typed bool value. pub(super) fn flags_valid(flags: *const [bool; 32]) -> bool { let bytes = unsafe { crate::intrinsics::read_via_copy(flags as *const [u8; 32]) }; @@ -1883,11 +1878,11 @@ mod verify { crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 )] #[kani::stub(crate::str::validations::utf8_char_width, modeled_utf8_width)] - #[kani::stub(crate::slice::Iter::as_slice, crate::slice::Iter::kani_as_slice_from_end)] fn harness_chars_advance_by() { // Every valid Chars state is a fresh iterator over its remaining valid // string. Both the length and requested character count are symbolic. - let text = symbolic_text(); + // Use one allocation path for the entry view as the loops abstract the cursor. + let text = symbolic_text_with_storage::(); let mut chars = text.chars(); let n: usize = kani::any(); // No request/count bound. let result = chars.advance_by(n); @@ -1929,7 +1924,6 @@ mod verify { crate::array::iter::iter_inner::PolymorphicIter::kani_fold_at_most_32 )] #[kani::stub(crate::str::validations::utf8_char_width, modeled_utf8_width)] - #[kani::stub(crate::slice::Iter::as_slice, crate::slice::Iter::kani_as_slice_from_end)] fn harness_chars_advance_by_empty() { let address: NonZero = kani::any(); let ptr = crate::ptr::without_provenance(address.get()); @@ -2423,7 +2417,6 @@ mod verify { } #[kani::proof] - #[kani::unwind(33)] fn check_sum_32_real() { check_sum_flags(); } @@ -2437,6 +2430,7 @@ mod verify { check_sum_flags(); } + const MAX_SEARCH_BYTES: usize = 16; const UTF8_PAD: usize = 4; fn verifier_utf8_valid(buf: &[u8; N], len: usize) -> bool { @@ -2494,20 +2488,68 @@ mod verify { } fn verifier_last_byte(needle: u8, bytes: &[u8]) -> Option { - let mut index = bytes.len(); - while index > 0 { - index -= 1; - if bytes[index] == needle { + verifier_find_byte(needle, bytes, true) + } + + fn verifier_first_byte(needle: u8, bytes: &[u8]) -> Option { + verifier_find_byte(needle, bytes, false) + } + + fn verifier_find_byte(needle: u8, bytes: &[u8], reverse: bool) -> Option { + assert!(bytes.len() <= MAX_SEARCH_BYTES); + for offset in 0..MAX_SEARCH_BYTES { + let index = if reverse { MAX_SEARCH_BYTES - 1 - offset } else { offset }; + if let Some(&byte) = bytes.get(index) + && byte == needle + { return Some(index); } } None } + fn verifier_slice_eq, U>(left: &[T], right: &[U]) -> bool { + if left.len() != right.len() { + return false; + } + assert!(left.len() <= MAX_SEARCH_BYTES); + for index in 0..MAX_SEARCH_BYTES { + if index < left.len() && left[index] != right[index] { + return false; + } + } + true + } + + fn fixed_char_search_step_budget() -> Option { + // Each continued step consumes at least one byte. A final empty probe can return. + Some(MAX_SEARCH_BYTES + 1) + } + + fn check_byte_slice_dependencies_at() { + let left: [u8; LEN] = kani::any(); + let right: [u8; LEN] = kani::any(); + let needle: u8 = kani::any(); + let actual_first = crate::slice::memchr::memchr(needle, &left); + assert_eq!(verifier_first_byte(needle, &left), actual_first); + assert_eq!(verifier_slice_eq(&left, &right), left[..] == right[..]); + } + + #[kani::proof] + fn check_byte_slice_dependencies() { + // Exercise the real dependency bodies with every concrete length in the domain. + const { assert!(MAX_SEARCH_BYTES == 16) } + macro_rules! check_lengths { + ($($len:literal),+ $(,)?) => { + $(check_byte_slice_dependencies_at::<$len>();)+ + }; + } + check_lengths!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + } + #[kani::proof] - #[kani::unwind(20)] fn harness_reverse_byte_model() { - let bytes: [u8; 16] = kani::any(); + let bytes: [u8; MAX_SEARCH_BYTES] = kani::any(); let len: usize = kani::any(); // INPUT-LENGTH: only prefixes of this initialized array are inputs. // INPUT DOMAIN: allocated prefix or index extent. @@ -2519,10 +2561,9 @@ mod verify { assert!(index < len); assert_eq!(bytes[index], needle); } - for index in 0..len { - if result.is_none_or(|last| last < index) { - assert_ne!(bytes[index], needle); - } + let index: usize = kani::any(); + if index < len && result.is_none_or(|last| last < index) { + assert_ne!(bytes[index], needle); } kani::cover(result.is_some(), "byte model: matching byte"); kani::cover(result.is_none(), "byte model: no match"); @@ -2532,7 +2573,7 @@ mod verify { } fn assert_char_searcher_direction(reverse: bool) { - let buf: [u8; 16 + UTF8_PAD] = kani::any(); + let buf: [u8; MAX_SEARCH_BYTES + UTF8_PAD] = kani::any(); let s = verifier_nondet_utf8(&buf); let (front, back) = any_window(s); let needle: char = kani::any(); @@ -2547,14 +2588,23 @@ mod verify { } #[kani::proof] - #[kani::unwind(18)] + #[kani::stub( + crate::str::pattern::verify::char_search_step_budget, + fixed_char_search_step_budget + )] + #[kani::stub(<[u8] as crate::cmp::PartialEq<[u8]>>::eq, verifier_slice_eq)] + #[kani::stub(crate::slice::memchr::memchr, verifier_first_byte)] fn harness_char_searcher_forward_refinement() { assert_char_searcher_direction(false); kani::cover(true, "C22-END: harness_char_searcher_forward_refinement completed"); } #[kani::proof] - #[kani::unwind(18)] + #[kani::stub( + crate::str::pattern::verify::char_search_step_budget, + fixed_char_search_step_budget + )] + #[kani::stub(<[u8] as crate::cmp::PartialEq<[u8]>>::eq, verifier_slice_eq)] #[kani::stub(crate::slice::memchr::memrchr, verifier_last_byte)] fn harness_char_searcher_reverse_refinement() { assert_char_searcher_direction(true); diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 00a083087f34b..be71a9ec6a02b 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -442,7 +442,11 @@ unsafe impl<'a> Searcher<'a> for CharSearcher<'a> { } #[inline] fn next_match(&mut self) -> Option<(usize, usize)> { + #[cfg(kani)] + let mut step_budget = verify::char_search_step_budget(); loop { + #[cfg(kani)] + verify::take_char_search_step(&mut step_budget); // get the haystack after the last character found let bytes = self.haystack.as_bytes().get(self.finger..self.finger_back)?; // the last byte of the utf8 encoded needle @@ -510,7 +514,11 @@ unsafe impl<'a> ReverseSearcher<'a> for CharSearcher<'a> { #[inline] fn next_match_back(&mut self) -> Option<(usize, usize)> { let haystack = self.haystack.as_bytes(); + #[cfg(kani)] + let mut step_budget = verify::char_search_step_budget(); loop { + #[cfg(kani)] + verify::take_char_search_step(&mut step_budget); // get the haystack up to but not including the last character searched let bytes = haystack.get(self.finger..self.finger_back)?; // the last byte of the utf8 encoded needle @@ -2105,6 +2113,19 @@ unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool { pub mod verify { use super::*; + // A regression can enable a checked local budget for the search loop. + #[inline(never)] + pub(in crate::str) fn char_search_step_budget() -> Option { + None + } + + pub(super) fn take_char_search_step(budget: &mut Option) { + if let Some(remaining) = budget { + assert!(*remaining > 0, "CharSearcher exceeded the regression step budget"); + *remaining -= 1; + } + } + #[cfg(all(kani, target_arch = "x86_64"))] // only called on x86 #[kani::proof] #[kani::unwind(4)] From b0c8a69a7d8524ecad99b3dd35ab6fc00feed50f Mon Sep 17 00:00:00 2001 From: v3risec Date: Thu, 19 Nov 2026 22:09:34 +0800 Subject: [PATCH 6/8] Verify Challenge 22 split transitions and chunk counts --- library/core/src/str/iter.rs | 208 ++++++++++++++++++++++++++--------- 1 file changed, 153 insertions(+), 55 deletions(-) diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index b2bb38052cc5b..fa7603e013601 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -75,14 +75,27 @@ impl<'a> Iterator for Chars<'a> { bytes_skipped += CHUNK_SIZE; let mut start_bytes = [false; CHUNK_SIZE]; - #[safety::loop_invariant(verify::flags_valid(&raw const start_bytes))] #[cfg_attr(kani, kani::loop_modifies(&raw mut start_bytes))] for i in 0..CHUNK_SIZE { + // Check the update and its frame at an arbitrary flag index. + #[cfg(kani)] + let (slot, expected) = { + let slot = kani::any::() as usize % CHUNK_SIZE; + (slot, if slot == i { chunk[i] & 0xc0 != 0x80 } else { start_bytes[slot] }) + }; start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); + #[cfg(kani)] + assert!(start_bytes[slot] == expected); } + // Each of the 32 iterations writes its flag and preserves the others. + #[cfg(kani)] + let expected_remainder = + remainder - verify::chunk_start_count(input, chunk, bytes_skipped, start_bytes); remainder -= start_bytes.into_iter().map(|i| i as u8).sum::() as usize; + #[cfg(kani)] + assert!(remainder == expected_remainder); } // SAFETY: The amount of bytes exists since we just iterated over them, @@ -1872,6 +1885,22 @@ mod verify { (lo | hi) & !0x0101_0101_0101_0101_0101_0101_0101_0101 == 0 } + pub(super) fn chunk_start_count( + input: &[u8], + chunk: &[u8; 32], + skipped: usize, + flags: [bool; 32], + ) -> usize { + assert!(32 <= skipped && skipped <= input.len()); + assert!(chunk.as_ptr() == input.as_ptr().wrapping_add(skipped - 32)); + // Each true flag has one set bit in its representation. + count_flag_words(unsafe { crate::intrinsics::transmute(flags) }) as usize + } + + fn count_flag_words(words: [u128; 2]) -> u32 { + words[0].count_ones() + words[1].count_ones() + } + #[kani::proof] #[kani::stub( crate::array::iter::iter_inner::PolymorphicIter::fold, @@ -2033,10 +2062,14 @@ mod verify { // prefix respectively. No double-ended matching semantics are required. struct ModelPattern; + type SearchMatch = Option<(usize, usize)>; + struct ModelSearcher<'a> { haystack: &'a str, front: usize, back: usize, + // Split harnesses choose the responses before calling the target. + match_plan: Option<&'a [SearchMatch]>, } // Issue #753: into_searcher must preserve the passed haystack by pointer AND @@ -2047,7 +2080,7 @@ mod verify { type Searcher<'a> = ModelSearcher<'a>; fn into_searcher(self, haystack: &str) -> ModelSearcher<'_> { - ModelSearcher { haystack, front: 0, back: haystack.len() } + ModelSearcher { haystack, front: 0, back: haystack.len(), match_plan: None } } } @@ -2072,6 +2105,27 @@ mod verify { (a, b) } + fn any_search_match(s: &str, front: usize, back: usize) -> SearchMatch { + kani::any::().then(|| any_match_range(s, front, back)) + } + + impl ModelSearcher<'_> { + fn choose_match(&mut self) -> SearchMatch { + let Some(plan) = self.match_plan else { + return any_search_match(self.haystack, self.front, self.back); + }; + let Some((&matched, rest)) = plan.split_first() else { + panic!("unexpected split search"); + }; + self.match_plan = Some(rest); + if let Some((a, b)) = matched { + assert!(self.front <= a && a <= b && b <= self.back); + assert!(self.haystack.is_char_boundary(a) && self.haystack.is_char_boundary(b)); + } + matched + } + } + // SAFETY: next emits adjacent, in-bounds UTF-8 ranges. The next_match // override summarizes zero or more skipped Rejects and one Match (or // exhaustion). Matching contents are intentionally over-approximated. @@ -2095,16 +2149,11 @@ mod verify { } } - fn next_match(&mut self) -> Option<(usize, usize)> { + fn next_match(&mut self) -> SearchMatch { assert!(type_invariant_searcher(self)); - if kani::any() { - let range = any_match_range(self.haystack, self.front, self.back); - self.front = range.1; - Some(range) - } else { - self.front = self.back; - None - } + let matched = self.choose_match(); + self.front = matched.map_or(self.back, |(_, end)| end); + matched } } @@ -2131,16 +2180,11 @@ mod verify { } } - fn next_match_back(&mut self) -> Option<(usize, usize)> { + fn next_match_back(&mut self) -> SearchMatch { assert!(type_invariant_searcher(self)); - if kani::any() { - let range = any_match_range(self.haystack, self.front, self.back); - self.back = range.0; - Some(range) - } else { - self.back = self.front; - None - } + let matched = self.choose_match(); + self.back = matched.map_or(self.front, |(start, _)| start); + matched } } @@ -2159,7 +2203,7 @@ mod verify { SplitInternal { start, end, - matcher: ModelSearcher { haystack: s, front, back }, + matcher: ModelSearcher { haystack: s, front, back, match_plan: None }, allow_trailing_empty: kani::any(), finished: kani::any(), } @@ -2170,23 +2214,25 @@ mod verify { assert!(same_slice(searcher.haystack(), s)); } - fn check_split_frame(s: &str, iter: &SplitInternal<'_, ModelPattern>) { - assert!(type_invariant_split(iter)); - assert!(same_slice(iter.matcher.haystack(), s)); - } - fn check_piece(s: &str, piece: &str) -> usize { let start = checked_offset(s, piece); check_range(s, piece, start, start + piece.len()); start } - // Closure of the safety invariant supports arbitrarily long iterator histories; - // exact matching contents, call counts and character ranks are not required. - fn check_split(s: &str, iter: &SplitInternal<'_, ModelPattern>, result: Option<&str>) { - check_split_frame(s, iter); - if let Some(part) = result { - check_piece(s, part); + // Closure of the safety invariant supports arbitrarily long iterator histories. + fn check_split( + s: &str, + iter: &SplitInternal<'_, ModelPattern>, + result: Option<&str>, + expected: SearchMatch, + ) { + assert!(type_invariant_split(iter)); + assert!(same_slice(iter.matcher.haystack(), s)); + assert!(iter.matcher.match_plan.is_some_and(<[_]>::is_empty)); + assert!(result.is_some() == expected.is_some()); + if let (Some(part), Some((start, end))) = (result, expected) { + check_range(s, part, start, end); } kani::cover(result.is_none(), "split: no remaining piece"); kani::cover(result.is_some_and(str::is_empty), "split: empty piece"); @@ -2209,7 +2255,7 @@ mod verify { fn harness_searcher_protocol() { let s = symbolic_text(); let (front, back) = any_window(s); - let mut searcher = ModelSearcher { haystack: s, front, back }; + let mut searcher = ModelSearcher { haystack: s, front, back, match_plan: None }; let reverse: bool = kani::any(); let result = if reverse { searcher.next_match_back() } else { searcher.next_match() }; check_searcher(s, &searcher); @@ -2273,48 +2319,101 @@ mod verify { fn harness_split_get_end() { let s = symbolic_text(); let mut iter = any_split(s); + iter.matcher.match_plan = Some(&[]); + let (start, end, trailing) = (iter.start, iter.end, iter.allow_trailing_empty); + let search_window = (iter.matcher.front, iter.matcher.back); + let expected = (!iter.finished && (trailing || start < end)).then_some((start, end)); let result = iter.get_end(); - check_split(s, &iter, result); + assert!(iter.finished); + assert!((iter.start, iter.end, iter.allow_trailing_empty) == (start, end, trailing)); + assert!((iter.matcher.front, iter.matcher.back) == search_window); + check_split(s, &iter, result, expected); } - #[kani::proof] - fn harness_split_next() { + fn check_split_step() -> Option { let s = symbolic_text(); let mut iter = any_split(s); - let result = iter.next(); - check_split(s, &iter, result); + let (start, end) = (iter.start, iter.end); + let (finished, trailing) = (iter.finished, iter.allow_trailing_empty); + let (front, back) = (iter.matcher.front, iter.matcher.back); + let first = if finished { None } else { any_search_match(s, front, back) }; + let split_at = |(a, b)| if INCLUSIVE { b } else { a }; + + // The reverse iterator suppresses one initial empty piece. A match + // that ends at the window end leaves the searcher bounded by its start. + let discarded = if BACK && !trailing { first.filter(|&(_, b)| b == end) } else { None }; + let second = discarded.and_then(|(a, _)| any_search_match(s, front, a)); + let steps = [first, second]; + let count = usize::from(!finished) + usize::from(discarded.is_some()); + iter.matcher.match_plan = Some(&steps[..count]); + + let piece_end = discarded.map_or(end, split_at); + let matched = if discarded.is_some() { second } else { first }; + let (expected, new_start, new_end) = match (finished, BACK, matched) { + (true, _, _) => (None, start, end), + (_, false, Some((a, b))) => (Some((start, split_at((a, b)))), b, end), + (_, true, Some((a, b))) => (Some((b, piece_end)), start, split_at((a, b))), + (_, _, None) => { + let keep_empty = trailing || discarded.is_some(); + ((keep_empty || start < piece_end).then_some((start, piece_end)), start, piece_end) + } + }; + let search_window = if finished { + (front, back) + } else if BACK { + (front, matched.map_or(front, |(a, _)| a)) + } else { + (matched.map_or(back, |(_, b)| b), back) + }; + + let result = match (BACK, INCLUSIVE) { + (false, false) => iter.next(), + (false, true) => iter.next_inclusive(), + (true, false) => iter.next_back(), + (true, true) => iter.next_back_inclusive(), + }; + assert!((iter.start, iter.end) == (new_start, new_end)); + assert!((iter.matcher.front, iter.matcher.back) == search_window); + assert!(iter.finished == (finished || matched.is_none())); + assert!(iter.allow_trailing_empty == (trailing || (BACK && !finished))); + check_split(s, &iter, result, expected); + discarded.is_some().then_some(second) + } + + #[kani::proof] + fn harness_split_next() { + let _ = check_split_step::(); } #[kani::proof] fn harness_split_next_inclusive() { - let s = symbolic_text(); - let mut iter = any_split(s); - let result = iter.next_inclusive(); - check_split(s, &iter, result); + let _ = check_split_step::(); + } + + fn check_split_back_step() { + let after_empty = check_split_step::(); + kani::cover(matches!(after_empty, Some(Some(_))), "matched after trailing empty"); + kani::cover(matches!(after_empty, Some(None)), "exhausted after trailing empty"); } #[kani::proof] fn harness_split_next_back() { - let s = symbolic_text(); - let mut iter = any_split(s); - let result = iter.next_back(); - check_split(s, &iter, result); + check_split_back_step::(); } #[kani::proof] fn harness_split_next_back_inclusive() { - let s = symbolic_text(); - let mut iter = any_split(s); - let result = iter.next_back_inclusive(); - check_split(s, &iter, result); + check_split_back_step::(); } #[kani::proof] fn harness_split_remainder() { let s = symbolic_text(); - let iter = any_split(s); + let mut iter = any_split(s); + iter.matcher.match_plan = Some(&[]); + let expected = (!iter.finished).then_some((iter.start, iter.end)); let result = iter.remainder(); - check_split(s, &iter, result); + check_split(s, &iter, result, expected); } #[kani::proof] @@ -2406,13 +2505,12 @@ mod verify { use super::super::super::pattern::verify::assert_char_searcher_step; use super::*; - use crate::mem; fn check_sum_flags() { let flags: [bool; 32] = kani::any(); - let words: [u128; 2] = unsafe { mem::transmute(flags) }; + let words = unsafe { crate::intrinsics::transmute(flags) }; let result = flags.into_iter().map(|flag| flag as u8).sum::(); - assert!(result as u32 == words[0].count_ones() + words[1].count_ones()); + assert!(result as u32 == count_flag_words(words)); kani::cover(result == 32, "all flags consumed after sum assertion"); } From 1ef00e2f8779ced7fa52caeb3a0261689154fc93 Mon Sep 17 00:00:00 2001 From: v3risec Date: Sat, 21 Nov 2026 18:47:54 +0800 Subject: [PATCH 7/8] Adapt Challenge 22 ModelPattern to unsafe Pattern --- library/core/src/str/iter.rs | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 7614ed0c3d362..3913196c1adde 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -2094,11 +2094,9 @@ mod verify { match_plan: Option<&'a [SearchMatch]>, } - // Issue #753: into_searcher must preserve the passed haystack by pointer AND - // length. The model and constructor proof uphold that requirement. Pattern is - // still a safe trait in this repository's pinned std, so this is a safe impl; - // change it to unsafe impl only when the upstream trait change is imported. - impl Pattern for ModelPattern { + // SAFETY: `into_searcher` stores the provided `haystack` slice, and + // `ModelSearcher::haystack` returns that same slice. + unsafe impl Pattern for ModelPattern { type Searcher<'a> = ModelSearcher<'a>; fn into_searcher(self, haystack: &str) -> ModelSearcher<'_> { From 238a686bdb61f9465a1011ce9a12d337c85c3c0a Mon Sep 17 00:00:00 2001 From: v3risec Date: Tue, 24 Nov 2026 17:29:47 +0800 Subject: [PATCH 8/8] Strengthen Challenge 22 string iterator proofs Check exact match results and searcher transitions. Carry byte classification through the chunk fill invariant and compare advance_by's decrement with an independent count. Check the local UTF-8 rule, simplify the consuming fold model, and prove the existing small_slice_eq contract. Add reachability covers without adding unwind bounds. --- library/core/src/array/iter/iter_inner.rs | 65 ++--- library/core/src/ops/index_range.rs | 16 +- library/core/src/str/iter.rs | 289 +++++++++++++--------- library/core/src/str/pattern.rs | 36 +-- 4 files changed, 215 insertions(+), 191 deletions(-) diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index 3223aeeb56c2c..8964c819cde52 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -191,10 +191,8 @@ impl Challenge22FoldElement for bool { impl PolymorphicIter<[MaybeUninit]> { /// Loop-free replacement used only by the Challenge 22 harnesses. /// - /// Unlike a non-consuming sum oracle, this advances `alive` before each - /// callback, just as `try_fold` does. Ordinary drop therefore sees exactly - /// the same remaining elements, including if a callback panics. - /// The assertions make uses outside the proved, fixed-size domain fail. + /// Advance `alive` before each callback, as `try_fold` does, so drop sees + /// the same remaining elements even if the callback panics. #[cfg(kani)] pub(crate) fn kani_fold_at_most_32(&mut self, init: B, mut f: impl FnMut(B, T) -> B) -> B { assert!(::admitted()); @@ -206,52 +204,22 @@ impl PolymorphicIter<[MaybeUninit]> { let data = self.data.as_ptr().cast::(); let mut accum = init; macro_rules! step { - ($k:expr) => { - if start + $k < end { - let idx = start + $k; - // A direct range assignment keeps the model's write target - // visible to CBMC's loop-frame inference. - self.alive = IndexRange::kani_from_bounds(idx + 1, end); - // SAFETY: The range update transfers the initialized - // element's ownership to the callback. - let ptr = data.wrapping_add(idx); - let elem = unsafe { crate::intrinsics::read_via_copy(ptr) }; - accum = f(accum, elem); - } + ($($k:literal),+ $(,)?) => { + $( + if start + $k < end { + let idx = start + $k; + self.alive = IndexRange::kani_from_bounds(idx + 1, end); + // SAFETY: This step consumes an initialized live element. + let elem = unsafe { crate::intrinsics::read_via_copy(data.wrapping_add(idx)) }; + accum = f(accum, elem); + } + )+ }; } - step!(0); - step!(1); - step!(2); - step!(3); - step!(4); - step!(5); - step!(6); - step!(7); - step!(8); - step!(9); - step!(10); - step!(11); - step!(12); - step!(13); - step!(14); - step!(15); - step!(16); - step!(17); - step!(18); - step!(19); - step!(20); - step!(21); - step!(22); - step!(23); - step!(24); - step!(25); - step!(26); - step!(27); - step!(28); - step!(29); - step!(30); - step!(31); + step!( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + ); accum } @@ -427,6 +395,7 @@ mod verify { let start: usize = kani::any(); let end: usize = kani::any(); kani::assume(start <= end && end <= 32); + kani::cover(start < end, "nonempty live range admitted"); // Same representation conversion as IntoIterator for arrays, without // array::map's unrelated construction and draining machinery. let data: [MaybeUninit; 32] = unsafe { crate::mem::transmute(flags) }; diff --git a/library/core/src/ops/index_range.rs b/library/core/src/ops/index_range.rs index b7f4781598c6b..619914f607dd7 100644 --- a/library/core/src/ops/index_range.rs +++ b/library/core/src/ops/index_range.rs @@ -40,13 +40,6 @@ impl IndexRange { IndexRange { start: 0, end } } - // The fold model uses this constructor inside a contracted loop. - #[cfg(kani)] - pub(crate) fn kani_from_bounds(start: usize, end: usize) -> Self { - assert!(start <= end); - Self { start, end } - } - #[inline] pub(crate) const fn start(&self) -> usize { self.start @@ -245,6 +238,15 @@ impl FusedIterator for IndexRange {} #[cfg(kani)] mod verify { use super::*; + + impl IndexRange { + // A direct range assignment keeps the fold model's write set explicit. + pub(crate) fn kani_from_bounds(start: usize, end: usize) -> Self { + assert!(start <= end); + Self { start, end } + } + } + #[kani::proof_for_contract(IndexRange::new_unchecked)] fn proof_for_index_range_new_unchecked() { let start = kani::any::(); diff --git a/library/core/src/str/iter.rs b/library/core/src/str/iter.rs index 3913196c1adde..94d3b8407b53f 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -57,9 +57,7 @@ impl<'a> Iterator for Chars<'a> { #[cfg(kani)] let input = self.iter.as_slice(); #[cfg(kani)] - let cursor = self.iter.kani_cursor_slot(); - #[cfg(kani)] - let requested = remainder; + let (cursor, requested) = (self.iter.kani_cursor_slot(), remainder); if remainder >= CHUNK_SIZE { let mut chunks = self.iter.as_slice().as_chunks::().0.iter(); @@ -75,24 +73,29 @@ impl<'a> Iterator for Chars<'a> { bytes_skipped += CHUNK_SIZE; let mut start_bytes = [false; CHUNK_SIZE]; - #[safety::loop_invariant(verify::flags_valid(&raw const start_bytes))] + + #[cfg(kani)] + let (slot, is_start) = { + let slot = kani::any::() as usize % CHUNK_SIZE; + (slot, chunk[slot] & 0xc0 != 0x80) + }; + #[cfg_attr(kani, kani::loop_invariant( + verify::chunk_flags_inv(&raw const start_bytes, slot, is_start, kani::index) + ))] #[cfg_attr(kani, kani::loop_modifies(&raw mut start_bytes))] for i in 0..CHUNK_SIZE { - // Check the update and its frame at an arbitrary flag index. - #[cfg(kani)] - let (slot, expected) = { - let slot = kani::any::() as usize % CHUNK_SIZE; - (slot, if slot == i { chunk[i] & 0xc0 != 0x80 } else { start_bytes[slot] }) - }; start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); - #[cfg(kani)] - assert!(start_bytes[slot] == expected); } - // Each of the 32 iterations writes its flag and preserves the others. #[cfg(kani)] - let expected_remainder = - remainder - verify::chunk_start_count(input, chunk, bytes_skipped, start_bytes); + let expected_remainder = remainder + - verify::chunk_start_count( + input, + chunk, + bytes_skipped, + start_bytes, + (slot, is_start), + ); remainder -= start_bytes.into_iter().map(|i| i as u8).sum::() as usize; #[cfg(kani)] assert!(remainder == expected_remainder); @@ -1731,13 +1734,15 @@ mod verify { fn symbolic_text_with_storage() -> &'static str { let len: usize = kani::any(); kani::assume(len <= MAX_ALLOCATION_BYTES); + kani::cover(len == MAX_ALLOCATION_BYTES, "maximum symbolic length admitted"); let p = if len == 0 && !ALLOCATE_EMPTY { - // An aligned nonnull dangling pointer is sufficient for an empty str. - 1usize as *mut u8 + let address: NonZero = kani::any(); + crate::ptr::without_provenance_mut(address.get()) } else { let storage_len = if ALLOCATE_EMPTY { len.max(1) } else { len }; let p = unsafe { malloc(storage_len) }; kani::assume(!p.is_null()); + kani::cover(true, "symbolic allocation succeeds"); // Initialize the shadow-memory state, then give every byte an // independent arbitrary initialized value. Neither builtin unwinds // a Rust loop over the symbolic length. @@ -1752,17 +1757,16 @@ mod verify { p }; let bytes = unsafe { slice::from_raw_parts(p, len) }; - // A valid nonempty input begins at a lead byte. This also justifies - // str indexing's optimized check when both endpoints are zero. + // Challenge 22 assumes valid UTF-8. Every nonempty input in that + // domain starts with a complete scalar followed by a boundary. kani::assume(bytes.is_empty() || utf8_sequence_width(bytes, 0) > 0); - // The C allocation supplies symbolic bytes. UTF-8 is assumed locally - // where bytes are consumed; this overapproximates all valid strings. + kani::cover(!bytes.is_empty(), "nonempty UTF-8 prefix admitted"); + // The model instantiates UTF-8 facts locally on the symbolic bytes. + // This condition admits every valid string, and also malformed suffixes. unsafe { from_utf8_unchecked(bytes) } } - // At harness exit these goals follow ALL input assumptions and target checks. - // Keeping them out of allocation and loop models avoids repeated cover goals - // inside induction. Covers check feasibility, not the truth of an assumption. + // These witnesses follow the target call and its postcondition checks. fn cover_completed_text(s: &str) { kani::cover(s.is_empty(), "completed on empty input"); kani::cover(s.len() > 4096, "completed beyond former input bounds"); @@ -1807,8 +1811,7 @@ mod verify { fn any_window(s: &str) -> (usize, usize) { let (a, b): (usize, usize) = (kani::any(), kani::any()); - kani::assume(a <= b && b <= s.len()); - kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); + kani::assume(a <= b && b <= s.len() && s.is_char_boundary(a) && s.is_char_boundary(b)); kani::cover(true, "a boundary window exists"); (a, b) } @@ -1886,10 +1889,8 @@ mod verify { // On valid UTF-8, any non-continuation byte begins a complete // scalar. This fact concerns the original bytes, even if the // algorithm supplies an unexpected offset. - let width = modeled_utf8_width(lead); - kani::assume(width > 0 && width <= input.len() - offset); - let next = offset + width; - kani::assume(next == input.len() || !utf8_is_cont_byte(input[next])); + // The symbolic-length harness covers this path, which the empty-input harness skips. + kani::assume(utf8_sequence_width(input, offset) > 0); } } @@ -1898,13 +1899,50 @@ mod verify { fn check_utf8_width_model() { let byte: u8 = kani::any(); assert!(modeled_utf8_width(byte) == super::super::validations::utf8_char_width(byte)); + kani::cover(byte == 0xf5, "width model checked an invalid lead byte"); } - // Read the representation as integers before requiring any typed bool value. - pub(super) fn flags_valid(flags: *const [bool; 32]) -> bool { - let bytes = unsafe { crate::intrinsics::read_via_copy(flags as *const [u8; 32]) }; + // A scalar and the first byte after it suffice to check the local rule. + #[kani::proof] + fn check_utf8_sequence_model() { + let storage: [u8; 5] = kani::any(); + let (width, len): (usize, usize) = (kani::any(), kani::any()); + kani::assume(1 <= width && width <= 4 && width <= len && len <= storage.len()); + kani::cover(true, "scalar window admitted"); + let bytes = &storage[..len]; + let scalar = char::from_u32(scalar_bits(bytes, 0, width)).is_some_and(|ch| { + let mut encoded = [0; 4]; + let encoded_len = ch.encode_utf8(&mut encoded).len(); + encoded_len == width + && encoded[0] == bytes[0] + && (width < 2 || encoded[1] == bytes[1]) + && (width < 3 || encoded[2] == bytes[2]) + && (width < 4 || encoded[3] == bytes[3]) + }); + let boundary = width == len || bytes[width] & 0xc0 != 0x80; + let modeled = utf8_sequence_width(bytes, 0); + assert!(modeled <= 4 && modeled <= len); + let admitted = modeled == width; + assert!(admitted == (scalar && boundary)); + kani::cover(admitted && width == 1, "UTF-8 sequence: one byte"); + kani::cover(admitted && width == 2, "UTF-8 sequence: two bytes"); + kani::cover(admitted && width == 3, "UTF-8 sequence: three bytes"); + kani::cover(admitted && width == 4, "UTF-8 sequence: four bytes"); + kani::cover(scalar && !boundary, "UTF-8 sequence: stray continuation after scalar"); + kani::cover(len < modeled_utf8_width(bytes[0]), "UTF-8 sequence: truncated scalar"); + } + + pub(super) fn chunk_flags_inv( + flags: *const [bool; 32], + slot: usize, + is_start: bool, + filled: usize, + ) -> bool { + // Check the representations before reading any havoced value as bool. + let bytes = unsafe { crate::intrinsics::read_via_copy(flags.cast::<[u8; 32]>()) }; let [lo, hi]: [u128; 2] = unsafe { crate::intrinsics::transmute(bytes) }; (lo | hi) & !0x0101_0101_0101_0101_0101_0101_0101_0101 == 0 + && bytes[slot] == u8::from(slot < filled && is_start) } pub(super) fn chunk_start_count( @@ -1912,11 +1950,20 @@ mod verify { chunk: &[u8; 32], skipped: usize, flags: [bool; 32], + (slot, is_start): (usize, bool), ) -> usize { assert!(32 <= skipped && skipped <= input.len()); assert!(chunk.as_ptr() == input.as_ptr().wrapping_add(skipped - 32)); - // Each true flag has one set bit in its representation. - count_flag_words(unsafe { crate::intrinsics::transmute(flags) }) as usize + // The arbitrary slot relates all flags to the original chunk at loop exit. + assert!(flags[slot] == is_start); + // Sum the flags directly, independently of the iterator pipeline. + macro_rules! count { + ($($i:literal),+ $(,)?) => { 0u8 $(+ flags[$i] as u8)+ }; + } + usize::from(count!( + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, + )) } fn count_flag_words(words: [u128; 2]) -> u32 { @@ -1948,15 +1995,12 @@ mod verify { assert!(missing.get() <= n && n - missing.get() <= skipped); } } + kani::cover(n == 0 && text.len() == MAX_ALLOCATION_BYTES, "maximum representable string"); + kani::cover(result.is_ok() && n == 33 && text.len() > 4096, "large input and chunk path"); + kani::cover(result.is_ok() && n == 1, "scalar path"); kani::cover( - result.is_ok() && n > 64 && text.len() == MAX_ALLOCATION_BYTES, - "maximum representable string and chunk path", - ); - kani::cover(result.is_err() && n > 64, "insufficient characters"); - kani::cover(result.is_ok() && n > 0 && n < 32, "scalar path"); - kani::cover( - n == usize::MAX && text.len() > 4096 && result.is_err(), - "maximum request remains admitted after UTF-8 assumptions", + n == usize::MAX && !text.is_empty() && result.is_err(), + "maximum request on nonempty input", ); kani::cover( text.len() == 4 @@ -1990,7 +2034,7 @@ mod verify { // Chars decoding and view proofs. - // Reference scalar from the payload bits of a previously validated sequence. + // Extract payload bits from a window of known width. Validity is checked separately. fn scalar_bits(bytes: &[u8], start: usize, width: usize) -> u32 { let lead = u32::from(bytes[start]); let tail = |i| u32::from(bytes[start + i] & 0x3f); @@ -2013,6 +2057,7 @@ mod verify { // The decoder and its unsafe reads are executed without a stub. let width = utf8_sequence_width(bytes, a); kani::assume(width > 0 && width <= b - a); + kani::cover(true, "complete leading scalar admitted"); width } else { 0 @@ -2044,8 +2089,10 @@ mod verify { // This symbolic width is an input witness, not a decoder result. let width: usize = kani::any(); kani::assume(1 <= width && width <= 4 && width <= b - a); + kani::cover(true, "trailing scalar width admitted"); let lead = b - width; kani::assume(utf8_sequence_width(bytes, lead) == width); + kani::cover(true, "complete trailing scalar admitted"); width } else { 0 @@ -2090,7 +2137,7 @@ mod verify { haystack: &'a str, front: usize, back: usize, - // Split harnesses choose the responses before calling the target. + // Consumer harnesses choose the responses before calling the target. match_plan: Option<&'a [SearchMatch]>, } @@ -2114,14 +2161,11 @@ mod verify { fn any_match_range(s: &str, front: usize, back: usize) -> (usize, usize) { let a: usize = kani::any(); let b: usize = kani::any(); - // These are Searcher guarantees imported under assumption 2, not - // properties of SplitInternal assumed after its execution. - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(front <= a && a <= b && b <= back); - kani::cover(true, "C22-A08: any_match_range assumption admitted"); - // CHALLENGE 22 assumption 2: dependency Searcher range guarantee. - kani::assume(s.is_char_boundary(a) && s.is_char_boundary(b)); - kani::cover(true, "C22-A09: any_match_range assumption admitted"); + // Challenge 22 assumption 2 gives this guarantee for search results. + kani::assume( + front <= a && a <= b && b <= back && s.is_char_boundary(a) && s.is_char_boundary(b), + ); + kani::cover(true, "valid search interval admitted"); (a, b) } @@ -2135,7 +2179,7 @@ mod verify { return any_search_match(self.haystack, self.front, self.back); }; let Some((&matched, rest)) = plan.split_first() else { - panic!("unexpected split search"); + panic!("unexpected search call"); }; self.match_plan = Some(rest); if let Some((a, b)) = matched { @@ -2234,12 +2278,6 @@ mod verify { assert!(same_slice(searcher.haystack(), s)); } - fn check_piece(s: &str, piece: &str) -> usize { - let start = checked_offset(s, piece); - check_range(s, piece, start, start + piece.len()); - start - } - // Closure of the safety invariant supports arbitrarily long iterator histories. fn check_split( s: &str, @@ -2260,42 +2298,58 @@ mod verify { cover_completed_text(s); } - fn check_match(s: &str, searcher: &ModelSearcher<'_>, result: Option<(usize, &str)>) { + fn check_search_step( + s: &str, + searcher: &ModelSearcher<'_>, + (front, back): (usize, usize), + reverse: bool, + matched: SearchMatch, + ) { check_searcher(s, searcher); - if let Some((index, part)) = result { - assert!(index == check_piece(s, part)); + if let Some((a, b)) = matched { + assert!(front <= a && a <= b && b <= back); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); } - kani::cover(result.is_none(), "matches: exhausted"); - kani::cover(result.is_some_and(|(_, part)| part.is_empty()), "matches: empty match"); - kani::cover(result.is_some_and(|(_, part)| part.len() > 4096), "matches: large match"); - cover_completed_text(s); + let expected = if reverse { + (front, matched.map_or(front, |(a, _)| a)) + } else { + (matched.map_or(back, |(_, b)| b), back) + }; + assert!((searcher.front, searcher.back) == expected); } #[kani::proof] fn harness_searcher_protocol() { + use super::super::pattern::SearchStep; + let s = symbolic_text(); let (front, back) = any_window(s); let mut searcher = ModelSearcher { haystack: s, front, back, match_plan: None }; let reverse: bool = kani::any(); - let result = if reverse { searcher.next_match_back() } else { searcher.next_match() }; - check_searcher(s, &searcher); - if let Some((a, b)) = result { - assert!(front <= a && a <= b && b <= back); - assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); - if reverse { - assert!(searcher.back == a); - } else { - assert!(searcher.front == b); - } - kani::cover(a == b, "protocol: zero-width match"); - kani::cover(b - a > 4, "protocol: multiple-character match"); - } else { - assert!(searcher.front == searcher.back); - } - if reverse { - assert!(searcher.front == front); + if kani::any() { + let step = if reverse { searcher.next_back() } else { searcher.next() }; + let range = match step { + SearchStep::Match(a, b) | SearchStep::Reject(a, b) => { + assert!(if reverse { b == back } else { a == front }); + Some((a, b)) + } + SearchStep::Done => { + assert!(front == back); + None + } + }; + check_search_step(s, &searcher, (front, back), reverse, range); + kani::cover(matches!(step, SearchStep::Match(..)), "protocol: matching step"); + kani::cover(matches!(step, SearchStep::Reject(..)), "protocol: rejecting step"); + kani::cover(matches!(step, SearchStep::Done), "protocol: exhausted step"); + kani::cover(range.is_some_and(|(a, b)| a == b), "protocol: zero-width step"); } else { - assert!(searcher.back == back); + let result = if reverse { searcher.next_match_back() } else { searcher.next_match() }; + check_search_step(s, &searcher, (front, back), reverse, result); + if let Some((a, b)) = result { + kani::cover(a == b, "protocol: zero-width match"); + kani::cover(b - a > 4, "protocol: multiple-character match"); + } } cover_completed_text(s); } @@ -2436,36 +2490,52 @@ mod verify { check_split(s, &iter, result, expected); } + fn check_match_step() { + let s = symbolic_text(); + let (front, back) = any_window(s); + let expected = any_search_match(s, front, back); + let plan = [expected]; + let searcher = ModelSearcher { haystack: s, front, back, match_plan: Some(&plan) }; + let (part, searcher) = if INDEXED { + let mut iter = MatchIndicesInternal::(searcher); + let result = if BACK { iter.next_back() } else { iter.next() }; + assert!(result.map(|(index, _)| index) == expected.map(|(start, _)| start)); + (result.map(|(_, part)| part), iter.0) + } else { + let mut iter = MatchesInternal::(searcher); + let result = if BACK { iter.next_back() } else { iter.next() }; + (result, iter.0) + }; + check_search_step(s, &searcher, (front, back), BACK, expected); + assert!(searcher.match_plan.is_some_and(<[_]>::is_empty)); + assert!(part.is_some() == expected.is_some()); + if let (Some(part), Some((a, b))) = (part, expected) { + check_range(s, part, a, b); + } + kani::cover(part.is_none(), "matches: exhausted"); + kani::cover(part.is_some_and(str::is_empty), "matches: empty match"); + kani::cover(part.is_some_and(|part| part.len() > 4096), "matches: large match"); + cover_completed_text(s); + } + #[kani::proof] fn harness_match_indices_next() { - let s = symbolic_text(); - let mut iter = MatchIndicesInternal::(any_split(s).matcher); - let result = iter.next(); - check_match(s, &iter.0, result); + check_match_step::(); } #[kani::proof] fn harness_match_indices_next_back() { - let s = symbolic_text(); - let mut iter = MatchIndicesInternal::(any_split(s).matcher); - let result = iter.next_back(); - check_match(s, &iter.0, result); + check_match_step::(); } #[kani::proof] fn harness_matches_next() { - let s = symbolic_text(); - let mut iter = MatchesInternal::(any_split(s).matcher); - let result = iter.next().map(|part| (checked_offset(s, part), part)); - check_match(s, &iter.0, result); + check_match_step::(); } #[kani::proof] fn harness_matches_next_back() { - let s = symbolic_text(); - let mut iter = MatchesInternal::(any_split(s).matcher); - let result = iter.next_back().map(|part| (checked_offset(s, part), part)); - check_match(s, &iter.0, result); + check_match_step::(); } #[kani::proof] @@ -2506,6 +2576,7 @@ mod verify { // inside a scalar. No character-boundary premise belongs here. let (start, end): (usize, usize) = (kani::any(), kani::any()); kani::assume(start <= end && end <= s.len()); + kani::cover(start < end, "nonempty byte window admitted"); let window = unsafe { s.as_bytes().get_unchecked(start..end) }; let mut iter = Bytes(window.iter().copied()); let index: usize = kani::any(); @@ -2595,12 +2666,10 @@ mod verify { fn verifier_nondet_utf8(buf: &[u8; N]) -> &str { let len: usize = kani::any(); - // INPUT DOMAIN: allocated prefix or index extent. kani::assume(len <= N - UTF8_PAD); - kani::cover(true, "C22-A01: verifier_nondet_utf8 assumption admitted"); - // CHALLENGE 22 assumption 4: valid UTF-8 input. + kani::cover(len == N - UTF8_PAD, "full auxiliary input length admitted"); kani::assume(verifier_utf8_valid(buf, len)); - kani::cover(true, "C22-A02: verifier_nondet_utf8 assumption admitted"); + kani::cover(len > 0, "nonempty valid auxiliary string admitted"); // SAFETY: verifier_utf8_valid characterizes valid UTF-8 exactly. unsafe { from_utf8_unchecked(&buf[..len]) } } @@ -2640,7 +2709,7 @@ mod verify { } fn fixed_char_search_step_budget() -> Option { - // Each continued step consumes at least one byte. A final empty probe can return. + // Each continued step consumes a byte. Allow one final exhausted probe. Some(MAX_SEARCH_BYTES + 1) } @@ -2663,16 +2732,15 @@ mod verify { }; } check_lengths!(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16); + kani::cover(true, "checked every auxiliary byte slice length"); } #[kani::proof] fn harness_reverse_byte_model() { let bytes: [u8; MAX_SEARCH_BYTES] = kani::any(); let len: usize = kani::any(); - // INPUT-LENGTH: only prefixes of this initialized array are inputs. - // INPUT DOMAIN: allocated prefix or index extent. kani::assume(len <= bytes.len()); - kani::cover(true, "C22-A23: harness_reverse_byte_model assumption admitted"); + kani::cover(len == bytes.len(), "full byte model input length admitted"); let needle: u8 = kani::any(); let result = verifier_last_byte(needle, &bytes[..len]); if let Some(index) = result { @@ -2687,7 +2755,6 @@ mod verify { kani::cover(result.is_none(), "byte model: no match"); kani::cover(len > 0 && result == Some(len - 1), "byte model: final byte matches"); kani::cover(len == 0 && result.is_none(), "byte model: empty prefix"); - kani::cover(true, "C22-END: harness_reverse_byte_model completed"); } fn assert_char_searcher_direction(reverse: bool) { @@ -2714,7 +2781,6 @@ mod verify { #[kani::stub(crate::slice::memchr::memchr, verifier_first_byte)] fn harness_char_searcher_forward_refinement() { assert_char_searcher_direction(false); - kani::cover(true, "C22-END: harness_char_searcher_forward_refinement completed"); } #[kani::proof] @@ -2726,7 +2792,6 @@ mod verify { #[kani::stub(crate::slice::memchr::memrchr, verifier_last_byte)] fn harness_char_searcher_reverse_refinement() { assert_char_searcher_direction(true); - kani::cover(true, "C22-END: harness_char_searcher_reverse_refinement completed"); } } } diff --git a/library/core/src/str/pattern.rs b/library/core/src/str/pattern.rs index 01939f1a6eaf1..9b10719bcb66f 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -2160,7 +2160,7 @@ unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool { pub mod verify { use super::*; - // A regression can enable a checked local budget for the search loop. + // An auxiliary regression can enable a checked local search budget. #[inline(never)] pub(in crate::str) fn char_search_step_budget() -> Option { None @@ -2173,43 +2173,31 @@ pub mod verify { } } - #[cfg(all(kani, target_arch = "x86_64"))] // only called on x86 - #[kani::proof] + #[cfg(target_arch = "x86_64")] + #[kani::proof_for_contract(small_slice_eq)] #[kani::unwind(4)] pub fn check_small_slice_eq() { - // TODO: ARR_SIZE can be `std::usize::MAX` with cbmc argument - // `--arrays-uf-always` + // This dependency regression uses bounded backing arrays. const ARR_SIZE: usize = 1000; let x: [u8; ARR_SIZE] = kani::any(); let y: [u8; ARR_SIZE] = kani::any(); let xs = kani::slice::any_slice_of_array(&x); let ys = kani::slice::any_slice_of_array(&y); - // UNSAFE PRECONDITION: required by the operation under test. - kani::assume(xs.len() == ys.len()); - kani::cover(true, "C22-A26: check_small_slice_eq assumption admitted"); unsafe { small_slice_eq(xs, ys); } - kani::cover(true, "C22-END: check_small_slice_eq completed"); + kani::cover(xs.len() < 4, "short slice comparison completed"); + kani::cover(xs.len() >= 4, "word comparison completed"); } - #[cfg(all(kani, target_arch = "x86_64"))] // only called on x86 + #[cfg(target_arch = "x86_64")] #[kani::proof] #[kani::unwind(4)] pub fn check_small_slice_eq_empty() { - // Zero-length raw slices still require non-null pointers. Make the - // former any_where filters explicit so each has a coverage witness. - let address_x: usize = kani::any(); - // UNSAFE PRECONDITION: required by the operation under test. - kani::assume(address_x != 0); - kani::cover(true, "C22-A27: check_small_slice_eq_empty assumption admitted"); - let address_y: usize = kani::any(); - // UNSAFE PRECONDITION: required by the operation under test. - kani::assume(address_y != 0); - kani::cover(true, "C22-A28: check_small_slice_eq_empty assumption admitted"); - let ptr_x = address_x as *const u8; - let ptr_y = address_y as *const u8; - // u8 has alignment one; prove this instead of filtering inputs. + use crate::num::NonZero; + + let ptr_x = crate::ptr::without_provenance::(kani::any::>().get()); + let ptr_y = crate::ptr::without_provenance::(kani::any::>().get()); assert!(ptr_x.is_aligned()); assert!(ptr_y.is_aligned()); assert_eq!( @@ -2221,7 +2209,7 @@ pub mod verify { }, true ); - kani::cover(true, "C22-END: check_small_slice_eq_empty completed"); + kani::cover(true, "empty slice comparison completed"); } fn char_searcher_invariant(searcher: &CharSearcher<'_>) -> bool {