Skip to content

Loop contracts can't verify code whose memory safety rests on a type Invariant (e.g. slice::Iter): havoc drops it with no user-side way to restore it #4993

Description

@kasimte

Requested feature: a way for a loop contract to re-establish the havoc'd state's type Invariant (core::ub_checks::Invariant), so a loop whose body is memory-safe only by that invariant can be verified.

Use case: proving provided-method loops over std cursors such as core::slice::Iter (and
str::pattern::Searcher, which loops over one). Iter::next is memory-safe by its ptr/end invariant, not a local bounds check. Under a loop contract the havoc resets the cursor, so next() dereferences an invalid pointer. The invariant lives in private fields, so no loop_invariant expression can restore it after havoc. There is no user-side workaround.

Test case:

#![feature(stmt_expr_attributes, proc_macro_hygiene)]

struct PtrCur { ptr: *const u8, end: *const u8 }

impl PtrCur {
    unsafe fn next(&mut self) -> Option<u8> {
        if self.ptr == self.end { return None; }
        let b = *self.ptr;             // safe only while the ptr/end invariant holds
        self.ptr = self.ptr.add(1);
        Some(b)
    }
}

#[cfg(kani)]
mod verify {
    use super::*;
    #[kani::proof]
    fn check_bug() {
        let a: [u8; 4] = kani::any();
        let p = a.as_ptr();
        let mut cur = PtrCur { ptr: p, end: unsafe { p.add(4) } };
        #[kani::loop_invariant(true)]
        loop {
            match unsafe { cur.next() } {
                Some(0) => continue,
                _ => break,
            }
        }
    }
}

Run: cargo kani -Z loop-contracts --harness verify::check_bug (Kani 0.68.0 standalone, CBMC 6.11.0).

Result: VERIFICATION:- FAILED, all failing checks at let b = *self.ptr (null pointer dereference, pointer invalid, dead object, deallocated, outside object bounds). The loop is contracted, not unwound: loop_invariant_base, loop_assigns, and loop_invariant_step pass, and CBMC reports it at iteration 1. So this is not an unwinding-bound issue. The havoc drops the cursor's invariant, and #[kani::loop_invariant(true)] cannot restore it. The same failure arises contracting the Searcher provided-method loop in verify-rust-std.

Activity

  1. kasimte commented on Oct 7, 2026

    @kasimte
    ContributorAuthor

    A possible direction: loop-contract havoc re-assumes the havoc'd state's type Invariant, as
    autoharness already does for nondet inputs (assume_safe). Open design questions:

    • Opt-in or automatic? A flag, or automatic when the type implements Invariant?
    • Loop-free predicate. slice::Iter::is_safe itself loops internally (can_dereference /
      same_allocation), so re-assuming it inside a contracted loop doesn't compose. Loop-free lowering, or
      special-case it in the instrumentation?
    • Library vs. tool split. ptr <= end + same_allocation(ptr, end) doesn't capture "cursor within
      the original allocation," so this needs a stronger relational library Invariant plus the tool
      mechanism. Where's the split?

    I've looked at this enough to be fairly confident a naive re-assume of the existing is_safe() isn't
    sufficient on its own (the three points above). If the overall direction looks reasonable, I'd be happy
    to be assigned and implement it.

  2. added
    [F] Spurious FailureIssues that cause Kani verification to fail despite the code being correct.
    Z-ContractsIssue related to code contracts
    on Nov 6, 2026
  3. added this to the Contracts milestone on Nov 6, 2026
  4. self-assigned this
    on Nov 6, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

Z-ContractsIssue related to code contracts[C] Feature / EnhancementA new feature request or enhancement to an existing feature.[F] Spurious FailureIssues that cause Kani verification to fail despite the code being correct.

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions