Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 92 additions & 0 deletions library/alloc/src/rcs/arc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@ use core::slice::from_raw_parts_mut;
use core::sync::atomic::Ordering::{Acquire, Relaxed, Release};
use core::sync::atomic::{self, Atomic};
use core::{borrow, fmt, hint, intrinsics};
#[cfg(kani)]
use core::{kani, ub_checks};

#[cfg(kani)]
use safety::{ensures, requires};

#[cfg(not(no_global_oom_handling))]
use crate::alloc::handle_alloc_error;
Expand Down Expand Up @@ -3096,6 +3101,8 @@ impl<A: Allocator> Arc<dyn Any + Send + Sync, A> {
/// [`downcast`]: Self::downcast
#[inline]
#[unstable(feature = "downcast_unchecked", issue = "90850")]
#[cfg_attr(kani, requires((*self).is::<T>()))]
#[cfg_attr(kani, ensures(|result| ub_checks::can_dereference(&**result as *const T)))]
pub unsafe fn downcast_unchecked<T>(self) -> Arc<T, A>
where
T: Any + Send + Sync,
Expand Down Expand Up @@ -5217,3 +5224,88 @@ impl<T: ?Sized + Allocator, A: Allocator> AllocatorNightly for Arc<T, A> {}

#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")]
unsafe impl<T: Allocator + ?Sized, A: AllocatorClone> AllocatorClone for Arc<T, A> {}

#[cfg(kani)]
#[unstable(feature = "kani", issue = "none")]
mod verify {
#![allow(missing_docs)]

use core::any::Any;
use core::kani;

use super::Arc;

/// Shows that the assumed precondition does not rule out every execution.
fn cover_reached() {
kani::cover(true, "non-vacuity witness: reached with the precondition assumed");
}

#[kani::proof_for_contract(Arc::<dyn core::any::Any + core::marker::Send + core::marker::Sync + 'static, A>::downcast_unchecked::<i32>)]
pub fn check_downcast_unchecked_i32() {
let value: i32 = kani::any();
let shared: bool = kani::any();
let erased: Arc<dyn Any + Send + Sync> =
if kani::any() { Arc::new(value) } else { Arc::new(0u16) };
let extra = if shared { Some(Arc::clone(&erased)) } else { None };
let expected_strong = if shared { 2 } else { 1 };
let arc = unsafe { erased.downcast_unchecked::<i32>() };
assert!(*arc == value);
assert!(Arc::strong_count(&arc) == expected_strong);
drop(extra);
cover_reached();
}

#[kani::proof_for_contract(Arc::<dyn core::any::Any + core::marker::Send + core::marker::Sync + 'static, A>::downcast_unchecked::<bool>)]
pub fn check_downcast_unchecked_bool() {
let value: bool = kani::any();
let erased: Arc<dyn Any + Send + Sync> =
if kani::any() { Arc::new(value) } else { Arc::new(0u16) };
let arc = unsafe { erased.downcast_unchecked::<bool>() };
assert!(*arc == value);
cover_reached();
}

#[kani::proof_for_contract(Arc::<dyn core::any::Any + core::marker::Send + core::marker::Sync + 'static, A>::downcast_unchecked::<()>)]
pub fn check_downcast_unchecked_zst() {
let erased: Arc<dyn Any + Send + Sync> =
if kani::any() { Arc::new(()) } else { Arc::new(0u16) };
let arc = unsafe { erased.downcast_unchecked::<()>() };
assert!(*arc == ());
cover_reached();
}

#[kani::proof]
pub fn check_downcast() {
let is_match: bool = kani::any();
let shared: bool = kani::any();
if is_match {
let value: i32 = kani::any();
let erased: Arc<dyn Any + Send + Sync> = Arc::new(value);
let extra = if shared { Some(Arc::clone(&erased)) } else { None };
let expected_strong = if shared { 2 } else { 1 };
match erased.downcast::<i32>() {
Ok(arc) => {
assert!(*arc == value);
assert!(Arc::strong_count(&arc) == expected_strong);
kani::cover(true, "downcast Ok branch reached");
}
Err(_) => unreachable!("matching concrete type must downcast to Ok"),
}
drop(extra);
} else {
let other: u16 = kani::any();
let erased: Arc<dyn Any + Send + Sync> = Arc::new(other);
let extra = if shared { Some(Arc::clone(&erased)) } else { None };
let expected_strong = if shared { 2 } else { 1 };
match erased.downcast::<i32>() {
Ok(_) => unreachable!("mismatched concrete type must downcast to Err"),
Err(orig) => {
assert!((*orig).is::<u16>());
assert!(Arc::strong_count(&orig) == expected_strong);
kani::cover(true, "downcast Err branch reached");
}
}
drop(extra);
}
}
}
1 change: 1 addition & 0 deletions verifast-proofs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ Specifically, it currently contains the following proofs:

- Partial proof of [LinkedList](alloc/collections/linked_list.rs/)
- Partial proof of [RawVec](alloc/raw_vec/mod.rs/)
- Proof of [Arc / Weak / UniqueArc](alloc/rcs/arc.rs/) (Challenge 27)

See each proof's accompanying README for a tour of the proof and applicable caveats.

Expand Down
128 changes: 128 additions & 0 deletions verifast-proofs/alloc/rcs/arc.rs/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
# Verification of `Arc`, `Weak`, `UniqueArc`, and `UniqueArcUninit` with VeriFast (Challenge 27)

With the caveats documented below (see [Caveats & Trust Base](#caveats--trust-base) and [`atomic_model/TRUSTED-MODEL.md`](atomic_model/TRUSTED-MODEL.md)), this directory formally verifies Rust's atomically reference-counted smart pointers in [`library/alloc/src/rcs/arc.rs`](../../../../library/alloc/src/rcs/arc.rs) for [Challenge 27](../../../../doc/src/challenges/0027-arc.md) using **VeriFast 26.10** (concurrent separation logic + RustBelt semantic well-typedness), complemented by **Kani** in `library/alloc/src/rcs/arc.rs` for the `dyn Any` downcast methods unsupported by VeriFast 26.10's frontend.

## Challenge 27 Coverage Summary

| Criterion (`doc/src/challenges/0027-arc.md`) | VeriFast 26.10 | Kani complement | Combined |
|---|---|---|---|
| Required `pub unsafe fn`s (12 total) | **11 / 12** | **1 / 12** (`downcast_unchecked`) | **12 / 12 (100%)** |
| Safe-with-unsafe functions (58 total, >= 75% / 44 required) | **46 / 58 (79.3%)** | **1 / 58** (`downcast`) | **47 / 58 (81.0%)** |
| Total verified functions | **107** (101 non-wrapper fns in `verified/arc.rs` + 5 verified non-`assume_correct` allocation helpers + `rc::is_dangling`) | **2 functions (4 harnesses)** (`downcast_unchecked` x3, `downcast` x1) | **109 functions** |

VeriFast verifies **3,634 statements (0 errors)** in `verified/lib.rs` (plus **1,170 statements (0 errors)** in `atomic_model/arc_weak_test.rs`).

### Verified `pub unsafe fn`s (11 / 12 in VeriFast + 1 / 12 in Kani)

All 11 VeriFast-verified `pub unsafe fn`s carry full concurrent separation-logic safety contracts (`Arc_own`, `Arc_own_in`, `Arc_raw_own`, `Weak_own`, `Weak_raw_own`, and `full_borrow_content`):

1. `Arc<MaybeUninit<T>, A>::assume_init`
2. `Arc<[MaybeUninit<T>], A>::assume_init`
3. `Arc<T: ?Sized>::from_raw`
4. `Arc<T: ?Sized>::increment_strong_count`
5. `Arc<T: ?Sized>::decrement_strong_count`
6. `Arc<T: ?Sized, A: Allocator>::from_raw_in`
7. `Arc<T: ?Sized, A: Allocator>::increment_strong_count_in`
8. `Arc<T: ?Sized, A: Allocator>::decrement_strong_count_in`
9. `Arc<T: ?Sized, A: Allocator>::get_mut_unchecked`
10. `Weak<T: ?Sized>::from_raw`
11. `Weak<T: ?Sized, A: Allocator>::from_raw_in`
12. `Arc<dyn Any + Send + Sync, A>::downcast_unchecked` — verified with Kani (`#[cfg_attr(kani, ...)]` contract + `proof_for_contract` in `library/alloc/src/rcs/arc.rs`), since VeriFast 26.10 does not yet support trait objects (`Dynamic types are not yet supported`).

*(Bonus verified `pub unsafe fn`: `UniqueArc<MaybeUninit<T>, A>::assume_init`.)*

### Verified Safe-with-Unsafe Functions (46 / 58 in VeriFast + 1 / 58 in Kani)

All 46 VeriFast-verified safe-with-unsafe functions are proven unconditionally safe under RustBelt semantic well-typedness (`own` / `share` / `full_borrow`, with explicit `safety_proof` blocks wherever a function also exposes a stronger internal specification):

- **Core `Arc` & `Weak` concurrent atomics (27):** `Arc::{into_inner_with_allocator, new, pin, try_pin, try_new, new_in, pin_in, try_pin_in, try_new_in, try_unwrap, into_inner, into_raw_with_allocator, as_ptr, inner, get_mut}`, `Clone for Arc`, `Drop for Arc`, `Default for Arc<T: Default>`, `Weak::{as_ptr, into_raw_with_allocator, upgrade, inner}`, `Drop for Weak`, `UniqueArcUninit::{data_ptr, Drop}`, `Deref for UniqueArc`, `DerefMut for UniqueArc`.
- **`UniqueArc` concurrent transitions (3):** `UniqueArc::into_arc`, `UniqueArc::downgrade`, `Drop for UniqueArc`.
- **`Arc` uninit/zeroed single & slice allocations (12):** `Arc<T>::{new_uninit, new_zeroed, try_new_uninit, try_new_zeroed}`, `Arc<T, A>::{new_uninit_in, new_zeroed_in, try_new_uninit_in, try_new_zeroed_in}`, `Arc<[T]>::{new_uninit_slice, new_zeroed_slice}`, `Arc<[T], A>::{new_uninit_slice_in, new_zeroed_slice_in}`.
- **`UniqueArcUninit` & conversions (4):** `UniqueArcUninit::new`, `Arc::from_box_in`, `ArcFromSlice<T: TrivialClone>::from_slice`, `From<Vec<T, A>> for Arc<[T], A>`.
- **`dyn Any` downcast (1, Kani):** `Arc<dyn Any + Send + Sync, A>::downcast` (in `library/alloc/src/rcs/arc.rs`).

### Additional Verified Safe & Internal Functions

Beyond the two Challenge 27 tables, VeriFast also verifies:
- **Safe concurrent methods without `unsafe {}`:** `Arc::{downgrade, is_unique, strong_count, weak_count, deref, ptr_eq, allocator, into_raw}`, `Weak::{new, new_in, Default, clone, strong_count, weak_count, ptr_eq, allocator, into_raw}`, `UniqueArc::{new, new_in, try_new, try_new_in, weak_count, inner, as_ptr, into_raw_with_allocator, into_inner_with_allocator}`, `UniqueArcUninit::try_new`, `arcinner_layout_for_value_layout`, `data_offset_alignment`, `panic_arc_overflow`, `rc::is_dangling`.
- **Internal `unsafe fn`s:** `Arc::{from_inner, from_ptr, from_inner_in, from_ptr_in, drop_slow, allocate_for_ptr_in, allocate_for_slice, allocate_for_slice_in, copy_from_slice}`, `UniqueArc::{from_inner_in, from_raw_with_allocator}`, `UniqueArcUninit::into_arc`, `data_offset`, and the 5 monomorphized allocation helpers (`Arc_*_alloc_*_in__VeriFast_wrapper`, all verified without `assume_correct`).

## Directory Structure

```text
verifast-proofs/alloc/rcs/arc.rs/
atomic_model/ Trusted Relaxed/Acquire/Release/fence extern_spec + standalone Arc/Weak protocol test
TRUSTED-MODEL.md Detailed protocol, weak-memory justification (RustBelt Relaxed), and 6 negative tests
arc_atomic.rs/.rsspec
arc_atomic_cas.rs/.rsspec
arc_weak_test.rs Standalone 6-state Arc/Weak proof (1,170 statements verified, 0 errors)
verify.sh
original/ Byte-identical copy of library/alloc/src/rcs/arc.rs + crate root lib.rs
with-directives/ original/ + /*@~mut@*/ directives + 6-line nightly-2026-09-25 compat.patch
verified/ Annotated VeriFast proof (arc.rs, lib.rs, arc_pin.rs, arc_pin.rsspec)
compat.patch Exact 6-line diff between original/arc.rs and directive-stripped with-directives/arc.rs
update.sh Upstream sync helper registered in verifast-proofs/patch-verifast-proofs.sh
verify.sh Runs VeriFast, refinement-checker, and all 3 upstream/patch diff checks
README.md This file
```

## Tour of the Proof

### Concurrent `ArcInner<T>` Protocol (`Arc_inv`)

Every heap-allocated `ArcInner<T>` is governed by an Iris-style atomic invariant `Arc_inv<T>` inside VeriFast's `atomic_space(Marc, ...)` (see [`atomic_model/TRUSTED-MODEL.md`](atomic_model/TRUSTED-MODEL.md) for the full state machine):

- **6 protocol modes (`arc_mode`):**
1. `ModeShared(dk)`: `strong == s_cnt >= 1`; `Arc_inv` owns `borrow_end_token(dk, <T>.full_borrow_content)` and `[_]<T>.share(dk, default_tid, &data)`.
2. `ModeExclusive`: `strong == 1`, `weak == 1`, `s_cnt == 0`, `w_cnt == 0`; the unique `Arc` owns `<T>.full_borrow_content` directly (enabling `Arc::get_mut` and `UniqueArc`).
3. `ModeExclusiveLocked`: transient state inside `Arc::is_unique` while `weak == usize::MAX`.
4. `ModeDataOut`: `strong == 0`, `weak == w_cnt + 1`; used when `Arc::drop` / `Arc::try_unwrap` / `Arc::into_inner` extracts `data` (holding the implicit weak reference) and during `UniqueArc`'s exclusive lifecycle before `UniqueArc::into_arc` publishes `ModeDataOut -> ModeShared(dk)` via `strong.store(1, Release)`.
5. `ModeDataDropped`: `strong == 0`, `weak == w_cnt >= 1`; `(*ptr).data |-> _` has been returned to `Arc_inv` after `drop_in_place` / `ptr::read` so the final `Weak::drop` can deallocate `ArcInner<T>`.
6. `ModeDealloced`: `strong == 0`, `weak == 0`; allocation freed exactly once.

### Ownership Predicates & Raw-Pointer Contracts

- `Arc_own<T, A>(t, arc)` / `Arc_own_in<T, A>(t, arc, alloc_id)` and `Weak_own<T, A>(t, weak)` capture the RustBelt semantic ownership of `Arc<T, A>` and `Weak<T, A>`, tracking either an exclusive `ModeExclusive` half-token or a counting ticket on `sgid`/`wgid` (or the `usize::MAX` dangling sentinel for `Weak::new()`).
- `Arc_raw_own<T>(t, ptr, alloc_id)` and `Weak_raw_own<T>(t, ptr, alloc_id)` separate allocator identity `alloc_id` from the allocator value `alloc: A`, matching Rust's `into_raw_with_allocator` -> `(ptr, alloc)` -> `from_raw_in(ptr, alloc)` and `increment_strong_count_in` / `decrement_strong_count_in` APIs cleanly for all `T: ?Sized`.
- `UniqueArc_own<T, A>(t, ua)` models `ModeDataOut` ownership of `data` with concurrent `Weak` references (`UniqueArc::downgrade`, `UniqueArc::weak_count`, `UniqueArc::into_arc`, `Drop for UniqueArc`).
- `UniqueArcUninit_own<T, A>(t, uau)` models an uninitialized `ArcInner<T>` allocation prior to `UniqueArcUninit::into_arc`.

### Coverage of the 5 Challenge 27 UB Categories

1. **Data races:** Enforced by `Arc_inv` + `arc_atomic_cas.rsspec` Release/Acquire/fence synchronization (`pending_acquire` locks extracted heap resources until `Acquire` or `fence(Acquire)`). Six negative soundness tests in `atomic_model/` confirm VeriFast rejects missing `fence(Acquire)`, weakened `Relaxed` orderings, and unsynchronized CAS error paths.
2. **Dangling / misaligned accesses:** Every live `Arc`/`Weak` proves `dealloced == false` via its counting ticket; `Weak::new()`'s `usize::MAX` sentinel is checked via `is_dangling` before any dereference; `ArcInner_meta` enforces alignment and `pointer_within_limits`.
3. **Compiler intrinsic UB:** Preconditions for `ptr::read`, `ptr::drop_in_place`, `ptr::copy_nonoverlapping`, `Layout` alignment/extension, and `intrinsics::abort` are mechanically checked at every call site.
4. **Mutating immutable bytes:** Exclusive mutation (`get_mut`, `get_mut_unchecked`, `UniqueArc::deref_mut`, `drop_in_place`) requires `<T>.full_borrow_content` with `s_cnt == 0` and all shared lifetimes `dk` ended.
5. **Invalid values:** RustBelt `own` / `share` invariants enforce type validity across `MaybeUninit::assume_init`, slice initialization, `Box` / `Vec` transfers, and raw pointer conversions.

## How to Run

Run the full VeriFast CI suite (including `linked_list.rs`, `raw_vec/mod.rs`, and `rcs/arc.rs`):

```bash
bash verifast-proofs/check-verifast-proofs.sh
```

Or run only `Arc` standalone:

```bash
cd verifast-proofs/alloc/rcs/arc.rs
PATH="../../..:$PATH" bash atomic_model/verify.sh
PATH="../../..:$PATH" bash verify.sh
```

## Caveats & Trust Base

1. **VeriFast CLI flags:** `verify.sh` invokes VeriFast 26.10 with `-skip_specless_fns -ignore_unwind_paths -allow_assume -allow_ignore_ref_creation -allow_dead_code`. Unwind paths are not verified (same as `linked_list.rs` and `raw_vec/mod.rs`), and `-allow_ignore_ref_creation` is used for `&` references to `AtomicUsize` fields inside `atomic_space` (same as VeriFast's `tests/rust/safe_abstraction/arc.rs`).
2. **Trusted atomic model (`atomic_model/TRUSTED-MODEL.md`):** VeriFast 26.10's built-in `std/lib.rsspec` only models `SeqCst` atomics and omits `Acquire`/`Release`/`fence`/`compare_exchange_weak`. `atomic_model/arc_atomic_cas.rsspec` provides the `-extern_spec` for `core::sync::atomic` operations, justified under C++20/Rust weak memory via RustBelt Relaxed (Dang et al., POPL 2020) and validated by 6 negative soundness tests.
3. **`assume` inventory in `verified/arc.rs`:**
- **Zero `assume(false)` inside any executable function body** and **zero vacuous (`req false`) preconditions**.
- **3 localized runtime `assume`s** strictly inside aborting `> MAX_REFCOUNT` overflow branches (`Arc::clone`, `Weak::clone`, `UniqueArc::downgrade`) modeling Rust's documented bounded-concurrent-thread assumption (`< isize::MAX - 1` threads paused between `fetch_add` and `intrinsics::abort()`), matching `atomic_model/TRUSTED-MODEL.md` §3.3.
- **Ghost lemma `assume`s** are limited to standard VeriFast 26.10 prelude/`?Sized` gaps (`*_own_mono`, `*_Sync_implies_T_Send_Sync`, `init_ref_*`, `?Sized` `open_struct`/wrapper lemmas, VeriFast issue #610, and `alloc_id.lft == 'static` matching `linked_list.rs:2212`).
4. **Extern-spec wrapper shims:** Minimal stdlib/intrinsic shims marked `//@ assume_correct` comprise **44** `__VeriFast_wrapper` functions in `verified/arc.rs` (`NonNull`, `Box`, `Vec`, `Allocator`, `ManuallyDrop`, `Layout`, `ptr::*`, plus the Rust-trait-bound-gated `TrivialClone_slice_identity__VeriFast_wrapper<T: TrivialClone>`), **2** in `verified/lib.rs` (`ptr_cast_unit`, `ptr_addr`), and **2** extern specs in `verified/arc_pin.rsspec` (`intrinsics::abort`, `Pin::new_unchecked`). Note two specific modeling caveats:
- **`Pin::new_unchecked` (`verified/arc_pin.rsspec`):** Specified with `req <Ptr>.own(?t, pointer)` (omitting Rust's general pinning invariant). This is sound for its only uses in `arc.rs` (`Arc::pin*` / `Arc::try_pin*`), which pin a freshly allocated `Arc<T, A>` whose value has never been exposed by `&mut T`, and should not be reused blindly for arbitrary `Pin::new_unchecked` callers.
- **`ManuallyDrop_clone_Arc__VeriFast_wrapper` (`verified/arc.rs`):** Because `std::mem::ManuallyDrop::clone` is absent from VeriFast 26.10's `std/lib.rsspec`, this `assume_correct` shim models `ManuallyDrop::clone` delegating to `Arc::clone` inside `Arc::increment_strong_count_in` (`Arc::clone` itself is verified directly against `Arc_inv`).
5. **`compat.patch` & `refinement-checker` shims in `verify.sh`:**
- `compat.patch` is a 6-line nightly-2026-09-25 compatibility shim between `original/arc.rs` and `with-directives/arc.rs` (removing `#[rustc_assert_variance(covariant)]` and 2 `#[rustc_diagnostic_item]` attributes, and mapping `intrinsics::abort_immediate()` to `intrinsics::abort()`), checked on every run by `verify.sh`.
- `verify.sh` verifies all annotated functions with `refinement-checker`, enforcing **exact full-body token equality on both `verified/arc.rs` and `with-directives/arc.rs`** (after stripping ghost comments) for the 23 functions (plus 2 `STATIC_INNER_SLICE` `debug_assert!`s and 2 scope-exit `drop(_weak)` lines) that hit VeriFast 26.10 `refinement-checker` frontend gaps: 6 `RawPtr` functions (`{Arc,Weak,UniqueArc}::as_ptr`, `Arc::{from_box_in, copy_from_slice}`, `From<Vec<T, A>>`), `arcinner_layout_for_value_layout` (`unwrap_or_else` closure), `Weak::upgrade` (`try_update` CAS expansion), `Drop for {Arc, Weak}` (`&STATIC_INNER_SLICE.inner` `debug_assert!`), `{Arc::drop_slow, Drop for UniqueArc}` (explicit `drop(_weak)` at scope exit for ghost lifetime passing), and 15 `allocate_for_layout` callers beta-reduced to 5 **fully verified** (non-`assume_correct`, asserted by `verify.sh`) monomorphized helpers (`Arc_*_alloc_*_in__VeriFast_wrapper`).
6. **General VeriFast caveats:** Results hold for the Rust toolchain's target architecture (`LP64`), and inherit VeriFast's [known limitations](https://github.com/verifast/verifast/issues?q=is%3Aissue+is%3Aopen+label%3Aunsoundness) regarding pointer aliasing rules, custom type variance, and unverified tool/prelude soundness (same as `linked_list.rs` and `raw_vec/mod.rs`).
Loading
Loading