Repository navigation
Description
Requested feature: A loop invariant on the loop of the compiler-generated slice drop glue, drop_glue::<[T]>, emitted by Kani itself. Either built in under -Z loop-contracts, or (what I think is needed, see "Why opt-in") enabled per harness by an attribute.
Use case: Unbounded proofs of std collection code that drops a slice of elements: VecDeque::truncate, drain, retain_mut, resize_with and Drop for VecDeque (verify-rust-std Challenge 25, model-checking/verify-rust-std#681), and the same call in Vec::truncate and vec::IntoIter::drop (Challenges 23 and 24, model-checking/verify-rust-std#598 and model-checking/verify-rust-std#599, whose descriptions list no element type with a destructor). The review of model-checking/verify-rust-std#681 asks for these paths without an unwind bound and notes that this "may need Kani support for loop contracts on drop_in_place::<[T]>". What model-checking/verify-rust-std#681 does instead, and what it costs, is under "What the PR does today instead".
Link to relevant documentation: https://model-checking.github.io/kani/reference/experimental/loop-contracts.html
Test case: below.
Environment
Kani built from c5e65fd (the merge commit of #4947 and the pin verify-rust-std uses today; kani --version reports 0.68.0), CBMC 6.11.0, nightly-2026-10-23, macOS arm64. All results below are from that build unless a row says otherwise. Times are from one machine and are indicative only.
Reproducer
// repro.rs
#![feature(stmt_expr_attributes)]
#![feature(proc_macro_hygiene)]
use std::ptr;
pub struct WithDrop(u8);
impl Drop for WithDrop {
fn drop(&mut self) {
// Reads the element, writes nothing outside it, frees nothing.
std::hint::black_box(self.0);
}
}
const MAX: usize = 1 << 20;
/// `len` initialised elements in a fresh heap allocation.
fn any_buf(len: usize) -> *mut WithDrop {
let layout = std::alloc::Layout::array::<WithDrop>(len).unwrap();
let p = unsafe { std::alloc::alloc(layout) } as *mut WithDrop;
kani::assume(!p.is_null());
unsafe { ptr::write_bytes(p as *mut u8, kani::any::<u8>(), len) };
p
}
/// (1) The real glue. No loop in the harness, no unwind bound possible for a symbolic `len`.
#[kani::proof]
fn slice_drop_glue_symbolic_len() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf(len);
unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(p, len)) };
}
/// (2) The same loop written in source with the obvious invariant.
#[kani::proof]
fn handwritten_loop_symbolic_len() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf(len);
let mut i: usize = 0;
#[kani::loop_invariant(i <= len)]
while i < len {
unsafe { ptr::drop_in_place(p.add(i)) };
i += 1;
}
}
/// (3) What works today on the real glue: a concrete length bound plus an unwind bound.
#[kani::proof]
#[kani::unwind(6)]
fn slice_drop_glue_bounded() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= 4);
let p = any_buf(len);
unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(p, len)) };
}| Command | Result |
|---|---|
kani repro.rs -Z loop-contracts --harness slice_drop_glue_symbolic_len |
no verdict. Killed after 300 s; CBMC had logged 8053 iterations of Unwinding loop ...drop_glue...WithDrop....0 (5202 in an earlier run) |
kani repro.rs -Z loop-contracts --harness handwritten_loop_symbolic_len |
VERIFICATION:- SUCCESSFUL, 0 of 122 failed, under 1 s |
kani repro.rs -Z loop-contracts --harness slice_drop_glue_bounded |
VERIFICATION:- SUCCESSFUL, 0 of 43 failed (length at most 4) |
kani repro.rs -Z loop-contracts -Z unstable-options --synthesize-loop-contracts --harness slice_drop_glue_symbolic_len |
terminates in under 1 s but VERIFICATION:- FAILED, 1 of 56: <WithDrop as Drop>::drop.pointer_dereference.5 "pointer outside object bounds". Spurious: the synthesised invariant is too weak |
Why nothing available today covers (1)
#[kani::loop_invariant]goes on a loop expression in source. The loop here is in a MIR shim that rustc builds during drop elaboration; there is no source for it, in the harness or in std.- Because the harness has no loop contract, kani-driver does not run the
goto-instrument --dfcc ... --apply-loop-contractsstep at all for it (visible with--verbose), even with-Z loop-contracts. #[kani::unwind(k)]bounds the slice length, which is what an unbounded proof must avoid.--synthesize-loop-contractsattaches to the shim loop but gives the spurious failure above.ptr::drop_in_placecan be stubbed (it has been an ordinary wrapper over thedrop_gluelang item since nightly-2026-06-01, see loop_modifies over a Vec no longer establishes drop_in_place's new reference-creation precondition #4761) with a hand-written loop like (2). That verifies, but the proof is then about a transcription of the compiler's loop, not the loop that ships. This is what Challenge 25: Verify the safety of VecDeque (symbolic capacity, head and length; contracts on all 13 unsafe fns) verify-rust-std#681 does; see the next section.
What the PR does today instead, and what it costs
In model-checking/verify-rust-std#681 at 6b291878317 (library/alloc/src/collections/vec_deque/mod.rs, mod verify, all under cfg(kani)):
#[kani::stub(core::ptr::drop_in_place, drop_in_place_model)]on the harnesses that reach a slice drop. The stub dispatches on the type (min_specialization). Non-slice types and slices of types without drop glue go to the real glue throughNonNull::drop_in_place. A slice of aneeds_droptype gets an assertion that the whole slice is readable and writable, then a source-level copy of the shim loop (drop_slice) with#[kani::loop_invariant(i <= len)].drop_slicecarries a contract. It is proved once per element shape for a slice of symbolic length (any sub-slice of a heap buffer of up to 2^48 bytes; for the zero-sized shape a dangling slice of any length) and used in the callers through#[kani::stub_verified]. A second copy,drop_slice_counted, has the destructor counter in its invariant and postcondition.- The compiler's loop is still run, with
#[kani::unwind]and at most 4 elements, in separate harnesses.
Measured at the pin with the flags of verify-rust-std CI (-Z function-contracts -Z mem-predicates -Z float-lib -Z c-ffi -Z loop-contracts -Z quantifiers -Z stubbing --no-assert-contracts, --object-bits 12), one run on a 12-core macOS arm64 machine, all VERIFICATION:- SUCCESSFUL:
| Harnesses | Count | Verification time, sum | Range |
|---|---|---|---|
| Proofs of the model's contract (one per shape: 1-byte, 8-byte, zero-sized, counting) | 4 | 16.7 s | 1.6 to 7.1 s |
Callers of the model, no unwind bound (truncate, drain, retain_mut, resize_with, Drop for VecDeque) |
15 | 602.6 s | 1.0 to 116.8 s |
The compiler's glue, bounded (kani::unwind, at most 4 elements) |
8 | 47.0 s | 0.2 to 14.2 s |
The 19 model harnesses are 619 s of the 4307 s the file's 227 harnesses take together. The change set that introduced the model added 868 lines to the file, comments included.
What the workaround does not give:
- The proofs without a bound are about the copy of the loop. That the copy matches rustc's
drop_looprests on readingrustc_mir_transform::elaborate_dropand on the bounded harnesses. The compiler's own loop is checked for at most 4 elements only. - In the callers the loop is replaced by its contract, so no element destructor runs there. The counting harnesses establish how many elements are handed to the glue, not that the glue runs that many destructors.
- The stub is keyed on the function, not on a type: it replaces every call of
ptr::drop_in_placethe harness reaches. Drops that the compiler inserts as MIRDropterminators do not go through it.
With the requested feature the stub, the two copies of the loop, their four contract proofs and the model/real-glue split would not be needed: the 15 callers would run the shim itself.
The shim
drop_glue::<[WithDrop]> as Kani emits it at this pin (goto-instrument --show-goto-functions; names shortened, DECL/DEAD/SKIP lines omitted; var_1 is the &mut [WithDrop] argument):
std::ptr::drop_glue::<[WithDrop]>
ASSIGN var_2 := var_1.len
ASSIGN var_3 := 0
GOTO 1
1: ASSIGN var_7 := cast(var_3 = var_2, c_bool[8])
IF var_7 = 0 THEN GOTO 3
GOTO 2
2: SET RETURN VALUE VoidUnit
GOTO 4
3: ASSIGN var_6 := address_of(*(var_1.data + var_3))
ASSIGN var_3 := var_3 + 1
CALL drop_glue::<WithDrop>(address_of(*var_6))
GOTO 1
4: END_FUNCTION
One loop, id <mangled drop_glue::<[WithDrop]>>.0, counter var_3, length var_2. rustc generates it during drop elaboration (drop_loop), so I expect the same shape for every element type; I looked at this one. The released Kani 0.68.0 (nightly-2026-08-21) emits the same instructions with the same local numbers for this file. The invariant that is needed is cur <= len.
The fixed invariant is checkable by CBMC on the real shim
CBMC 6.11.0's goto-instrument already accepts loop contracts from a file (--loop-contracts-file); kani-driver does not pass that flag. So the experiment needs no Kani change: take the goto binary Kani produces, replay kani-driver's own post-codegen commands as --verbose prints them, and add one argument that attaches cur <= len to the shim loop.
kani file.rs --only-codegen --keep-temps -Z loop-contracts -Z unstable-options [--no-assertion-reach-checks]
goto-cc H.symtab.out <kani>/library/kani/kani_lib.c -o w.out
goto-cc w.out --function H -o w.out
goto-instrument --dfcc H --no-malloc-may-fail --apply-loop-contracts --loop-contracts-no-unwind \
--disable-loop-contracts-side-effect-check --loop-contracts-file lc.json w.out w.out # only lc.json is new
goto-instrument --add-library --no-malloc-may-fail w.out w.out
goto-instrument --generate-function-body-options assert-false-assume-false --generate-function-body '.*' --drop-unused-functions w.out w.out
goto-instrument --ensure-one-backedge-per-target w.out w.out
cbmc --no-malloc-may-fail --no-undefined-shift-check --no-signed-overflow-check --nan-check --no-self-loops-to-assumptions \
--no-pointer-primitive-check --object-bits 12 --sat-solver cadical --slice-formula w.out --verbosity 9
lc.json, with G the mangled name of drop_glue::<[WithDrop]> taken from goto-instrument --show-loops:
{ "sources": [], "functions": [
{ "G": [ { "loop_id": "0", "invariants": "cur <= len",
"symbol_map": "cur,G::1::var_3;len,G::1::var_2" } ] }
], "output": "OUTPUT" }The invariant is checked, not assumed: CBMC emits loop_invariant_base, loop_invariant_step and loop_assigns properties for std::ptr::drop_glue::<[WithDrop]>.0, and checks every write in the loop body, including inside the destructor, against the write set it infers.
Results. Harnesses use the stock std of the toolchain, not the code of model-checking/verify-rust-std#681. VecDeque harnesses build the deque from a symbolic-length allocation, len up to 2^48, every byte initialised. "CBMC verdict" is CBMC's own last line, on binaries compiled with --no-assertion-reach-checks so that no reachability property is counted as a failure.
| Harness | Injected | CBMC verdict | Shim loop checks | CBMC time |
|---|---|---|---|---|
| reproducer (1) above | cur <= len |
VERIFICATION SUCCESSFUL, 0 of 87 |
base, step, assigns: SUCCESS | < 1 s |
| reproducer (1) above | cur < len (wrong on purpose) |
VERIFICATION FAILED, 1 of 87 |
loop_invariant_step: FAILURE |
< 1 s |
VecDeque<WithDrop>: truncate(k), symbolic k, then drop the deque |
cur <= len |
VERIFICATION SUCCESSFUL, 0 of 287 |
base, step, assigns: SUCCESS | 2 s |
| same | cur < len |
VERIFICATION FAILED, 1 of 287 |
loop_invariant_step: FAILURE |
1 s |
| same | cur <= len, decreases: len - cur |
VERIFICATION SUCCESSFUL, 0 of 288 |
plus loop_decreases: SUCCESS |
2-5 s |
| same | nothing (today's pipeline) | none: killed at 60 s, 2176 iterations and counting | n/a | n/a |
VecDeque<WithDrop>: drop only |
cur <= len |
VERIFICATION SUCCESSFUL, 0 of 253 |
SUCCESS | < 1 s |
VecDeque<WithDrop>: drain(a..b) dropped, then drop the deque |
cur <= len |
VERIFICATION SUCCESSFUL, 0 of 493 |
SUCCESS | 24-31 s |
VecDeque<WithDrop>: wrapped ring (pop_back + push_front), truncate, drop |
cur <= len |
1 of 711 "failed": the kani::cover! for the wrapped layout, i.e. satisfied; nothing else |
SUCCESS | 15-34 s |
control: slice claims len + 1 elements in a len-element allocation |
cur <= len |
VERIFICATION FAILED, 2 of 89: drop_in_place::<[WithDrop]> "pointer invalid", <WithDrop as Drop>::drop "pointer outside object bounds" |
SUCCESS | < 1 s |
control: VecDeque over len + 1 claimed elements, truncate(0) |
cur <= len |
VERIFICATION FAILED, 4 of 236, including <WithDrop as Drop>::drop "pointer outside object bounds" |
SUCCESS | 1 s |
Notes on reading these:
- With the contract applied, CBMC at
--verbosity 9still printsUnwinding loop ...drop_glue... iteration 1once per visit to the shim (5 lines in the truncate harness) and never a higher iteration. That is the single abstract step of the contract transformation, the same line a source-level#[kani::loop_invariant]loop produces under plain Kani (harness (2) prints it once). - The truncate harness with
kani::cover!added and default reachability checks has all four covers satisfied: a proper non-empty tail is dropped,len == 2^48is reached, the deque is non-empty when dropped, and the end of the harness is reached after both glue calls. So the code after the abstracted loop is reachable. - The two controls fail inside the destructor, so the destructor body in the abstract iteration is reached and checked.
Proposed shape of the feature
Not prototyped; from reading the source at c5e65fd.
The back edge of the shim loop is the goto that codegen_drop emits after a Drop terminator (kani-compiler/src/codegen_cprover_gotoc/codegen/statement.rs:685, the Stmt::goto(bb_label(*target), loc) at line 735). When the function being compiled is the drop shim of a slice and the opt-in is set, recognise rustc's drop_loop shape (a head block ending in _t = Eq(copy cur, copy len); switchInt(move _t), and a Drop terminator whose target is that head), attach cur <= len to that goto with the existing Stmt::with_loop_contracts (cprover_bindings/src/goto_program/stmt.rs:330), and set has_loop_contracts (as overrides/hooks.rs:874 does) so that kani-driver runs --apply-loop-contracts for the harness (kani-driver/src/call_goto_instrument.rs:45). If the shape is not recognised, emit nothing and behave as today.
The pattern match adds no trust, because CBMC checks whatever is attached: the wrong-invariant rows above fail.
An alternative is a library model of the slice glue that replaces the shim body under the flag. I prefer the codegen route because the loop that is verified stays the one rustc generated.
Why opt-in
drop(vec![Box::new(1u8), Box::new(2u8)]) passes today under plain Kani by unwinding the shim loop twice (VERIFICATION:- SUCCESSFUL, 0 of 141 failed). With cur <= len attached to drop_glue::<[Box<u8>]> the same harness fails (3 of 189): free argument must be NULL or valid pointer, double free, Check that ptr is freeable. That is #3587 (no free inside a loop under a loop contract). An always-on invariant would therefore break harnesses that pass now, for every element type whose destructor frees memory. verify-rust-std passes -Z loop-contracts to all of its harnesses, so the unstable flag alone is not a narrow enough switch. Hence a per-harness attribute (name to be decided).
Known limits of the minimal version
- Destructors that free memory (
Box,Vec,Stringelements): fail as above until Supportmallocandfreein loops with loop contracts #3587 is addressed. - Destructors that write a static: with only
cur <= lenand CBMC's inferred write set, a destructor doingDROPS = DROPS.wrapping_add(1)fails<CountedDrop as Drop>::drop.assigns.1 Check that *var_5 is assignable. That is a sound failure, not a silent pass. With an explicit assigns clause and a counting invariant in the contract file (assigns: cur, DROPS;invariants: cur <= len && DROPS == __CPROVER_loop_entry(DROPS) + cur) the real glue verifies and the exact count is proved:DROPS == lenafter dropping a raw slice (0 of 124 failed),DROPS == len - kafterVecDeque::truncate(k)andDROPS == lenafter the deque is dropped (0 of 326), and a wrong expected count fails. So optionalmodifiesand extra-invariant arguments on the attribute would cover this case; the minimal version does not. (The failures I reported in proof_for_contract harness fails in its own setup code when the element type's destructor writes a static (Kani 1640445, CBMC 6.11) #4992 for a static-writing destructor are, I think, a different problem, Constant read from astatic's storage when their initial bytes match: false proofs #5088, and not a limit of this proposal.) - Termination:
cur <= lenalone gives partial correctness.decreases: len - curis accepted on the shim (row above), so a decreases clause could be emitted too. - Unwinding paths are out of scope as everywhere else (
codegen_dropdoesn't handle unwinding #221). - Not tested with the injection:
[T; N]array glue with aneeds_dropelement, element types other than 1-byte structs, anything inside the verify-rust-std build. No Kani source change has been written.
Related
- Loop contracts have no attach site for loops inside called iterator combinators (
fold/try_for_each/collect) #4893: same class of gap, a loop inside a callee that the harness author cannot annotate. There the callee is an iterator combinator and the invariant depends on the caller. Here the callee is compiler-generated and the invariant is fixed, so Kani can supply it. - loop_modifies over a Vec no longer establishes drop_in_place's new reference-creation precondition #4761: describes the nightly-2026-06-01 change that made
ptr::drop_in_placea wrapper over thedrop_gluelang item. The wrapper's&mut *to_dropcheck stays in force with this proposal (it is what fails first in thelen + 1controls). - Verify generic code once for an abstract
T(symbolic size, alignment and trait behaviour) #5041: the RFC for verifying generic code once lists "Drop glue and trait dispatch for the abstract type need the stub-plus-contract treatment". This request is the concrete-type counterpart for the one loop in the glue. - Support
mallocandfreein loops with loop contracts #3587:malloc/freein loops with loop contracts. The reason for the opt-in and for the first limit. - [Bug] Infinite unwinding of
std::ptr::drop_in_placein program containing enum wrapping std::io::Error in very specific manner #2538: endless unwinding insidedrop_in_placewith nothing in user code to bound. Same symptom, different cause (a recursion in the glue for an enum wrappingstd::io::Error); this request would not fix it. - Dropping an
Arcaround an emptyVecunrolls the element drop loop and times out, depending on the struct's other fields #5173: CBMC unwindsdrop_glue::<[T]>for a vector that is concretely empty. Same loop, different situation: there the length is known and the unwinding is the problem to explain; here the length is symbolic and no bound exists. Its element type frees memory, so the first limit above would apply. - Challenge 25: Verify the safety of VecDeque (symbolic capacity, head and length; contracts on all 13 unsafe fns) verify-rust-std#681, Challenge 23: Verify Vec Part1 safety with Kani verify-rust-std#598, Challenge 24: Verify Vec Part2 safety with Kani verify-rust-std#599: the proofs that would use it.
Script for the experiment (the commands of the script I ran, inject_pin.sh; its timeout, its no-injection switch and its log summaries are left out, and the tool paths are shortened)
#!/bin/bash
# usage: inject_pin.sh <dir> <crate> <harness-substring> <tag> [object-bits]
# env: INV (default "cur <= len"), ASSIGNS, DECR, XMAP (extra symbol_map entries)
set -u
D=$1; C=$2; HS=$3; TAG=$4; OB=${5:-12}
KLIB=<kani checkout>/library/kani/kani_lib.c
cd "$D" || exit 2
SYM=$(ls ${C}__*${HS}*.symtab.out | head -1)
H=${SYM#${C}__}; H=_${H%.symtab.out}
W=w_$TAG.out
goto-cc $SYM $KLIB -o $W || exit 3
goto-cc $W --function $H -o $W || exit 3
# every loop inside a drop_glue::<[..]> shim
goto-instrument --show-loops $W 2>/dev/null | grep -B1 'function std::ptr::drop_glue::<\[' | grep '^Loop ' \
| sed 's/^Loop \(.*\)\.\([0-9]*\):$/\1 \2/' > loops_$TAG.txt
{
echo '{ "sources": [], "functions": ['
first=1
while read -r G ID; do
[ $first = 1 ] || echo ','
first=0
X=""; [ -n "${ASSIGNS:-}" ] && X="$X \"assigns\": \"$ASSIGNS\","; [ -n "${DECR:-}" ] && X="$X \"decreases\": \"$DECR\","
echo " { \"$G\": [ { \"loop_id\": \"$ID\", \"invariants\": \"${INV:-cur <= len}\",$X \"symbol_map\": \"cur,$G::1::var_3;len,$G::1::var_2${XMAP:+;$XMAP}\" } ] }"
done < loops_$TAG.txt
echo '], "output": "OUTPUT" }'
} > lc_$TAG.json
goto-instrument --dfcc $H --no-malloc-may-fail --apply-loop-contracts --loop-contracts-no-unwind \
--disable-loop-contracts-side-effect-check --loop-contracts-file lc_$TAG.json $W $W || exit 4
goto-instrument --add-library --no-malloc-may-fail $W $W
goto-instrument --generate-function-body-options assert-false-assume-false --generate-function-body '.*' --drop-unused-functions $W $W
goto-instrument --ensure-one-backedge-per-target $W $W
cbmc --no-malloc-may-fail --no-undefined-shift-check --no-signed-overflow-check --nan-check --no-self-loops-to-assumptions \
--no-pointer-primitive-check --object-bits $OB --sat-solver cadical --slice-formula $W --verbosity 9 > cbmc_$TAG.log 2>&1
grep -E '^VERIFICATION|^\*\* ' cbmc_$TAG.log
grep -E 'drop_glue::<\[.*(loop_invariant|loop_assigns|loop_decreases)' cbmc_$TAG.logHarness file for the VecDeque rows, the two controls, the Vec<Box<u8>> example and the counting runs (l0.rs)
Rows of the table with the "Injected" column, from the third on: r4_deque_truncate_then_drop (four rows), r3_deque_drop, r5_deque_drain_then_drop, r8_wrapped_truncate_then_drop, r2_raw_slice_oob_must_fail, r7_deque_truncate_oob_must_fail. The four covers are in r4c_deque_truncate_then_drop_covers, the Vec<Box<u8>> harness is v1_vec_of_box_concrete, the counting harnesses are s2_counted_raw_slice, s3_counted_raw_slice_wrong_must_fail and s4_counted_deque_truncate.
// Layer 0 at the pin: the REAL compiler-generated slice drop glue, no stub, no model, no unwind.
// The loop invariant `cur <= len` is attached to the shim's loop in Kani's goto binary by
// `goto-instrument --loop-contracts-file` (see inject_pin.sh). Std is the stock library of the
// pinned Kani's toolchain, not the verify-rust-std tree.
use std::collections::VecDeque;
use std::ptr;
/// Read-only destructor.
pub struct WithDrop(u8);
impl Drop for WithDrop {
fn drop(&mut self) {
std::hint::black_box(self.0);
}
}
/// Destructor that writes a static.
static mut DROPS: usize = 0;
pub struct CountedDrop(u8);
impl Drop for CountedDrop {
fn drop(&mut self) {
unsafe { DROPS = DROPS.wrapping_add(1) };
}
}
const MAX: usize = 1 << 48;
/// `len` elements in a fresh heap allocation, every byte initialised to one symbolic value.
fn any_buf<T>(len: usize) -> *mut T {
let layout = std::alloc::Layout::array::<T>(len).unwrap();
let p = unsafe { std::alloc::alloc(layout) } as *mut T;
kani::assume(!p.is_null());
unsafe { ptr::write_bytes(p as *mut u8, kani::any::<u8>(), len * std::mem::size_of::<T>()) };
p
}
fn any_deque<T>() -> (VecDeque<T>, usize) {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf::<T>(len);
let v = unsafe { Vec::from_raw_parts(p, len, len) };
(VecDeque::from(v), len)
}
#[kani::proof]
fn r1_raw_slice() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf::<WithDrop>(len);
unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(p, len)) };
}
// control: slice one element longer than the allocation
#[kani::proof]
fn r2_raw_slice_oob_must_fail() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf::<WithDrop>(len);
unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(p, len + 1)) };
}
#[kani::proof]
fn r3_deque_drop() {
let (dq, _len) = any_deque::<WithDrop>();
drop(dq);
}
// primary: VecDeque::truncate (drops the tail through the glue), then Drop for VecDeque
#[kani::proof]
fn r4_deque_truncate_then_drop() {
let (mut dq, len) = any_deque::<WithDrop>();
let k: usize = kani::any();
dq.truncate(k);
assert!(dq.len() == if k < len { k } else { len });
drop(dq);
}
// r4 with covers (kept separate so that r4, compiled with --no-assertion-reach-checks, has no
// property that CBMC reports as failed when it is reachable)
#[kani::proof]
fn r4c_deque_truncate_then_drop_covers() {
let (mut dq, len) = any_deque::<WithDrop>();
let k: usize = kani::any();
kani::cover!(k > 0 && k < len, "truncate drops a proper non-empty tail");
kani::cover!(len == MAX, "largest length reached");
dq.truncate(k);
assert!(dq.len() == if k < len { k } else { len });
kani::cover!(dq.len() > 0, "Drop for VecDeque runs on a non-empty deque");
drop(dq);
kani::cover!(true, "end of harness reached after both glue calls");
}
#[kani::proof]
fn r5_deque_drain_then_drop() {
let (mut dq, len) = any_deque::<WithDrop>();
let a: usize = kani::any();
let b: usize = kani::any();
kani::assume(a <= b && b <= len);
drop(dq.drain(a..b));
assert!(dq.len() == len - (b - a));
drop(dq);
}
// control at deque level: len+1 claimed elements in a len-element allocation
#[kani::proof]
fn r7_deque_truncate_oob_must_fail() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf::<WithDrop>(len);
let v = unsafe { Vec::from_raw_parts(p, len + 1, len + 1) };
let dq = VecDeque::from(v);
let mut dq = std::mem::ManuallyDrop::new(dq);
dq.truncate(0);
}
// wrapped ring layout (head = cap - 1), symbolic length, truncate + Drop
#[kani::proof]
fn r8_wrapped_truncate_then_drop() {
let (mut dq, len) = any_deque::<WithDrop>();
kani::assume(len >= 2);
let last = dq.pop_back().unwrap();
dq.push_front(last);
let (front, back) = dq.as_slices();
kani::cover!(front.len() == 1 && back.len() == len - 1, "wrapped layout reached");
let k: usize = kani::any();
dq.truncate(k);
drop(dq);
}
// static-writing destructor, exact count through the real glue
#[kani::proof]
fn s2_counted_raw_slice() {
let len: usize = kani::any();
kani::assume(len > 0 && len <= MAX);
let p = any_buf::<CountedDrop>(len);
unsafe {
DROPS = 0;
ptr::drop_in_place(ptr::slice_from_raw_parts_mut(p, len));
assert!(DROPS == len);
}
}
// control: wrong count
#[kani::proof]
fn s3_counted_raw_slice_wrong_must_fail() {
let len: usize = kani::any();
kani::assume(len > 1 && len <= MAX);
let p = any_buf::<CountedDrop>(len);
unsafe {
DROPS = 0;
ptr::drop_in_place(ptr::slice_from_raw_parts_mut(p, len));
assert!(DROPS == len - 1);
}
}
#[kani::proof]
fn s4_counted_deque_truncate() {
let (mut dq, len) = any_deque::<CountedDrop>();
let k: usize = kani::any();
kani::assume(k <= len);
unsafe { DROPS = 0 };
dq.truncate(k);
unsafe { assert!(DROPS == len - k) };
drop(dq);
unsafe { assert!(DROPS == len) };
}
// heap-freeing destructor, concrete length: passes today by unwinding the glue loop
#[kani::proof]
fn v1_vec_of_box_concrete() {
let v: Vec<Box<u8>> = vec![Box::new(1u8), Box::new(2u8)];
drop(v);
}
Activity