Repository navigation
Description
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
jrey8343 commentedon Nov 14, 2026
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. Nostaticand nounsafein the user's code:Saved as
clause2.rs, atc5e65fd:The goto program of that harness (
goto-instrument --show-goto-functions, names shortened) passes the counter toid: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 underclause2.rs; the true postcondition fails (1 of 73) underfour.rsandsix.rs; the other 13 names give the correct verdicts. With the released 0.68.0, 8 names: the true postcondition fails underfour.rs, the false one verifies undersix.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_contractthat 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 writesCOUNTER, and fails (1 of 100) under 5 of the 15 file names I tried. In its goto program:3. std's own constants are affected: what it did in verify-rust-std
alloc::raw_vechasconst ZERO_CAP: Cap = unsafe { Cap::new_unchecked(0) };, read inRawVecInner::new_in.Capis a struct over a pattern type, so Kani emits the constant through memory. EveryVec::new(),VecDeque::new()andwith_capacity(0)reads it. Harness (4) below shows it in one file:Vec::<u64>::new().capacity() == 5verifies.In model-checking/verify-rust-std#681 the harness module of
library/alloc/src/collections/vec_deque/mod.rshadstatic mut DROPS: usize = 0;, written by the destructor of a test element type. Four#[kani::proof]harnesses with#[kani::stub_verified(..)](thecheck_*_counteddropharnesses of6b291878317) callVecDeque::with_capacity(requested)with a symbolicrequestedbefore they assignDROPS. 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:allocZERO_CAPinRawVecInner::new_inis emitted asCs8oHsYivBLHV_5alloc*(struct Cap*)&__CPROVER_kani_contract_clause_depthCs4u85O0AGOxm_5alloc*(struct Cap*)&alloc::collections::vec_deque::verify::DROPSIn B the dump has, in
RawVecInner::new_inand in__CPROVER_initialize:So
VecDeque::with_capacity(0)returned a deque whose capacity was the arbitrary initial value ofDROPSover 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_CAPreads Kani's clause-depth counter. That counter is 0 wherenew_inruns 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_0001and 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_allocationlooks upalloc_map,operand.rs:515;codegen_alloc_in_memoryinserts every static,operand.rs:618, called fromcodegen_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. Undertwo.rsthe static is emitted first and the constant creates no allocation of its own. Underone.rsthe constant comes first and getsone...::global::0::. The two keys are equal, including alignment and mutability (log lines of thetwo.rsrun, bytes abbreviated):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.rsabove has none.Not done
c5e65fdboth show it.two.rsin two directories); the crate name does.Second file: a
static mut, a contract harness that never writes it, andVec::new()Correct verdicts: (1) SUCCESSFUL, (2) FAILED, (3) SUCCESSFUL, (4) FAILED.
kani <name>.rs -Z function-contractsatc5e65fd, 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 undertwo.rsandsix.rs; at least one is wrong under 11 of the 15 names.true_statementfalse_statementtrue_statement_in_contract_harnessfalse_statement_about_vecstatic_alias.rsrepro.rsone.rstwo.rsthree.rsfour.rsfive.rssix.rsseven.rseight.rsalias.rsa.rsb.rsc.rsd.rsWith the released 0.68.0 (
nightly-2026-08-21), 8 names: at least one verdict is wrong under 7 of them (all correct underthree.rs).Controls at
c5e65fd, on a two-harness file that has only theVec::new()statements (capacity() == 0andcapacity() == 5afterCOUNTER = 5). Under the nametwo.rsboth verdicts are wrong andnew_inreadsCOUNTER. Withstatic mut COUNTER: usize = 1both verdicts are correct andnew_inreads an allocation of its own. With an immutablestatic COUNTER: usize = 0that is only read, the same.The two-harness file, run as
kani two.rs(in the immutable variantlet _ = COUNTER;stands in place of each store):Do not reuse a static's storage for an equal-bytes constant (model-ch…