Skip to content

Constant read from a static's storage when their initial bytes match: false proofs #5088

Closed

Description

@r-near

Kani can give a constant the same storage as a static whose initializer has the same bytes, so a store to the static changes the constant. This produces both false proofs and false failures. The reproducer below has no unsafe or dependencies.

I tried this code:

#![no_std]
use core::sync::atomic::{AtomicBool, Ordering::SeqCst};

#[derive(Clone, Copy)]
pub enum Mode { A, B }
pub trait HasMode { const MODE: Mode; }
pub struct Small;
impl HasMode for Small { const MODE: Mode = Mode::A; }

#[inline(never)]
fn mode_id(m: Mode) -> u32 { match m { Mode::A => 1, Mode::B => 2 } }
fn generic_mode<T: HasMode>() -> u32 { mode_id(T::MODE) }

// Zero-initialised statics: same bytes as `Mode::A`. Several are used because
// whether one collides depends on symbol-hash order.
macro_rules! flags {
    ($($s:ident)*) => {
        $(static $s: AtomicBool = AtomicBool::new(false);)*
        pub fn set_flags() { $($s.store(true, SeqCst);)* }
    };
}
flags!(S0 S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 S11 S12 S13 S14 S15);

#[test]
fn native() {
    set_flags();
    assert_eq!(generic_mode::<Small>(), 1); // passes
}

#[cfg(kani)]
#[kani::proof]
fn false_success() {
    set_flags();
    assert!(generic_mode::<Small>() == 2); // false in Rust; Kani: SUCCESSFUL
}

#[cfg(kani)]
#[kani::proof]
fn false_failure() {
    set_flags();
    assert!(generic_mode::<Small>() == 1); // true in Rust; Kani: FAILED
}

using the following command line invocation:

cargo kani

with Kani version: 0.68.0, CBMC 6.11.0, macOS aarch64.

I expected to see this happen: false_success fails and false_failure verifies, matching the native test.

Instead, this happened: false_success is SUCCESSFUL and false_failure FAILED. The --gen-c output reads the constant from a static:

unsigned int var_0=mode_id(*((struct Mode *)(unsigned char *)&S4));

Cause: alloc_map, which is used to share identical constant allocations, also gets each static's initializer: codegen_static → codegen_alloc_in_memory → alloc_map.insert. So codegen_const_allocation can return a static's address for a constant with equal bytes, provided the static was codegen'd first. That order follows symbol hashes, which is why one static alone triggers the bug for some names and not for others.

The same thing can happen to atomic Ordering operands, because Relaxed is also a zero byte. The load then hits Kani's invalid-ordering panic and the path is silently cut.

Suggested fix: only add constants to alloc_map. I've tested this on 0.68.0: both harnesses are correct, and Kani's static/const tests are unchanged.

--- a/kani-compiler/src/codegen_cprover_gotoc/codegen/operand.rs
+++ b/kani-compiler/src/codegen_cprover_gotoc/codegen/operand.rs
@@ -523,6 +523,9 @@ fn codegen_const_allocation(
                     has_interior_mutabity,
                     is_definitely_const,
                 );
+                // Only constant allocations may be shared. Statics have their own storage
+                // and must never be reused for a constant with the same bytes.
+                self.alloc_map.insert(alloc.clone(), alloc_name.clone());
                 alloc_name
             }
             Some(name) => name.clone(),
@@ -614,8 +617,6 @@ pub fn codegen_alloc_in_memory(
             loc,
             init_fn,
         );
-
-        self.alloc_map.insert(alloc, name);
     }

Happy to open a PR. Possibly related: #4992.

Activity

  1. self-assigned this
    on Oct 31, 2026
  2. added
    T-High Priority
    on Nov 6, 2026
  3. added this to the Soundness milestone on Nov 6, 2026
  4. added
    Z-Kani Compiler
    on Nov 6, 2026
  5. added theissue type on Nov 6, 2026
  6. added
    [F] Soundness
    on Nov 13, 2026
  7. jrey8343 commented on Nov 14, 2026

    @jrey8343

    I ran into this in verify-rust-std (model-checking/verify-rust-std#681) and can confirm it at Kani c5e65fd (the commit verify-rust-std pins; merge of #4947), CBMC 6.11.0, nightly-2026-10-23, macOS arm64. The released 0.68.0 gives the same kind of result on the two files below. Three things the report does not have yet:

    1. No user static is needed

    Kani's library has a static with eight zero bytes: CONTRACT_CLAUSE_DEPTH (library/kani_core/src/lib.rs:796, exported as __CPROVER_kani_contract_clause_depth). It is non-zero while a contract clause is evaluated. A constant with eight zero bytes that is read inside a clause can be emitted as a read of it. No static and no unsafe in the user's code:

    // kani clause2.rs -Z function-contracts
    // No user static and no `unsafe`. The only static with eight zero bytes is Kani's own
    // contract-clause depth counter, which is 1 while a contract clause is evaluated.
    use std::num::NonZeroUsize;
    
    const NONE: Option<NonZeroUsize> = None;
    
    #[inline(never)]
    fn id(x: Option<NonZeroUsize>) -> Option<NonZeroUsize> {
        x
    }
    
    /// A true postcondition.
    #[kani::ensures(|_| id(NONE).is_none())]
    fn true_ensures() {}
    
    /// A false postcondition.
    #[kani::ensures(|_| id(NONE) == NonZeroUsize::new(1))]
    fn false_ensures() {}
    
    #[kani::proof_for_contract(true_ensures)]
    fn check_true_ensures() {
        true_ensures()
    }
    
    #[kani::proof_for_contract(false_ensures)]
    fn check_false_ensures() {
        false_ensures()
    }

    Saved as clause2.rs, at c5e65fd:

    Checking harness check_false_ensures...
    	 - Description: "|_| id(NONE) == NonZeroUsize::new(1)"
     ** 0 of 109 failed
    VERIFICATION:- SUCCESSFUL
    

    The goto program of that harness (goto-instrument --show-goto-functions, names shortened) passes the counter to id:

    CALL ...false_ensures...::var_4 := id(*(cast(cast(address_of(__CPROVER_kani_contract_clause_depth), unsignedbv[8]*), struct tag-...*)), ...)
    

    The outcome depends on the crate name (the report says it follows symbol-hash order). The same file under 16 file names at c5e65fd: the false postcondition verifies under clause2.rs; the true postcondition fails (1 of 73) under four.rs and six.rs; the other 13 names give the correct verdicts. With the released 0.68.0, 8 names: the true postcondition fails under four.rs, the false one verifies under six.rs.

    2. In a contract harness the static does not have to be written

    The reproducer in the report stores to the statics. Under proof_for_contract that is not needed, because the contract instrumentation gives a user static an arbitrary value at entry. Harness (3) of the file in the details below asserts a true statement, never writes COUNTER, and fails (1 of 100) under 5 of the 15 file names I tried. In its goto program:

    ASSIGN ...true_statement_in_contract_harness::1::var_5::x := *(cast(cast(address_of(_RNvCs2nTU3WrrQyd_3two7COUNTER), unsignedbv[8]*), struct tag-...*))
    ...
    ASSIGN _RNvCs2nTU3WrrQyd_3two7COUNTER := side_effect statement="nondet" is_nondet_nullable="1"      (in __CPROVER_initialize)
    

    3. std's own constants are affected: what it did in verify-rust-std

    alloc::raw_vec has const ZERO_CAP: Cap = unsafe { Cap::new_unchecked(0) };, read in RawVecInner::new_in. Cap is a struct over a pattern type, so Kani emits the constant through memory. Every Vec::new(), VecDeque::new() and with_capacity(0) reads it. Harness (4) below shows it in one file: Vec::<u64>::new().capacity() == 5 verifies.

    In model-checking/verify-rust-std#681 the harness module of library/alloc/src/collections/vec_deque/mod.rs had static mut DROPS: usize = 0;, written by the destructor of a test element type. Four #[kani::proof] harnesses with #[kani::stub_verified(..)] (the check_*_counteddrop harnesses of 6b291878317) call VecDeque::with_capacity(requested) with a symbolic requested before they assign DROPS. That combination was never pushed: in the pushed history of the PR the commit that adds these four harnesses already has the workaround below. Same source, same Kani binary, same flags (-Z function-contracts -Z mem-predicates -Z float-lib -Z c-ffi -Z loop-contracts -Z quantifiers -Z stubbing --no-assert-contracts, --cbmc-args --object-bits 12), three checkouts at different paths:

    checkout crate disambiguator of alloc ZERO_CAP in RawVecInner::new_in is emitted as the four harnesses
    A Cs8oHsYivBLHV_5alloc *(struct Cap*)&__CPROVER_kani_contract_clause_depth SUCCESSFUL
    B Cs4u85O0AGOxm_5alloc *(struct Cap*)&alloc::collections::vec_deque::verify::DROPS FAILED (11 of 647, 13 of 693, 17 of 873, 16 of 1058 checks)
    C not extracted not extracted the two I ran: FAILED (11 of 647, 13 of 693, the same checks as in B)

    In B the dump has, in RawVecInner::new_in and in __CPROVER_initialize:

    ASSIGN ...RawVecInner6new_in...::var_0 := { *(cast(cast(address_of(_RNvNtNtNtCs4u85O0AGOxm_5alloc11collections9vec_deque6verify5DROPS), unsignedbv[8]*), struct tag-...*)), ...ptr, ...alloc }
    ASSIGN _RNvNtNtNtCs4u85O0AGOxm_5alloc11collections9vec_deque6verify5DROPS := side_effect statement="nondet" is_nondet_nullable="1"
    

    So VecDeque::with_capacity(0) returned a deque whose capacity was the arbitrary initial value of DROPS over a dangling pointer. The failed checks were in the harness's own setup and in the deallocation ("memset destination region writeable", "rust_dealloc must be called on an object whose allocated size matches its layout", "Offset value overflows isize", "free argument must be dynamic object"). No destructor had run.

    In A the harnesses pass, but the constant is not its own there either: in the harness I dumped, ZERO_CAP reads Kani's clause-depth counter. That counter is 0 where new_in runs in these harnesses.

    I think this is what I reported as #4992. I have checked the mechanism only at c5e65fd, not at the commit #4992 names.

    Workaround in model-checking/verify-rust-std#681 (at 6b291878317): no harness static has an initializer whose bytes a constant is likely to share (0x5EED_D50B_C0DE_0001 and successors instead of 0). With that change all four harnesses verify in A, B and C. It does not remove the read of __CPROVER_kani_contract_clause_depth: the one binary I dumped after the change, in B, has it.

    On the cause and on #5089

    I read the same cause in the source at c5e65fd (codegen_const_allocation looks up alloc_map, operand.rs:515; codegen_alloc_in_memory inserts every static, operand.rs:618, called from codegen_static, static_var.rs:22; items are emitted in fingerprint order, kani_middle/reachability.rs:73). The compiler's debug log shows it directly for the file below. Under two.rs the static is emitted first and the constant creates no allocation of its own. Under one.rs the constant comes first and gets one...::global::0::. The two keys are equal, including alignment and mutability (log lines of the two.rs run, bytes abbreviated):

    codegen_alloc_in_memory, name="_RNvCs2nTU3WrrQyd_3two7COUNTER", alloc=Allocation { bytes: [8 x Some(0)], provenance: ProvenanceMap { ptrs: [] }, align: 8, mutability: Mut }
    codegen_const_allocation, name=None,                           alloc=Allocation { bytes: [8 x Some(0)], provenance: ProvenanceMap { ptrs: [] }, align: 8, mutability: Mut }
    

    By reading its diff, #5089 covers all three cases above, because statics no longer enter alloc_map. I have not built it and have not run these files against it. Both tests in the PR use user statics; clause2.rs above has none.

    Not done

    • Not bisected: I do not know which Kani version introduced it. The released 0.68.0 and c5e65fd both show it.
    • Do not reuse a static's storage for an equal-bytes constant #5089 not tested.
    • In the verify-rust-std tree I saw failures only. The false-proof direction is shown in the single files only.
    • macOS arm64 only.
    • I did not trace why the item order differs between checkouts beyond the crate disambiguators being different. For a single file the directory does not matter (same result for two.rs in two directories); the crate name does.
    Second file: a static mut, a contract harness that never writes it, and Vec::new()
    // kani static_alias.rs -Z function-contracts
    use std::num::NonZeroUsize;
    
    static mut COUNTER: usize = 0;
    
    // Eight zero bytes, alignment 8: the same bytes as the initializer of `COUNTER`.
    const NONE: Option<NonZeroUsize> = None;
    
    /// (1) A true statement. It fails when `NONE` is emitted as a read of `COUNTER`.
    #[kani::proof]
    fn true_statement() {
        unsafe { COUNTER = 5 };
        let x = NONE;
        assert!(x.is_none());
    }
    
    /// (2) A false statement. It verifies when `NONE` is emitted as a read of `COUNTER`.
    #[kani::proof]
    fn false_statement() {
        unsafe { COUNTER = 5 };
        let x = NONE;
        assert!(x == NonZeroUsize::new(5));
    }
    
    #[kani::ensures(|r| *r == x)]
    fn id(x: u8) -> u8 {
        x
    }
    
    /// (3) The same true statement in a contract harness that never writes `COUNTER`.
    /// Contract instrumentation gives `COUNTER` an arbitrary value at entry.
    #[kani::proof_for_contract(id)]
    fn true_statement_in_contract_harness() {
        let _counter_is_reachable = unsafe { COUNTER };
        let x = NONE;
        assert!(x.is_none());
        id(kani::any());
    }
    
    /// (4) The same with a constant inside std: `RawVec`'s `ZERO_CAP`. A false statement.
    #[kani::proof]
    fn false_statement_about_vec() {
        unsafe { COUNTER = 5 };
        let v: Vec<u64> = Vec::new();
        assert!(v.capacity() == 5);
        std::mem::forget(v);
    }

    Correct verdicts: (1) SUCCESSFUL, (2) FAILED, (3) SUCCESSFUL, (4) FAILED. kani <name>.rs -Z function-contracts at c5e65fd, the same file under 15 names. In (1) to (3) the constant is read in the harness function itself, and each harness function has its own place in the item order, so the columns vary independently. All four are wrong under two.rs and six.rs; at least one is wrong under 11 of the 15 names.

    file (1) true_statement (2) false_statement (3) true_statement_in_contract_harness (4) false_statement_about_vec
    static_alias.rs FAILED (1 of 16) FAILED (1 of 52) FAILED (1 of 100) FAILED (1 of 15)
    repro.rs SUCCESSFUL (0 of 16) SUCCESSFUL (0 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    one.rs SUCCESSFUL (0 of 16) FAILED (1 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    two.rs FAILED (1 of 16) SUCCESSFUL (0 of 52) FAILED (1 of 100) SUCCESSFUL (0 of 15)
    three.rs FAILED (1 of 16) SUCCESSFUL (0 of 52) SUCCESSFUL (0 of 100) SUCCESSFUL (0 of 15)
    four.rs SUCCESSFUL (0 of 16) FAILED (1 of 52) FAILED (1 of 100) FAILED (1 of 15)
    five.rs SUCCESSFUL (0 of 16) SUCCESSFUL (0 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    six.rs FAILED (1 of 16) SUCCESSFUL (0 of 52) FAILED (1 of 100) SUCCESSFUL (0 of 15)
    seven.rs FAILED (1 of 16) SUCCESSFUL (0 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    eight.rs SUCCESSFUL (0 of 16) FAILED (1 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    alias.rs SUCCESSFUL (0 of 16) FAILED (1 of 52) FAILED (1 of 100) SUCCESSFUL (0 of 15)
    a.rs FAILED (1 of 16) FAILED (1 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    b.rs SUCCESSFUL (0 of 16) SUCCESSFUL (0 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    c.rs SUCCESSFUL (0 of 16) FAILED (1 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)
    d.rs SUCCESSFUL (0 of 16) FAILED (1 of 52) SUCCESSFUL (0 of 100) FAILED (1 of 15)

    With the released 0.68.0 (nightly-2026-08-21), 8 names: at least one verdict is wrong under 7 of them (all correct under three.rs).

    Controls at c5e65fd, on a two-harness file that has only the Vec::new() statements (capacity() == 0 and capacity() == 5 after COUNTER = 5). Under the name two.rs both verdicts are wrong and new_in reads COUNTER. With static mut COUNTER: usize = 1 both verdicts are correct and new_in reads an allocation of its own. With an immutable static COUNTER: usize = 0 that is only read, the same.

    The two-harness file, run as kani two.rs (in the immutable variant let _ = COUNTER; stands in place of each store):

    // One user static with eight zero bytes; RawVec's ZERO_CAP constant has the same bytes.
    static mut COUNTER: usize = 0;
    
    /// True statement. Fails if `ZERO_CAP` is emitted as a read of `COUNTER`.
    #[kani::proof]
    fn new_vec_has_capacity_zero() {
        unsafe { COUNTER = 5 };
        let v: Vec<u64> = Vec::new();
        assert!(v.capacity() == 0);
    }
    
    /// False statement. Verifies if `ZERO_CAP` is emitted as a read of `COUNTER`.
    #[kani::proof]
    fn new_vec_has_capacity_five() {
        unsafe { COUNTER = 5 };
        let v: Vec<u64> = Vec::new();
        assert!(v.capacity() == 5);
        std::mem::forget(v);
    }
  8. added a commit that references this issue on Nov 19, 2026
    8e9b91c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

T-High PriorityZ-Kani Compiler[F] Soundness

Type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions