diff --git a/library/core/src/array/iter/iter_inner.rs b/library/core/src/array/iter/iter_inner.rs index d93cbf32c0162..8964c819cde52 100644 --- a/library/core/src/array/iter/iter_inner.rs +++ b/library/core/src/array/iter/iter_inner.rs @@ -167,7 +167,62 @@ 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. + /// + /// 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()); + 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: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, 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 + } + #[inline] pub(super) fn as_slice(&self) -> &[T] { // SAFETY: We know that all elements within `alive` are properly initialized. @@ -324,3 +379,46 @@ 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] + 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); + 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) }; + 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| { + 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); + 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/ops/index_range.rs b/library/core/src/ops/index_range.rs index 1fc721b3a9e2e..619914f607dd7 100644 --- a/library/core/src/ops/index_range.rs +++ b/library/core/src/ops/index_range.rs @@ -238,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/slice/iter.rs b/library/core/src/slice/iter.rs index 9e5a8338b8afc..1eca942a3c4ff 100644 --- a/library/core/src/slice/iter.rs +++ b/library/core/src/slice/iter.rs @@ -168,6 +168,30 @@ impl AsRef<[T]> for Iter<'_, T> { } } +#[cfg(kani)] +impl<'a, T> Iter<'a, T> { + /// 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, + /// 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 } 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)) } + } +} + #[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 cc7b0e6324fbc..94d3b8407b53f 100644 --- a/library/core/src/str/iter.rs +++ b/library/core/src/str/iter.rs @@ -54,11 +54,19 @@ 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, requested) = (self.iter.kani_cursor_slot(), 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, input, requested, remainder, + ))] while remainder > CHUNK_SIZE && let Some(chunk) = chunks.next() { @@ -66,11 +74,31 @@ impl<'a> Iterator for Chars<'a> { let mut start_bytes = [false; CHUNK_SIZE]; + #[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 { start_bytes[i] = !super::validations::utf8_is_cont_byte(chunk[i]); } + #[cfg(kani)] + 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); } // SAFETY: The amount of bytes exists since we just iterated over them, @@ -78,6 +106,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, input, bytes_skipped, false, + ))] + #[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) { @@ -88,9 +120,16 @@ impl<'a> Iterator for Chars<'a> { } } + #[safety::loop_invariant( + remainder <= requested + && verify::bytes_inv(&raw const self.iter, input, requested - remainder, true) + )] + #[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) @@ -1663,3 +1702,1096 @@ macro_rules! escape_types_impls { } escape_types_impls!(EscapeDebug, EscapeDefault, EscapeUnicode); + +#[cfg(kani)] +#[unstable(feature = "kani", issue = "none")] +mod verify { + //! 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::*; + + // 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 __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); + kani::cover(len == MAX_ALLOCATION_BYTES, "maximum symbolic length admitted"); + let p = if len == 0 && !ALLOCATE_EMPTY { + 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. + unsafe { + p.write_bytes(0, storage_len); + if ALLOCATE_EMPTY { + __CPROVER_havoc_slice(p, storage_len); + } else { + __CPROVER_havoc_object(p.cast()); + } + } + p + }; + let bytes = unsafe { slice::from_raw_parts(p, len) }; + // 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); + 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) } + } + + // 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"); + } + + fn modeled_utf8_width(byte: u8) -> usize { + match byte { + 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), + } + } + + // 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 + } + } + + fn any_window(s: &str) -> (usize, usize) { + let (a, b): (usize, usize) = (kani::any(), kani::any()); + 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) + } + + // 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); + } + + // Loop invariants and dependency models for Chars::advance_by. + + 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 + } + + // 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. + // The symbolic-length harness covers this path, which the empty-input harness skips. + kani::assume(utf8_sequence_width(input, offset) > 0); + } + } + + // 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)); + kani::cover(byte == 0xf5, "width model checked an invalid lead byte"); + } + + // 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( + input: &[u8], + 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)); + // 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 { + words[0].count_ones() + words[1].count_ones() + } + + #[kani::proof] + #[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)] + 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. + // 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); + 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(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( + n == usize::MAX && !text.is_empty() && result.is_err(), + "maximum request on nonempty input", + ); + kani::cover( + 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", + ); + } + + // 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( + 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)] + fn harness_chars_advance_by_empty() { + 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()); + 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"); + } + + // Chars decoding and view proofs. + + // 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); + 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); + 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. + let width = utf8_sequence_width(bytes, a); + kani::assume(width > 0 && width <= b - a); + kani::cover(true, "complete leading scalar admitted"); + 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()); + 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"); + kani::cover(ch.len_utf8() == 4, "four-byte scalar"); + } else { + assert!(a == b); + } + cover_completed_text(s); + kani::cover(a > 4096 && b - a > 4096, "completed on a large interior window"); + } + + #[kani::proof] + fn harness_chars_next_back() { + let s = symbolic_text(); + let (a, b) = any_window(s); + 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); + 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 + }; + 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() == 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"); + kani::cover(ch.len_utf8() == 4, "four-byte scalar"); + } else { + assert!(a == b); + } + cover_completed_text(s); + kani::cover(a > 4096 && b - a > 4096, "completed on a large interior window"); + } + + #[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(a > 4096 && b - a > 4096, "completed on a large interior window"); + } + + // 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; + + type SearchMatch = Option<(usize, usize)>; + + struct ModelSearcher<'a> { + haystack: &'a str, + front: usize, + back: usize, + // Consumer harnesses choose the responses before calling the target. + match_plan: Option<&'a [SearchMatch]>, + } + + // 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<'_> { + ModelSearcher { haystack, front: 0, back: haystack.len(), match_plan: None } + } + } + + 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(); + // 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) + } + + 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 search call"); + }; + 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. + 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) -> SearchMatch { + assert!(type_invariant_searcher(self)); + let matched = self.choose_match(); + self.front = matched.map_or(self.back, |(_, end)| end); + matched + } + } + + // 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) -> SearchMatch { + assert!(type_invariant_searcher(self)); + let matched = self.choose_match(); + self.back = matched.map_or(self.front, |(start, _)| start); + matched + } + } + + 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) = any_window(s); + let (front, back) = any_match_range(s, start, end); + SplitInternal { + start, + end, + matcher: ModelSearcher { haystack: s, front, back, match_plan: None }, + allow_trailing_empty: kani::any(), + finished: kani::any(), + } + } + + fn check_searcher(s: &str, searcher: &ModelSearcher<'_>) { + assert!(type_invariant_searcher(searcher)); + assert!(same_slice(searcher.haystack(), s)); + } + + // 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"); + kani::cover(result.is_some_and(|part| part.len() > 4096), "split: large piece"); + cover_completed_text(s); + } + + fn check_search_step( + s: &str, + searcher: &ModelSearcher<'_>, + (front, back): (usize, usize), + reverse: bool, + matched: SearchMatch, + ) { + check_searcher(s, searcher); + if let Some((a, b)) = matched { + assert!(front <= a && a <= b && b <= back); + assert!(s.is_char_boundary(a) && s.is_char_boundary(b)); + } + 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(); + 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 { + 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); + } + + 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_iterator_constructors() { + let s = symbolic_text(); + 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); + } + + #[kani::proof] + 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(); + 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); + } + + fn check_split_step() -> Option { + let s = symbolic_text(); + let mut iter = any_split(s); + 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 _ = 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() { + check_split_back_step::(); + } + + #[kani::proof] + fn harness_split_next_back_inclusive() { + check_split_back_step::(); + } + + #[kani::proof] + fn harness_split_remainder() { + let s = symbolic_text(); + 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, 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() { + check_match_step::(); + } + + #[kani::proof] + fn harness_match_indices_next_back() { + check_match_step::(); + } + + #[kani::proof] + fn harness_matches_next() { + check_match_step::(); + } + + #[kani::proof] + fn harness_matches_next_back() { + check_match_step::(); + } + + #[kani::proof] + fn harness_split_ascii_whitespace_remainder() { + let s = symbolic_text(); + let mut iter = s.split_ascii_whitespace(); + 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) = 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); + 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(), "ASCII whitespace remainder: nonempty window"); + } + None => { + assert!(finished); + kani::cover(true, "ASCII whitespace remainder: finished"); + } + } + 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)] + 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()); + 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(); + let item = unsafe { iter.__iterator_get_unchecked(index) }; + assert!(item == window[index]); + kani::cover(index > 0, "bytes::get_unchecked: index past first byte"); + kani::cover(!s.is_char_boundary(start), "byte cursor inside a scalar"); + // idx < len excludes empty byte windows; cover the admissible domain. + kani::cover( + end - start > 4096 && index > 4096, + "completed contract on a large byte window and index", + ); + } + + mod auxiliary { + //! Fixed-size fold checks and bounded real-searcher regressions. + + use super::super::super::pattern::verify::assert_char_searcher_step; + use super::*; + + fn check_sum_flags() { + let flags: [bool; 32] = kani::any(); + let words = unsafe { crate::intrinsics::transmute(flags) }; + let result = flags.into_iter().map(|flag| flag as u8).sum::(); + assert!(result as u32 == count_flag_words(words)); + kani::cover(result == 32, "all flags consumed after sum assertion"); + } + + #[kani::proof] + fn check_sum_32_real() { + check_sum_flags(); + } + + #[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() { + check_sum_flags(); + } + + const MAX_SEARCH_BYTES: usize = 16; + 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(); + kani::assume(len <= N - UTF8_PAD); + kani::cover(len == N - UTF8_PAD, "full auxiliary input length admitted"); + kani::assume(verifier_utf8_valid(buf, len)); + kani::cover(len > 0, "nonempty valid auxiliary string admitted"); + // SAFETY: verifier_utf8_valid characterizes valid UTF-8 exactly. + unsafe { from_utf8_unchecked(&buf[..len]) } + } + + fn verifier_last_byte(needle: u8, bytes: &[u8]) -> Option { + 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 a byte. Allow one final exhausted probe. + 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::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(); + kani::assume(len <= bytes.len()); + 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 { + assert!(index < len); + assert_eq!(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"); + kani::cover(len > 0 && result == Some(len - 1), "byte model: final byte matches"); + kani::cover(len == 0 && result.is_none(), "byte model: empty prefix"); + } + + fn assert_char_searcher_direction(reverse: bool) { + 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(); + 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( + 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::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::proof] + #[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 4ff3487f8f69b..9b10719bcb66f 100644 --- a/library/core/src/str/pattern.rs +++ b/library/core/src/str/pattern.rs @@ -489,7 +489,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 @@ -557,7 +561,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 @@ -2152,31 +2160,46 @@ unsafe fn small_slice_eq(x: &[u8], y: &[u8]) -> bool { pub mod verify { use super::*; - #[cfg(all(kani, target_arch = "x86_64"))] // only called on x86 - #[kani::proof] + // An auxiliary regression can enable a checked local search budget. + #[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(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); - kani::assume(xs.len() == ys.len()); unsafe { small_slice_eq(xs, ys); } + 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() { - 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()); + 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!( unsafe { small_slice_eq( @@ -2186,5 +2209,71 @@ pub mod verify { }, true ); + kani::cover(true, "empty slice comparison completed"); + } + + 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(); + 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]) + } + + // 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, + 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!(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!(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 } }