Skip to content

Loop contracts: an explicit loop_modifies on a for loop fails the assigns check on Kani's generated variables #4940

Closed

Description

@feliperodri

An explicit #[kani::loop_modifies] on a for loop fails verification even when it lists everything the loop body writes. The assigns check fails on variables that Kani's for-loop rewrite generates (the loop pattern binding and kani_index_*), which the user cannot name.

#![feature(proc_macro_hygiene)]
#![feature(stmt_expr_attributes)]

#[kani::proof]
fn for_complete_modifies() {
    let a: [u8; 3] = kani::any();
    let mut s: u32 = 0;
    #[kani::loop_modifies(&s)]
    #[kani::loop_invariant(s <= kani::index as u32 * 255)]
    for x in a { s += x as u32; }
    assert!(s <= 3 * 255);
}
$ kani for_modifies.rs -Z loop-contracts
Failed Checks: Check that x is assignable
Failed Checks: Check that kani_index_<...> is assignable
VERIFICATION:- FAILED

Expected: verification succeeds, since the loop only writes s.

Observed on main at 7207ac1 with CBMC 6.11.0.

Why. transform_for_to_loop (library/kani_macros/src/sysroot/loop_contracts/mod.rs) rewrites for pat in expr into a while loop. The new loop's body re-binds pat with kani::KaniIter::nth and increments kani_index_*. Those writes happen inside the loop, but the user's loop_modifies clause can't name them, so CBMC's assigns check flags them. The rewrite knows both identifiers, so it could add them to the assigns set itself.

Attribute order. With loop_modifies written after loop_invariant, the clause is currently ignored (#4929), so the harness above verifies. #4930 fixes #4929 by carrying the clause onto the rewritten loop, which makes this bug hit both orders. See the review there: #4930 (review)

Related: #4906 (writes to loop-body temporaries failing the assigns check).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    [C] BugThis is a bug. Something isn't working.

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions