diff --git a/library/alloc/src/rcs/arc.rs b/library/alloc/src/rcs/arc.rs index b76001e55ae65..1a7fb0a01fb1d 100644 --- a/library/alloc/src/rcs/arc.rs +++ b/library/alloc/src/rcs/arc.rs @@ -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; @@ -3096,6 +3101,8 @@ impl Arc { /// [`downcast`]: Self::downcast #[inline] #[unstable(feature = "downcast_unchecked", issue = "90850")] + #[cfg_attr(kani, requires((*self).is::()))] + #[cfg_attr(kani, ensures(|result| ub_checks::can_dereference(&**result as *const T)))] pub unsafe fn downcast_unchecked(self) -> Arc where T: Any + Send + Sync, @@ -5217,3 +5224,88 @@ impl AllocatorNightly for Arc {} #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] unsafe impl AllocatorClone for Arc {} + +#[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::::downcast_unchecked::)] + pub fn check_downcast_unchecked_i32() { + let value: i32 = kani::any(); + let shared: bool = kani::any(); + let erased: Arc = + 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::() }; + assert!(*arc == value); + assert!(Arc::strong_count(&arc) == expected_strong); + drop(extra); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::)] + pub fn check_downcast_unchecked_bool() { + let value: bool = kani::any(); + let erased: Arc = + if kani::any() { Arc::new(value) } else { Arc::new(0u16) }; + let arc = unsafe { erased.downcast_unchecked::() }; + assert!(*arc == value); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::<()>)] + pub fn check_downcast_unchecked_zst() { + let erased: Arc = + 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 = Arc::new(value); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + 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 = Arc::new(other); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + Ok(_) => unreachable!("mismatched concrete type must downcast to Err"), + Err(orig) => { + assert!((*orig).is::()); + assert!(Arc::strong_count(&orig) == expected_strong); + kani::cover(true, "downcast Err branch reached"); + } + } + drop(extra); + } + } +} diff --git a/verifast-proofs/README.md b/verifast-proofs/README.md index 096d3e32e9061..3eb07aa902df5 100644 --- a/verifast-proofs/README.md +++ b/verifast-proofs/README.md @@ -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. diff --git a/verifast-proofs/alloc/rcs/arc.rs/README.md b/verifast-proofs/alloc/rcs/arc.rs/README.md new file mode 100644 index 0000000000000..679ad31558cb0 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/README.md @@ -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, A>::assume_init` +2. `Arc<[MaybeUninit], A>::assume_init` +3. `Arc::from_raw` +4. `Arc::increment_strong_count` +5. `Arc::decrement_strong_count` +6. `Arc::from_raw_in` +7. `Arc::increment_strong_count_in` +8. `Arc::decrement_strong_count_in` +9. `Arc::get_mut_unchecked` +10. `Weak::from_raw` +11. `Weak::from_raw_in` +12. `Arc::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, 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`, `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::{new_uninit, new_zeroed, try_new_uninit, try_new_zeroed}`, `Arc::{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::from_slice`, `From> for Arc<[T], A>`. +- **`dyn Any` downcast (1, Kani):** `Arc::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` Protocol (`Arc_inv`) + +Every heap-allocated `ArcInner` is governed by an Iris-style atomic invariant `Arc_inv` 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, .full_borrow_content)` and `[_].share(dk, default_tid, &data)`. + 2. `ModeExclusive`: `strong == 1`, `weak == 1`, `s_cnt == 0`, `w_cnt == 0`; the unique `Arc` owns `.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`. + 6. `ModeDealloced`: `strong == 0`, `weak == 0`; allocation freed exactly once. + +### Ownership Predicates & Raw-Pointer Contracts + +- `Arc_own(t, arc)` / `Arc_own_in(t, arc, alloc_id)` and `Weak_own(t, weak)` capture the RustBelt semantic ownership of `Arc` and `Weak`, 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, ptr, alloc_id)` and `Weak_raw_own(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, ua)` models `ModeDataOut` ownership of `data` with concurrent `Weak` references (`UniqueArc::downgrade`, `UniqueArc::weak_count`, `UniqueArc::into_arc`, `Drop for UniqueArc`). +- `UniqueArcUninit_own(t, uau)` models an uninitialized `ArcInner` 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 `.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`), **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 .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` 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>`), `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`). diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/TRUSTED-MODEL.md b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/TRUSTED-MODEL.md new file mode 100644 index 0000000000000..0bbef74785b44 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/TRUSTED-MODEL.md @@ -0,0 +1,105 @@ +# Trusted Atomic & Concurrency Model for `alloc::sync::Arc` / `Weak` (Challenge 27) + +This directory (`verifast-proofs/alloc/rcs/arc.rs/atomic_model/`) provides a sound concurrent separation-logic specification for `core::sync::atomic` operations used by `library/alloc/src/rcs/arc.rs` together with a complete, mechanically verified 6-state protocol for `ArcInner` (`arc_weak_test.rs`, **1,170 statements verified, 0 errors** in VeriFast 26.10). + +--- + +## 1. Why a Custom `-extern_spec` Is Required in VeriFast 26.10 + +VeriFast 26.10's built-in `bin/rust/std/lib.rsspec` (L1814–1917): +- Only declares `Ordering::{Relaxed, SeqCst}` (missing `Acquire`, `Release`, `AcqRel`). +- Hardcodes `Ordering::SeqCst` (`Relaxed => false`) on `AtomicUsize::{load, fetch_add, fetch_sub, compare_exchange}`. +- Omits `atomic::fence`, `AtomicUsize::{store, compare_exchange_weak, try_update}`, and `core::hint::spin_loop`. + +Rather than modifying the VeriFast toolchain or altering `library/alloc/src/rcs/arc.rs`, we attach trusted specifications via VeriFast's official `-extern_spec` mechanism on tiny zero-cost re-export crates: +- **`arc_atomic.rs` + `arc_atomic.rsspec`**: re-exports `core::sync::atomic::{Atomic, AtomicUsize, Ordering, fence}` and `core::hint::spin_loop`. Compatible with `std::alloc::Allocator` and all non-CAS functions in `arc.rs`. +- **`arc_atomic_cas.rs` + `arc_atomic_cas.rsspec`**: additionally re-exports `core::result::Result` to specify `compare_exchange`, `compare_exchange_weak`, and `try_update`. + +> **VeriFast 26.10 Limitations Documented for Integration:** +> 1. **`-extern_spec` isolation from `std/lib.rsspec`:** VeriFast 26.10 typechecks `-extern_spec` files against `prelude.rsspec` only, so an `.rsspec` file cannot name `std::result::Result`. Re-exporting `Result` in `arc_atomic_cas` enables `compare_exchange` / `compare_exchange_weak` / `try_update`, but clashes with `std::alloc::Allocator::allocate` if both are verified in the same pass. In `verify.sh`, all non-CAS functions verify in one pass under `arc_atomic`, and the 5 CAS functions (`try_unwrap`, `downgrade`, `make_mut`, `is_unique`/`get_mut`, `Weak::upgrade`) verify under `arc_atomic_cas` via `-focus : -allow_dead_code`. +> 2. **`try_update(..., checked_increment)` (`Weak::upgrade` L3460):** VeriFast 26.10's MIR translator aborts on `fn`-item operands (`Todo: Functions as operand in rvalues are not supported yet`). Passing a closure `|n| checked_increment(n)` avoids the crash, or expanding `try_update` to its standard `load(Relaxed)` + `compare_exchange_weak(Acquire, Relaxed)` CAS loop (as done in `arc_weak_test.rs`) verifies every step directly without any trusted `try_update` axiom. +> 3. **Reference creation (`-ignore_ref_creation`):** Like VeriFast's own `tests/rust/safe_abstraction/arc.rs`, verifying shared references to `AtomicUsize` fields inside an `atomic_space` requires `-ignore_ref_creation`, and VeriFast's boilerplate `*_own_mono` / `init_ref_*` lemmas use `assume(false)`. + +--- + +## 2. Concurrent Separation-Logic Protocol for `ArcInner` + +Every heap-allocated `ArcInner` (aligned to at least 2 bytes, guaranteeing `ptr as usize != usize::MAX`) is governed by an Iris-style atomic invariant `Arc_inv(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)` inside `atomic_space(Marc, ...)`. + +### Fixed Ghost State +| Ghost Cell / Counter | Role | +|---|---| +| `inv_gid: arc_mode` | Current protocol phase (6 states below); split `[1/2]` in `Arc_inv` and `[1/2]` in the unique `Arc` when exclusive. | +| `sgid` (`counting(dlft_pred, sgid, s_cnt, dk_opt)`) | Strong-reference tickets anchored at a **single fixed** `sgid`. Holds `some(dk)` + `lifetime_token(dk)` in `ModeShared(dk)`, and `none` otherwise. | +| `wgid` (`counting(weak_pred, wgid, w_cnt, dealloced)`) | Explicit `Weak` tickets (`w_cnt >= 0`). Holding any explicit `Weak` ticket mechanically proves `dealloced == false` and `w_cnt >= 1`, which rules out `ModeExclusive`, `ModeDealloced`, and the `usize::MAX` weak lock (`locked == true`). | +| `lock_gid: weak_lock_state` (`LockFree \| LockExcl \| LockShared(lf)`) | Models the `usize::MAX` weak-count lock in `Arc::is_unique`. In `LockShared(lf)`, the locking thread deposits `[lf]ghost_cell(sgid, some(dk))` into `Arc_inv`, which mechanically proves that `Arc::drop` cannot drop `strong` to `0` while the lock is held. | +| `imp_gid: i32` (`0 \| 1 \| 2`) | Tracks the single implicit weak reference held collectively by strong references (`0`), materialized when `strong: 1 -> 0` (`1`, split `[1/2]` in `Arc_inv` and `[1/2]` in the dropping thread), and dropped after `drop_in_place`/`ptr::read` returns `(*ptr).data \|-> _` (`2`). | + +### The 6-State Machine (`arc_mode`) +1. **`ModeShared(dk)`**: `strong == s_cnt >= 1`, `weak == usize::MAX` (if locked, forcing `w_cnt == 0`) or `w_cnt + 1 < usize::MAX`. `Arc_inv` owns `borrow_end_token(dk, .full_borrow_content)` and `[_].share(dk, default_tid, &data)`. +2. **`ModeExclusive`**: `strong == 1`, `weak == 1`, `s_cnt == 0`, `w_cnt == 0`, `lock_gid == LockFree`. The sole `Arc` owns `[1/2]ghost_cell(inv_gid, ModeExclusive)` and `.full_borrow_content(default_tid, &data)` directly. Entered by `Arc::new` and by `Arc::get_mut` (allowing empty-mask `full_borrow_convert_strong` restoration when `&mut T` ends!); transitions back to `ModeShared(dk')` with a fresh lifetime `dk'` in `Arc_share_full`. +3. **`ModeExclusiveLocked`**: Transient state inside `Arc::is_unique` between `weak.compare_exchange(1, usize::MAX, Acquire, Relaxed)` and `weak.store(1, Release)` when unique. +4. **`ModeDataOut`**: `strong == 0`, `weak == w_cnt + 1`, `lock_gid == LockFree`, `imp_gid == 1` (`[1/2]` in `Arc_inv`, `[1/2]` in the winning thread). Also re-usable for: + - **`Arc::new_cyclic_in`**: initializes `ArcInner` in `ModeDataOut` (`strong == 0`, `weak == 1`, `[1/2]ghost_cell(imp_gid, 1)` held by the constructor), constructs `T` while `&Weak` can observe `strong == 0`, writes `data`, and publishes `ModeDataOut -> ModeShared(dk)` via `strong.fetch_add(1, Release)`. + - **`Arc::make_mut`**: transitions `ModeShared -> ModeDataOut` via `strong.compare_exchange(1, 0, Acquire, Relaxed)`, then either transitions back `ModeDataOut -> ModeShared(dk')` via `strong.store(1, Release)` (if `weak == 1`) or drops the implicit weak after moving `data` out. +5. **`ModeDataDropped`**: `strong == 0`, `weak == w_cnt >= 1`, `imp_gid == 2`. The implicit weak reference has finished and deposited `(*ptr).data |-> _` back into `Arc_inv` so the last explicit `Weak::drop` can call `dealloc`. +6. **`ModeDealloced`**: `strong == 0`, `weak == 0`, `dealloced == true`. All physical resources (`strong`, `weak`, `data`, padding, `alloc_block`) have been extracted and deallocated exactly once. + +### Data-Race & UB Absence Guarantees +- **No data races:** All concurrent accesses to `strong` and `weak` occur via `AtomicUsize` inside `Arc_inv`. All reads of `data` occur under `[_].share(dk, ...)` while `dk` is alive (`strong >= 1`). Any mutation (`get_mut`), move (`try_unwrap`), or destruction (`drop_in_place`) of `data` occurs only after `dk` has ended (all strong tickets destroyed -> `s_cnt == 0`) and `Acquire` synchronization has completed. +- **No dangling/misaligned access:** Every non-dangling `Arc`/`Weak` proves `dealloced == false` via its counting ticket before accessing `ArcInner`. `Weak::new()` uses the `usize::MAX` sentinel and is explicitly guarded by `is_dangling(ptr)` before every dereference. +- **No double-drop / double-free / mutating immutable bytes / invalid values:** Enforced linearly by `.full_borrow_content`, `imp_gid`, `alloc_block`, and RustBelt's `own`/`share` type invariants. + +--- + +## 3. Soundness Assumptions in the Trusted Atomic Specification + +### 3.1 Ordering Validity & Release-Acquire-Fence Enforcement (Mechanically Checked) +Our specs (`arc_atomic.rsspec`, `arc_atomic_cas.rsspec`) contain **zero inconsistent axioms** (no global refcount-wrap axiom) and strictly enforce: +- **Rust ordering preconditions:** + - `load`: forbids `Release`/`AcqRel` (`valid_load_order(order) == true`). + - `store`: forbids `Acquire`/`AcqRel` (`valid_store_order(order) == true`) and requires `has_release(order) == true`. + - `fetch_sub`: requires `has_release(order) == true` (rejecting `fetch_sub(1, Relaxed)`). + - `fetch_add`: split by ordering: + - `has_release(order) == true`: uses `AtomicUsize_fetch_add_ghop(self, val, pre, post_imm, post_acq)` (may publish/release physical ownership into an invariant, e.g. `Arc::new_cyclic_in`; `post_acq` is locked in `pending_acquire` unless `has_acquire(order)`). + - `order == Ordering::Relaxed`: requires `val > 0` and uses `AtomicUsize_fetch_add_relaxed_ghop(self, val, frame, ghost_post)`, which **preserves `frame()` identically** (cannot consume/release physical ownership into an invariant; restricted to ghost ticket minting as in `Arc::clone` / `Weak::clone`). + - `compare_exchange` / `compare_exchange_weak` / `try_update`: forbid `Release`/`AcqRel` on failure (`valid_load_order(failure) == true`). + - `fence`: forbids `Relaxed` (`valid_fence_order(order) == true`). +- **Acquire-fence enforcement via `pending_acquire(P)` on BOTH success and failure paths:** + - `load(Relaxed)`: preserves `frame()` identically, exposes pure boolean facts `pure_post(result) == true` about the loaded atomic word itself (e.g. `cnt >= 1` for upstream `Arc::weak_count`'s `if cnt == usize::MAX { 0 } else { cnt - 1 }`), and locks any newly extracted heap resources inside `pending_acquire(app_usize(post_acq, result))`. + - `fetch_sub(Release)`: locks its postcondition in `pending_acquire(...)` until `atomic::fence(Acquire)` executes. + - `compare_exchange` / `compare_exchange_weak` / `try_update`: + - On `Ok(v)`: locks `post_ok(v)` in `pending_acquire(...)` unless `has_acquire(success)`. + - On `Err(v)`: preserves `pre()` identically and locks `post_err_acq(v)` in `pending_acquire(...)` unless `has_acquire(failure)`. +- **Adversarial spurious failure:** `compare_exchange_weak` universally quantifies `spurious: bool` in `_op`, forcing `Arc::downgrade` and `Weak::upgrade` to retry cleanly even when `v0 == current`. + +**Six negative soundness checks verified directly against our specs (all rejected by VeriFast):** +1. Removing `atomic::fence(Acquire)` in `Arc::drop` -> **rejected** (`No matching heap chunks: app_usize(Post, ...)()`). +2. Weakening `fetch_sub(1, Release)` to `Relaxed` in `Arc::drop` -> **rejected** (`Cannot prove has_release(Relaxed) <==> true`). +3. Weakening `strong.load(Acquire)` to `Relaxed` in `Arc::is_unique_and_take` -> **rejected** (`No matching heap chunks: is_AtomicUsize_load_relaxed_ghop(...)`). +4. Weakening `weak.store(1, Release)` to `Relaxed` in `Arc::is_unique_and_take` -> **rejected** (`Cannot prove has_release(Relaxed) <==> true`). +5. Smuggling a heap resource out of an invariant via CAS `Err` under `failure == Relaxed` without `fence(Acquire)` -> **rejected** (`No matching heap chunks: PostErrAcq(v)` — locked in `pending_acquire`). +6. Weakening `fetch_add(1, Release)` to `Relaxed` when publishing physical ownership into an invariant -> **rejected** (`No matching heap chunks: is_AtomicUsize_fetch_add_relaxed_ghop(...)`). + +### 3.2 Justification Under C++20 / Rust Weak Memory (RustBelt Relaxed) +VeriFast's underlying `atomic_space` logic does not include Iris/GPS view modalities (`▽`/`△`), so our `.rsspec` encodes Release-Acquire-Fence discipline structurally via `pending_acquire` + ordering preconditions, complemented by two lightweight syntactic audit conditions checked on every atomic proof site: +1. **Non-Acquire acquisition rule:** non-Acquire operations (`store(Release)`, `fetch_add(Release)`'s `post_imm`, `fetch_add(Relaxed)`'s `ghost_post`, and non-Acquire CAS `Ok` paths) must not extract physical heap `|->` resources out of `Arc_inv` outside `pending_acquire`. +2. **Non-Release CAS publication rule:** `compare_exchange` / `compare_exchange_weak` / `try_update` with `!has_release(success)` do not enforce `has_release(success)` on `Ok(v)` in the `.rsspec`, so their `Ok` ghost updates must not publish (release) physical heap `|->` resources from `pre()` into `Arc_inv`. + +Both rules hold trivially across `arc_weak_test.rs` and all 5 CAS sites in `library/alloc/src/rcs/arc.rs` (`downgrade`, `is_unique`, `try_unwrap`, `make_mut`, `Weak::upgrade`), which only perform ghost-ticket, weak-lock, or `ModeShared -> ModeDataOut` transitions on non-Release CAS `Ok` paths (never publishing physical heap ownership into `Arc_inv` without a `Release` `store`/`fetch_add`/`fetch_sub`). + +Soundness of the `Arc`/`Weak` synchronization protocol under C++20/Rust weak memory follows the mechanized Coq/Iris proof of Rust's `Arc` in **RustBelt Relaxed** (Dang, Jourdan, Kaiser, Dreyer, *POPL 2020*, "RustBelt Meets Relaxed Memory", §6): +- **`Arc::clone` / `Weak::clone` (`fetch_add(1, Relaxed)`):** Caller already holds `&Arc`/`&Weak`, which has already synchronized-with `Arc::new`/`downgrade`; incrementing the counter adds no new non-atomic ownership transfer and forms part of the release sequence on `strong`/`weak`. +- **`Arc::drop` / `Arc::into_inner` (`fetch_sub(1, Release)` + `fence(Acquire)`):** Every prior non-last `Arc::drop` releases its accesses to `data` into the release sequence on `strong`. The last `Arc::drop` (observing `1 -> 0`) executes `fence(Acquire)`, synchronizing-with all prior `Release` decrements on `strong` before calling `drop_in_place` / `ptr::read`. +- **`Weak::drop` (`fetch_sub(1, Release)` + `fence(Acquire)`):** Same release-sequence argument on `weak` (including the implicit weak decrement after `drop_in_place`/`ptr::read`), ensuring all accesses to `ArcInner` happen-before `dealloc`. +- **`Arc::try_unwrap` (`compare_exchange(1, 0, Relaxed, Relaxed)` + `fence(Acquire)`):** Observing `strong == 1` on `Ok` and executing `fence(Acquire)` synchronizes-with all prior `Release` decrements of `strong` before `ptr::read(&data)`. +- **`Arc::is_unique` (`weak.compare_exchange(1, usize::MAX, Acquire, Relaxed)` -> `strong.load(Acquire)` -> `weak.store(1, Release)`):** `weak` CAS (`Acquire`) synchronizes with prior `Weak::drop` (`Release`); `strong.load(Acquire)` synchronizes with prior `Arc::drop` (`Release`); `weak.store(1, Release)` synchronizes with `Arc::downgrade`'s `weak.compare_exchange_weak(..., Acquire, Relaxed)`. +- **`Weak::upgrade` (`compare_exchange_weak(n, n + 1, Acquire, Relaxed)`):** `Acquire` on success synchronizes with `Arc::new_cyclic`'s `Release` initialization of `strong`. + +### 3.3 Localized Refcount-Overflow Wrap Assumption (Clone Only) +Both `Arc::clone` (`arc.rs` L2526–2544) and `Weak::clone` (`arc.rs` L3594–3599) execute `fetch_add(1, Relaxed)` *before* checking `if old_size > MAX_REFCOUNT { abort(); }`. As documented in `library/alloc/src/rcs/arc.rs` L2536–2542, wrapping past `usize::MAX` (or colliding with the `usize::MAX` weak-lock sentinel) would require `>= isize::MAX - 1` (`2^63 - 2` on 64-bit platforms) threads concurrently paused between `fetch_add` and `abort()`. + +Rather than adding a globally inconsistent axiom to `.rsspec`, this standard Rust assumption is **strictly localized** to the aborting `v0 > isize::MAX as usize` branch inside `Arc::clone` (`assume(v0 < usize::MAX)`) and `Weak::clone` (`assume(v0 < usize::MAX - 1)`). `Arc::downgrade` and `Weak::upgrade` check `cur > MAX_REFCOUNT` *before* their CAS and use **no** `assume` at all. + +### 3.4 `try_update` Closure Soundness +In `arc_atomic_cas.rsspec`, `AtomicUsize::try_update` requires an abstract witness predicate `try_update_fn::(f, step)` binding the closure `f` to its pure partial step function `step: fix(usize, option)`. No caller can forge an arbitrary `step` unrelated to `f`. Wherever possible (as in `arc_weak_test.rs`), expanding `try_update` to its explicit `load(Relaxed)` + `compare_exchange_weak(Acquire, Relaxed)` loop eliminates even this predicate. diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic.rs b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic.rs new file mode 100644 index 0000000000000..b588027083ec2 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic.rs @@ -0,0 +1,9 @@ +#![no_std] +#![feature(generic_atomic)] + +// Re-exports `core::sync::atomic` items so VeriFast's `-extern_spec` attaches +// sound concurrent separation-logic specifications to all orderings and +// operations used in `library/alloc/src/rcs/arc.rs` without modifying the +// VeriFast toolchain or `arc.rs`. +pub use ::core::hint::spin_loop; +pub use ::core::sync::atomic::{Atomic, AtomicUsize, Ordering, fence}; diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic.rsspec b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic.rsspec new file mode 100644 index 0000000000000..281a6fc931021 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic.rsspec @@ -0,0 +1,229 @@ +// Trusted concurrent separation-logic specification for `core::sync::atomic` +// (non-Result-returning operations, compatible with `std::alloc::Allocator`). +// +// Enforces: +// 1. Exact Rust ordering validity preconditions (forbidding e.g. `load(Release)`, +// `store(Acquire)`, `fence(Relaxed)`). +// 2. Release/Acquire fence discipline via `pending_acquire`: +// - `load(Relaxed)` preserves the caller's `frame()` unchanged, allows pure +// boolean facts `pure_post(result)` about the loaded atomic word, and locks +// any newly extracted heap resources inside `pending_acquire(...)`. +// - `store` requires `has_release(order) == true`. +// - `fetch_sub` requires `has_release(order) == true` and locks acquired +// resources inside `pending_acquire(...)` when `!has_acquire(order)`. +// - `fetch_add(Relaxed)` uses `AtomicUsize_fetch_add_relaxed_ghop`, which +// preserves `frame()` unchanged (cannot consume/release physical ownership +// into an invariant; restricted to ghost counter tickets as in `Arc::clone` / +// `Weak::clone`). Releasing ownership (as in `Arc::new_cyclic_in`) requires +// `has_release(order) == true`. +// - `fence(Acquire | AcqRel | SeqCst)` unwraps `pending_acquire(P)` into `P()`. +// 3. Exact wrapping modular arithmetic on `fetch_add` and `fetch_sub`. +// 4. Zero inconsistent axioms (no global refcount-wrap axiom). +// +// See `TRUSTED-MODEL.md` for full soundness justification under C++20/Rust +// Release-Acquire-Relaxed semantics (RustBelt Relaxed, Dang et al. POPL 2020). + +enum Ordering { + Relaxed, + Release, + Acquire, + AcqRel, + SeqCst, +} + +struct Atomic; + +type AtomicUsize = Atomic; + +/*@ + +lem_auto size_of_AtomicUsize(); + req true; + ens std::mem::size_of::() == std::mem::size_of::(); + +lem_auto align_of_AtomicUsize(); + req true; + ens std::mem::align_of::() == std::mem::size_of::(); + +fix has_acquire(o: Ordering) -> bool { + match o { + Ordering::Relaxed => false, + Ordering::Release => false, + Ordering::Acquire => true, + Ordering::AcqRel => true, + Ordering::SeqCst => true, + } +} + +fix has_release(o: Ordering) -> bool { + match o { + Ordering::Relaxed => false, + Ordering::Release => true, + Ordering::Acquire => false, + Ordering::AcqRel => true, + Ordering::SeqCst => true, + } +} + +fix valid_load_order(o: Ordering) -> bool { + match o { + Ordering::Relaxed => true, + Ordering::Release => false, + Ordering::Acquire => true, + Ordering::AcqRel => false, + Ordering::SeqCst => true, + } +} + +fix valid_store_order(o: Ordering) -> bool { + match o { + Ordering::Relaxed => true, + Ordering::Release => true, + Ordering::Acquire => false, + Ordering::AcqRel => false, + Ordering::SeqCst => true, + } +} + +fix valid_fence_order(o: Ordering) -> bool { + match o { + Ordering::Relaxed => false, + Ordering::Release => true, + Ordering::Acquire => true, + Ordering::AcqRel => true, + Ordering::SeqCst => true, + } +} + +// Deferred acquisition token: resources extracted by a non-Acquire atomic +// operation (`load(Relaxed)`, `fetch_sub(Release)`) are locked inside +// `pending_acquire(P)` and CANNOT be accessed until `atomic::fence(Acquire)` +// (or `AcqRel`/`SeqCst`) synchronizes-with the releasing writes. +pred pending_acquire(P: pred()); + +// Discarding an unused deferred acquisition obligation is always sound: the +// thread simply relinquishes any resources inside `P` without accessing them. +lem discard_pending_acquire(P: pred()); + req pending_acquire(P); + ens true; + +fix Atomic::inner(v: Atomic) -> T; +pred AtomicUsize(p: *AtomicUsize; v: usize) = *p |-> ?v_ &*& v == v_.inner(); + +lem AtomicUsize_to_usize(p: *AtomicUsize); + req *p |-> ?v; + ens *(p as *usize) |-> v.inner() &*& (p as usize) % std::mem::size_of::() == 0; + +lem usize_to_AtomicUsize(p: *usize); + nonghost_callers_only + req *p |-> ?v0 &*& (p as usize) % std::mem::size_of::() == 0; + ens AtomicUsize(p as *AtomicUsize, v0); + +// --- Atomic operation ghost update types --- + +lem_type AtomicUsize_load_op(self: *AtomicUsize, P: pred(), Q: pred(usize)) = lem(); + req [?f]AtomicUsize(self, ?v) &*& P(); + ens [f]AtomicUsize(self, v) &*& Q(v); + +lem_type AtomicUsize_load_ghop(self: *AtomicUsize, pre: pred(), post: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(?op, self, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(op, self, P, Q) &*& Q(?result) &*& post(result); + +// Relaxed load ghost update: `frame()` is preserved identically, `pure_post(result)` +// reports a pure boolean fact about the loaded atomic word itself (e.g. `cnt >= 1`), +// and any newly extracted heap resources go into `post_acq(result)` (locked in `pending_acquire`). +lem_type AtomicUsize_load_relaxed_ghop(self: *AtomicUsize, frame: pred(), pure_post: fix(usize, bool), post_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(?op, self, ?P, ?Q) &*& P() &*& frame(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(op, self, P, Q) &*& Q(?result) &*& frame() &*& pure_post(result) == true &*& post_acq(result); + +lem_type AtomicUsize_store_op(self: *AtomicUsize, val: usize, P: pred(), Q: pred()) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens AtomicUsize(self, val) &*& Q(); + +lem_type AtomicUsize_store_ghop(self: *AtomicUsize, val: usize, pre: pred(), post: pred()) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_store_op(?op, self, val, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_store_op(op, self, val, P, Q) &*& Q() &*& post(); + +lem_type AtomicUsize_fetch_add_op(self: *AtomicUsize, val: usize, P: pred(), Q: pred(usize)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens AtomicUsize(self, (v0 + val) % (usize::MAX + 1)) &*& Q(v0); + +// Release/AcqRel/SeqCst fetch_add: may publish (release) resources from `pre()` into +// the atomic invariant; newly acquired resources are immediate only if `has_acquire(order)`. +lem_type AtomicUsize_fetch_add_ghop(self: *AtomicUsize, val: usize, pre: pred(), post_imm: pred(usize), post_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(?op, self, val, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(op, self, val, P, Q) &*& Q(?result) &*& post_imm(result) &*& post_acq(result); + +// Relaxed fetch_add (for `Arc::clone`, `Weak::clone`, `UniqueArc::downgrade`): +// requires `val > 0`, preserves `frame()` identically (cannot release physical +// ownership into the invariant), and permits only ghost-ticket minting in +// `ghost_post(result)` (see TRUSTED-MODEL.md §3.2). +lem_type AtomicUsize_fetch_add_relaxed_ghop(self: *AtomicUsize, val: usize, frame: pred(), ghost_post: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(?op, self, val, ?P, ?Q) &*& P() &*& frame(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(op, self, val, P, Q) &*& Q(?result) &*& frame() &*& ghost_post(result); + +lem_type AtomicUsize_fetch_sub_op(self: *AtomicUsize, val: usize, P: pred(), Q: pred(usize)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens AtomicUsize(self, (v0 - val + usize::MAX + 1) % (usize::MAX + 1)) &*& Q(v0); + +lem_type AtomicUsize_fetch_sub_ghop(self: *AtomicUsize, val: usize, pre: pred(), post: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_sub_op(?op, self, val, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_sub_op(op, self, val, P, Q) &*& Q(?result) &*& post(result); + +pred_ctor app_usize(post: pred(usize), v: usize)() = post(v); + +@*/ + +fn spin_loop(); +//@ req true; +//@ ens true; +//@ on_unwind_ens false; + +fn fence(order: Ordering); +//@ req valid_fence_order(order) == true &*& if has_acquire(order) { pending_acquire(?P) &*& ens P() on_unwind_ens false } else { ens true on_unwind_ens false }; +//@ ens true; +//@ on_unwind_ens false; + +impl Atomic { + fn new(v: usize) -> AtomicUsize; + //@ req true; + //@ ens result.inner() == v; + //@ on_unwind_ens false; + + fn load<'a>(self: &'a AtomicUsize, order: Ordering) -> usize; + /*@ + req valid_load_order(order) == true &*& + if has_acquire(order) { + is_AtomicUsize_load_ghop(?ghop, self, ?pre, ?post) &*& pre() &*& ens post(result) on_unwind_ens false + } else { + is_AtomicUsize_load_relaxed_ghop(?ghop, self, ?frame, ?pure_post, ?post_acq) &*& frame() &*& + ens frame() &*& pure_post(result) == true &*& pending_acquire(app_usize(post_acq, result)) on_unwind_ens false + }; + @*/ + //@ ens true; + //@ on_unwind_ens false; + + fn store<'a>(self: &'a AtomicUsize, val: usize, order: Ordering); + //@ req valid_store_order(order) == true &*& has_release(order) == true &*& is_AtomicUsize_store_ghop(?ghop, self, val, ?pre, ?post) &*& pre(); + //@ ens post(); + //@ on_unwind_ens false; + + fn fetch_add<'a>(self: &'a AtomicUsize, val: usize, order: Ordering) -> usize; + /*@ + req if has_release(order) { + is_AtomicUsize_fetch_add_ghop(?ghop, self, val, ?pre, ?post_imm, ?post_acq) &*& pre() &*& + ens post_imm(result) &*& (if has_acquire(order) { post_acq(result) } else { pending_acquire(app_usize(post_acq, result)) }) on_unwind_ens false + } else { + order == Ordering::Relaxed &*& val > 0 &*& + is_AtomicUsize_fetch_add_relaxed_ghop(?ghop, self, val, ?frame, ?ghost_post) &*& frame() &*& + ens frame() &*& ghost_post(result) on_unwind_ens false + }; + @*/ + //@ ens true; + //@ on_unwind_ens false; + + fn fetch_sub<'a>(self: &'a AtomicUsize, val: usize, order: Ordering) -> usize; + //@ req has_release(order) == true &*& is_AtomicUsize_fetch_sub_ghop(?ghop, self, val, ?pre, ?post) &*& pre(); + //@ ens if has_acquire(order) { post(result) } else { pending_acquire(app_usize(post, result)) }; + //@ on_unwind_ens false; +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic_cas.rs b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic_cas.rs new file mode 100644 index 0000000000000..311a67e695d33 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic_cas.rs @@ -0,0 +1,12 @@ +#![no_std] +#![feature(generic_atomic)] + +// Full atomic re-export crate for functions that also call `compare_exchange`, +// `compare_exchange_weak`, or `try_update` (which return `core::result::Result`). +// VeriFast 26.10 `-extern_spec` files cannot reference `std::result::Result` +// from built-in `std/lib.rsspec`, so this crate re-exports `Result` alongside +// `core::sync::atomic`. +pub use ::core::hint::spin_loop; +pub use ::core::ops::ControlFlow; +pub use ::core::result::Result; +pub use ::core::sync::atomic::{Atomic, AtomicUsize, Ordering, fence}; diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic_cas.rsspec b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic_cas.rsspec new file mode 100644 index 0000000000000..30c6dff5e5d59 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_atomic_cas.rsspec @@ -0,0 +1,377 @@ +// Trusted concurrent separation-logic specification for `core::sync::atomic` +// including `compare_exchange`, `compare_exchange_weak` (with spurious failure), +// and `try_update`. +// +// Enforces: +// 1. Exact Rust ordering validity preconditions. +// 2. Release/Acquire fence discipline via `pending_acquire` + `fence(Acquire)` +// on BOTH success AND failure paths: +// - `load(Relaxed)`: preserves `frame()`, exposes pure `pure_post(result)`, +// locks newly acquired heap resources in `pending_acquire`. +// - `store`: requires `has_release(order) == true`. +// - `fetch_sub`: requires `has_release(order) == true` and locks acquired +// resources in `pending_acquire` when `!has_acquire(order)`. +// - `fetch_add`: `Release`/`AcqRel`/`SeqCst` for releasing ownership; `Relaxed` +// requires `val > 0` and preserves `frame()` identically (ghost-ticket-only). +// - `compare_exchange` / `compare_exchange_weak` / `try_update`: +// * On `Ok(v)`: locks `post_ok(v)` in `pending_acquire` unless `has_acquire(success)`. +// * On `Err(v)`: preserves `pre()` identically and locks `post_err_acq(v)` in +// `pending_acquire` unless `has_acquire(failure)`. +// 3. Adversarial spurious failure (`spurious: bool`) on `compare_exchange_weak`. +// 4. Exact wrapping modular arithmetic on `fetch_add` and `fetch_sub`. +// 5. Zero inconsistent axioms (no global refcount-wrap axiom). +// +// See `TRUSTED-MODEL.md` for full soundness justification under C++20/Rust +// Release-Acquire-Relaxed semantics (RustBelt Relaxed, Dang et al. POPL 2020). + +enum ControlFlow { + Continue(C), + Break(B), +} + +enum Result { + Ok(T), + Err(E), +} + +impl std::ops::Try for arc_atomic_cas::Result { + fn branch(self: Result) -> ControlFlow, T>; + //@ req true; + /*@ + ens match self { + Result::Ok(v) => result == ControlFlow::Continue(v), + Result::Err(e) => result == ControlFlow::Break(Result::Err(e)) + }; + @*/ + //@ on_unwind_ens false; +} + +impl std::ops::FromResidual> for arc_atomic_cas::Result { + fn from_residual(residual: Result) -> Result; + //@ req true; + //@ ens match residual { Result::Ok(v) => result == Result::Err(default_value::), Result::Err(e) => result == Result::Err(e) }; + //@ on_unwind_ens false; +} + +impl Result { + fn is_ok<'a>(self: &'a Result) -> bool; + //@ req [?f](*self |-> ?v); + //@ ens [f](*self |-> v) &*& result == match v { Result::Ok(_x) => true, Result::Err(_e) => false }; + //@ on_unwind_ens false; + + fn is_err<'a>(self: &'a Result) -> bool; + //@ req [?f](*self |-> ?v); + //@ ens [f](*self |-> v) &*& result == match v { Result::Ok(_x) => false, Result::Err(_e) => true }; + //@ on_unwind_ens false; + + fn unwrap(self: Result) -> T; + /*@ + req thread_token(?t) &*& + match self { + Result::Ok(r) => ens thread_token(t) &*& result == r, + Result::Err(err) => .own(t, err) &*& ens false + }; + @*/ + //@ ens true; + //@ on_unwind_ens thread_token(t); +} + +enum Ordering { + Relaxed, + Release, + Acquire, + AcqRel, + SeqCst, +} + +struct Atomic; + +type AtomicUsize = Atomic; + +/*@ + +lem_auto size_of_AtomicUsize(); + req true; + ens std::mem::size_of::() == std::mem::size_of::(); + +lem_auto align_of_AtomicUsize(); + req true; + ens std::mem::align_of::() == std::mem::size_of::(); + +fix has_acquire(o: Ordering) -> bool { + match o { + Ordering::Relaxed => false, + Ordering::Release => false, + Ordering::Acquire => true, + Ordering::AcqRel => true, + Ordering::SeqCst => true, + } +} + +fix has_release(o: Ordering) -> bool { + match o { + Ordering::Relaxed => false, + Ordering::Release => true, + Ordering::Acquire => false, + Ordering::AcqRel => true, + Ordering::SeqCst => true, + } +} + +fix valid_load_order(o: Ordering) -> bool { + match o { + Ordering::Relaxed => true, + Ordering::Release => false, + Ordering::Acquire => true, + Ordering::AcqRel => false, + Ordering::SeqCst => true, + } +} + +fix valid_store_order(o: Ordering) -> bool { + match o { + Ordering::Relaxed => true, + Ordering::Release => true, + Ordering::Acquire => false, + Ordering::AcqRel => false, + Ordering::SeqCst => true, + } +} + +fix valid_fence_order(o: Ordering) -> bool { + match o { + Ordering::Relaxed => false, + Ordering::Release => true, + Ordering::Acquire => true, + Ordering::AcqRel => true, + Ordering::SeqCst => true, + } +} + +// Deferred acquisition token: resources extracted by a non-Acquire atomic +// operation (`load(Relaxed)`, `fetch_sub(Release)`, or CAS on `Ok`/`Err` with +// non-Acquire ordering) are locked inside `pending_acquire(P)` until +// `atomic::fence(Acquire)` executes. +pred pending_acquire(P: pred()); + +lem discard_pending_acquire(P: pred()); + req pending_acquire(P); + ens true; + +fix Atomic::inner(v: Atomic) -> T; +pred AtomicUsize(p: *AtomicUsize; v: usize) = *p |-> ?v_ &*& v == v_.inner(); + +lem AtomicUsize_to_usize(p: *AtomicUsize); + req *p |-> ?v; + ens *(p as *usize) |-> v.inner() &*& (p as usize) % std::mem::size_of::() == 0; + +lem usize_to_AtomicUsize(p: *usize); + nonghost_callers_only + req *p |-> ?v0 &*& (p as usize) % std::mem::size_of::() == 0; + ens AtomicUsize(p as *AtomicUsize, v0); + +// --- Atomic operation ghost update types --- + +lem_type AtomicUsize_load_op(self: *AtomicUsize, P: pred(), Q: pred(usize)) = lem(); + req [?f]AtomicUsize(self, ?v) &*& P(); + ens [f]AtomicUsize(self, v) &*& Q(v); + +lem_type AtomicUsize_load_ghop(self: *AtomicUsize, pre: pred(), post: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(?op, self, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(op, self, P, Q) &*& Q(?result) &*& post(result); + +lem_type AtomicUsize_load_relaxed_ghop(self: *AtomicUsize, frame: pred(), pure_post: fix(usize, bool), post_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(?op, self, ?P, ?Q) &*& P() &*& frame(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_load_op(op, self, P, Q) &*& Q(?result) &*& frame() &*& pure_post(result) == true &*& post_acq(result); + +lem_type AtomicUsize_store_op(self: *AtomicUsize, val: usize, P: pred(), Q: pred()) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens AtomicUsize(self, val) &*& Q(); + +lem_type AtomicUsize_store_ghop(self: *AtomicUsize, val: usize, pre: pred(), post: pred()) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_store_op(?op, self, val, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_store_op(op, self, val, P, Q) &*& Q() &*& post(); + +lem_type AtomicUsize_fetch_add_op(self: *AtomicUsize, val: usize, P: pred(), Q: pred(usize)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens AtomicUsize(self, (v0 + val) % (usize::MAX + 1)) &*& Q(v0); + +lem_type AtomicUsize_fetch_add_ghop(self: *AtomicUsize, val: usize, pre: pred(), post_imm: pred(usize), post_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(?op, self, val, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(op, self, val, P, Q) &*& Q(?result) &*& post_imm(result) &*& post_acq(result); + +lem_type AtomicUsize_fetch_add_relaxed_ghop(self: *AtomicUsize, val: usize, frame: pred(), ghost_post: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(?op, self, val, ?P, ?Q) &*& P() &*& frame(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_add_op(op, self, val, P, Q) &*& Q(?result) &*& frame() &*& ghost_post(result); + +lem_type AtomicUsize_fetch_sub_op(self: *AtomicUsize, val: usize, P: pred(), Q: pred(usize)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens AtomicUsize(self, (v0 - val + usize::MAX + 1) % (usize::MAX + 1)) &*& Q(v0); + +lem_type AtomicUsize_fetch_sub_ghop(self: *AtomicUsize, val: usize, pre: pred(), post: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_sub_op(?op, self, val, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_fetch_sub_op(op, self, val, P, Q) &*& Q(?result) &*& post(result); + +lem_type AtomicUsize_compare_exchange_op(self: *AtomicUsize, current: usize, new: usize, P: pred(), Q: pred(Result)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens if v0 == current { AtomicUsize(self, new) &*& Q(Result::Ok(v0)) } else + { AtomicUsize(self, v0) &*& Q(Result::Err(v0)) }; + +// On `Ok(v)`, `pre()` is transformed into `post_ok(v)` (locked in `pending_acquire` +// unless `has_acquire(success)`). On `Err(v)`, `pre()` MUST be preserved unchanged +// and any newly extracted resource goes into `post_err_acq(v)` (locked in +// `pending_acquire` unless `has_acquire(failure)`). +lem_type AtomicUsize_compare_exchange_ghop(self: *AtomicUsize, current: usize, new: usize, pre: pred(), post_ok: pred(usize), post_err_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_compare_exchange_op(?op, self, current, new, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_compare_exchange_op(op, self, current, new, P, Q) &*& Q(?result) &*& + match result { + Result::Ok(v) => post_ok(v), + Result::Err(v) => pre() &*& post_err_acq(v), + }; + +// Spurious failure is explicitly modeled: `spurious: bool` is universally +// quantified (chosen adversarially by the hardware/environment). When +// `spurious == true`, the CAS fails with `Err(v0)` even if `v0 == current`. +lem_type AtomicUsize_compare_exchange_weak_op(self: *AtomicUsize, current: usize, new: usize, spurious: bool, P: pred(), Q: pred(Result)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens if v0 == current && !spurious { AtomicUsize(self, new) &*& Q(Result::Ok(v0)) } else + { AtomicUsize(self, v0) &*& Q(Result::Err(v0)) }; + +lem_type AtomicUsize_compare_exchange_weak_ghop(self: *AtomicUsize, current: usize, new: usize, pre: pred(), post_ok: pred(usize), post_err_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_compare_exchange_weak_op(?op, self, current, new, ?spurious, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_compare_exchange_weak_op(op, self, current, new, spurious, P, Q) &*& Q(?result) &*& + match result { + Result::Ok(v) => post_ok(v), + Result::Err(v) => pre() &*& post_err_acq(v), + }; + +// Abstract witness tying closure `f: F` to its pure mathematical transition `step`. +pred try_update_fn(f: F, step: fix(usize, option)); + +lem_type AtomicUsize_try_update_op(self: *AtomicUsize, step: fix(usize, option), P: pred(), Q: pred(Result)) = lem(); + req AtomicUsize(self, ?v0) &*& P(); + ens match step(v0) { + some(v1) => AtomicUsize(self, v1) &*& Q(Result::Ok(v0)), + none => AtomicUsize(self, v0) &*& Q(Result::Err(v0)), + }; + +lem_type AtomicUsize_try_update_ghop(self: *AtomicUsize, step: fix(usize, option), pre: pred(), post_ok: pred(usize), post_err_acq: pred(usize)) = lem(); + req atomic_mask(MaskTop) &*& is_AtomicUsize_try_update_op(?op, self, step, ?P, ?Q) &*& P() &*& pre(); + ens atomic_mask(MaskTop) &*& is_AtomicUsize_try_update_op(op, self, step, P, Q) &*& Q(?result) &*& + match result { + Result::Ok(v) => post_ok(v), + Result::Err(v) => pre() &*& post_err_acq(v), + }; + +pred_ctor app_usize(post: pred(usize), v: usize)() = post(v); + +@*/ + +fn spin_loop(); +//@ req true; +//@ ens true; +//@ on_unwind_ens false; + +fn fence(order: Ordering); +//@ req valid_fence_order(order) == true &*& if has_acquire(order) { pending_acquire(?P) &*& ens P() on_unwind_ens false } else { ens true on_unwind_ens false }; +//@ ens true; +//@ on_unwind_ens false; + +impl Atomic { + fn new(v: usize) -> AtomicUsize; + //@ req true; + //@ ens result.inner() == v; + //@ on_unwind_ens false; + + fn load<'a>(self: &'a AtomicUsize, order: Ordering) -> usize; + /*@ + req valid_load_order(order) == true &*& + if has_acquire(order) { + is_AtomicUsize_load_ghop(?ghop, self, ?pre, ?post) &*& pre() &*& ens post(result) on_unwind_ens false + } else { + is_AtomicUsize_load_relaxed_ghop(?ghop, self, ?frame, ?pure_post, ?post_acq) &*& frame() &*& + ens frame() &*& pure_post(result) == true &*& pending_acquire(app_usize(post_acq, result)) on_unwind_ens false + }; + @*/ + //@ ens true; + //@ on_unwind_ens false; + + fn store<'a>(self: &'a AtomicUsize, val: usize, order: Ordering); + //@ req valid_store_order(order) == true &*& has_release(order) == true &*& is_AtomicUsize_store_ghop(?ghop, self, val, ?pre, ?post) &*& pre(); + //@ ens post(); + //@ on_unwind_ens false; + + fn fetch_add<'a>(self: &'a AtomicUsize, val: usize, order: Ordering) -> usize; + /*@ + req if has_release(order) { + is_AtomicUsize_fetch_add_ghop(?ghop, self, val, ?pre, ?post_imm, ?post_acq) &*& pre() &*& + ens post_imm(result) &*& (if has_acquire(order) { post_acq(result) } else { pending_acquire(app_usize(post_acq, result)) }) on_unwind_ens false + } else { + order == Ordering::Relaxed &*& val > 0 &*& + is_AtomicUsize_fetch_add_relaxed_ghop(?ghop, self, val, ?frame, ?ghost_post) &*& frame() &*& + ens frame() &*& ghost_post(result) on_unwind_ens false + }; + @*/ + //@ ens true; + //@ on_unwind_ens false; + + fn fetch_sub<'a>(self: &'a AtomicUsize, val: usize, order: Ordering) -> usize; + //@ req has_release(order) == true &*& is_AtomicUsize_fetch_sub_ghop(?ghop, self, val, ?pre, ?post) &*& pre(); + //@ ens if has_acquire(order) { post(result) } else { pending_acquire(app_usize(post, result)) }; + //@ on_unwind_ens false; + + fn compare_exchange<'a>(self: &'a AtomicUsize, current: usize, new: usize, success: Ordering, failure: Ordering) -> Result; + /*@ + req valid_load_order(failure) == true &*& + is_AtomicUsize_compare_exchange_ghop(?ghop, self, current, new, ?pre, ?post_ok, ?post_err_acq) &*& pre(); + @*/ + /*@ + ens match result { + Result::Ok(v) => + if has_acquire(success) { post_ok(v) } + else { pending_acquire(app_usize(post_ok, v)) }, + Result::Err(v) => + pre() &*& + if has_acquire(failure) { post_err_acq(v) } + else { pending_acquire(app_usize(post_err_acq, v)) }, + }; + @*/ + //@ on_unwind_ens false; + + fn compare_exchange_weak<'a>(self: &'a AtomicUsize, current: usize, new: usize, success: Ordering, failure: Ordering) -> Result; + /*@ + req valid_load_order(failure) == true &*& + is_AtomicUsize_compare_exchange_weak_ghop(?ghop, self, current, new, ?pre, ?post_ok, ?post_err_acq) &*& pre(); + @*/ + /*@ + ens match result { + Result::Ok(v) => + if has_acquire(success) { post_ok(v) } + else { pending_acquire(app_usize(post_ok, v)) }, + Result::Err(v) => + pre() &*& + if has_acquire(failure) { post_err_acq(v) } + else { pending_acquire(app_usize(post_err_acq, v)) }, + }; + @*/ + //@ on_unwind_ens false; + + fn try_update<'a, F>(self: &'a AtomicUsize, set_order: Ordering, fetch_order: Ordering, f: F) -> Result; + /*@ + req valid_load_order(fetch_order) == true &*& + try_update_fn::(f, ?step) &*& + is_AtomicUsize_try_update_ghop(?ghop, self, step, ?pre, ?post_ok, ?post_err_acq) &*& pre(); + @*/ + /*@ + ens match result { + Result::Ok(v) => + if has_acquire(set_order) { post_ok(v) } + else { pending_acquire(app_usize(post_ok, v)) }, + Result::Err(v) => + pre() &*& + if has_acquire(fetch_order) { post_err_acq(v) } + else { pending_acquire(app_usize(post_err_acq, v)) }, + }; + @*/ + //@ on_unwind_ens false; +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_weak_test.rs b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_weak_test.rs new file mode 100644 index 0000000000000..1f7cff82dacc1 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/arc_weak_test.rs @@ -0,0 +1,1883 @@ +// Standalone VeriFast 26.10 proof of concurrent `Arc` + `Weak` with: +// - Both `strong: AtomicUsize` and `weak: AtomicUsize` counts +// - `usize::MAX` weak-lock sentinel (`Arc::is_unique` / `Arc::get_mut` vs `Arc::downgrade`) +// - `Weak::new()` dangling `usize::MAX` pointer sentinel +// - Real `core::sync::atomic` operations with `Relaxed` / `Acquire` / `Release` + `atomic::fence(Acquire)` +// via `-extern_spec arc_atomic_cas=arc_atomic_cas.rsspec` +// +// Proves: `Arc::new`, `Arc::deref`, `Arc::clone`, `Arc::drop`, `Arc::downgrade`, +// `Arc::is_unique`, `Arc::get_mut`, `Arc::strong_count`, `Arc::weak_count`, +// `Weak::new`, `Weak::clone`, `Weak::upgrade`, `Weak::drop`. + +#![allow(dead_code)] + +extern crate arc_atomic_cas; + +use std::process::abort; +use std::ptr::NonNull; +use std::sync::atomic::Ordering::{Acquire, Relaxed, Release}; +use std::sync::atomic::{self, AtomicUsize}; + +const MAX_REFCOUNT: usize = (isize::MAX) as usize; + +#[inline] +fn is_dangling(ptr: *const T) -> bool +//@ req true; +//@ ens result == (ptr as usize == usize::MAX); +//@ on_unwind_ens false; +{ + (ptr as usize) == usize::MAX +} + +#[repr(C, align(2))] +struct ArcInner { + strong: AtomicUsize, + weak: AtomicUsize, + data: T, +} + +pub struct Arc { + ptr: NonNull>, +} + +pub struct Weak { + ptr: NonNull>, +} + +/*@ + +fix Narc() -> *u8 { 42 as *u8 } +fix Marc() -> mask_t { MaskSingle(Narc) } +fix always_true(r: usize) -> bool { true } +fix ge_one(r: usize) -> bool { r >= 1 } + +inductive arc_mode = + | ModeShared(dk: lifetime_t) + | ModeExclusive + | ModeExclusiveLocked + | ModeDataOut + | ModeDataDropped + | ModeDealloced; + +// Strong-reference counting predicate anchored at fixed ghost cell `sgid`. +// Holds `some(dk)` + `lifetime_token(dk)` while in `ModeShared(dk)`, and `none` +// in all other modes. +pred dlft_pred(sgid: i32; dk_opt: option) = + ghost_cell(sgid, dk_opt) &*& + match dk_opt { + some(dk) => lifetime_token(dk), + none => true, + }; + +// Explicit weak-reference counting predicate anchored at fixed ghost cell `wgid`. +// Holds `false` while the `ArcInner` allocation is live, `true` once deallocated. +pred weak_pred(wgid: i32; dealloced: bool) = + ghost_cell(wgid, dealloced); + +inductive weak_lock_state = + | LockFree + | LockExcl + | LockShared(lf: real); + +// Weak-lock invariant in `ModeShared(dk)`: +// - When unlocked: `lock_gid` holds `LockFree` (full `[1]` owned by `Arc_inv`). +// - When locked (`weak == usize::MAX`): `lock_gid` holds `LockShared(lf)` (`[1/2]` in `Arc_inv`, +// `[1/2]` in the locking thread) AND `Arc_inv` holds `[lf]ghost_cell(sgid, some(dk))` +// (which mechanically proves `locked` cannot be `true` when the last strong +// reference drops `s_cnt` to `0`, and returns the exact `lf` fraction on unlock!). +pred shared_weak_lock(lock_gid: i32, sgid: i32, dk: lifetime_t, locked: bool) = + [1/2]ghost_cell::(lock_gid, ?ls) &*& + match ls { + LockShared(lf) => locked == true &*& 0 < lf &*& [lf]ghost_cell(sgid, some(dk)), + LockFree => locked == false &*& [1/2]ghost_cell::(lock_gid, LockFree), + LockExcl => false, + }; + +// 6-state concurrent separation-logic invariant for `ArcInner`. +// Fixed parameters: `(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)`. +pred_ctor Arc_inv(inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, ptr: *ArcInner)() = + counting(dlft_pred, sgid, ?s_cnt, ?dk_opt) &*& + counting(weak_pred, wgid, ?w_cnt, ?dealloced) &*& + [1/2]ghost_cell::(inv_gid, ?mode) &*& + s_cnt >= 0 &*& w_cnt >= 0 &*& + match mode { + ModeShared(dk) => + [1/2]ghost_cell(inv_gid, ModeShared(dk)) &*& + dk_opt == some(dk) &*& + dealloced == false &*& + s_cnt >= 1 &*& s_cnt <= usize::MAX &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, s_cnt) &*& + shared_weak_lock(lock_gid, sgid, dk, ?locked) &*& + if locked { w_cnt == 0 &*& arc_atomic_cas::AtomicUsize(&(*ptr).weak, usize::MAX) } + else { w_cnt + 1 < usize::MAX &*& arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt + 1) } &*& + ghost_cell(imp_gid, 0) &*& + borrow_end_token(dk, .full_borrow_content(default_tid, &(*ptr).data)) &*& + [_](.share)(dk, default_tid, &(*ptr).data) &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) &*& + struct_ArcInner_padding::(ptr), + ModeExclusive => + // The other `[1/2]ghost_cell(inv_gid, ModeExclusive)` and `.full_borrow_content` + // are owned directly by the unique `Arc` handle. + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + w_cnt == 0 &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 1) &*& + ghost_cell::(lock_gid, LockFree) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, 1) &*& + ghost_cell(imp_gid, 0) &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) &*& + struct_ArcInner_padding::(ptr), + ModeExclusiveLocked => + // Transient state during `is_unique` between `weak.compare_exchange(1, usize::MAX)` + // and `weak.store(1, Release)` while unique ownership is held by `is_unique`. + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + w_cnt == 0 &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 1) &*& + [1/2]ghost_cell::(lock_gid, LockExcl) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, usize::MAX) &*& + ghost_cell(imp_gid, 0) &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) &*& + struct_ArcInner_padding::(ptr), + ModeDataOut => + // `strong` reached 0; the winning thread holds `[1/2]ghost_cell(imp_gid, 1)` + // and is dropping/reading `(*ptr).data`, after which it drops its implicit Weak. + [1/2]ghost_cell(inv_gid, ModeDataOut) &*& + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + ghost_cell::(lock_gid, LockFree) &*& + w_cnt + 1 < usize::MAX &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt + 1) &*& + [1/2]ghost_cell(imp_gid, 1) &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) &*& + struct_ArcInner_padding::(ptr), + ModeDataDropped => + // Implicit weak has dropped and returned `(*ptr).data |-> _` to `Arc_inv`. + // At least one explicit `Weak` remains (`w_cnt >= 1`). + [1/2]ghost_cell(inv_gid, ModeDataDropped) &*& + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + w_cnt >= 1 &*& w_cnt < usize::MAX &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + ghost_cell::(lock_gid, LockFree) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt) &*& + ghost_cell(imp_gid, 2) &*& + (*ptr).data |-> _ &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) &*& + struct_ArcInner_padding::(ptr), + ModeDealloced => + [1/2]ghost_cell(inv_gid, ModeDealloced) &*& + dk_opt == none &*& + dealloced == true &*& + s_cnt == 0 &*& + w_cnt == 0 &*& + ghost_cell::(lock_gid, LockFree) &*& + ghost_cell(imp_gid, 2), + }; + +// Persistent metadata shared by all `Arc` and `Weak` handles to the same `ArcInner`. +pred ArcInner_meta(inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, ptr: *ArcInner;) = + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + pointer_within_limits(&(*ptr).strong) == true &*& + pointer_within_limits(&(*ptr).weak) == true &*& + pointer_within_limits(&(*ptr).data) == true &*& + (ptr as usize) != 0 &*& (ptr as usize) != usize::MAX &*& + is_Send(typeid(T)) == true &*& is_Sync(typeid(T)) == true; + +// Ownership of `Arc`: either Exclusive (unique strong + zero explicit weaks, +// directly holding `.full_borrow_content`) or Shared (holding a strong ticket +// for active lifetime `dk`). +pred >.own(t, arc) = + [_]std::ptr::NonNull_own(default_tid, arc.ptr) &*& + [_]exists(?ptr) &*& arc.ptr.as_ptr() == ptr &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + exists::(?exclusive) &*& + if exclusive { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(?dk)) &*& + [_](.share)(dk, default_tid, &(*ptr).data) + }; + +pred_ctor Arc_frac_bc(l: *Arc, nnp: std::ptr::NonNull>)(;) = (*l).ptr |-> nnp; +pred_ctor strong_ticket_(sgid: i32, dk: lifetime_t, frac: real)(;) = + ticket(dlft_pred, sgid, frac) &*& [frac]ghost_cell(sgid, some(dk)); + +pred >.share(k, t, l) = + [_]exists(?nnp) &*& [_]frac_borrow(k, Arc_frac_bc(l, nnp)) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + [_]exists(?dk) &*& [_]exists(?frac) &*& + [_]frac_borrow(k, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) &*& + [_](.share)(dk, default_tid, &(*ptr).data); + +// Ownership of `Weak`: either dangling (`ptr == usize::MAX`, from `Weak::new()`) +// or an explicit weak handle holding a `weak_pred` ticket. +pred >.own(t, weak) = + [_]std::ptr::NonNull_own(default_tid, weak.ptr) &*& + [_]exists(?ptr) &*& weak.ptr.as_ptr() == ptr &*& + if (ptr as usize) == usize::MAX { + true + } else { + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + ticket(weak_pred, wgid, ?wfrac) &*& + [wfrac]weak_pred(wgid, false) + }; + +// Internal ownership of the implicit `Weak` created in `Arc::drop` after `T` is dropped. +pred Weak_implicit_own(nnp: std::ptr::NonNull>) = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + [1/2]ghost_cell(imp_gid, 1) &*& + (*ptr).data |-> _; + +pred_ctor Weak_frac_bc(l: *Weak, nnp: std::ptr::NonNull>)(;) = (*l).ptr |-> nnp; +pred_ctor weak_ticket_(wgid: i32, wfrac: real)(;) = + ticket(weak_pred, wgid, wfrac) &*& [wfrac]weak_pred(wgid, false); + +pred >.share(k, t, l) = + [_]exists(?nnp) &*& [_]frac_borrow(k, Weak_frac_bc(l, nnp)) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + if (ptr as usize) == usize::MAX { + true + } else { + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + [_]exists(?wfrac) &*& + [_]frac_borrow(k, weak_ticket_(wgid, wfrac)) + }; + +// Helper state predicate for `Arc::is_unique_and_take` across the 3 atomic steps. +pred UniqueState(inv_gid: i32, sgid: i32, lock_gid: i32, ptr: *ArcInner, locked: bool, is_excl: bool) = + if is_excl { + (if locked { [1/2]ghost_cell(inv_gid, ModeExclusiveLocked) &*& [1/2]ghost_cell::(lock_gid, LockExcl) } + else { [1/2]ghost_cell(inv_gid, ModeExclusive) }) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + if locked { + [1/2]ghost_cell::(lock_gid, LockShared(frac / 2)) &*& + [frac/2]ghost_cell(sgid, some(?dk)) &*& + [frac]lifetime_token(dk) &*& + [_](.share)(dk, default_tid, &(*ptr).data) + } else { + [frac]dlft_pred(sgid, some(?dk)) &*& + [_](.share)(dk, default_tid, &(*ptr).data) + } + }; + +lem peek_dk_if_shared(exclusive: bool, sgid: i32, ptr: *ArcInner) -> lifetime_t + req if exclusive { true } else { ticket(dlft_pred, sgid, ?f) &*& [f]dlft_pred(sgid, some(?dk)) &*& [_](.share)(dk, default_tid, &(*ptr).data) }; + ens if exclusive { true } else { ticket(dlft_pred, sgid, ?f2) &*& [f2]dlft_pred(sgid, some(result)) &*& [_](.share)(result, default_tid, &(*ptr).data) }; +{ + if exclusive { + return default_value; + } else { + assert [?f]dlft_pred(sgid, some(?dk)); + return dk; + } +} + +// --- Helper arithmetic & lifetime lemmas --- + +lem mod_eq_minus_one(x: i32, m: i32) + req 1 <= x &*& x <= m; + ens (x + m) % (m + 1) == x - 1; +{ + div_rem_nonneg(x + m, m + 1); + assert x + m == (x + m) / (m + 1) * (m + 1) + (x + m) % (m + 1); + if ((x + m) / (m + 1) < 1) {} else { + if ((x + m) / (m + 1) > 1) { + assert 2 <= (x + m) / (m + 1); + mul_mono_l(2, (x + m) / (m + 1), m + 1); + } else {} + } + assert (x + m) / (m + 1) == 1; +} + +lem mod_eq_plus_one(x: i32, m: i32) + req 0 <= x &*& x < m; + ens (x + 1) % (m + 1) == x + 1; +{ + div_rem_nonneg(x + 1, m + 1); + assert x + 1 == (x + 1) / (m + 1) * (m + 1) + (x + 1) % (m + 1); + if ((x + 1) / (m + 1) >= 1) { + mul_mono_l(1, (x + 1) / (m + 1), m + 1); + } else {} + assert (x + 1) / (m + 1) == 0; +} + +lem close_dlft_pred_some(sgid: i32, dk: lifetime_t) -> real + req [?q]ghost_cell(sgid, some(dk)) &*& [?q1]lifetime_token(dk); + ens [result]dlft_pred(sgid, some(dk)) &*& [q - result]ghost_cell(sgid, some(dk)) &*& [q1 - result]lifetime_token(dk) &*& 0 < result; +{ + lifetime_token_inv(dk); + ghost_cell_fraction_info(sgid); + let r = if q < q1 { q / 2 } else { q1 / 2 }; + close [r]dlft_pred(sgid, some(dk)); + return r; +} + +lem Arc_is_shared_from_borrow(sgid: i32, dk: lifetime_t, frac: real) + req atomic_mask(?mask) &*& mask_le(Nlft, mask) == true &*& + counting(dlft_pred, sgid, ?s_cnt, ?dk_opt) &*& + [_]frac_borrow(?k, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) &*& + [?q]lifetime_token(k); + ens atomic_mask(mask) &*& counting(dlft_pred, sgid, s_cnt, dk_opt) &*& + [q]lifetime_token(k) &*& dk_opt == some(dk); +{ + open_frac_borrow_m(k, strong_ticket_(sgid, dk, frac), q / 2); + open_frac_borrow_m(k, lifetime_token_(frac, dk), q / 2); + open [?qt]strong_ticket_(sgid, dk, frac)(); + open [?qdk]lifetime_token_(frac, dk)(); + let qp = close_dlft_pred_some(sgid, dk); + counting_match_fraction(dlft_pred, sgid); + open [qp]dlft_pred(sgid, some(dk)); + close [qdk]lifetime_token_(frac, dk)(); + close [qt]strong_ticket_(sgid, dk, frac)(); + close_frac_borrow_m(qdk, lifetime_token_(frac, dk)); + close_frac_borrow_m(qt, strong_ticket_(sgid, dk, frac)); +} + +lem Weak_is_live_from_borrow(wgid: i32, wfrac: real) + req atomic_mask(?mask) &*& mask_le(Nlft, mask) == true &*& + counting(weak_pred, wgid, ?w_cnt, ?dealloced) &*& w_cnt >= 0 &*& + [_]frac_borrow(?k, weak_ticket_(wgid, wfrac)) &*& + [?q]lifetime_token(k); + ens atomic_mask(mask) &*& counting(weak_pred, wgid, w_cnt, dealloced) &*& + [q]lifetime_token(k) &*& dealloced == false &*& w_cnt >= 1; +{ + open_frac_borrow_m(k, weak_ticket_(wgid, wfrac), q); + open [?qw]weak_ticket_(wgid, wfrac)(); + counting_match_fraction(weak_pred, wgid); + if w_cnt == 0 { + open [qw * wfrac]weak_pred(wgid, false); + ghost_cell_fraction_info(wgid); + stop_counting(weak_pred, wgid); + open weak_pred(wgid, false); + merge_fractions ghost_cell::(wgid, _); + ghost_cell_fraction_info(wgid); + } else {} + close [qw]weak_ticket_(wgid, wfrac)(); + close_frac_borrow_m(qw, weak_ticket_(wgid, wfrac)); +} + +// Transition an `Exclusive` Arc to `Shared(dk)` at `MaskTop` (used by `Arc_share_full`). +lem Arc_exclusive_to_shared(inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, ptr: *ArcInner) + req type_interp::() &*& atomic_mask(MaskTop) &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr) &*& + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))(); + ens type_interp::() &*& atomic_mask(MaskTop) &*& + [_]exists(?dk) &*& + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(dk)) &*& + [_](.share)(dk, default_tid, &(*ptr).data); +{ + open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + let dk = begin_lifetime_m(); + borrow_m(dk, (.full_borrow_content)(default_tid, &(*ptr).data)); + share_full_borrow_m::(dk, default_tid, &(*ptr).data); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + ghost_cell_mutate(inv_gid, ModeShared(dk)); + stop_counting(dlft_pred, sgid); + open dlft_pred(sgid, none); + ghost_cell_mutate(sgid, some(dk)); + close dlft_pred(sgid, some(dk)); + start_counting(dlft_pred, sgid); + let frac = create_ticket(dlft_pred, sgid); + close shared_weak_lock(lock_gid, sgid, dk, false); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + leak exists(dk); +} + +// --- RustBelt type-system proof obligations for `Arc` and `Weak` --- + +lem Arc_own_mono() + req type_interp::() &*& type_interp::() &*& Arc_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& Arc_own::(t, Arc:: { ptr: upcast(v.ptr) }); +{ + assume(false); // Standard VeriFast NonNull variance axiom (same as VeriFast's tests/rust/safe_abstraction/arc.rs) +} + +lem Weak_own_mono() + req type_interp::() &*& type_interp::() &*& Weak_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& Weak_own::(t, Weak:: { ptr: upcast(v.ptr) }); +{ + assume(false); // Standard VeriFast NonNull variance axiom +} + +lem Arc_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Arc) + req lifetime_inclusion(k1, k) == true &*& [_]Arc_share::(k, t, l); + ens [_]Arc_share::(k1, t, l); +{ + open Arc_share::(k, t, l); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + [_]exists::(?dk) &*& [_]exists::(?frac); + frac_borrow_mono(k, k1, Arc_frac_bc(l, nnp)); + frac_borrow_mono(k, k1, strong_ticket_(sgid, dk, frac)); + frac_borrow_mono(k, k1, lifetime_token_(frac, dk)); + close Arc_share::(k1, t, l); + leak Arc_share::(k1, t, l); +} + +lem Weak_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Weak) + req lifetime_inclusion(k1, k) == true &*& [_]Weak_share::(k, t, l); + ens [_]Weak_share::(k1, t, l); +{ + open Weak_share::(k, t, l); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + frac_borrow_mono(k, k1, Weak_frac_bc(l, nnp)); + if (ptr as usize) == usize::MAX { + } else { + assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + [_]exists::(?wfrac); + frac_borrow_mono(k, k1, weak_ticket_(wgid, wfrac)); + } + close Weak_share::(k1, t, l); + leak Weak_share::(k1, t, l); +} + +pred_ctor Arc_Ctx(nnp: std::ptr::NonNull>, inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, dk: lifetime_t, l: *Arc)() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr) &*& + [_]exists(dk) &*& + [_](.share)(dk, default_tid, &(*ptr).data) &*& + struct_Arc_padding::(l); + +lem Arc_share_full(k: lifetime_t, t: thread_id_t, l: *Arc) + req type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& full_borrow(k, Arc_full_borrow_content::(t, l)); + ens type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& [_]Arc_share::(k, t, l); +{ + let klong = open_full_borrow_strong_m(k, Arc_full_borrow_content::(t, l), q); + open Arc_full_borrow_content::(t, l)(); + open Arc_own::(t, ?arc); + let nnp = arc.ptr; + assert [_]exists::<*ArcInner>(?ptr) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + open exists::(?exclusive); + if exclusive { + Arc_exclusive_to_shared::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + } else {} + assert ticket(dlft_pred, sgid, ?frac) &*& [frac]dlft_pred(sgid, some(?dk)); + leak exists(dk); + open [frac]dlft_pred(sgid, some(dk)); + close Arc_frac_bc::(l, nnp)(); + close strong_ticket_(sgid, dk, frac)(); + close lifetime_token_(frac, dk)(); + close sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))(); + close sep(Arc_frac_bc(l, nnp), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Arc_Ctx(nnp, inv_gid, sgid, wgid, lock_gid, imp_gid, dk, l), + sep(Arc_frac_bc(l, nnp), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))), + klong, + Arc_full_borrow_content::(t, l) + )() { + open sep(Arc_frac_bc(l, nnp), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))(); + open Arc_frac_bc::(l, nnp)(); + open sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))(); + open strong_ticket_(sgid, dk, frac)(); + open lifetime_token_(frac, dk)(); + close [frac]dlft_pred(sgid, some(dk)); + open Arc_Ctx::(nnp, inv_gid, sgid, wgid, lock_gid, imp_gid, dk, l)(); + close exists(false); + close Arc_own::(t, arc); + close Arc_full_borrow_content::(t, l)(); + } { + close Arc_Ctx::(nnp, inv_gid, sgid, wgid, lock_gid, imp_gid, dk, l)(); + close_full_borrow_strong_m( + klong, + Arc_full_borrow_content::(t, l), + sep(Arc_frac_bc(l, nnp), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))) + ); + } + full_borrow_mono(klong, k, sep(Arc_frac_bc(l, nnp), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))); + full_borrow_split_m(k, Arc_frac_bc(l, nnp), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))); + full_borrow_split_m(k, strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)); + full_borrow_into_frac_m(k, Arc_frac_bc(l, nnp)); + full_borrow_into_frac_m(k, strong_ticket_(sgid, dk, frac)); + full_borrow_into_frac_m(k, lifetime_token_(frac, dk)); + leak exists(nnp); + leak exists(frac); + close Arc_share::(k, t, l); + leak Arc_share::(k, t, l); +} + +pred_ctor Weak_Ctx_dangling(nnp: std::ptr::NonNull>, l: *Weak)() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + (ptr as usize) == usize::MAX &*& + struct_Weak_padding::(l); + +pred_ctor Weak_Ctx_live(nnp: std::ptr::NonNull>, inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, l: *Weak)() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + (ptr as usize) != usize::MAX &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr) &*& + struct_Weak_padding::(l); + +lem Weak_share_full(k: lifetime_t, t: thread_id_t, l: *Weak) + req atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& full_borrow(k, Weak_full_borrow_content::(t, l)); + ens atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& [_]Weak_share::(k, t, l); +{ + let klong = open_full_borrow_strong_m(k, Weak_full_borrow_content::(t, l), q); + open Weak_full_borrow_content::(t, l)(); + open Weak_own::(t, ?weak); + let nnp = weak.ptr; + assert [_]exists::<*ArcInner>(?ptr); + close Weak_frac_bc::(l, nnp)(); + if (ptr as usize) == usize::MAX { + produce_lem_ptr_chunk full_borrow_convert_strong( + Weak_Ctx_dangling(nnp, l), + Weak_frac_bc(l, nnp), + klong, + Weak_full_borrow_content::(t, l) + )() { + open Weak_frac_bc::(l, nnp)(); + open Weak_Ctx_dangling::(nnp, l)(); + close Weak_own::(t, weak); + close Weak_full_borrow_content::(t, l)(); + } { + close Weak_Ctx_dangling::(nnp, l)(); + close_full_borrow_strong_m(klong, Weak_full_borrow_content::(t, l), Weak_frac_bc(l, nnp)); + } + full_borrow_mono(klong, k, Weak_frac_bc(l, nnp)); + full_borrow_into_frac_m(k, Weak_frac_bc(l, nnp)); + leak exists(nnp); + close Weak_share::(k, t, l); + leak Weak_share::(k, t, l); + } else { + assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + ticket(weak_pred, wgid, ?wfrac); + close weak_ticket_(wgid, wfrac)(); + close sep(Weak_frac_bc(l, nnp), weak_ticket_(wgid, wfrac))(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Weak_Ctx_live(nnp, inv_gid, sgid, wgid, lock_gid, imp_gid, l), + sep(Weak_frac_bc(l, nnp), weak_ticket_(wgid, wfrac)), + klong, + Weak_full_borrow_content::(t, l) + )() { + open sep(Weak_frac_bc(l, nnp), weak_ticket_(wgid, wfrac))(); + open Weak_frac_bc::(l, nnp)(); + open weak_ticket_(wgid, wfrac)(); + open Weak_Ctx_live::(nnp, inv_gid, sgid, wgid, lock_gid, imp_gid, l)(); + close Weak_own::(t, weak); + close Weak_full_borrow_content::(t, l)(); + } { + close Weak_Ctx_live::(nnp, inv_gid, sgid, wgid, lock_gid, imp_gid, l)(); + close_full_borrow_strong_m(klong, Weak_full_borrow_content::(t, l), sep(Weak_frac_bc(l, nnp), weak_ticket_(wgid, wfrac))); + } + full_borrow_mono(klong, k, sep(Weak_frac_bc(l, nnp), weak_ticket_(wgid, wfrac))); + full_borrow_split_m(k, Weak_frac_bc(l, nnp), weak_ticket_(wgid, wfrac)); + full_borrow_into_frac_m(k, Weak_frac_bc(l, nnp)); + full_borrow_into_frac_m(k, weak_ticket_(wgid, wfrac)); + leak exists(nnp); + leak exists(wfrac); + close Weak_share::(k, t, l); + leak Weak_share::(k, t, l); + } +} + +lem init_ref_Arc(p: *Arc) + req type_interp::() &*& is_Send(typeid(T)) == true &*& + atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]Arc_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]Arc_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + assume(false); // Standard VeriFast ref_init_perm axiom (same as VeriFast's tests/rust/safe_abstraction/arc.rs) +} + +lem init_ref_Weak(p: *Weak) + req type_interp::() &*& is_Send(typeid(T)) == true &*& + atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& [_]Weak_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& [_]Weak_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + assume(false); // Standard VeriFast ref_init_perm axiom +} + +@*/ + +unsafe impl Send for Arc {} +unsafe impl Sync for Arc {} +unsafe impl Send for Weak {} +unsafe impl Sync for Weak {} + +impl Arc { + pub fn new(data: T) -> Arc { + unsafe { + let l = std::alloc::Layout::new::>(); + let p = std::alloc::alloc(l) as *mut ArcInner; + if p.is_null() { + std::alloc::handle_alloc_error(l); + } + //@ close_struct(p); + std::ptr::write(p, ArcInner { + strong: AtomicUsize::new(1), + weak: AtomicUsize::new(1), + data, + }); + let ret = Self { + ptr: NonNull::new_unchecked(p), + }; + //@ let nnp = ret.ptr; + //@ let inv_gid = create_ghost_cell(ModeExclusive); + //@ let sgid = create_ghost_cell(none); + //@ close dlft_pred(sgid, none); + //@ start_counting(dlft_pred, sgid); + //@ let wgid = create_ghost_cell(false); + //@ close weak_pred(wgid, false); + //@ start_counting(weak_pred, wgid); + //@ let lock_gid = create_ghost_cell::(LockFree); + //@ let imp_gid = create_ghost_cell(0); + //@ close arc_atomic_cas::AtomicUsize(&(*p).strong, 1); + //@ close arc_atomic_cas::AtomicUsize(&(*p).weak, 1); + //@ open ArcInner_data(p, ?v); + //@ points_to_limits(&(*p).strong); + //@ assert thread_token(?t); + //@ produce_type_interp::(); + //@ Send::send::(t, default_tid, v); + //@ leak type_interp::(); + //@ close_full_borrow_content::(default_tid, &(*p).data); + //@ close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, p)(); + //@ create_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, p)); + //@ leak atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, p)); + //@ close ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, p); + //@ leak ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, p); + //@ leak exists(p); + //@ std::ptr::close_NonNull_own::>()(default_tid, nnp); + //@ leak std::ptr::NonNull_own::>()(default_tid, nnp); + //@ close exists(true); + //@ close Arc_own::(_t, ret); + ret + } + } + + pub fn strong_count<'a>(this: &'a Self) -> usize { + unsafe { + //@ open Arc_share::('a, _t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + //@ open_frac_borrow('a, Arc_frac_bc(this, nnp), _q_a / 2); + //@ open [?qnnp]Arc_frac_bc::(this, nnp)(); + let inner = this.ptr.as_ref(); + let ret; + { + /*@ + pred Frame() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).strong, Frame, always_true, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Arc_is_shared_from_borrow(sgid, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame(); + close PostAcq(r); + }; + @*/ + //@ close Frame(); + ret = inner.strong.load(Relaxed); + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, ret)); + } + //@ close [qnnp]Arc_frac_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_frac_bc(this, nnp)); + ret + } + } + + pub fn weak_count<'a>(this: &'a Self) -> usize { + unsafe { + //@ open Arc_share::('a, _t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + //@ open_frac_borrow('a, Arc_frac_bc(this, nnp), _q_a / 2); + //@ open [?qnnp]Arc_frac_bc::(this, nnp)(); + let inner = this.ptr.as_ref(); + let cnt; + { + /*@ + pred Frame() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).weak, Frame, ge_one, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Arc_is_shared_from_borrow(sgid, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame(); + close PostAcq(r); + }; + @*/ + //@ close Frame(); + cnt = inner.weak.load(Relaxed); + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, cnt)); + } + //@ close [qnnp]Arc_frac_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_frac_bc(this, nnp)); + if cnt == usize::MAX { 0 } else { cnt - 1 } + } + } + + pub fn downgrade<'a>(this: &'a Self) -> Weak { + unsafe { + //@ open Arc_share::('a, _t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + //@ open_frac_borrow('a, Arc_frac_bc(this, nnp), _q_a / 2); + //@ open [?qnnp]Arc_frac_bc::(this, nnp)(); + let inner = this.ptr.as_ref(); + let mut cur; + { + /*@ + pred Frame() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).weak, Frame, always_true, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Arc_is_shared_from_borrow(sgid, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame(); + close PostAcq(r); + }; + @*/ + //@ close Frame(); + cur = inner.weak.load(Relaxed); + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, cur)); + } + loop { + /*@ + inv [_q_a / 2]lifetime_token('a) &*& + [qnnp]((*this).ptr |-> nnp) &*& + close_frac_borrow_token(qnnp, Arc_frac_bc(this, nnp), _q_a / 2, 'a) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + @*/ + if cur == usize::MAX { + std::hint::spin_loop(); + { + /*@ + pred Frame2() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq2(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).weak, Frame2, always_true, PostAcq2)() { + open Frame2(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Arc_is_shared_from_borrow(sgid, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame2(); + close PostAcq2(r); + }; + @*/ + //@ close Frame2(); + cur = inner.weak.load(Relaxed); + //@ open Frame2(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq2, cur)); + } + continue; + } + if cur > MAX_REFCOUNT { + abort(); + } + { + /*@ + pred Pre() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostOk(v: usize) = [_q_a / 2]lifetime_token('a) &*& + ticket(weak_pred, wgid, ?wfrac) &*& [wfrac]weak_pred(wgid, false); + pred PostErrAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_weak_ghop(&(*ptr).weak, cur, cur + 1, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Arc_is_shared_from_borrow(sgid, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_weak_op(?op, _, _, _, ?spurious, _, ?Q); + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + create_ticket(weak_pred, wgid); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + }; + @*/ + //@ close Pre(); + let res = inner.weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed); + /*@ + match res { + Result::Ok(v_res) => { open PostOk(v_res); } + Result::Err(v_err) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_err)); + } + } + @*/ + match res { + Ok(_) => { + let w = Weak { ptr: this.ptr }; + //@ close [qnnp]Arc_frac_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_frac_bc(this, nnp)); + //@ close Weak_own::(_t, w); + return w; + } + Err(old) => { + cur = old; + } + } + } + } + } + } + + // Matches `Arc::is_unique` (`library/alloc/src/rcs/arc.rs` L2929): + // Locks weak count with `usize::MAX` (`Acquire`), checks `strong == 1` (`Acquire`), + // and releases the weak lock back to `1` (`Release`). + // If unique, transitions `Arc_own` to `ModeExclusive` (extracting `.full_borrow_content`). + unsafe fn is_unique_and_take<'a>(this: &'a mut Self) -> bool + //@ req (*this).ptr |-> ?nnp &*& Arc_own::(?t, Arc:: { ptr: nnp }); + /*@ + ens (*this).ptr |-> nnp &*& + if result { + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))() + } else { + Arc_own::(t, Arc:: { ptr: nnp }) + }; + @*/ + //@ on_unwind_ens false; + { + //@ let arc = Arc:: { ptr: nnp }; + //@ open Arc_own::(t, arc); + //@ assert [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ open exists::(?exclusive); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + let inner = unsafe { this.ptr.as_ref() }; + //@ close UniqueState::(inv_gid, sgid, lock_gid, ptr, false, exclusive); + + let locked_ok; + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + UniqueState::(inv_gid, sgid, lock_gid, ptr, false, exclusive); + pred PostOk(v: usize) = UniqueState::(inv_gid, sgid, lock_gid, ptr, true, exclusive); + pred PostErrAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_ghop(&(*ptr).weak, 1, usize::MAX, Pre, PostOk, PostErrAcq)() { + open Pre(); + open UniqueState::(inv_gid, sgid, lock_gid, ptr, false, exclusive); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_op(?op, _, _, _, _, ?Q); + if exclusive { + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + ghost_cell_mutate(inv_gid, ModeExclusiveLocked); + ghost_cell_mutate::(lock_gid, LockExcl); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, true, true); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => {} + } + } else { + assert ticket(dlft_pred, sgid, ?frac) &*& [frac]dlft_pred(sgid, some(?dk)); + counting_match_fraction(dlft_pred, sgid); + assert shared_weak_lock(lock_gid, sgid, dk, ?locked); + open shared_weak_lock(lock_gid, sgid, dk, locked); + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + open [frac]dlft_pred(sgid, some(dk)); + ghost_cell_fraction_info(sgid); + ghost_cell_mutate::(lock_gid, LockShared(frac / 2)); + close shared_weak_lock(lock_gid, sgid, dk, true); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, true, false); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close shared_weak_lock(lock_gid, sgid, dk, locked); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, false, false); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + } + }; + @*/ + //@ close Pre(); + let lock_res = inner.weak.compare_exchange(1, usize::MAX, Acquire, Relaxed); + locked_ok = lock_res.is_ok(); + /*@ + match lock_res { + Result::Ok(v_res) => { + open PostOk(v_res); + } + Result::Err(v_res) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_res)); + } + } + @*/ + } + + if locked_ok { + let s_val; + { + /*@ + pred Pre2() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + UniqueState::(inv_gid, sgid, lock_gid, ptr, true, exclusive); + pred Post2(r: usize) = UniqueState::(inv_gid, sgid, lock_gid, ptr, true, r == 1); + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_ghop(&(*ptr).strong, Pre2, Post2)() { + open Pre2(); + open UniqueState::(inv_gid, sgid, lock_gid, ptr, true, exclusive); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + if exclusive { + op(); + assert Q(?r); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, true, true); + } else { + assert ticket(dlft_pred, sgid, ?frac) &*& [frac]lifetime_token(?dk); + let qp = close_dlft_pred_some(sgid, dk); + counting_match_fraction(dlft_pred, sgid); + open [qp]dlft_pred(sgid, some(dk)); + assert shared_weak_lock(lock_gid, sgid, dk, ?locked); + open shared_weak_lock(lock_gid, sgid, dk, locked); + op(); + assert Q(?r); + if r == 1 { + close [frac]dlft_pred(sgid, some(dk)); + destroy_ticket(dlft_pred, sgid); + stop_counting(dlft_pred, sgid); + open dlft_pred(sgid, some(dk)); + end_lifetime_m(dk); + borrow_end_m(dk, (.full_borrow_content)(default_tid, &(*ptr).data)); + ghost_cell_mutate(sgid, none); + close dlft_pred(sgid, none); + start_counting(dlft_pred, sgid); + ghost_cell_mutate::(lock_gid, LockExcl); + ghost_cell_mutate(inv_gid, ModeExclusiveLocked); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, true, true); + } else { + close shared_weak_lock(lock_gid, sgid, dk, true); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, true, false); + } + } + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?res_r); + close Post2(res_r); + }; + @*/ + //@ close Pre2(); + s_val = inner.strong.load(Acquire); + //@ open Post2(s_val); + } + let unique = s_val == 1; + { + /*@ + pred Pre3() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + UniqueState::(inv_gid, sgid, lock_gid, ptr, true, unique); + pred Post3() = UniqueState::(inv_gid, sgid, lock_gid, ptr, false, unique); + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_store_ghop(&(*ptr).weak, 1, Pre3, Post3)() { + open Pre3(); + open UniqueState::(inv_gid, sgid, lock_gid, ptr, true, unique); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_store_op(?op, _, _, _, ?Q); + if unique { + ghost_cell_mutate(inv_gid, ModeExclusive); + ghost_cell_mutate::(lock_gid, LockFree); + op(); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, false, true); + } else { + assert ticket(dlft_pred, sgid, ?frac) &*& [frac]lifetime_token(?dk); + let qp = close_dlft_pred_some(sgid, dk); + counting_match_fraction(dlft_pred, sgid); + open [qp]dlft_pred(sgid, some(dk)); + assert shared_weak_lock(lock_gid, sgid, dk, ?locked); + open shared_weak_lock(lock_gid, sgid, dk, locked); + ghost_cell_mutate::(lock_gid, LockFree); + close shared_weak_lock(lock_gid, sgid, dk, false); + close [frac]dlft_pred(sgid, some(dk)); + op(); + close UniqueState::(inv_gid, sgid, lock_gid, ptr, false, false); + } + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Post3(); + }; + @*/ + //@ close Pre3(); + inner.weak.store(1, Release); + //@ open Post3(); + } + //@ open UniqueState::(inv_gid, sgid, lock_gid, ptr, false, unique); + if unique { + return true; + } else { + //@ close exists(false); + //@ close Arc_own::(t, arc); + return false; + } + } else { + //@ open UniqueState::(inv_gid, sgid, lock_gid, ptr, false, exclusive); + //@ close exists(exclusive); + //@ close Arc_own::(t, arc); + return false; + } + } + + pub fn get_mut<'a>(this: &'a mut Self) -> Option<&'a mut T> { + unsafe { + //@ let klong = open_full_borrow_strong('a, Arc_full_borrow_content::(_t, this), _q_a); + //@ open Arc_full_borrow_content::(_t, this)(); + if Self::is_unique_and_take(this) { + //@ assert (*this).ptr |-> ?nnp &*& [_]exists::<*ArcInner>(?ptr); + //@ let arc = Arc:: { ptr: nnp }; + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + //@ open_full_borrow_content::(default_tid, &(*ptr).data); + //@ assert (*ptr).data |-> ?v; + //@ produce_type_interp::(); + //@ Send::send::(default_tid, _t, v); + //@ close_full_borrow_content::(_t, &(*ptr).data); + let data_ptr: *mut T = &raw mut (*this.ptr.as_ptr()).data; + { + /*@ + pred Ctx() = + type_interp::() &*& + (*this).ptr |-> nnp &*& + struct_Arc_padding::(this) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr) &*& + [1/2]ghost_cell(inv_gid, ModeExclusive); + @*/ + /*@ + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + .full_borrow_content(_t, data_ptr), + klong, + Arc_full_borrow_content::(_t, this) + )() { + open Ctx(); + open_full_borrow_content::(_t, data_ptr); + assert *data_ptr |-> ?v1; + Send::send::(_t, default_tid, v1); + leak type_interp::(); + close_full_borrow_content::(default_tid, &(*ptr).data); + close exists(true); + close Arc_own::(_t, arc); + close Arc_full_borrow_content::(_t, this)(); + } { + close Ctx(); + close_full_borrow_strong(klong, Arc_full_borrow_content::(_t, this), .full_borrow_content(_t, data_ptr)); + } + @*/ + } + //@ full_borrow_mono(klong, 'a, .full_borrow_content(_t, data_ptr)); + let r = &mut *data_ptr; + //@ close_ref_mut_own::<'a, T>(_t, r); + let ret = Some(r); + //@ close std::option::Option_own::<&'a mut T>(_t, ret); + return ret; + } else { + //@ close Arc_full_borrow_content::(_t, this)(); + { + /*@ + pred EmptyCtx() = true; + @*/ + /*@ + produce_lem_ptr_chunk full_borrow_convert_strong( + EmptyCtx, + Arc_full_borrow_content::(_t, this), + klong, + Arc_full_borrow_content::(_t, this) + )() { + open EmptyCtx(); + } { + close EmptyCtx(); + close_full_borrow_strong(klong, Arc_full_borrow_content::(_t, this), Arc_full_borrow_content::(_t, this)); + } + @*/ + } + //@ leak full_borrow(klong, _); + //@ close std::option::Option_own::<&'a mut T>(_t, std::option::Option::None); + return None; + } + } + } + + // Matches `Arc::try_unwrap` (`library/alloc/src/rcs/arc.rs` L1052): + // Uses `strong.compare_exchange(1, 0, Relaxed, Relaxed)` followed by + // `atomic::fence(Acquire)` before `ptr::read(&data)` and dropping the implicit Weak. + pub fn try_unwrap(this: Self) -> Result { + //@ open Arc_own::(_t, this); + //@ assert [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ open exists::(?exclusive); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + //@ let dk_val = peek_dk_if_shared::(exclusive, sgid, ptr); + let p = this.ptr; + unsafe { + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + if exclusive { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))() + } else { + [_](.share)(dk_val, default_tid, &(*ptr).data) &*& + ticket(dlft_pred, sgid, ?frac) &*& [frac]dlft_pred(sgid, some(dk_val)) + }; + pred PostOk(v: usize) = + [1/2]ghost_cell(imp_gid, 1) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))(); + pred PostErrAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_ghop(&(*ptr).strong, 1, 0, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_op(?op, _, _, _, _, ?Q); + if exclusive { + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + ghost_cell_mutate(inv_gid, ModeDataOut); + ghost_cell_mutate(imp_gid, 1); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => {} + } + } else { + assert ticket(dlft_pred, sgid, ?frac); + counting_match_fraction(dlft_pred, sgid); + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + destroy_ticket(dlft_pred, sgid); + stop_counting(dlft_pred, sgid); + open dlft_pred(sgid, some(dk_val)); + assert shared_weak_lock(lock_gid, sgid, dk_val, ?locked); + open shared_weak_lock(lock_gid, sgid, dk_val, locked); + if locked { + merge_fractions ghost_cell::>(sgid, _); + ghost_cell_fraction_info(sgid); + } else {} + end_lifetime_m(dk_val); + borrow_end_m(dk_val, (.full_borrow_content)(default_tid, &(*ptr).data)); + ghost_cell_mutate(sgid, none); + close dlft_pred(sgid, none); + start_counting(dlft_pred, sgid); + ghost_cell_mutate(inv_gid, ModeDataOut); + ghost_cell_mutate(imp_gid, 1); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + } + }; + @*/ + //@ close Pre(); + let cas_res = p.as_ref().strong.compare_exchange(1, 0, Relaxed, Relaxed); + let is_err = cas_res.is_err(); + /*@ + match cas_res { + Result::Ok(v_res) => {} + Result::Err(v_err_res) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_err_res)); + } + } + @*/ + if is_err { + //@ close exists(exclusive); + //@ close Arc_own::(_t, this); + let err = Err(this); + //@ close arc_atomic_cas::Result_own::>(_t, err); + return err; + } + // `compare_exchange` succeeded with `Relaxed`, so acquired resources are + // locked in `pending_acquire` until `atomic::fence(Acquire)` executes! + atomic::fence(Acquire); + /*@ + match cas_res { + Result::Ok(v_res) => { + open arc_atomic_cas::app_usize(PostOk, v_res)(); + open PostOk(v_res); + } + Result::Err(v_err_res) => {} + } + @*/ + } + //@ open_full_borrow_content::(default_tid, &(*ptr).data); + //@ assert (*ptr).data |-> ?v; + //@ produce_type_interp::(); + //@ Send::send::(default_tid, _t, v); + //@ leak type_interp::(); + let elem = std::ptr::read(&p.as_ref().data); + let _md = std::mem::ManuallyDrop::new(this); + //@ close ArcInner_data(ptr, v); + //@ close Weak_implicit_own::(p); + Weak::::drop_implicit(p); + let ret = Ok(elem); + //@ close arc_atomic_cas::Result_own::>(_t, ret); + ret + } + } +} + +impl std::ops::Deref for Arc { + type Target = T; + + fn deref<'a>(&'a self) -> &'a T { + unsafe { + //@ open Arc_share::('a, _t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& [_]exists::(?frac) &*& [_]exists::(?dk); + //@ open ArcInner_meta::(_, _, _, _, _, ptr); + //@ open_frac_borrow('a, Arc_frac_bc(self, nnp), _q_a); + //@ open [?qnnp]Arc_frac_bc::(self, nnp)(); + let ret = &self.ptr.as_ref().data; + //@ close [qnnp]Arc_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Arc_frac_bc(self, nnp)); + //@ frac_borrow_lft_incl('a, frac, dk); + //@ produce_type_interp::(); + //@ share_mono::(dk, 'a, default_tid, ret); + //@ Sync::sync::('a, default_tid, _t, ret); + //@ leak type_interp::(); + ret + } + } +} + +impl Clone for Arc { + fn clone<'a>(&'a self) -> Arc { + unsafe { + //@ open Arc_share::('a, _t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + //@ open_frac_borrow('a, Arc_frac_bc(self, nnp), _q_a / 2); + //@ open [?qnnp]Arc_frac_bc::(self, nnp)(); + let old_size; + { + /*@ + pred Frame() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred GhostPost(r: usize) = + ticket(dlft_pred, sgid, ?frac1) &*& [frac1]dlft_pred(sgid, some(dk)); + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_add_relaxed_ghop(&(*ptr).strong, 1, Frame, GhostPost)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Arc_is_shared_from_borrow(sgid, dk, frac); + assert arc_atomic_cas::AtomicUsize(&(*ptr).strong, ?v0); + if v0 > isize::MAX as usize { + // Localized bounded-thread assumption (matching `library/alloc/src/rcs/arc.rs` L2536): + // the `> MAX_REFCOUNT` branch aborts immediately, and fewer than `isize::MAX` + // threads can concurrently pause between `fetch_add(1, Relaxed)` and `abort()`. + assume(v0 < usize::MAX); + } else {} + mod_eq_plus_one(v0, usize::MAX); + assert arc_atomic_cas::is_AtomicUsize_fetch_add_op(?op, _, _, _, ?Q); + op(); + assert Q(?r); + create_ticket(dlft_pred, sgid); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Frame(); + close GhostPost(r); + }; + @*/ + //@ close Frame(); + old_size = self.ptr.as_ref().strong.fetch_add(1, Relaxed); + //@ open Frame(); + //@ open GhostPost(old_size); + } + if old_size > MAX_REFCOUNT { + abort(); + } + let ret = Self { ptr: self.ptr }; + //@ close [qnnp]Arc_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Arc_frac_bc(self, nnp)); + //@ close exists(false); + //@ close Arc_own::(_t, ret); + ret + } + } +} + +impl Weak { + pub fn new() -> Weak { + unsafe { + let ret = Weak { + ptr: NonNull::new_unchecked(usize::MAX as *mut ArcInner), + }; + //@ let nnp = ret.ptr; + //@ leak exists(nnp.as_ptr()); + //@ std::ptr::close_NonNull_own::>()(default_tid, nnp); + //@ leak std::ptr::NonNull_own::>()(default_tid, nnp); + //@ close Weak_own::(_t, ret); + ret + } + } + + // Internal drop for the implicit Weak held collectively by strong references, + // called from `Arc::drop` after `drop_in_place(&mut (*ptr).data)` completes. + unsafe fn drop_implicit(p: NonNull>) + //@ req Weak_implicit_own::(p); + //@ ens true; + //@ on_unwind_ens false; + { + //@ open Weak_implicit_own::(p); + //@ assert [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + unsafe { + let old_weak; + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [1/2]ghost_cell(imp_gid, 1) &*& + (*ptr).data |-> _; + pred Post(r: usize) = if r == 1 { + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, 0) &*& + (*ptr).data |-> _ &*& + struct_ArcInner_padding::(ptr) &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) + } else { true }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_sub_ghop(&(*ptr).weak, 1, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + merge_fractions ghost_cell(imp_gid, _); + ghost_cell_fraction_info(imp_gid); + ghost_cell_mutate(imp_gid, 2); + assert arc_atomic_cas::AtomicUsize(&(*ptr).weak, ?v0); + mod_eq_minus_one(v0, usize::MAX); + assert arc_atomic_cas::is_AtomicUsize_fetch_sub_op(?op, _, _, _, ?Q); + op(); + assert Q(?r); + if r == 1 { + stop_counting(weak_pred, wgid); + open weak_pred(wgid, false); + ghost_cell_mutate(wgid, true); + close weak_pred(wgid, true); + start_counting(weak_pred, wgid); + ghost_cell_mutate(inv_gid, ModeDealloced); + } else { + ghost_cell_mutate(inv_gid, ModeDataDropped); + } + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Post(r); + }; + @*/ + //@ close Pre(); + old_weak = p.as_ref().weak.fetch_sub(1, Release); + if old_weak == 1 { + atomic::fence(Acquire); + //@ open arc_atomic_cas::app_usize(Post, old_weak)(); + //@ open Post(old_weak); + //@ open arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0); + //@ open arc_atomic_cas::AtomicUsize(&(*ptr).weak, 0); + //@ open_struct(ptr); + std::alloc::dealloc(p.as_ptr() as *mut u8, std::alloc::Layout::new::>()); + } else { + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(Post, old_weak)); + } + } + } + } + + pub fn upgrade<'a>(&'a self) -> Option> { + unsafe { + //@ open Weak_share::('a, _t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ open_frac_borrow('a, Weak_frac_bc(self, nnp), _q_a / 2); + //@ open [?qnnp]Weak_frac_bc::(self, nnp)(); + if is_dangling(self.ptr.as_ptr()) { + //@ close [qnnp]Weak_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_frac_bc(self, nnp)); + //@ close std::option::Option_own::>(_t, std::option::Option::None); + return None; + } + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& [_]exists::(?wfrac); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + let inner = self.ptr.as_ref(); + let mut n; + { + /*@ + pred Frame() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, weak_ticket_(wgid, wfrac)); + pred PostAcq(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).strong, Frame, always_true, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Weak_is_live_from_borrow(wgid, wfrac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame(); + close PostAcq(r); + }; + @*/ + //@ close Frame(); + n = inner.strong.load(Relaxed); + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, n)); + } + loop { + /*@ + inv [_q_a / 2]lifetime_token('a) &*& + [qnnp]((*self).ptr |-> nnp) &*& + close_frac_borrow_token(qnnp, Weak_frac_bc(self, nnp), _q_a / 2, 'a) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, weak_ticket_(wgid, wfrac)); + @*/ + if n == 0 { + //@ close [qnnp]Weak_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_frac_bc(self, nnp)); + //@ close std::option::Option_own::>(_t, std::option::Option::None); + return None; + } + if n > MAX_REFCOUNT { + abort(); + } + { + /*@ + pred Pre() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, weak_ticket_(wgid, wfrac)); + pred PostOk(v: usize) = [_q_a / 2]lifetime_token('a) &*& + [_]exists(?dk) &*& + ticket(dlft_pred, sgid, ?sfrac) &*& + [sfrac]dlft_pred(sgid, some(dk)) &*& + [_](.share)(dk, default_tid, &(*ptr).data); + pred PostErrAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_weak_ghop(&(*ptr).strong, n, n + 1, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Weak_is_live_from_borrow(wgid, wfrac); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_weak_op(?op, _, _, _, ?spurious, _, ?Q); + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + assert [1/2]ghost_cell(inv_gid, ModeShared(?dk)); + create_ticket(dlft_pred, sgid); + leak exists(dk); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + }; + @*/ + //@ close Pre(); + let res = inner.strong.compare_exchange_weak(n, n + 1, Acquire, Relaxed); + /*@ + match res { + Result::Ok(v_res) => { open PostOk(v_res); } + Result::Err(v_err_res) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_err_res)); + } + } + @*/ + match res { + Ok(_) => { + let a = Arc { ptr: self.ptr }; + //@ close [qnnp]Weak_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_frac_bc(self, nnp)); + //@ close exists(false); + //@ close Arc_own::(_t, a); + let ret = Some(a); + //@ close std::option::Option_own::>(_t, ret); + return ret; + } + Err(prev) => { + n = prev; + } + } + } + } + } + } +} + +impl Clone for Weak { + fn clone<'a>(&'a self) -> Weak { + unsafe { + //@ open Weak_share::('a, _t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ open_frac_borrow('a, Weak_frac_bc(self, nnp), _q_a / 2); + //@ open [?qnnp]Weak_frac_bc::(self, nnp)(); + if is_dangling(self.ptr.as_ptr()) { + let d = Weak { ptr: self.ptr }; + //@ close [qnnp]Weak_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_frac_bc(self, nnp)); + //@ close Weak_own::(_t, d); + return d; + } + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr) &*& [_]exists::(?wfrac); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + let old_size; + { + /*@ + pred Frame() = [_q_a / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + [_]frac_borrow('a, weak_ticket_(wgid, wfrac)); + pred GhostPost(r: usize) = + ticket(weak_pred, wgid, ?wfrac1) &*& [wfrac1]weak_pred(wgid, false); + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_add_relaxed_ghop(&(*ptr).weak, 1, Frame, GhostPost)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + Weak_is_live_from_borrow(wgid, wfrac); + assert arc_atomic_cas::AtomicUsize(&(*ptr).weak, ?v0); + if v0 > isize::MAX as usize { + // Localized bounded-thread assumption (matching `library/alloc/src/rcs/arc.rs` L3529): + // the `> MAX_REFCOUNT` branch aborts immediately, and fewer than `isize::MAX - 1` + // threads can concurrently pause between `fetch_add(1, Relaxed)` and `abort()`. + assume(v0 < usize::MAX - 1); + } else {} + mod_eq_plus_one(v0, usize::MAX); + assert arc_atomic_cas::is_AtomicUsize_fetch_add_op(?op, _, _, _, ?Q); + op(); + assert Q(?r); + create_ticket(weak_pred, wgid); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Frame(); + close GhostPost(r); + }; + @*/ + //@ close Frame(); + old_size = self.ptr.as_ref().weak.fetch_add(1, Relaxed); + //@ open Frame(); + //@ open GhostPost(old_size); + } + if old_size > MAX_REFCOUNT { + abort(); + } + let ret = Weak { ptr: self.ptr }; + //@ close [qnnp]Weak_frac_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_frac_bc(self, nnp)); + //@ close Weak_own::(_t, ret); + ret + } + } +} + +impl Drop for Weak { + fn drop<'a>(&'a mut self) { + unsafe { + //@ open Weak_full_borrow_content::(_t, self)(); + //@ open Weak_own::(_t, ?weak); + //@ assert [_]exists::<*ArcInner>(?ptr); + if is_dangling(self.ptr.as_ptr()) { + //@ std::ptr::open_NonNull_own::>(default_tid, weak.ptr); + //@ std::ptr::close_NonNull_own::>()(_t, weak.ptr); + return; + } + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + let old_weak; + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + ticket(weak_pred, wgid, ?wfrac) &*& [wfrac]weak_pred(wgid, false); + pred Post(r: usize) = if r == 1 { + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, 0) &*& + (*ptr).data |-> _ &*& + struct_ArcInner_padding::(ptr) &*& + std::alloc::alloc_block(ptr as *u8, std::alloc::Layout::new::>()) + } else { true }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_sub_ghop(&(*ptr).weak, 1, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + counting_match_fraction(weak_pred, wgid); + assert counting(weak_pred, wgid, ?w_cnt, false); + if w_cnt == 0 { + assert [?wf]weak_pred(wgid, false); + open [wf]weak_pred(wgid, false); + ghost_cell_fraction_info(wgid); + stop_counting(weak_pred, wgid); + open weak_pred(wgid, false); + merge_fractions ghost_cell::(wgid, _); + ghost_cell_fraction_info(wgid); + } else {} + destroy_ticket(weak_pred, wgid); + assert arc_atomic_cas::AtomicUsize(&(*ptr).weak, ?v0); + mod_eq_minus_one(v0, usize::MAX); + assert arc_atomic_cas::is_AtomicUsize_fetch_sub_op(?op, _, _, _, ?Q); + op(); + assert Q(?r); + if r == 1 { + stop_counting(weak_pred, wgid); + open weak_pred(wgid, false); + ghost_cell_mutate(wgid, true); + close weak_pred(wgid, true); + start_counting(weak_pred, wgid); + ghost_cell_mutate(inv_gid, ModeDealloced); + } else {} + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + close Post(r); + }; + @*/ + //@ close Pre(); + old_weak = self.ptr.as_ref().weak.fetch_sub(1, Release); + //@ std::ptr::open_NonNull_own::>(default_tid, weak.ptr); + //@ std::ptr::close_NonNull_own::>()(_t, weak.ptr); + if old_weak == 1 { + atomic::fence(Acquire); + //@ open arc_atomic_cas::app_usize(Post, old_weak)(); + //@ open Post(old_weak); + //@ open arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0); + //@ open arc_atomic_cas::AtomicUsize(&(*ptr).weak, 0); + //@ open_struct(ptr); + std::alloc::dealloc(self.ptr.as_ptr() as *mut u8, std::alloc::Layout::new::>()); + } else { + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(Post, old_weak)); + } + } + } + } +} + +impl Drop for Arc { + fn drop<'a>(&'a mut self) { + //@ open Arc_full_borrow_content::(_t, self)(); + //@ open Arc_own::(_t, ?arc); + //@ assert [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ptr); + //@ open exists::(?exclusive); + //@ open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr); + unsafe { + let old_strong; + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)) &*& + if exclusive { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& [frac]dlft_pred(sgid, some(?dk)) + }; + pred Post(r: usize) = if r == 1 { + [1/2]ghost_cell(imp_gid, 1) &*& + ((.full_borrow_content)(default_tid, &(*ptr).data))() + } else { true }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_sub_ghop(&(*ptr).strong, 1, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_fetch_sub_op(?op, _, _, _, ?Q); + if exclusive { + // `[1/2]ghost_cell(inv_gid, ModeExclusive)` proves `mode == ModeExclusive` (`strong == 1, weak == 1, lock_gid == false`)! + mod_eq_minus_one(1, usize::MAX); + op(); + assert Q(?r); + ghost_cell_mutate(inv_gid, ModeDataOut); + ghost_cell_mutate(imp_gid, 1); + } else { + assert ticket(dlft_pred, sgid, ?frac) &*& [frac]dlft_pred(sgid, some(?dk)); + counting_match_fraction(dlft_pred, sgid); + assert arc_atomic_cas::AtomicUsize(&(*ptr).strong, ?v0); + destroy_ticket(dlft_pred, sgid); + mod_eq_minus_one(v0, usize::MAX); + op(); + assert Q(?r); + if r == 1 { + stop_counting(dlft_pred, sgid); + open dlft_pred(sgid, some(dk)); + // Prove `locked == false`! If `locked == true`, `shared_weak_lock` holds `[lf]ghost_cell(sgid, some(dk))` + // contradicting full `[1]ghost_cell(sgid, some(dk))`! + assert shared_weak_lock(lock_gid, sgid, dk, ?locked); + open shared_weak_lock(lock_gid, sgid, dk, locked); + if locked { + merge_fractions ghost_cell::>(sgid, _); + ghost_cell_fraction_info(sgid); + } else {} + end_lifetime_m(dk); + borrow_end_m(dk, (.full_borrow_content)(default_tid, &(*ptr).data)); + ghost_cell_mutate(sgid, none); + close dlft_pred(sgid, none); + start_counting(dlft_pred, sgid); + ghost_cell_mutate(inv_gid, ModeDataOut); + ghost_cell_mutate(imp_gid, 1); + } else {} + } + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, ptr)(); + close_atomic_space(Marc); + assert Q(?res_r); + close Post(res_r); + }; + @*/ + //@ close Pre(); + old_strong = self.ptr.as_ref().strong.fetch_sub(1, Release); + //@ std::ptr::open_NonNull_own::>(default_tid, arc.ptr); + //@ std::ptr::close_NonNull_own::>()(_t, arc.ptr); + if old_strong != 1 { + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(Post, old_strong)); + return; + } + atomic::fence(Acquire); + //@ open arc_atomic_cas::app_usize(Post, old_strong)(); + //@ open Post(old_strong); + } + //@ open_full_borrow_content::(default_tid, &(*ptr).data); + //@ assert (*ptr).data |-> ?v; + //@ produce_type_interp::(); + //@ Send::send::(default_tid, _t, v); + //@ leak type_interp::(); + std::ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data); + //@ close Weak_implicit_own::(arc.ptr); + Weak::::drop_implicit(self.ptr); + } + } +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/atomic_model/verify.sh b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/verify.sh new file mode 100755 index 0000000000000..02792c20544f4 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/atomic_model/verify.sh @@ -0,0 +1,25 @@ +#!/bin/bash +set -e -x + +cd "$(dirname "$0")" + +export VFVERSION=26.10 +. ../../../../setup-verifast-home + +RUSTC_CMD="${RUSTC:-rustc +nightly-2026-09-25}" + +BUILD_DIR="$(mktemp -d "${TMPDIR:-/tmp}/arc_atomic_model.XXXXXX")" +trap 'rm -rf "$BUILD_DIR"' EXIT + +# Build the zero-overhead re-export crates into a temp dir (never into the working tree) +$RUSTC_CMD --edition 2024 --crate-type=lib --crate-name=arc_atomic arc_atomic.rs -o "$BUILD_DIR/libarc_atomic.rlib" +$RUSTC_CMD --edition 2024 --crate-type=lib --crate-name=arc_atomic_cas arc_atomic_cas.rs -o "$BUILD_DIR/libarc_atomic_cas.rlib" + +# Verify standalone Arc + Weak concurrent proof (new, deref, clone, drop, +# downgrade, upgrade, is_unique/get_mut, try_unwrap, strong_count, weak_count, +# Weak::new, Weak::clone, Weak::drop) under real Relaxed/Acquire/Release + fence(Acquire). +../../../../verifast \ + -rustc_args "--edition 2024 --extern arc_atomic_cas=$BUILD_DIR/libarc_atomic_cas.rlib" \ + -extern_spec "arc_atomic_cas=$PWD/arc_atomic_cas.rsspec" \ + -ignore_unwind_paths -ignore_ref_creation -allow_assume \ + arc_weak_test.rs diff --git a/verifast-proofs/alloc/rcs/arc.rs/compat.patch b/verifast-proofs/alloc/rcs/arc.rs/compat.patch new file mode 100644 index 0000000000000..2ce549f676b86 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/compat.patch @@ -0,0 +1,52 @@ +@@ -259,7 +259,6 @@ + /// + /// [rc_examples]: crate::rc#examples + #[doc(search_unbox)] +-#[rustc_diagnostic_item = "Arc"] + #[stable(feature = "rust1", since = "1.0.0")] + #[rustc_insignificant_dtor] + #[diagnostic::on_move( +@@ -268,7 +267,7 @@ + note = "consider using `Arc::clone`" + )] + pub struct Arc< +- #[rustc_assert_variance(covariant)] T: ?Sized, ++ T: ?Sized, + // FIXME: When stabilizing this parameter, the `AllocatorNightly` + // bound on the `From` impl *must* be weaked to `Allocator`, + // as `Box` is fundamental! +@@ -355,7 +354,6 @@ + /// + /// [`upgrade`]: Weak::upgrade + #[stable(feature = "arc_weak", since = "1.4.0")] +-#[rustc_diagnostic_item = "ArcWeak"] + pub struct Weak< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +@@ -2546,7 +2544,7 @@ + // Otherwise, the counter could be brought to an almost-overflow using a compare-exchange loop, + // and then overflow using a few `fetch_add`s. + if old_size > MAX_REFCOUNT { +- intrinsics::abort_immediate(); ++ intrinsics::abort(); + } + + // SAFETY: Pointer is valid & allocator corresponds to the one used to allocate it. +@@ -3602,7 +3600,7 @@ + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { +- intrinsics::abort_immediate(); ++ intrinsics::abort(); + } + } + +@@ -5080,7 +5078,7 @@ + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { +- intrinsics::abort_immediate(); ++ intrinsics::abort(); + } + + Weak { ptr: this.ptr, alloc: this.alloc.clone() } diff --git a/verifast-proofs/alloc/rcs/arc.rs/original/arc.rs b/verifast-proofs/alloc/rcs/arc.rs/original/arc.rs new file mode 100644 index 0000000000000..1a7fb0a01fb1d --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/original/arc.rs @@ -0,0 +1,5311 @@ +use core::any::Any; +use core::cell::CloneFromCell; +#[cfg(not(no_global_oom_handling))] +use core::clone::TrivialClone; +use core::clone::{CloneToUninit, Share, UseCloned}; +use core::cmp::Ordering; +use core::hash::{Hash, Hasher}; +#[cfg(not(no_global_oom_handling))] +use core::iter; +use core::marker::{PhantomData, Unsize}; +use core::mem::{self, Alignment, ManuallyDrop}; +use core::num::NonZeroUsize; +use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver}; +#[cfg(not(no_global_oom_handling))] +use core::ops::{Residual, Try}; +use core::panic::{RefUnwindSafe, UnwindSafe}; +use core::pin::{Pin, PinSafePointer}; +use core::ptr::{self, NonNull}; +#[cfg(not(no_global_oom_handling))] +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; +use crate::alloc::{ + AllocError, Allocator, AllocatorClone, AllocatorNightly, Global, Layout, StaticAllocator, +}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::rc::is_dangling; +#[cfg(not(no_global_oom_handling))] +use crate::string::String; +#[cfg(not(no_global_oom_handling))] +use crate::vec::Vec; + +/// A soft limit on the amount of references that may be made to an `Arc`. +/// +/// Going above this limit will abort your program (although not +/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references. +/// Trying to go above it might call a `panic` (if not actually going above it). +/// +/// This is a global invariant, and also applies when using a compare-exchange loop. +/// +/// See comment in `Arc::clone`. +const MAX_REFCOUNT: usize = (isize::MAX) as usize; + +#[cold] +#[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] +#[track_caller] +fn panic_arc_overflow() -> ! { + panic!("Arc counter overflow"); +} + +#[cfg(not(sanitize = "thread"))] +macro_rules! acquire { + ($x:expr) => { + atomic::fence(Acquire) + }; +} + +// ThreadSanitizer does not support memory fences. To avoid false positive +// reports in Arc / Weak implementation use atomic loads for synchronization +// instead. +#[cfg(sanitize = "thread")] +macro_rules! acquire { + ($x:expr) => { + $x.load(Acquire) + }; +} + +/// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically +/// Reference Counted'. +/// +/// The type `Arc` provides shared ownership of a value of type `T`, +/// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces +/// a new `Arc` instance, which points to the same allocation on the heap as the +/// source `Arc`, while increasing a reference count. When the last `Arc` +/// pointer to a given allocation is destroyed, the value stored in that allocation (often +/// referred to as "inner value") is also dropped. +/// +/// Shared references in Rust disallow mutation by default, and `Arc` is no +/// exception: you cannot generally obtain a mutable reference to something +/// inside an `Arc`. If you do need to mutate through an `Arc`, you have several options: +/// +/// 1. Use interior mutability with synchronization primitives like [`Mutex`][mutex], +/// [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types. +/// +/// 2. Use clone-on-write semantics with [`Arc::make_mut`] which provides efficient mutation +/// without requiring interior mutability. This approach clones the data only when +/// needed (when there are multiple references) and can be more efficient when mutations +/// are infrequent. +/// +/// 3. Use [`Arc::get_mut`] when you know your `Arc` is not shared (has a reference count of 1), +/// which provides direct mutable access to the inner value without any cloning. +/// +/// ``` +/// use std::sync::Arc; +/// +/// let mut data = Arc::new(vec![1, 2, 3]); +/// +/// // This will clone the vector only if there are other references to it +/// Arc::make_mut(&mut data).push(4); +/// +/// assert_eq!(*data, vec![1, 2, 3, 4]); +/// ``` +/// +/// **Note**: This type is only available on platforms that support atomic +/// loads and stores of pointers, which includes all platforms that support +/// the `std` crate but not all those which only support [`alloc`](crate). +/// This may be detected at compile time using `#[cfg(target_has_atomic = "ptr")]`. +/// +/// ## Thread Safety +/// +/// Unlike [`Rc`], `Arc` uses atomic operations for its reference +/// counting. This means that it is thread-safe. The disadvantage is that +/// atomic operations are more expensive than ordinary memory accesses. If you +/// are not sharing reference-counted allocations between threads, consider using +/// [`Rc`] for lower overhead. [`Rc`] is a safe default, because the +/// compiler will catch any attempt to send an [`Rc`] between threads. +/// However, a library might choose `Arc` in order to give library consumers +/// more flexibility. +/// +/// `Arc` will implement [`Send`] and [`Sync`] as long as the `T` implements +/// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an +/// `Arc` to make it thread-safe? This may be a bit counter-intuitive at +/// first: after all, isn't the point of `Arc` thread safety? The key is +/// this: `Arc` makes it thread safe to have multiple ownership of the same +/// data, but it doesn't add thread safety to its data. Consider +/// Arc<[RefCell\]>. [`RefCell`] isn't [`Sync`], and if `Arc` was always +/// [`Send`], Arc<[RefCell\]> would be as well. But then we'd have a problem: +/// [`RefCell`] is not thread safe; it keeps track of the borrowing count using +/// non-atomic operations. +/// +/// In the end, this means that you may need to pair `Arc` with some sort of +/// [`std::sync`] type, usually [`Mutex`][mutex]. +/// +/// ## Breaking cycles with `Weak` +/// +/// The [`downgrade`][downgrade] method can be used to create a non-owning +/// [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d +/// to an `Arc`, but this will return [`None`] if the value stored in the allocation has +/// already been dropped. In other words, `Weak` pointers do not keep the value +/// inside the allocation alive; however, they *do* keep the allocation +/// (the backing store for the value) alive. +/// +/// A cycle between `Arc` pointers will never be deallocated. For this reason, +/// [`Weak`] is used to break cycles. For example, a tree could have +/// strong `Arc` pointers from parent nodes to children, and [`Weak`] +/// pointers from children back to their parents. +/// +/// # Cloning references +/// +/// Creating a new reference from an existing reference-counted pointer is done using the +/// `Clone` trait implemented for [`Arc`][Arc] and [`Weak`][Weak]. +/// +/// ``` +/// use std::sync::Arc; +/// let foo = Arc::new(vec![1.0, 2.0, 3.0]); +/// // The two syntaxes below are equivalent. +/// let a = foo.clone(); +/// let b = Arc::clone(&foo); +/// // a, b, and foo are all Arcs that point to the same memory location +/// ``` +/// +/// ## `Deref` behavior +/// +/// `Arc` automatically dereferences to `T` (via the [`Deref`] trait), +/// so you can call `T`'s methods on a value of type `Arc`. To avoid name +/// clashes with `T`'s methods, the methods of `Arc` itself are associated +/// functions, called using [fully qualified syntax]: +/// +/// ``` +/// use std::sync::Arc; +/// +/// let my_arc = Arc::new(()); +/// let my_weak = Arc::downgrade(&my_arc); +/// ``` +/// +/// `Arc`'s implementations of traits like `Clone` may also be called using +/// fully qualified syntax. Some people prefer to use fully qualified syntax, +/// while others prefer using method-call syntax. +/// +/// ``` +/// use std::sync::Arc; +/// +/// let arc = Arc::new(()); +/// // Method-call syntax +/// let arc2 = arc.clone(); +/// // Fully qualified syntax +/// let arc3 = Arc::clone(&arc); +/// ``` +/// +/// [`Weak`][Weak] does not auto-dereference to `T`, because the inner value may have +/// already been dropped. +/// +/// [`Rc`]: crate::rc::Rc +/// [clone]: Clone::clone +/// [mutex]: ../../std/sync/struct.Mutex.html +/// [rwlock]: ../../std/sync/struct.RwLock.html +/// [atomic]: core::sync::atomic +/// [downgrade]: Arc::downgrade +/// [upgrade]: Weak::upgrade +/// [RefCell\]: core::cell::RefCell +/// [`RefCell`]: core::cell::RefCell +/// [`std::sync`]: ../../std/sync/index.html +/// [`Arc::clone(&from)`]: Arc::clone +/// [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name +/// +/// # Examples +/// +/// Sharing some immutable data between threads: +/// +/// ```ignore-wasm +/// use std::sync::Arc; +/// use std::thread; +/// +/// let five = Arc::new(5); +/// +/// for _ in 0..10 { +/// let five = Arc::clone(&five); +/// +/// thread::spawn(move || { +/// println!("{five:?}"); +/// }); +/// } +/// ``` +/// +/// Sharing a mutable [`AtomicUsize`]: +/// +/// [`AtomicUsize`]: core::sync::atomic::AtomicUsize "sync::atomic::AtomicUsize" +/// +/// ```ignore-wasm +/// use std::sync::Arc; +/// use std::sync::atomic::{AtomicUsize, Ordering}; +/// use std::thread; +/// +/// let val = Arc::new(AtomicUsize::new(5)); +/// +/// for _ in 0..10 { +/// let val = Arc::clone(&val); +/// +/// thread::spawn(move || { +/// let v = val.fetch_add(1, Ordering::Relaxed); +/// println!("{v:?}"); +/// }); +/// } +/// ``` +/// +/// See the [`rc` documentation][rc_examples] for more examples of reference +/// counting in general. +/// +/// [rc_examples]: crate::rc#examples +#[doc(search_unbox)] +#[rustc_diagnostic_item = "Arc"] +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +#[diagnostic::on_move( + message = "the type `{Self}` does not implement `Copy`", + label = "this move could be avoided by cloning the original `{Self}`, which is inexpensive", + note = "consider using `Arc::clone`" +)] +pub struct Arc< + #[rustc_assert_variance(covariant)] T: ?Sized, + // FIXME: When stabilizing this parameter, the `AllocatorNightly` + // bound on the `From` impl *must* be weaked to `Allocator`, + // as `Box` is fundamental! + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + ptr: NonNull>, + phantom: PhantomData>, + alloc: A, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Arc {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for Arc {} + +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe + for Arc +{ +} + +#[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> for Arc {} + +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for Arc {} + +// SAFETY: `Arc::clone` doesn't access any `Cell`s which could contain the `Arc` being cloned. +#[unstable(feature = "cell_get_cloned", issue = "145329")] +unsafe impl CloneFromCell for Arc {} + +impl Arc { + unsafe fn from_inner(ptr: NonNull>) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_inner_in(ptr, Global) } + } + + unsafe fn from_ptr(ptr: *mut ArcInner) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_ptr_in(ptr, Global) } + } +} + +impl Arc { + #[inline] + fn into_inner_with_allocator(this: Self) -> (NonNull>, A) { + let this = mem::ManuallyDrop::new(this); + // SAFETY: Pointer is valid for reads. + (this.ptr, unsafe { ptr::read(&this.alloc) }) + } + + #[inline] + unsafe fn from_inner_in(ptr: NonNull>, alloc: A) -> Self { + Self { ptr, phantom: PhantomData, alloc } + } + + #[inline] + unsafe fn from_ptr_in(ptr: *mut ArcInner, alloc: A) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_inner_in(NonNull::new_unchecked(ptr), alloc) } + } +} + +/// `Weak` is a version of [`Arc`] that holds a non-owning reference to the +/// managed allocation. +/// +/// The allocation is accessed by calling [`upgrade`] on the `Weak` +/// pointer, which returns an [Option]<[Arc]\>. +/// +/// Since a `Weak` reference does not count towards ownership, it will not +/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no +/// guarantees about the value still being present. Thus it may return [`None`] +/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation +/// itself (the backing store) from being deallocated. +/// +/// A `Weak` pointer is useful for keeping a temporary reference to the allocation +/// managed by [`Arc`] without preventing its inner value from being dropped. It is also used to +/// prevent circular references between [`Arc`] pointers, since mutual owning references +/// would never allow either [`Arc`] to be dropped. For example, a tree could +/// have strong [`Arc`] pointers from parent nodes to children, and `Weak` +/// pointers from children back to their parents. +/// +/// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`]. +/// +/// [`upgrade`]: Weak::upgrade +#[stable(feature = "arc_weak", since = "1.4.0")] +#[rustc_diagnostic_item = "ArcWeak"] +pub struct Weak< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + // This is a `NonNull` to allow optimizing the size of this type in enums, + // but it is not necessarily a valid pointer. + // `Weak::new` sets this to `usize::MAX` so that it doesn’t need + // to allocate space on the heap. That's not a value a real pointer + // will ever have because ArcInner has alignment at least 2. + ptr: NonNull>, + alloc: A, +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl Send for Weak {} +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl Sync for Weak {} + +#[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> for Weak {} +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for Weak {} + +// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned. +#[unstable(feature = "cell_get_cloned", issue = "145329")] +unsafe impl CloneFromCell for Weak {} + +#[stable(feature = "arc_weak", since = "1.4.0")] +impl fmt::Debug for Weak { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "(Weak)") + } +} + +// This is repr(C) to future-proof against possible field-reordering, which +// would interfere with otherwise safe [into|from]_raw() of transmutable +// inner types. +// Unlike RcInner, repr(align(2)) is not strictly required because atomic types +// have the alignment same as its size, but we use it for consistency and clarity. +#[repr(C, align(2))] +struct ArcInner { + strong: Atomic, + + // the value usize::MAX acts as a sentinel for temporarily "locking" the + // weak count, preventing `Arc::downgrade` from racing to create new + // `Weak` references. `Arc::is_unique` (which backs `Arc::get_mut`) + // needs to observe both the strong and weak counts as indicating + // uniqueness in one logical atomic step; since they live in separate + // atomic words, it locks the weak count while reading the strong + // count to keep the two reads consistent. + weak: Atomic, + + data: T, +} + +/// Calculate layout for `ArcInner` using the inner value's layout +fn arcinner_layout_for_value_layout(layout: Layout) -> Layout { + // Calculate layout using the given value layout. + // Previously, layout was calculated on the expression + // `&*(ptr as *const ArcInner)`, but this created a misaligned + // reference (see #54908). + Layout::new::>() + .extend(layout) + .unwrap_or_else(|_| panic!("capacity overflow")) + .0 + .pad_to_align() +} + +unsafe impl Send for ArcInner {} +unsafe impl Sync for ArcInner {} + +impl Arc { + /// Constructs a new `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn new(data: T) -> Arc { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x: Box<_> = Box::new(ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }); + // SAFETY: Pointer is valid. + unsafe { Self::from_inner(Box::into_non_null(x)) } + } + + /// Constructs a new `Arc` while giving you a `Weak` to the allocation, + /// to allow you to construct a `T` which holds a weak pointer to itself. + /// + /// Generally, a structure circularly referencing itself, either directly or + /// indirectly, should not hold a strong reference to itself to prevent a memory leak. + /// Using this function, you get access to the weak pointer during the + /// initialization of `T`, before the `Arc` is created, such that you can + /// clone and store it inside the `T`. + /// + /// `new_cyclic` first allocates the managed allocation for the `Arc`, + /// then calls your closure, giving it a `Weak` to this allocation, + /// and only afterwards completes the construction of the `Arc` by placing + /// the `T` returned from your closure into the allocation. + /// + /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic` + /// returns, calling [`upgrade`] on the weak reference inside your closure will + /// fail and result in a `None` value. + /// + /// # Panics + /// + /// If `data_fn` panics, the panic is propagated to the caller, and the + /// temporary [`Weak`] is dropped normally. + /// + /// # Example + /// + /// ``` + /// # #![allow(dead_code)] + /// use std::sync::{Arc, Weak}; + /// + /// struct Gadget { + /// me: Weak, + /// } + /// + /// impl Gadget { + /// /// Constructs a reference counted Gadget. + /// fn new() -> Arc { + /// // `me` is a `Weak` pointing at the new allocation of the + /// // `Arc` we're constructing. + /// Arc::new_cyclic(|me| { + /// // Create the actual struct here. + /// Gadget { me: me.clone() } + /// }) + /// } + /// + /// /// Returns a reference counted pointer to Self. + /// fn me(&self) -> Arc { + /// self.me.upgrade().unwrap() + /// } + /// } + /// ``` + /// [`upgrade`]: Weak::upgrade + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "arc_new_cyclic", since = "1.60.0")] + pub fn new_cyclic(data_fn: F) -> Arc + where + F: FnOnce(&Weak) -> T, + { + Self::new_cyclic_in(data_fn, Global) + } + + /// Constructs a new `Arc` with uninitialized contents. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut five = Arc::::new_uninit(); + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use] + pub fn new_uninit() -> Arc> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr(Arc::allocate_for_layout( + Layout::new::(), + |layout| Global.allocate(layout), + <*mut u8>::cast, + )) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let zero = Arc::::new_zeroed(); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_zeroed_alloc", since = "1.92.0")] + #[must_use] + pub fn new_zeroed() -> Arc> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr(Arc::allocate_for_layout( + Layout::new::(), + |layout| Global.allocate_zeroed(layout), + <*mut u8>::cast, + )) + } + } + + /// Constructs a new `Pin>`. If `T` does not implement `Unpin`, then + /// `data` will be pinned in memory and unable to be moved. + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "pin", since = "1.33.0")] + #[must_use] + pub fn pin(data: T) -> Pin> { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::new(data)) } + } + + /// Constructs a new `Pin>`, return an error if allocation fails. + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_pin(data: T) -> Result>, AllocError> { + // SAFETY: We own and create the pinned pointer. + unsafe { Ok(Pin::new_unchecked(Arc::try_new(data)?)) } + } + + /// Constructs a new `Arc`, returning an error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// + /// let five = Arc::try_new(5)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new(data: T) -> Result, AllocError> { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x: Box<_> = Box::try_new(ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + })?; + // SAFETY: Pointer is valid. + unsafe { Ok(Self::from_inner(Box::into_non_null(x))) } + } + + /// Constructs a new `Arc` with uninitialized contents, returning an error + /// if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// + /// let mut five = Arc::::try_new_uninit()?; + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_new_uninit() -> Result>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr(Arc::try_allocate_for_layout( + Layout::new::(), + |layout| Global.allocate(layout), + <*mut u8>::cast, + )?)) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, returning an error if allocation fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature( allocator_ext)] + /// + /// use std::sync::Arc; + /// + /// let zero = Arc::::try_new_zeroed()?; + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_new_zeroed() -> Result>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr(Arc::try_allocate_for_layout( + Layout::new::(), + |layout| Global.allocate_zeroed(layout), + <*mut u8>::cast, + )?)) + } + } +} + +impl Arc { + /// Constructs a new `Arc` in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// ``` + #[inline] + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_in(data: T, alloc: A) -> Arc { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x = Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + ); + let (ptr, alloc) = Box::into_non_null_with_allocator(x); + // SAFETY: Pointer is valid. + unsafe { Self::from_inner_in(ptr, alloc) } + } + + /// Constructs a new `Arc` with uninitialized contents in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut five = Arc::::new_uninit_in(System); + /// + /// let five = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); + /// + /// five.assume_init() + /// }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_uninit_in(alloc: A) -> Arc, A> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr_in( + Arc::allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate(layout), + <*mut u8>::cast, + ), + alloc, + ) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, in the provided allocator. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let zero = Arc::::new_zeroed_in(System); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_zeroed_in(alloc: A) -> Arc, A> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr_in( + Arc::allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate_zeroed(layout), + <*mut u8>::cast, + ), + alloc, + ) + } + } + + /// Constructs a new `Arc` in the given allocator while giving you a `Weak` to the allocation, + /// to allow you to construct a `T` which holds a weak pointer to itself. + /// + /// Generally, a structure circularly referencing itself, either directly or + /// indirectly, should not hold a strong reference to itself to prevent a memory leak. + /// Using this function, you get access to the weak pointer during the + /// initialization of `T`, before the `Arc` is created, such that you can + /// clone and store it inside the `T`. + /// + /// `new_cyclic_in` first allocates the managed allocation for the `Arc`, + /// then calls your closure, giving it a `Weak` to this allocation, + /// and only afterwards completes the construction of the `Arc` by placing + /// the `T` returned from your closure into the allocation. + /// + /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic_in` + /// returns, calling [`upgrade`] on the weak reference inside your closure will + /// fail and result in a `None` value. + /// + /// # Panics + /// + /// If `data_fn` panics, the panic is propagated to the caller, and the + /// temporary [`Weak`] is dropped normally. + /// + /// # Example + /// + /// See [`new_cyclic`] + /// + /// [`new_cyclic`]: Arc::new_cyclic + /// [`upgrade`]: Weak::upgrade + #[cfg(not(no_global_oom_handling))] + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_cyclic_in(data_fn: F, alloc: A) -> Arc + where + F: FnOnce(&Weak) -> T, + { + // Construct the inner in the "uninitialized" state with a single + // weak reference. + let (uninit_ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + weak: atomic::AtomicUsize::new(1), + data: mem::MaybeUninit::::uninit(), + }, + alloc, + )); + let init_ptr: NonNull> = uninit_ptr.cast(); + + let weak = Weak { ptr: init_ptr, alloc }; + + // It's important we don't give up ownership of the weak pointer, or + // else the memory might be freed by the time `data_fn` returns. If + // we really wanted to pass ownership, we could create an additional + // weak pointer for ourselves, but this would result in additional + // updates to the weak reference count which might not be necessary + // otherwise. + let data = data_fn(&weak); + + // Now we can properly initialize the inner value and turn our weak + // reference into a strong reference. + let inner = init_ptr.as_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::write(&raw mut (*inner).data, data); + + // The above write to the data field must be visible to any threads which + // observe a non-zero strong count. Therefore we need at least "Release" ordering + // in order to synchronize with the `compare_exchange_weak` in `Weak::upgrade`. + // + // "Acquire" ordering is not required. When considering the possible behaviors + // of `data_fn` we only need to look at what it could do with a reference to a + // non-upgradeable `Weak`: + // - It can *clone* the `Weak`, increasing the weak reference count. + // - It can drop those clones, decreasing the weak reference count (but never to zero). + // + // These side effects do not impact us in any way, and no other side effects are + // possible with safe code alone. + let prev_value = (*inner).strong.fetch_add(1, Release); + debug_assert_eq!(prev_value, 0, "No prior strong references should exist"); + + // Strong references should collectively own a shared weak reference, + // so don't run the destructor for our old weak reference. + // Calling into_raw_with_allocator has the double effect of giving us back the allocator, + // and forgetting the weak reference. + let alloc = weak.into_raw_with_allocator().1; + + Arc::from_inner_in(init_ptr, alloc) + } + } + + /// Constructs a new `Pin>` in the provided allocator. If `T` does not implement `Unpin`, + /// then `data` will be pinned in memory and unable to be moved. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn pin_in(data: T, alloc: A) -> Pin> + where + A: StaticAllocator, + { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::new_in(data, alloc)) } + } + + /// Constructs a new `Pin>` in the provided allocator, return an error if allocation + /// fails. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_pin_in(data: T, alloc: A) -> Result>, AllocError> + where + A: StaticAllocator, + { + // SAFETY: We own and create the pinned pointer. + unsafe { Ok(Pin::new_unchecked(Arc::try_new_in(data, alloc)?)) } + } + + /// Constructs a new `Arc` in the provided allocator, returning an error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::try_new_in(5, System)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_in(data: T, alloc: A) -> Result, AllocError> { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x = Box::try_new_in( + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + )?; + let (ptr, alloc) = Box::into_non_null_with_allocator(x); + // SAFETY: Pointer is valid since we created it. + Ok(unsafe { Self::from_inner_in(ptr, alloc) }) + } + + /// Constructs a new `Arc` with uninitialized contents, in the provided allocator, returning an + /// error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut five = Arc::::try_new_uninit_in(System)?; + /// + /// let five = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); + /// + /// five.assume_init() + /// }; + /// + /// assert_eq!(*five, 5); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_uninit_in(alloc: A) -> Result, A>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr_in( + Arc::try_allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate(layout), + <*mut u8>::cast, + )?, + alloc, + )) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, in the provided allocator, returning an error if allocation + /// fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let zero = Arc::::try_new_zeroed_in(System)?; + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_zeroed_in(alloc: A) -> Result, A>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr_in( + Arc::try_allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate_zeroed(layout), + <*mut u8>::cast, + )?, + alloc, + )) + } + } + /// Returns the inner value, if the `Arc` has exactly one strong reference. + /// + /// Otherwise, an [`Err`] is returned with the same `Arc` that was + /// passed in. + /// + /// This will succeed even if there are outstanding weak references. + /// + /// It is strongly recommended to use [`Arc::into_inner`] instead if you don't + /// keep the `Arc` in the [`Err`] case. + /// Immediately dropping the [`Err`]-value, as the expression + /// `Arc::try_unwrap(this).ok()` does, can cause the strong count to + /// drop to zero and the inner value of the `Arc` to be dropped. + /// For instance, if two threads execute such an expression in parallel, + /// there is a race condition without the possibility of unsafety: + /// The threads could first both check whether they own the last instance + /// in `Arc::try_unwrap`, determine that they both do not, and then both + /// discard and drop their instance in the call to [`ok`][`Result::ok`]. + /// In this scenario, the value inside the `Arc` is safely destroyed + /// by exactly one of the threads, but neither thread will ever be able + /// to use the value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// assert_eq!(Arc::try_unwrap(x), Ok(3)); + /// + /// let x = Arc::new(4); + /// let _y = Arc::clone(&x); + /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn try_unwrap(this: Self) -> Result { + if this.inner().strong.compare_exchange(1, 0, Relaxed, Relaxed).is_err() { + return Err(this); + } + + acquire!(this.inner().strong); + + let this = ManuallyDrop::new(this); + // SAFETY: Pointer is valid for reads, contains initialised memory, + // and not dropped multiple times (we return it). + let elem: T = unsafe { ptr::read(&this.ptr.as_ref().data) }; + // SAFETY: As above, but we explicitly drop the allocator only once + // upon creating and dropping a weak pointer. + let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator + + // Make a weak pointer to clean up the implicit strong-weak reference + let _weak = Weak { ptr: this.ptr, alloc }; + + Ok(elem) + } + + /// Returns the inner value, if the `Arc` has exactly one strong reference. + /// + /// Otherwise, [`None`] is returned and the `Arc` is dropped. + /// + /// This will succeed even if there are outstanding weak references. + /// + /// If `Arc::into_inner` is called on every clone of this `Arc`, + /// it is guaranteed that exactly one of the calls returns the inner value. + /// This means in particular that the inner value is not dropped. + /// + /// [`Arc::try_unwrap`] is conceptually similar to `Arc::into_inner`, but it + /// is meant for different use-cases. If used as a direct replacement + /// for `Arc::into_inner` anyway, such as with the expression + /// [Arc::try_unwrap]\(this).[ok][Result::ok](), then it does + /// **not** give the same guarantee as described in the previous paragraph. + /// For more information, see the examples below and read the documentation + /// of [`Arc::try_unwrap`]. + /// + /// # Examples + /// + /// Minimal example demonstrating the guarantee that `Arc::into_inner` gives. + /// ```ignore-wasm + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// let y = Arc::clone(&x); + /// + /// // Two threads calling `Arc::into_inner` on both clones of an `Arc`: + /// let x_thread = std::thread::spawn(|| Arc::into_inner(x)); + /// let y_thread = std::thread::spawn(|| Arc::into_inner(y)); + /// + /// let x_inner_value = x_thread.join().unwrap(); + /// let y_inner_value = y_thread.join().unwrap(); + /// + /// // One of the threads is guaranteed to receive the inner value: + /// assert!(matches!( + /// (x_inner_value, y_inner_value), + /// (None, Some(3)) | (Some(3), None) + /// )); + /// // The result could also be `(None, None)` if the threads called + /// // `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead. + /// ``` + /// + /// A more practical example demonstrating the need for `Arc::into_inner`: + /// ```ignore-wasm + /// use std::sync::Arc; + /// + /// // Definition of a simple singly linked list using `Arc`: + /// #[derive(Clone)] + /// struct LinkedList(Option>>); + /// struct Node(T, Option>>); + /// + /// // Dropping a long `LinkedList` relying on the destructor of `Arc` + /// // can cause a stack overflow. To prevent this, we can provide a + /// // manual `Drop` implementation that does the destruction in a loop: + /// impl Drop for LinkedList { + /// fn drop(&mut self) { + /// let mut link = self.0.take(); + /// while let Some(arc_node) = link.take() { + /// if let Some(Node(_value, next)) = Arc::into_inner(arc_node) { + /// link = next; + /// } + /// } + /// } + /// } + /// + /// // Implementation of `new` and `push` omitted + /// impl LinkedList { + /// /* ... */ + /// # fn new() -> Self { + /// # LinkedList(None) + /// # } + /// # fn push(&mut self, x: T) { + /// # self.0 = Some(Arc::new(Node(x, self.0.take()))); + /// # } + /// } + /// + /// // The following code could have still caused a stack overflow + /// // despite the manual `Drop` impl if that `Drop` impl had used + /// // `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`. + /// + /// // Create a long list and clone it + /// let mut x = LinkedList::new(); + /// let size = 100000; + /// # let size = if cfg!(miri) { 100 } else { size }; + /// for i in 0..size { + /// x.push(i); // Adds i to the front of x + /// } + /// let y = x.clone(); + /// + /// // Drop the clones in parallel + /// let x_thread = std::thread::spawn(|| drop(x)); + /// let y_thread = std::thread::spawn(|| drop(y)); + /// x_thread.join().unwrap(); + /// y_thread.join().unwrap(); + /// ``` + #[inline] + #[stable(feature = "arc_into_inner", since = "1.70.0")] + pub fn into_inner(this: Self) -> Option { + // Make sure that the ordinary `Drop` implementation isn’t called as well + let mut this = mem::ManuallyDrop::new(this); + + // Following the implementation of `drop` and `drop_slow` + if this.inner().strong.fetch_sub(1, Release) != 1 { + return None; + } + + acquire!(this.inner().strong); + + // SAFETY: This mirrors the line + // + // unsafe { ptr::drop_in_place(Self::get_mut_unchecked(self)) }; + // + // in `drop_slow`. Instead of dropping the value behind the pointer, + // it is read and eventually returned; `ptr::read` has the same + // safety conditions as `ptr::drop_in_place`. + let inner = unsafe { ptr::read(Self::get_mut_unchecked(&mut this)) }; + // SAFETY: Pointer is valid for reads. + let alloc = unsafe { ptr::read(&this.alloc) }; + + drop(Weak { ptr: this.ptr, alloc }); + + Some(inner) + } + + /// Maps the value in an `Arc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `Arc`, and the result is returned, also in + /// an `Arc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::map(a, f)` instead of `r.map(a)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let r = Arc::new(7); + /// let new = Arc::map(r, |i| i + 7); + /// assert_eq!(*new, 14); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "smart_pointer_map", since = "1.100.0")] + pub fn map(this: Self, f: impl FnOnce(&T) -> U) -> Arc { + if size_of::() == size_of::() + && align_of::() == align_of::() + && Arc::is_unique(&this) + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + let value = ptr.read(); + let mut allocation = Arc::from_raw_in(ptr.cast::>(), alloc); + + Arc::get_mut_unchecked(&mut allocation).write(f(&value)); + allocation.assume_init() + } + } else { + let output = f(&*this); + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::decrement_strong_count_in(ptr, &alloc) } + + Arc::new_in(output, alloc) + } + } + + /// Attempts to map the value in an `Arc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `Arc`, and if the operation succeeds, the + /// result is returned, also in an `Arc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::try_map(a, f)` instead of `a.try_map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(smart_pointer_try_map)] + /// + /// use std::sync::Arc; + /// + /// let b = Arc::new(7); + /// let new = Arc::try_map(b, |&i| u32::try_from(i)).unwrap(); + /// assert_eq!(*new, 7); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "smart_pointer_try_map", issue = "144419")] + pub fn try_map( + this: Self, + f: impl FnOnce(&T) -> R, + ) -> >>::TryType + where + R: Try, + R::Residual: Residual>, + { + if size_of::() == size_of::() + && align_of::() == align_of::() + && Arc::is_unique(&this) + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + let value = ptr.read(); + let mut allocation = + Arc::from_raw_in(ptr.cast::>(), alloc); + + Arc::get_mut_unchecked(&mut allocation).write(f(&value)?); + try { allocation.assume_init() } + } + } else { + let output = f(&*this)?; + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::decrement_strong_count_in(ptr, &alloc) } + + try { Arc::new_in(output, alloc) } + } + } +} + +impl Arc<[T]> { + /// Constructs a new atomically reference-counted slice with uninitialized contents. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut values = Arc::<[u32]>::new_uninit_slice(3); + /// + /// // Deferred initialization: + /// let data = Arc::get_mut(&mut values).unwrap(); + /// data[0].write(1); + /// data[1].write(2); + /// data[2].write(3); + /// + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use] + pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit]> { + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr(Arc::allocate_for_slice(len)) } + } + + /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being + /// filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and + /// incorrect usage of this method. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let values = Arc::<[u32]>::new_zeroed_slice(3); + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_zeroed_alloc", since = "1.92.0")] + #[must_use] + pub fn new_zeroed_slice(len: usize) -> Arc<[mem::MaybeUninit]> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr(Arc::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| Global.allocate_zeroed(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[mem::MaybeUninit]>, + )) + } + } +} + +impl Arc<[T], A> { + /// Constructs a new atomically reference-counted slice with uninitialized contents in the + /// provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut values = Arc::<[u32], _>::new_uninit_slice_in(3, System); + /// + /// let values = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1); + /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2); + /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3); + /// + /// values.assume_init() + /// }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_uninit_slice_in(len: usize, alloc: A) -> Arc<[mem::MaybeUninit], A> { + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr_in(Arc::allocate_for_slice_in(len, &alloc), alloc) } + } + + /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being + /// filled with `0` bytes, in the provided allocator. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and + /// incorrect usage of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let values = Arc::<[u32], _>::new_zeroed_slice_in(3, System); + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Arc<[mem::MaybeUninit], A> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr_in( + Arc::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| alloc.allocate_zeroed(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[mem::MaybeUninit]>, + ), + alloc, + ) + } + } + + /// Converts the reference-counted slice into a reference-counted array. + /// + /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type. + /// + /// # Errors + /// + /// Returns the original `Arc<[T]>` in the `Err` variant if `self.len()` does not equal `N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(alloc_slice_into_array)] + /// use std::sync::Arc; + /// + /// let arc_slice: Arc<[i32]> = Arc::new([1, 2, 3]); + /// + /// let arc_array: Arc<[i32; 3]> = arc_slice.into_array().unwrap(); + /// ``` + #[unstable(feature = "alloc_slice_into_array", issue = "148082")] + #[inline] + pub fn into_array(self) -> Result, Self> { + if self.len() == N { + let (ptr, alloc) = Self::into_raw_with_allocator(self); + let ptr = ptr as *const [T; N]; + + // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length. + let me = unsafe { Arc::from_raw_in(ptr, alloc) }; + Ok(me) + } else { + Err(self) + } + } +} + +impl Arc, A> { + /// Converts to `Arc`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the inner value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut five = Arc::::new_uninit(); + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub unsafe fn assume_init(self) -> Arc { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_inner_in(ptr.cast(), alloc) } + } +} + +impl Arc { + /// Constructs a new `Arc` with a clone of `value`. + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// use std::sync::Arc; + /// + /// let hello: Arc = Arc::clone_from_ref("hello"); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "clone_from_ref", issue = "149075")] + pub fn clone_from_ref(value: &T) -> Arc { + Arc::clone_from_ref_in(value, Global) + } + + /// Constructs a new `Arc` with a clone of `value`, returning an error if allocation fails + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// use std::sync::Arc; + /// + /// let hello: Arc = Arc::try_clone_from_ref("hello")?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_clone_from_ref(value: &T) -> Result, AllocError> { + Arc::try_clone_from_ref_in(value, Global) + } +} + +impl Arc { + /// Constructs a new `Arc` with a clone of `value` in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let hello: Arc = Arc::clone_from_ref_in("hello", System); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn clone_from_ref_in(value: &T, alloc: A) -> Arc { + // `in_progress` drops the allocation if we panic before finishing initializing it. + let mut in_progress: UniqueArcUninit = UniqueArcUninit::new(value, alloc); + + // Initialize with clone of value. + // ignore-tidy-undocumented-unsafe + unsafe { + // Clone. If the clone panics, `in_progress` will be dropped and clean up. + value.clone_to_uninit(in_progress.data_ptr().cast()); + // Cast type of pointer, now that it is initialized. + in_progress.into_arc() + } + } + + /// Constructs a new `Arc` with a clone of `value` in the provided allocator, returning an error if allocation fails + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let hello: Arc = Arc::try_clone_from_ref_in("hello", System)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_clone_from_ref_in(value: &T, alloc: A) -> Result, AllocError> { + // `in_progress` drops the allocation if we panic before finishing initializing it. + let mut in_progress: UniqueArcUninit = UniqueArcUninit::try_new(value, alloc)?; + + // Initialize with clone of value. + // ignore-tidy-undocumented-unsafe + let initialized_clone = unsafe { + // Clone. If the clone panics, `in_progress` will be dropped and clean up. + value.clone_to_uninit(in_progress.data_ptr().cast()); + // Cast type of pointer, now that it is initialized. + in_progress.into_arc() + }; + + Ok(initialized_clone) + } +} + +impl Arc<[mem::MaybeUninit], A> { + /// Converts to `Arc<[T]>`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the inner value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut values = Arc::<[u32]>::new_uninit_slice(3); + /// + /// // Deferred initialization: + /// let data = Arc::get_mut(&mut values).unwrap(); + /// data[0].write(1); + /// data[1].write(2); + /// data[2].write(3); + /// + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub unsafe fn assume_init(self) -> Arc<[T], A> { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + // SAFETY: Upheld by caller. + unsafe { Arc::from_ptr_in(ptr.as_ptr() as _, alloc) } + } +} + +impl Arc { + /// Constructs an `Arc` from a raw pointer. + /// + /// The raw pointer must have been previously returned by a call to + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator]. + /// + /// # Safety + /// + /// * Creating a `Arc` from a pointer other than one returned from + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator] + /// is undefined behavior. + /// * If `U` is sized, it must have the same size and alignment as `T`. This + /// is trivially true if `U` is `T`. + /// * If `U` is unsized, its data pointer must have the same size and + /// alignment as `T`. This is trivially true if `Arc` was constructed + /// through `Arc` and then converted to `Arc` through an [unsized + /// coercion]. + /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size + /// and alignment, this is basically like transmuting references of + /// different types. See [`mem::transmute`][transmute] for more information + /// on what restrictions apply in this case. + /// * The raw pointer must point to a block of memory allocated by the global allocator. + /// * The user of `from_raw` has to make sure a specific value of `T` is only + /// dropped once. + /// + /// This function is unsafe because improper use may lead to memory unsafety, + /// even if the returned `Arc` is never accessed. + /// + /// [into_raw]: Arc::into_raw + /// [into_raw_with_allocator]: Arc::into_raw_with_allocator + /// [transmute]: core::mem::transmute + /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let x_ptr = Arc::into_raw(x); + /// + /// unsafe { + /// // Convert back to an `Arc` to prevent leak. + /// let x = Arc::from_raw(x_ptr); + /// assert_eq!(&*x, "hello"); + /// + /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. + /// } + /// + /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! + /// ``` + /// + /// Convert a slice back into its original array: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x: Arc<[u32]> = Arc::new([1, 2, 3]); + /// let x_ptr: *const [u32] = Arc::into_raw(x); + /// + /// unsafe { + /// let x: Arc<[u32; 3]> = Arc::from_raw(x_ptr.cast::<[u32; 3]>()); + /// assert_eq!(&*x, &[1, 2, 3]); + /// } + /// ``` + #[inline] + #[stable(feature = "rc_raw", since = "1.17.0")] + pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: Upheld by caller. + unsafe { Arc::from_raw_in(ptr, Global) } + } + + /// Consumes the `Arc`, returning the wrapped pointer. + /// + /// To avoid a memory leak the pointer must be converted back to an `Arc` using + /// [`Arc::from_raw`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let x_ptr = Arc::into_raw(x); + /// assert_eq!(unsafe { &*x_ptr }, "hello"); + /// # // Prevent leaks for Miri. + /// # drop(unsafe { Arc::from_raw(x_ptr) }); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "rc_raw", since = "1.17.0")] + #[lint::never_returns_null_ptr] + pub fn into_raw(this: Self) -> *const T { + let this = ManuallyDrop::new(this); + Self::as_ptr(&*this) + } + + /// Increments the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory + /// allocated by the global allocator. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// unsafe { + /// let ptr = Arc::into_raw(five); + /// Arc::increment_strong_count(ptr); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// # // Prevent leaks for Miri. + /// # Arc::decrement_strong_count(ptr); + /// } + /// ``` + #[inline] + #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] + pub unsafe fn increment_strong_count(ptr: *const T) { + // SAFETY: Upheld by caller. + unsafe { Arc::increment_strong_count_in(ptr, Global) } + } + + /// Decrements the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) when invoking this method, and `ptr` must point to a block of memory + /// allocated by the global allocator. This method can be used to release the final + /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been + /// released. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// unsafe { + /// let ptr = Arc::into_raw(five); + /// Arc::increment_strong_count(ptr); + /// + /// // Those assertions are deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// Arc::decrement_strong_count(ptr); + /// assert_eq!(1, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] + pub unsafe fn decrement_strong_count(ptr: *const T) { + // SAFETY: Upheld by caller. + unsafe { Arc::decrement_strong_count_in(ptr, Global) } + } + + /// Gets the number of strong (`Arc`) pointers to the allocation behind the given raw + /// pointer. + /// + /// This method does not consume or drop the `Arc` behind this pointer. + /// + /// # Safety + /// + /// The pointer must point to (and have valid metadata for) the value inside a live `Arc` + /// allocation, such as a pointer returned by [`Arc::into_raw`], + /// [`Arc::into_raw_with_allocator`], or [`Arc::as_ptr`]. + /// `T` must have the same alignment as that value. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method. + /// + /// Using this method correctly also requires extra care: another thread can change the + /// strong count at any time, including between calling this method and acting on the + /// result. + /// + /// # Examples + /// + /// ``` + /// #![feature(arc_raw_get_strong)] + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _also_five = Arc::clone(&five); + /// let ptr = Arc::into_raw(five); + /// + /// unsafe { + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// assert_eq!(2, Arc::strong_count_from_raw(ptr)); + /// + /// // Convert back to an `Arc` to avoid leaking memory. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[must_use] + #[unstable(feature = "arc_raw_get_strong", issue = "157021")] + pub unsafe fn strong_count_from_raw(ptr: *const T) -> usize { + // SAFETY: Upheld by caller. + let offset = unsafe { data_offset(ptr) }; + // Reverse the offset to find the original ArcInner. + // SAFETY: Caller ensures this pointer was to an `Arc` allocation, + // so offsetting must be inbounds. + let arc_ptr = unsafe { ptr.byte_sub(offset) as *mut ArcInner }; + // SAFETY: Per the above, an `ArcInner` is stored here. + unsafe { (*arc_ptr).strong.load(Relaxed) } + } +} + +impl Arc { + /// Returns a reference to the underlying allocator. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::allocator(&a)` instead of `a.allocator()`. This + /// is so that there is no conflict with a method on the inner type. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn allocator(this: &Self) -> &A { + &this.alloc + } + + /// Consumes the `Arc`, returning the wrapped pointer and allocator. + /// + /// To avoid a memory leak the pointer must be converted back to an `Arc` using + /// [`Arc::from_raw_in`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x = Arc::new_in("hello".to_owned(), System); + /// let (ptr, alloc) = Arc::into_raw_with_allocator(x); + /// assert_eq!(unsafe { &*ptr }, "hello"); + /// let x = unsafe { Arc::from_raw_in(ptr, alloc) }; + /// assert_eq!(&*x, "hello"); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn into_raw_with_allocator(this: Self) -> (*const T, A) { + let this = mem::ManuallyDrop::new(this); + let ptr = Self::as_ptr(&this); + // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped + let alloc = unsafe { ptr::read(&this.alloc) }; + (ptr, alloc) + } + + /// Provides a raw pointer to the data. + /// + /// The counts are not affected in any way and the `Arc` is not consumed. The pointer is valid for + /// as long as there are strong counts in the `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let y = Arc::clone(&x); + /// let x_ptr = Arc::as_ptr(&x); + /// assert_eq!(x_ptr, Arc::as_ptr(&y)); + /// assert_eq!(unsafe { &*x_ptr }, "hello"); + /// ``` + #[must_use] + #[stable(feature = "rc_as_ptr", since = "1.45.0")] + #[lint::never_returns_null_ptr] + pub fn as_ptr(this: &Self) -> *const T { + let ptr: *mut ArcInner = NonNull::as_ptr(this.ptr); + + // SAFETY: This cannot go through Deref::deref or ArcInnerPtr::inner because + // this is required to retain raw/mut provenance such that e.g. `get_mut` can + // write through the pointer after the Arc is recovered through `from_raw`. + unsafe { &raw mut (*ptr).data } + } + + /// Constructs an `Arc` from a raw pointer. + /// + /// The raw pointer must have been previously returned by a call to [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator]. + /// + /// # Safety + /// + /// * Creating a `Arc` from a pointer other than one returned from + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator] + /// is undefined behavior. + /// * If `U` is sized, it must have the same size and alignment as `T`. This + /// is trivially true if `U` is `T`. + /// * If `U` is unsized, its data pointer must have the same size and + /// alignment as `T`. This is trivially true if `Arc` was constructed + /// through `Arc` and then converted to `Arc` through an [unsized + /// coercion]. + /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size + /// and alignment, this is basically like transmuting references of + /// different types. See [`mem::transmute`][transmute] for more information + /// on what restrictions apply in this case. + /// * The raw pointer must point to a block of memory allocated by `alloc` + /// * The user of `from_raw` has to make sure a specific value of `T` is only + /// dropped once. + /// + /// This function is unsafe because improper use may lead to memory unsafety, + /// even if the returned `Arc` is never accessed. + /// + /// [into_raw]: Arc::into_raw + /// [into_raw_with_allocator]: Arc::into_raw_with_allocator + /// [transmute]: core::mem::transmute + /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x = Arc::new_in("hello".to_owned(), System); + /// let (x_ptr, alloc) = Arc::into_raw_with_allocator(x); + /// + /// unsafe { + /// // Convert back to an `Arc` to prevent leak. + /// let x = Arc::from_raw_in(x_ptr, System); + /// assert_eq!(&*x, "hello"); + /// + /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. + /// } + /// + /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! + /// ``` + /// + /// Convert a slice back into its original array: + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x: Arc<[u32], _> = Arc::new_in([1, 2, 3], System); + /// let x_ptr: *const [u32] = Arc::into_raw_with_allocator(x).0; + /// + /// unsafe { + /// let x: Arc<[u32; 3], _> = Arc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System); + /// assert_eq!(&*x, &[1, 2, 3]); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self { + // SAFETY: Upheld by caller. + unsafe { + let offset = data_offset(ptr); + + // Reverse the offset to find the original ArcInner. + let arc_ptr = ptr.byte_sub(offset) as *mut ArcInner; + + Self::from_ptr_in(arc_ptr, alloc) + } + } + + /// Creates a new [`Weak`] pointer to this allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let weak_five = Arc::downgrade(&five); + /// ``` + #[must_use = "this returns a new `Weak` pointer, \ + without modifying the original `Arc`"] + #[stable(feature = "arc_weak", since = "1.4.0")] + pub fn downgrade(this: &Self) -> Weak + where + A: AllocatorClone, + { + // This Relaxed is OK because we're checking the value in the CAS + // below. + let mut cur = this.inner().weak.load(Relaxed); + + loop { + // check if the weak counter is currently "locked"; if so, spin. + if cur == usize::MAX { + hint::spin_loop(); + cur = this.inner().weak.load(Relaxed); + continue; + } + + // We can't allow the refcount to increase much past `MAX_REFCOUNT`. + if cur > MAX_REFCOUNT { + panic_arc_overflow(); + } + // NOTE: this code currently ignores the possibility of overflow + // into usize::MAX; in general both Rc and Arc need to be adjusted + // to deal with overflow. + + // Unlike with Clone(), we need this to be an Acquire read to + // synchronize with the write coming from `is_unique`, so that the + // events prior to that write happen before this read. + match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) { + Ok(_) => { + // Make sure we do not create a dangling Weak + debug_assert!(!is_dangling(this.ptr.as_ptr())); + return Weak { ptr: this.ptr, alloc: this.alloc.clone() }; + } + Err(old) => cur = old, + } + } + } + + /// Gets the number of [`Weak`] pointers to this allocation. + /// + /// # Safety + /// + /// This method by itself is safe, but using it correctly requires extra care. + /// Another thread can change the weak count at any time, + /// including potentially between calling this method and acting on the result. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _weak_five = Arc::downgrade(&five); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` or `Weak` between threads. + /// assert_eq!(1, Arc::weak_count(&five)); + /// ``` + #[inline] + #[must_use] + #[stable(feature = "arc_counts", since = "1.15.0")] + pub fn weak_count(this: &Self) -> usize { + let cnt = this.inner().weak.load(Relaxed); + // If the weak count is currently locked, the value of the + // count was 0 just before taking the lock. + if cnt == usize::MAX { 0 } else { cnt - 1 } + } + + /// Gets the number of strong (`Arc`) pointers to this allocation. + /// + /// # Safety + /// + /// This method by itself is safe, but using it correctly requires extra care. + /// Another thread can change the strong count at any time, + /// including potentially between calling this method and acting on the result. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _also_five = Arc::clone(&five); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// assert_eq!(2, Arc::strong_count(&five)); + /// ``` + #[inline] + #[must_use] + #[stable(feature = "arc_counts", since = "1.15.0")] + pub fn strong_count(this: &Self) -> usize { + this.inner().strong.load(Relaxed) + } + + /// Increments the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory + /// allocated by `alloc`. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// + /// unsafe { + /// let (ptr, _alloc) = Arc::into_raw_with_allocator(five); + /// Arc::increment_strong_count_in(ptr, System); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw_in(ptr, System); + /// assert_eq!(2, Arc::strong_count(&five)); + /// # // Prevent leaks for Miri. + /// # Arc::decrement_strong_count_in(ptr, System); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A) + where + A: AllocatorClone, + { + // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop + // SAFETY: Upheld by caller. + let arc = unsafe { mem::ManuallyDrop::new(Arc::from_raw_in(ptr, alloc)) }; + // Now increase refcount, but don't drop new refcount either + let _arc_clone: mem::ManuallyDrop<_> = arc.clone(); + } + + /// Decrements the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) when invoking this method, and `ptr` must point to a block of memory + /// allocated by `alloc`. This method can be used to release the final + /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been + /// released. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// + /// unsafe { + /// let (ptr, _alloc) = Arc::into_raw_with_allocator(five); + /// Arc::increment_strong_count_in(ptr, System); + /// + /// // Those assertions are deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw_in(ptr, System); + /// assert_eq!(2, Arc::strong_count(&five)); + /// Arc::decrement_strong_count_in(ptr, System); + /// assert_eq!(1, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A) { + // SAFETY: Upheld by caller. + unsafe { drop(Arc::from_raw_in(ptr, alloc)) }; + } + + #[inline] + fn inner(&self) -> &ArcInner { + // SAFETY: While this arc is alive we're guaranteed + // that the inner pointer is valid. Furthermore, we know that the + // `ArcInner` structure itself is `Sync` if the inner data is + // `Sync` as well, so we're ok loaning out an immutable pointer to these + // contents. + unsafe { self.ptr.as_ref() } + } + + // Non-inlined part of `drop`. + #[inline(never)] + unsafe fn drop_slow(&mut self) { + // Drop the weak ref collectively held by all strong references when this + // variable goes out of scope. This ensures that the memory is deallocated + // even if the destructor of `T` panics. + // Take a reference to `self.alloc` instead of cloning because 1. it'll last long + // enough, and 2. you should be able to drop `Arc`s with unclonable allocators + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + + // Destroy the data at this time, even though we must not free the box + // allocation itself (there might still be weak pointers lying around). + // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed. + // ignore-tidy-undocumented-unsafe + unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) }; + } + + /// Returns `true` if the two `Arc`s point to the same allocation in a vein similar to + /// [`ptr::eq`]. This function ignores the metadata of `dyn Trait` pointers. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let same_five = Arc::clone(&five); + /// let other_five = Arc::new(5); + /// + /// assert!(Arc::ptr_eq(&five, &same_five)); + /// assert!(!Arc::ptr_eq(&five, &other_five)); + /// ``` + /// + /// [`ptr::eq`]: core::ptr::eq "ptr::eq" + #[inline] + #[must_use] + #[stable(feature = "ptr_eq", since = "1.17.0")] + pub fn ptr_eq(this: &Self, other: &Self) -> bool { + ptr::addr_eq(this.ptr.as_ptr(), other.ptr.as_ptr()) + } +} + +impl Arc { + /// Allocates an `ArcInner` with sufficient space for + /// a possibly-unsized inner value where the value has the layout provided. + /// + /// The function `mem_to_arcinner` is called with the data pointer + /// and must return back a (potentially fat)-pointer for the `ArcInner`. + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_layout( + value_layout: Layout, + allocate: impl FnOnce(Layout) -> Result, AllocError>, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> *mut ArcInner { + let layout = arcinner_layout_for_value_layout(value_layout); + + let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)); + + // ignore-tidy-undocumented-unsafe + unsafe { Self::initialize_arcinner(ptr, layout, mem_to_arcinner) } + } + + /// Allocates an `ArcInner` with sufficient space for + /// a possibly-unsized inner value where the value has the layout provided, + /// returning an error if allocation fails. + /// + /// The function `mem_to_arcinner` is called with the data pointer + /// and must return back a (potentially fat)-pointer for the `ArcInner`. + unsafe fn try_allocate_for_layout( + value_layout: Layout, + allocate: impl FnOnce(Layout) -> Result, AllocError>, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> Result<*mut ArcInner, AllocError> { + let layout = arcinner_layout_for_value_layout(value_layout); + + let ptr = allocate(layout)?; + + // ignore-tidy-undocumented-unsafe + let inner = unsafe { Self::initialize_arcinner(ptr, layout, mem_to_arcinner) }; + + Ok(inner) + } + + unsafe fn initialize_arcinner( + ptr: NonNull<[u8]>, + layout: Layout, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> *mut ArcInner { + let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr()); + // SAFETY: Upheld by caller. + debug_assert_eq!(unsafe { Layout::for_value_raw(inner) }, layout); + + // ignore-tidy-undocumented-unsafe + unsafe { + (&raw mut (*inner).strong).write(atomic::AtomicUsize::new(1)); + (&raw mut (*inner).weak).write(atomic::AtomicUsize::new(1)); + } + + inner + } +} + +impl Arc { + /// Allocates an `ArcInner` with sufficient space for an unsized inner value. + #[inline] + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_ptr_in(ptr: *const T, alloc: &A) -> *mut ArcInner { + // Allocate for the `ArcInner` using the given value. + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::allocate_for_layout( + Layout::for_value_raw(ptr), + |layout| alloc.allocate(layout), + |mem| mem.with_metadata_of(ptr as *const ArcInner), + ) + } + } + + #[cfg(not(no_global_oom_handling))] + fn from_box_in(src: Box) -> Arc { + // ignore-tidy-undocumented-unsafe + unsafe { + let value_size = size_of_val(&*src); + let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src)); + + // Copy value as bytes + ptr::copy_nonoverlapping( + (&raw const *src) as *const u8, + (&raw mut (*ptr).data) as *mut u8, + value_size, + ); + + // Free the allocation without dropping its contents + let (bptr, alloc) = Box::into_raw_with_allocator(src); + let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop, &alloc); + drop(src); + + Self::from_ptr_in(ptr, alloc) + } + } +} + +impl Arc<[T]> { + /// Allocates an `ArcInner<[T]>` with the given length. + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> { + // ignore-tidy-undocumented-unsafe + unsafe { + Self::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| Global.allocate(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[T]>, + ) + } + } + + /// Copy elements from slice into newly allocated `Arc<[T]>` + /// + /// Unsafe because the caller must either take ownership, bind `T: Copy` or + /// bind `T: TrivialClone`. + #[cfg(not(no_global_oom_handling))] + unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> { + // ignore-tidy-undocumented-unsafe + unsafe { + let ptr = Self::allocate_for_slice(v.len()); + + ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).data) as *mut T, v.len()); + + Self::from_ptr(ptr) + } + } + + /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size. + /// + /// Behavior is undefined should the size be wrong. + #[cfg(not(no_global_oom_handling))] + unsafe fn from_iter_exact(iter: impl Iterator, len: usize) -> Arc<[T]> { + // Panic guard while cloning T elements. + // In the event of a panic, elements that have been written + // into the new ArcInner will be dropped, then the memory freed. + struct Guard { + mem: NonNull, + elems: *mut T, + layout: Layout, + n_elems: usize, + } + + impl Drop for Guard { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + let slice = from_raw_parts_mut(self.elems, self.n_elems); + ptr::drop_in_place(slice); + + Global.deallocate(self.mem, self.layout); + } + } + } + + // ignore-tidy-undocumented-unsafe + unsafe { + let ptr = Self::allocate_for_slice(len); + + let mem = ptr as *mut _ as *mut u8; + let layout = Layout::for_value_raw(ptr); + + // Pointer to first element + let elems = (&raw mut (*ptr).data) as *mut T; + + let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 }; + + for (i, item) in iter.enumerate() { + ptr::write(elems.add(i), item); + guard.n_elems += 1; + } + + // All clear. Forget the guard so it doesn't free the new ArcInner. + mem::forget(guard); + + Self::from_ptr(ptr) + } + } +} + +impl Arc<[T], A> { + /// Allocates an `ArcInner<[T]>` with the given length. + #[inline] + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_slice_in(len: usize, alloc: &A) -> *mut ArcInner<[T]> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| alloc.allocate(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[T]>, + ) + } + } +} + +/// Specialization trait used for `From<&[T]>`. +#[cfg(not(no_global_oom_handling))] +trait ArcFromSlice { + fn from_slice(slice: &[T]) -> Self; +} + +#[cfg(not(no_global_oom_handling))] +impl ArcFromSlice for Arc<[T]> { + #[inline] + default fn from_slice(v: &[T]) -> Self { + // ignore-tidy-undocumented-unsafe + unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } + } +} + +#[cfg(not(no_global_oom_handling))] +impl ArcFromSlice for Arc<[T]> { + #[inline] + fn from_slice(v: &[T]) -> Self { + // SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent + // to the above. + unsafe { Arc::copy_from_slice(v) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Clone for Arc { + /// Makes a clone of the `Arc` pointer. + /// + /// This creates another pointer to the same allocation, increasing the + /// strong reference count. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let _ = Arc::clone(&five); + /// ``` + #[inline] + fn clone(&self) -> Arc { + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object. + // + // As explained in the [Boost documentation][1], Increasing the + // reference counter can always be done with memory_order_relaxed: New + // references to an object can only be formed from an existing + // reference, and passing an existing reference from one thread to + // another must already provide any required synchronization. + // + // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) + let old_size = self.inner().strong.fetch_add(1, Relaxed); + + // However we need to guard against massive refcounts in case someone is `mem::forget`ing + // Arcs. If we don't do this the count can overflow and users will use-after free. This + // branch will never be taken in any realistic program. We abort because such a program is + // incredibly degenerate, and we don't care to support it. + // + // This check is not 100% water-proof: we error when the refcount grows beyond `isize::MAX`. + // But we do that check *after* having done the increment, so there is a chance here that + // the worst already happened and we actually do overflow the `usize` counter. However, that + // requires the counter to grow from `isize::MAX` to `usize::MAX` between the increment + // above and the `abort` below, which seems exceedingly unlikely. + // + // This is a global invariant, and also applies when using a compare-exchange loop to increment + // counters in other methods. + // Otherwise, the counter could be brought to an almost-overflow using a compare-exchange loop, + // and then overflow using a few `fetch_add`s. + if old_size > MAX_REFCOUNT { + intrinsics::abort_immediate(); + } + + // SAFETY: Pointer is valid & allocator corresponds to the one used to allocate it. + unsafe { Self::from_inner_in(self.ptr, self.alloc.clone()) } + } +} + +#[unstable(feature = "ergonomic_clones", issue = "132290")] +impl UseCloned for Arc {} + +#[unstable(feature = "share_trait", issue = "156756")] +impl Share for Arc {} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Deref for Arc { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + &self.inner().data + } +} + +// The API of this pointer type enforces that if the `T` is pinned, then *all* +// clones of this `Arc` are wrapped as `Pin>`. Since an `&Arc` +// could be used to obtain an `Arc` that is not wrapped in `Pin` (and later +// used with `Arc::get_mut`), this means that this type treats `&Arc` as +// evidence that the `T` is not pinned. The implementations of various traits +// are written accordingly. Since this type is not fundamental, downstream +// crates cannot provide malicious implementations of any of the traits relevant +// for `Pin`. +#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")] +unsafe impl PinSafePointer for Arc {} + +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for Arc {} + +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Arc {} + +#[cfg(not(no_global_oom_handling))] +impl Arc { + /// Makes a mutable reference into the given `Arc`. + /// + /// If there are other `Arc` pointers to the same allocation, then `make_mut` will + /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also + /// referred to as clone-on-write. + /// + /// However, if there are no other `Arc` pointers to this allocation, but some [`Weak`] + /// pointers, then the [`Weak`] pointers will be dissociated and the inner value will not + /// be cloned. + /// + /// See also [`get_mut`], which will fail rather than cloning the inner value + /// or dissociating [`Weak`] pointers. + /// + /// [`clone`]: Clone::clone + /// [`get_mut`]: Arc::get_mut + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut data = Arc::new(5); + /// + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// let mut other_data = Arc::clone(&data); // Won't clone inner data + /// *Arc::make_mut(&mut data) += 1; // Clones inner data + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything + /// + /// // Now `data` and `other_data` point to different allocations. + /// assert_eq!(*data, 8); + /// assert_eq!(*other_data, 12); + /// ``` + /// + /// [`Weak`] pointers will be dissociated: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut data = Arc::new(75); + /// let weak = Arc::downgrade(&data); + /// + /// assert!(75 == *data); + /// assert!(75 == *weak.upgrade().unwrap()); + /// + /// *Arc::make_mut(&mut data) += 1; + /// + /// assert!(76 == *data); + /// assert!(weak.upgrade().is_none()); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn make_mut(this: &mut Self) -> &mut T { + let size_of_val = size_of_val::(&**this); + + // Note that we hold both a strong reference and a weak reference. + // Thus, releasing our strong reference only will not, by itself, cause + // the memory to be deallocated. + // + // Use Acquire to ensure that we see any writes to `weak` that happen + // before release writes (i.e., decrements) to `strong`. Since we hold a + // weak count, there's no chance the ArcInner itself could be + // deallocated. + if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() { + // Another strong pointer exists, so we must clone. + *this = Arc::clone_from_ref_in(&**this, this.alloc.clone()); + } else if this.inner().weak.load(Relaxed) != 1 { + // Relaxed suffices in the above because this is fundamentally an + // optimization: we are always racing with weak pointers being + // dropped. Worst case, we end up allocated a new Arc unnecessarily. + + // We removed the last strong ref, but there are additional weak + // refs remaining. We'll move the contents to a new Arc, and + // invalidate the other weak refs. + + // Note that it is not possible for the read of `weak` to yield + // usize::MAX (i.e., locked), since the weak count can only be + // locked by a thread with a strong reference. + + // Guard against panics while using the allocator. + // If we unwind before the Arc is overwritten, we expose a strong + // count of 0, resulting in a UAF (#155746, #157203). + // Until the new Arc is written, the old Arc must remain valid + struct Guard<'a, T: ?Sized> { + inner: &'a ArcInner, + } + impl<'a, T: ?Sized> Drop for Guard<'a, T> { + fn drop(&mut self) { + self.inner.strong.store(1, Release); + } + } + let guard = Guard { inner: this.inner() }; + + // Can just steal the data, all that's left is Weaks + // Note that this can panic in two ways: + // - The allocation can fail + // - The allocator clone can fail + let mut in_progress: UniqueArcUninit = + UniqueArcUninit::new(&**this, this.alloc.clone()); + + // ignore-tidy-undocumented-unsafe + unsafe { + // Initialize `in_progress` with move of **this. + // We have to express this in terms of bytes because `T: ?Sized`; there is no + // operation that just copies a value based on its `size_of_val()`. + ptr::copy_nonoverlapping( + ptr::from_ref(&**this).cast::(), + in_progress.data_ptr().cast::(), + size_of_val, + ); + + // We are now safe from panics. + mem::forget(guard); + + // Materialize our own implicit weak pointer, so that it can clean + // up the ArcInner as needed. + // Make sure the allocator is not leaked when the Arc is overwritten. + // Only drop at the end of the scope to avoid panics. + let _weak = Weak { ptr: this.ptr, alloc: ptr::read(&this.alloc) }; + + ptr::write(this, in_progress.into_arc()); + } + } else { + // We were the sole reference of either kind; bump back up the + // strong ref count. + this.inner().strong.store(1, Release); + } + + // SAFETY: As with `get_mut()`, our reference was + // either unique to begin with, or became one upon cloning the contents. + unsafe { Self::get_mut_unchecked(this) } + } +} + +impl Arc { + /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the + /// clone. + /// + /// Assuming `arc_t` is of type `Arc`, this function is functionally equivalent to + /// `(*arc_t).clone()`, but will avoid cloning the inner value where possible. + /// + /// # Examples + /// + /// ``` + /// # use std::{ptr, sync::Arc}; + /// let inner = String::from("test"); + /// let ptr = inner.as_ptr(); + /// + /// let arc = Arc::new(inner); + /// let inner = Arc::unwrap_or_clone(arc); + /// // The inner value was not cloned + /// assert!(ptr::eq(ptr, inner.as_ptr())); + /// + /// let arc = Arc::new(inner); + /// let arc2 = arc.clone(); + /// let inner = Arc::unwrap_or_clone(arc); + /// // Because there were 2 references, we had to clone the inner value. + /// assert!(!ptr::eq(ptr, inner.as_ptr())); + /// // `arc2` is the last reference, so when we unwrap it we get back + /// // the original `String`. + /// let inner = Arc::unwrap_or_clone(arc2); + /// assert!(ptr::eq(ptr, inner.as_ptr())); + /// ``` + #[inline] + #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")] + pub fn unwrap_or_clone(this: Self) -> T { + Arc::try_unwrap(this).unwrap_or_else(|arc| (*arc).clone()) + } +} + +impl Arc { + /// Returns a mutable reference into the given `Arc`, if there are + /// no other `Arc` or [`Weak`] pointers to the same allocation. + /// + /// Returns [`None`] otherwise, because it is not safe to + /// mutate a shared value. + /// + /// See also [`make_mut`][make_mut], which will [`clone`][clone] + /// the inner value when there are other `Arc` pointers. + /// + /// [make_mut]: Arc::make_mut + /// [clone]: Clone::clone + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut x = Arc::new(3); + /// *Arc::get_mut(&mut x).unwrap() = 4; + /// assert_eq!(*x, 4); + /// + /// let _y = Arc::clone(&x); + /// assert!(Arc::get_mut(&mut x).is_none()); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn get_mut(this: &mut Self) -> Option<&mut T> { + if Self::is_unique(this) { + // SAFETY: We're guaranteed that the pointer + // returned is the *only* pointer that will ever be returned to T. Our + // reference count is guaranteed to be 1 at this point, and we required + // the Arc itself to be `mut`, so we're returning the only possible + // reference to the inner data. + unsafe { Some(Arc::get_mut_unchecked(this)) } + } else { + None + } + } + + /// Returns a mutable reference into the given `Arc`, + /// without any check. + /// + /// See also [`get_mut`], which is safe and does appropriate checks. + /// + /// [`get_mut`]: Arc::get_mut + /// + /// # Safety + /// + /// If any other `Arc` or [`Weak`] pointers to the same allocation exist, then + /// they must not be dereferenced or have active borrows for the duration + /// of the returned borrow, and their inner type must be exactly the same as the + /// inner type of this Arc (including lifetimes). This is trivially the case if no + /// such pointers exist, for example immediately after `Arc::new`. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let mut x = Arc::new(String::new()); + /// unsafe { + /// Arc::get_mut_unchecked(&mut x).push_str("foo") + /// } + /// assert_eq!(*x, "foo"); + /// ``` + /// Other `Arc` pointers to the same allocation must be to the same type. + /// ```no_run + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let x: Arc = Arc::from("Hello, world!"); + /// let mut y: Arc<[u8]> = x.clone().into(); + /// unsafe { + /// // this is Undefined Behavior, because x's inner type is str, not [u8] + /// Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8 + /// } + /// println!("{}", &*x); // Invalid UTF-8 in a str + /// ``` + /// Other `Arc` pointers to the same allocation must be to the exact same type, including lifetimes. + /// ```no_run + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let x: Arc<&str> = Arc::new("Hello, world!"); + /// { + /// let s = String::from("Oh, no!"); + /// let mut y: Arc<&str> = x.clone(); + /// unsafe { + /// // this is Undefined Behavior, because x's inner type + /// // is &'long str, not &'short str + /// *Arc::get_mut_unchecked(&mut y) = &s; + /// } + /// } + /// println!("{}", &*x); // Use-after-free + /// ``` + #[inline] + #[unstable(feature = "get_mut_unchecked", issue = "63292")] + pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { + // We are careful to *not* create a reference covering the "count" fields, as + // this would alias with concurrent access to the reference counts (e.g. by `Weak`). + // ignore-tidy-undocumented-unsafe + unsafe { &mut (*this.ptr.as_ptr()).data } + } + + /// Determine whether this is the unique reference to the underlying data. + /// + /// Returns `true` if there are no other `Arc` or [`Weak`] pointers to the same allocation; + /// returns `false` otherwise. + /// + /// If this function returns `true`, then it is guaranteed to be safe to call [`get_mut_unchecked`] + /// on this `Arc`, as long as no clones occur in between. + /// + /// The result can become stale if another thread can call `clone` or + /// `downgrade` through a shared reference. Make sure you have exclusive + /// access to the `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// assert!(Arc::is_unique(&x)); + /// + /// let y = Arc::clone(&x); + /// assert!(!Arc::is_unique(&x)); + /// drop(y); + /// + /// // Weak references also count, because they could be upgraded at any time. + /// let z = Arc::downgrade(&x); + /// assert!(!Arc::is_unique(&x)); + /// ``` + /// + /// # Pointer invalidation + /// + /// This function will always return the same value as `Arc::get_mut(arc).is_some()`. However, + /// unlike that operation it does not produce any mutable references to the underlying data, + /// meaning no pointers to the data inside the `Arc` are invalidated by the call. Thus, the + /// following code is valid: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let arc = Arc::new(5); + /// let pointer: *const i32 = &*arc; + /// assert!(Arc::is_unique(&arc)); + /// assert_eq!(unsafe { *pointer }, 5); + /// ``` + /// + /// The following changes would make the example unsound: + /// + /// - Using `Arc::get_mut` to create a mutable reference while also accessing the value + /// through `pointer`. + /// - Dropping `arc` before dereferencing `pointer`, leaving it dangling. + /// + /// # Atomic orderings + /// + /// Concurrent drops to other `Arc` pointers to the same allocation will synchronize with this + /// call - that is, this call performs an `Acquire` operation on the underlying strong and weak + /// ref counts. This ensures that calling `get_mut_unchecked` is safe. + /// + /// Note that this operation requires locking the weak ref count, so concurrent calls to + /// `downgrade` may spin-loop for a short period of time. + /// + /// [`get_mut_unchecked`]: Self::get_mut_unchecked + #[inline] + #[stable(feature = "arc_is_unique", since = "1.101.0")] + pub fn is_unique(this: &Self) -> bool { + // lock the weak pointer count if we appear to be the sole weak pointer + // holder. + // + // The acquire label here ensures a happens-before relationship with any + // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements + // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded + // weak ref was never dropped, the CAS here will fail so we do not care to synchronize. + if this.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() { + // This needs to be an `Acquire` to synchronize with the decrement of the `strong` + // counter in `drop` -- the only access that happens when any but the last reference + // is being dropped. + let unique = this.inner().strong.load(Acquire) == 1; + + // The release write here synchronizes with a read in `downgrade`, + // effectively preventing the above read of `strong` from happening + // after the write. + this.inner().weak.store(1, Release); // release the lock + unique + } else { + false + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Arc { + /// Drops the `Arc`. + /// + /// This will decrement the strong reference count. If the strong reference + /// count reaches zero then the only other references (if any) are + /// [`Weak`], so we `drop` the inner value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// struct Foo; + /// + /// impl Drop for Foo { + /// fn drop(&mut self) { + /// println!("dropped!"); + /// } + /// } + /// + /// let foo = Arc::new(Foo); + /// let foo2 = Arc::clone(&foo); + /// + /// drop(foo); // Doesn't print anything + /// drop(foo2); // Prints "dropped!" + /// ``` + #[inline] + fn drop(&mut self) { + // Because `fetch_sub` is already atomic, we do not need to synchronize + // with other threads unless we are going to delete the object. This + // same logic applies to the below `fetch_sub` to the `weak` count. + if self.inner().strong.fetch_sub(1, Release) != 1 { + return; + } + + // This fence is needed to prevent reordering of use of the data and + // deletion of the data. Because it is marked `Release`, the decreasing + // of the reference count synchronizes with this `Acquire` fence. This + // means that use of the data happens before decreasing the reference + // count, which happens before this fence, which happens before the + // deletion of the data. + // + // As explained in the [Boost documentation][1], + // + // > It is important to enforce any possible access to the object in one + // > thread (through an existing reference) to *happen before* deleting + // > the object in a different thread. This is achieved by a "release" + // > operation after dropping a reference (any access to the object + // > through this reference must obviously happened before), and an + // > "acquire" operation before deleting the object. + // + // In particular, while the contents of an Arc are usually immutable, it's + // possible to have interior writes to something like a Mutex. Since a + // Mutex is not acquired when it is deleted, we can't rely on its + // synchronization logic to make writes in thread A visible to a destructor + // running in thread B. + // + // Also note that the Acquire fence here could probably be replaced with an + // Acquire load, which could improve performance in highly-contended + // situations. See [2]. + // + // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) + // [2]: (https://github.com/rust-lang/rust/pull/41714) + acquire!(self.inner().strong); + + // Make sure we aren't trying to "drop" the shared static for empty slices + // used by Default::default. + debug_assert!( + !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner), + "Arcs backed by a static should never reach a strong count of 0. \ + Likely decrement_strong_count or from_raw were called too many times.", + ); + + // ignore-tidy-undocumented-unsafe + unsafe { + self.drop_slow(); + } + } +} + +impl Arc { + /// Attempts to downcast the `Arc` to a concrete type. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// fn print_if_string(value: Arc) { + /// if let Ok(string) = value.downcast::() { + /// println!("String ({}): {}", string.len(), string); + /// } + /// } + /// + /// let my_string = "Hello World".to_string(); + /// print_if_string(Arc::new(my_string)); + /// print_if_string(Arc::new(0i8)); + /// ``` + #[inline] + #[stable(feature = "rc_downcast", since = "1.29.0")] + pub fn downcast(self) -> Result, Self> + where + T: Any + Send + Sync, + { + if (*self).is::() { + // SAFETY: Check ensures the typecast is okay. + unsafe { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + Ok(Arc::from_inner_in(ptr.cast(), alloc)) + } + } else { + Err(self) + } + } + + /// Downcasts the `Arc` to a concrete type. + /// + /// For a safe alternative see [`downcast`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(downcast_unchecked)] + /// + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// let x: Arc = Arc::new(1_usize); + /// + /// unsafe { + /// assert_eq!(*x.downcast_unchecked::(), 1); + /// } + /// ``` + /// + /// # Safety + /// + /// The contained value must be of type `T`. Calling this method + /// with the incorrect type is *undefined behavior*. + /// + /// + /// [`downcast`]: Self::downcast + #[inline] + #[unstable(feature = "downcast_unchecked", issue = "90850")] + #[cfg_attr(kani, requires((*self).is::()))] + #[cfg_attr(kani, ensures(|result| ub_checks::can_dereference(&**result as *const T)))] + pub unsafe fn downcast_unchecked(self) -> Arc + where + T: Any + Send + Sync, + { + // SAFETY: Upheld by caller. + unsafe { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + Arc::from_inner_in(ptr.cast(), alloc) + } + } +} + +impl Weak { + /// Constructs a new `Weak`, without allocating any memory. + /// Calling [`upgrade`] on the return value always gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// use std::sync::Weak; + /// + /// let empty: Weak = Weak::new(); + /// assert!(empty.upgrade().is_none()); + /// ``` + #[inline] + #[stable(feature = "downgraded_weak", since = "1.10.0")] + #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")] + #[must_use] + pub const fn new() -> Weak { + Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global } + } +} + +impl Weak { + /// Constructs a new `Weak`, without allocating any memory, technically in the provided + /// allocator. + /// Calling [`upgrade`] on the return value always gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Weak; + /// use std::alloc::System; + /// + /// let empty: Weak = Weak::new_in(System); + /// assert!(empty.upgrade().is_none()); + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_in(alloc: A) -> Weak { + Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc } + } +} + +/// Helper type to allow accessing the reference counts without +/// making any assertions about the data field. +struct WeakInner<'a> { + weak: &'a Atomic, + strong: &'a Atomic, +} + +impl Weak { + /// Converts a raw pointer previously created by [`into_raw`] back into `Weak`. + /// + /// This can be used to safely get a strong reference (by calling [`upgrade`] + /// later) or to deallocate the weak count by dropping the `Weak`. + /// + /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], + /// as these don't own anything; the method still works on them). + /// + /// # Safety + /// + /// The pointer must have originated from the [`into_raw`] and must still own its potential + /// weak reference, and must point to a block of memory allocated by global allocator. + /// + /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this + /// takes ownership of one weak reference currently represented as a raw pointer (the weak + /// count is not modified by this operation) and therefore it must be paired with a previous + /// call to [`into_raw`]. + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// + /// let raw_1 = Arc::downgrade(&strong).into_raw(); + /// let raw_2 = Arc::downgrade(&strong).into_raw(); + /// + /// assert_eq!(2, Arc::weak_count(&strong)); + /// + /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); + /// assert_eq!(1, Arc::weak_count(&strong)); + /// + /// drop(strong); + /// + /// // Decrement the last weak count. + /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); + /// ``` + /// + /// [`new`]: Weak::new + /// [`into_raw`]: Weak::into_raw + /// [`upgrade`]: Weak::upgrade + #[inline] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: Upheld by caller. + unsafe { Weak::from_raw_in(ptr, Global) } + } + + /// Consumes the `Weak` and turns it into a raw pointer. + /// + /// This converts the weak pointer into a raw pointer, while still preserving the ownership of + /// one weak reference (the weak count is not modified by this operation). It can be turned + /// back into the `Weak` with [`from_raw`]. + /// + /// The same restrictions of accessing the target of the pointer as with + /// [`as_ptr`] apply. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// let weak = Arc::downgrade(&strong); + /// let raw = weak.into_raw(); + /// + /// assert_eq!(1, Arc::weak_count(&strong)); + /// assert_eq!("hello", unsafe { &*raw }); + /// + /// drop(unsafe { Weak::from_raw(raw) }); + /// assert_eq!(0, Arc::weak_count(&strong)); + /// ``` + /// + /// [`from_raw`]: Weak::from_raw + /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub fn into_raw(self) -> *const T { + ManuallyDrop::new(self).as_ptr() + } +} + +impl Weak { + /// Returns a reference to the underlying allocator. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn allocator(&self) -> &A { + &self.alloc + } + + /// Returns a raw pointer to the object `T` pointed to by this `Weak`. + /// + /// The pointer is valid only if there are some strong references. The pointer may be dangling, + /// unaligned or even [`null`] otherwise. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::ptr; + /// + /// let strong = Arc::new("hello".to_owned()); + /// let weak = Arc::downgrade(&strong); + /// // Both point to the same object + /// assert!(ptr::eq(&*strong, weak.as_ptr())); + /// // The strong here keeps it alive, so we can still access the object. + /// assert_eq!("hello", unsafe { &*weak.as_ptr() }); + /// + /// drop(strong); + /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to + /// // undefined behavior. + /// // assert_eq!("hello", unsafe { &*weak.as_ptr() }); + /// ``` + /// + /// [`null`]: core::ptr::null "ptr::null" + #[must_use] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub fn as_ptr(&self) -> *const T { + let ptr: *mut ArcInner = NonNull::as_ptr(self.ptr); + + if is_dangling(ptr) { + // If the pointer is dangling, we return the sentinel directly. This cannot be + // a valid payload address, as the payload is at least as aligned as ArcInner (usize). + ptr as *const T + } else { + // SAFETY: if is_dangling returns false, then the pointer is dereferenceable. + // The payload may be dropped at this point, and we have to maintain provenance, + // so use raw pointer manipulation. + unsafe { &raw mut (*ptr).data } + } + } + + /// Consumes the `Weak`, returning the wrapped pointer and allocator. + /// + /// This converts the weak pointer into a raw pointer, while still preserving the ownership of + /// one weak reference (the weak count is not modified by this operation). It can be turned + /// back into the `Weak` with [`from_raw_in`]. + /// + /// The same restrictions of accessing the target of the pointer as with + /// [`as_ptr`] apply. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::{Arc, Weak}; + /// use std::alloc::System; + /// + /// let strong = Arc::new_in("hello".to_owned(), System); + /// let weak = Arc::downgrade(&strong); + /// let (raw, alloc) = weak.into_raw_with_allocator(); + /// + /// assert_eq!(1, Arc::weak_count(&strong)); + /// assert_eq!("hello", unsafe { &*raw }); + /// + /// drop(unsafe { Weak::from_raw_in(raw, alloc) }); + /// assert_eq!(0, Arc::weak_count(&strong)); + /// ``` + /// + /// [`from_raw_in`]: Weak::from_raw_in + /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn into_raw_with_allocator(self) -> (*const T, A) { + let this = mem::ManuallyDrop::new(self); + let result = this.as_ptr(); + // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped + let alloc = unsafe { ptr::read(&this.alloc) }; + (result, alloc) + } + + /// Converts a raw pointer previously created by [`into_raw`] back into `Weak` in the provided + /// allocator. + /// + /// This can be used to safely get a strong reference (by calling [`upgrade`] + /// later) or to deallocate the weak count by dropping the `Weak`. + /// + /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], + /// as these don't own anything; the method still works on them). + /// + /// # Safety + /// + /// The pointer must have originated from the [`into_raw`] and must still own its potential + /// weak reference, and must point to a block of memory allocated by `alloc`. + /// + /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this + /// takes ownership of one weak reference currently represented as a raw pointer (the weak + /// count is not modified by this operation) and therefore it must be paired with a previous + /// call to [`into_raw`]. + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// + /// let raw_1 = Arc::downgrade(&strong).into_raw(); + /// let raw_2 = Arc::downgrade(&strong).into_raw(); + /// + /// assert_eq!(2, Arc::weak_count(&strong)); + /// + /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); + /// assert_eq!(1, Arc::weak_count(&strong)); + /// + /// drop(strong); + /// + /// // Decrement the last weak count. + /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); + /// ``` + /// + /// [`new`]: Weak::new + /// [`into_raw`]: Weak::into_raw + /// [`upgrade`]: Weak::upgrade + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self { + // See Weak::as_ptr for context on how the input pointer is derived. + + let ptr = if is_dangling(ptr) { + // This is a dangling Weak. + ptr as *mut ArcInner + } else { + // Otherwise, we're guaranteed the pointer came from a nondangling Weak. + // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T. + let offset = unsafe { data_offset(ptr) }; + // Thus, we reverse the offset to get the whole ArcInner. + // SAFETY: the pointer originated from a Weak, so this offset is safe. + unsafe { ptr.byte_sub(offset) as *mut ArcInner } + }; + + // SAFETY: we now have recovered the original Weak pointer, so can create the Weak. + Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc } + } +} + +impl Weak { + /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying + /// dropping of the inner value if successful. + /// + /// Returns [`None`] in the following cases: + /// + /// 1. The inner value has since been dropped or moved out. + /// + /// 2. This `Weak` does not point to an allocation. + /// + /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let weak_five = Arc::downgrade(&five); + /// + /// let strong_five: Option> = weak_five.upgrade(); + /// assert!(strong_five.is_some()); + /// + /// // Destroy all strong pointers. + /// drop(strong_five); + /// drop(five); + /// + /// assert!(weak_five.upgrade().is_none()); + /// ``` + #[must_use = "this returns a new `Arc`, \ + without modifying the original weak pointer"] + #[stable(feature = "arc_weak", since = "1.4.0")] + pub fn upgrade(&self) -> Option> + where + A: AllocatorClone, + { + #[inline] + fn checked_increment(n: usize) -> Option { + // Any write of 0 we can observe leaves the field in permanently zero state. + if n == 0 { + return None; + } + // See comments in `Arc::clone` for why we do this (for `mem::forget`). + if n > MAX_REFCOUNT { + panic_arc_overflow(); + } + Some(n + 1) + } + + // We use a CAS loop to increment the strong count instead of a + // fetch_add as this function should never take the reference count + // from zero to one. + // + // Relaxed is fine for the failure case because we don't have any expectations about the new state. + // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner + // value can be initialized after `Weak` references have already been created. In that case, we + // expect to observe the fully initialized value. + if self.inner()?.strong.try_update(Acquire, Relaxed, checked_increment).is_ok() { + // SAFETY: pointer is not null, verified in checked_increment + unsafe { Some(Arc::from_inner_in(self.ptr, self.alloc.clone())) } + } else { + None + } + } + + /// Gets the number of strong (`Arc`) pointers pointing to this allocation. + /// + /// If `self` was created using [`Weak::new`], this will return 0. + #[must_use] + #[stable(feature = "weak_counts", since = "1.41.0")] + pub fn strong_count(&self) -> usize { + if let Some(inner) = self.inner() { inner.strong.load(Relaxed) } else { 0 } + } + + /// Gets an approximation of the number of `Weak` pointers pointing to this + /// allocation. + /// + /// If `self` was created using [`Weak::new`], or if there are no remaining + /// strong pointers, this will return 0. + /// + /// # Accuracy + /// + /// Due to implementation details, the returned value can be off by 1 in + /// either direction when other threads are manipulating any `Arc`s or + /// `Weak`s pointing to the same allocation. + #[must_use] + #[stable(feature = "weak_counts", since = "1.41.0")] + pub fn weak_count(&self) -> usize { + if let Some(inner) = self.inner() { + let weak = inner.weak.load(Acquire); + let strong = inner.strong.load(Relaxed); + if strong == 0 { + 0 + } else { + // Since we observed that there was at least one strong pointer + // after reading the weak count, we know that the implicit weak + // reference (present whenever any strong references are alive) + // was still around when we observed the weak count, and can + // therefore safely subtract it. + weak - 1 + } + } else { + 0 + } + } + + /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`, + /// (i.e., when this `Weak` was created by `Weak::new`). + #[inline] + fn inner(&self) -> Option> { + let ptr = self.ptr.as_ptr(); + if is_dangling(ptr) { + None + } else { + // We are careful to *not* create a reference covering the "data" field, as + // the field may be mutated concurrently (for example, if the last `Arc` + // is dropped, the data field will be dropped in-place). + // ignore-tidy-undocumented-unsafe + Some(unsafe { WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } }) + } + } + + /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if + /// both don't point to any allocation (because they were created with `Weak::new()`). However, + /// this function ignores the metadata of `dyn Trait` pointers. + /// + /// # Notes + /// + /// Since this compares pointers it means that `Weak::new()` will equal each + /// other, even though they don't point to any allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let first_rc = Arc::new(5); + /// let first = Arc::downgrade(&first_rc); + /// let second = Arc::downgrade(&first_rc); + /// + /// assert!(first.ptr_eq(&second)); + /// + /// let third_rc = Arc::new(5); + /// let third = Arc::downgrade(&third_rc); + /// + /// assert!(!first.ptr_eq(&third)); + /// ``` + /// + /// Comparing `Weak::new`. + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let first = Weak::new(); + /// let second = Weak::new(); + /// assert!(first.ptr_eq(&second)); + /// + /// let third_rc = Arc::new(()); + /// let third = Arc::downgrade(&third_rc); + /// assert!(!first.ptr_eq(&third)); + /// ``` + /// + /// [`ptr::eq`]: core::ptr::eq "ptr::eq" + #[inline] + #[must_use] + #[stable(feature = "weak_ptr_eq", since = "1.39.0")] + pub fn ptr_eq(&self, other: &Self) -> bool { + ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr()) + } +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +impl Clone for Weak { + /// Makes a clone of the `Weak` pointer that points to the same allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let weak_five = Arc::downgrade(&Arc::new(5)); + /// + /// let _ = Weak::clone(&weak_five); + /// ``` + #[inline] + fn clone(&self) -> Weak { + if let Some(inner) = self.inner() { + // See comments in Arc::clone() for why this is relaxed. This can use a + // fetch_add (ignoring the lock) because the weak count is only locked + // where are *no other* weak pointers in existence. (So we can't be + // running this code in that case). + let old_size = inner.weak.fetch_add(1, Relaxed); + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { + intrinsics::abort_immediate(); + } + } + + Weak { ptr: self.ptr, alloc: self.alloc.clone() } + } +} + +#[unstable(feature = "ergonomic_clones", issue = "132290")] +impl UseCloned for Weak {} + +#[stable(feature = "downgraded_weak", since = "1.10.0")] +impl Default for Weak { + /// Constructs a new `Weak`, without allocating memory. + /// Calling [`upgrade`] on the return value always + /// gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// use std::sync::Weak; + /// + /// let empty: Weak = Default::default(); + /// assert!(empty.upgrade().is_none()); + /// ``` + fn default() -> Weak { + Weak::new() + } +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak { + /// Drops the `Weak` pointer. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// struct Foo; + /// + /// impl Drop for Foo { + /// fn drop(&mut self) { + /// println!("dropped!"); + /// } + /// } + /// + /// let foo = Arc::new(Foo); + /// let weak_foo = Arc::downgrade(&foo); + /// let other_weak_foo = Weak::clone(&weak_foo); + /// + /// drop(weak_foo); // Doesn't print anything + /// drop(foo); // Prints "dropped!" + /// + /// assert!(other_weak_foo.upgrade().is_none()); + /// ``` + fn drop(&mut self) { + // If we find out that we were the last weak pointer, then its time to + // deallocate the data entirely. See the discussion in Arc::drop() about + // the memory orderings + // + // It's not necessary to check for the locked state here, because the + // weak count can only be locked if there was precisely one weak ref, + // meaning that drop could only subsequently run ON that remaining weak + // ref, which can only happen after the lock is released. + let inner = if let Some(inner) = self.inner() { inner } else { return }; + + if inner.weak.fetch_sub(1, Release) == 1 { + acquire!(inner.weak); + + // Make sure we aren't trying to "deallocate" the shared static for empty slices + // used by Default::default. + debug_assert!( + !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner), + "Arc/Weaks backed by a static should never be deallocated. \ + Likely decrement_strong_count or from_raw were called too many times.", + ); + + // ignore-tidy-undocumented-unsafe + unsafe { + self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())) + } + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +trait ArcEqIdent { + fn eq(&self, other: &Arc) -> bool; + fn ne(&self, other: &Arc) -> bool; +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + default fn eq(&self, other: &Arc) -> bool { + **self == **other + } + #[inline] + default fn ne(&self, other: &Arc) -> bool { + **self != **other + } +} + +/// We're doing this specialization here, and not as a more general optimization on `&T`, because it +/// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to +/// store large values, that are slow to clone, but also heavy to check for equality, causing this +/// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to +/// the same value, than two `&T`s. +/// +/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + fn eq(&self, other: &Arc) -> bool { + ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other + } + + #[inline] + fn ne(&self, other: &Arc) -> bool { + !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialEq for Arc { + /// Equality for two `Arc`s. + /// + /// Two `Arc`s are equal if their inner values are equal, even if they are + /// stored in different allocation. + /// + /// If `T` also implements `Eq` (implying reflexivity of equality), + /// two `Arc`s that point to the same allocation are always equal. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five == Arc::new(5)); + /// ``` + #[inline] + fn eq(&self, other: &Arc) -> bool { + ArcEqIdent::eq(self, other) + } + + /// Inequality for two `Arc`s. + /// + /// Two `Arc`s are not equal if their inner values are not equal. + /// + /// If `T` also implements `Eq` (implying reflexivity of equality), + /// two `Arc`s that point to the same value are always equal. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five != Arc::new(6)); + /// ``` + #[inline] + fn ne(&self, other: &Arc) -> bool { + ArcEqIdent::ne(self, other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialOrd for Arc { + /// Partial comparison for two `Arc`s. + /// + /// The two are compared by calling `partial_cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::cmp::Ordering; + /// + /// let five = Arc::new(5); + /// + /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); + /// ``` + fn partial_cmp(&self, other: &Arc) -> Option { + (**self).partial_cmp(&**other) + } + + /// Less-than comparison for two `Arc`s. + /// + /// The two are compared by calling `<` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five < Arc::new(6)); + /// ``` + fn lt(&self, other: &Arc) -> bool { + *(*self) < *(*other) + } + + /// 'Less than or equal to' comparison for two `Arc`s. + /// + /// The two are compared by calling `<=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five <= Arc::new(5)); + /// ``` + fn le(&self, other: &Arc) -> bool { + *(*self) <= *(*other) + } + + /// Greater-than comparison for two `Arc`s. + /// + /// The two are compared by calling `>` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five > Arc::new(4)); + /// ``` + fn gt(&self, other: &Arc) -> bool { + *(*self) > *(*other) + } + + /// 'Greater than or equal to' comparison for two `Arc`s. + /// + /// The two are compared by calling `>=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five >= Arc::new(5)); + /// ``` + fn ge(&self, other: &Arc) -> bool { + *(*self) >= *(*other) + } +} +#[stable(feature = "rust1", since = "1.0.0")] +impl Ord for Arc { + /// Comparison for two `Arc`s. + /// + /// The two are compared by calling `cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::cmp::Ordering; + /// + /// let five = Arc::new(5); + /// + /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6))); + /// ``` + fn cmp(&self, other: &Arc) -> Ordering { + (**self).cmp(&**other) + } +} +#[stable(feature = "rust1", since = "1.0.0")] +impl Eq for Arc {} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Pointer for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&(&raw const **self), f) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Default for Arc { + /// Creates a new `Arc`, with the `Default` value for `T`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x: Arc = Default::default(); + /// assert_eq!(*x, 0); + /// ``` + fn default() -> Arc { + // ignore-tidy-undocumented-unsafe + unsafe { + Self::from_inner(Box::into_non_null(Box::write( + Box::new_uninit(), + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: T::default(), + }, + ))) + } + } +} + +/// Struct to hold the static `ArcInner` used for empty `Arc` as +/// returned by `Default::default`. +/// +/// Layout notes: +/// * `repr(align(16))` so we can use it for `[T]` with `align_of::() <= 16`. +/// * `repr(C)` so `inner` is at offset 0 (and thus guaranteed to actually be aligned to 16). +/// * `[u8; 1]` (to be initialized with 0) so it can be used for `Arc`. +#[repr(C, align(16))] +struct SliceArcInnerForStatic { + inner: ArcInner<[u8; 1]>, +} +#[cfg(not(no_global_oom_handling))] +const MAX_STATIC_INNER_SLICE_ALIGNMENT: usize = 16; + +static STATIC_INNER_SLICE: SliceArcInnerForStatic = SliceArcInnerForStatic { + inner: ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: [0], + }, +}; + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc { + /// Creates an empty str inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + let arc: Arc<[u8]> = Default::default(); + debug_assert!(core::str::from_utf8(&arc).is_ok()); + let (ptr, alloc) = Arc::into_inner_with_allocator(arc); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr_in(ptr.as_ptr() as *mut ArcInner, alloc) } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc { + /// Creates an empty CStr inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + use core::ffi::CStr; + let inner: NonNull> = NonNull::from(&STATIC_INNER_SLICE.inner); + let inner: NonNull> = + NonNull::new(inner.as_ptr() as *mut ArcInner).unwrap(); + // `this` semantically is the Arc "owned" by the static, so make sure not to drop it. + let this: mem::ManuallyDrop> = + // ignore-tidy-undocumented-unsafe + unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) }; + (*this).clone() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc<[T]> { + /// Creates an empty `[T]` inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + if align_of::() <= MAX_STATIC_INNER_SLICE_ALIGNMENT { + // We take a reference to the whole struct instead of the ArcInner<[u8; 1]> inside it so + // we don't shrink the range of bytes the ptr is allowed to access under Stacked Borrows. + // (Miri complains on 32-bit targets with Arc<[Align16]> otherwise.) + // (Note that NonNull::from(&STATIC_INNER_SLICE.inner) is fine under Tree Borrows.) + let inner: NonNull = NonNull::from(&STATIC_INNER_SLICE); + let inner: NonNull> = inner.cast(); + // `this` semantically is the Arc "owned" by the static, so make sure not to drop it. + let this: mem::ManuallyDrop> = + // ignore-tidy-undocumented-unsafe + unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) }; + return (*this).clone(); + } + + // If T's alignment is too large for the static, make a new unique allocation. + let arr: [T; 0] = []; + Arc::from(arr) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "pin_default_impls", since = "1.91.0")] +impl Default for Pin> +where + T: ?Sized, + Arc: Default, +{ + #[inline] + fn default() -> Self { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::::default()) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Hash for Arc { + fn hash(&self, state: &mut H) { + (**self).hash(state) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "from_for_ptrs", since = "1.6.0")] +impl From for Arc { + /// Converts a `T` into an `Arc` + /// + /// The conversion moves the value into a + /// newly allocated `Arc`. It is equivalent to + /// calling `Arc::new(t)`. + /// + /// # Example + /// ```rust + /// # use std::sync::Arc; + /// let x = 5; + /// let arc = Arc::new(5); + /// + /// assert_eq!(Arc::from(x), arc); + /// ``` + fn from(t: T) -> Self { + Arc::new(t) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_array", since = "1.74.0")] +impl From<[T; N]> for Arc<[T]> { + /// Converts a [`[T; N]`](prim@array) into an `Arc<[T]>`. + /// + /// The conversion moves the array into a newly allocated `Arc`. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let original: [i32; 3] = [1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: [T; N]) -> Arc<[T]> { + Arc::<[T; N]>::from(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From<&[T]> for Arc<[T]> { + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let original: &[i32] = &[1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: &[T]) -> Arc<[T]> { + >::from_slice(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_mut_slice", since = "1.84.0")] +impl From<&mut [T]> for Arc<[T]> { + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let mut original = [1, 2, 3]; + /// let original: &mut [i32] = &mut original; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: &mut [T]) -> Arc<[T]> { + Arc::from(&*v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From<&str> for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let shared: Arc = Arc::from("eggplant"); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: &str) -> Arc { + let arc = Arc::<[u8]>::from(v.as_bytes()); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_mut_slice", since = "1.84.0")] +impl From<&mut str> for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let mut original = String::from("eggplant"); + /// let original: &mut str = &mut original; + /// let shared: Arc = Arc::from(original); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: &mut str) -> Arc { + Arc::from(&*v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: String = "eggplant".to_owned(); + /// let shared: Arc = Arc::from(unique); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: String) -> Arc { + Arc::from(&v[..]) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From> for Arc { + /// Move a boxed object to a new, reference-counted allocation. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: Box = Box::from("eggplant"); + /// let shared: Arc = Arc::from(unique); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: Box) -> Arc { + Arc::from_box_in(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From> for Arc<[T], A> { + /// Allocates a reference-counted slice and moves `v`'s items into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: Vec = vec![1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(unique); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: Vec) -> Arc<[T], A> { + // ignore-tidy-undocumented-unsafe + unsafe { + let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); + + let rc_ptr = Self::allocate_for_slice_in(len, &alloc); + ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len); + + // Create a `Vec` with length 0, to deallocate the buffer + // without dropping its contents or the allocator + let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc); + + Self::from_ptr_in(rc_ptr, alloc) + } + } +} + +#[stable(feature = "shared_from_cow", since = "1.45.0")] +impl<'a, B> From> for Arc +where + B: ToOwned + ?Sized, + Arc: From<&'a B> + From, +{ + /// Creates an atomically reference-counted pointer from a clone-on-write + /// pointer by copying its content. + /// + /// # Example + /// + /// ```rust + /// # use std::sync::Arc; + /// # use std::borrow::Cow; + /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant"); + /// let shared: Arc = Arc::from(cow); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(cow: Cow<'a, B>) -> Arc { + match cow { + Cow::Borrowed(s) => Arc::from(s), + Cow::Owned(s) => Arc::from(s), + } + } +} + +#[stable(feature = "shared_from_str", since = "1.62.0")] +impl From> for Arc<[u8]> { + /// Converts an atomically reference-counted string slice into a byte slice. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let string: Arc = Arc::from("eggplant"); + /// let bytes: Arc<[u8]> = Arc::from(string); + /// assert_eq!("eggplant".as_bytes(), bytes.as_ref()); + /// ``` + #[inline] + fn from(rc: Arc) -> Self { + // SAFETY: `str` has the same layout as `[u8]`. + unsafe { Arc::from_raw(Arc::into_raw(rc) as *const [u8]) } + } +} + +#[stable(feature = "boxed_slice_try_from", since = "1.43.0")] +impl TryFrom> for Arc<[T; N], A> { + type Error = Arc<[T], A>; + + fn try_from(boxed_slice: Arc<[T], A>) -> Result { + if boxed_slice.len() == N { + let (ptr, alloc) = Arc::into_inner_with_allocator(boxed_slice); + // ignore-tidy-undocumented-unsafe + Ok(unsafe { Arc::from_inner_in(ptr.cast(), alloc) }) + } else { + Err(boxed_slice) + } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_iter", since = "1.37.0")] +impl FromIterator for Arc<[T]> { + /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`. + /// + /// # Performance characteristics + /// + /// ## The general case + /// + /// In the general case, collecting into `Arc<[T]>` is done by first + /// collecting into a `Vec`. That is, when writing the following: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect(); + /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); + /// ``` + /// + /// this behaves as if we wrote: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0) + /// .collect::>() // The first set of allocations happens here. + /// .into(); // A second allocation for `Arc<[T]>` happens here. + /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); + /// ``` + /// + /// This will allocate as many times as needed for constructing the `Vec` + /// and then it will allocate once for turning the `Vec` into the `Arc<[T]>`. + /// + /// ## Iterators of known length + /// + /// When your `Iterator` implements `TrustedLen` and is of an exact size, + /// a single allocation will be made for the `Arc<[T]>`. For example: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here. + /// # assert_eq!(&*evens, &*(0..10).collect::>()); + /// ``` + fn from_iter>(iter: I) -> Self { + ToArcSlice::to_arc_slice(iter.into_iter()) + } +} + +#[cfg(not(no_global_oom_handling))] +/// Specialization trait used for collecting into `Arc<[T]>`. +trait ToArcSlice: Iterator + Sized { + fn to_arc_slice(self) -> Arc<[T]>; +} + +#[cfg(not(no_global_oom_handling))] +impl> ToArcSlice for I { + default fn to_arc_slice(self) -> Arc<[T]> { + self.collect::>().into() + } +} + +#[cfg(not(no_global_oom_handling))] +impl> ToArcSlice for I { + fn to_arc_slice(self) -> Arc<[T]> { + // This is the case for a `TrustedLen` iterator. + let (low, high) = self.size_hint(); + if let Some(high) = high { + debug_assert_eq!( + low, + high, + "TrustedLen iterator's size hint is not exact: {:?}", + (low, high) + ); + + // SAFETY: We need to ensure that the iterator has an exact length and we have. + unsafe { Arc::from_iter_exact(self, low) } + } else { + // TrustedLen contract guarantees that `upper_bound == None` implies an iterator + // length exceeding `usize::MAX`. + // The default implementation would collect into a vec which would panic. + // Thus we panic here immediately without invoking `Vec` code. + panic!("capacity overflow"); + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl borrow::Borrow for Arc { + fn borrow(&self) -> &T { + self + } +} + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsRef for Arc { + fn as_ref(&self) -> &T { + self + } +} + +#[stable(feature = "pin", since = "1.33.0")] +impl Unpin for Arc {} + +/// Gets the offset within an `ArcInner` for the payload behind a pointer. +/// +/// # Safety +/// +/// The pointer must point to (and have valid metadata for) a previously +/// valid instance of T, but the T is allowed to be dropped. +unsafe fn data_offset(ptr: *const T) -> usize { + // Align the unsized value to the end of the ArcInner. + // Because ArcInner is repr(C), it will always be the last field in memory. + // SAFETY: since the only unsized types possible are slices, trait objects, + // and extern types, the input safety requirement is currently enough to + // satisfy the requirements of Alignment::of_val_raw; this is an implementation + // detail of the language that must not be relied upon outside of std. + unsafe { data_offset_alignment(Alignment::of_val_raw(ptr)) } +} + +#[inline] +fn data_offset_alignment(alignment: Alignment) -> usize { + let layout = Layout::new::>(); + layout.size() + layout.padding_needed_for(alignment) +} + +/// A unique owning pointer to an [`ArcInner`] **that does not imply the contents are initialized,** +/// but will deallocate it (without dropping the value) when dropped. +/// +/// This is a helper for [`Arc::make_mut()`] to ensure correct cleanup on panic. +struct UniqueArcUninit { + ptr: NonNull>, + layout_for_value: Layout, + alloc: Option, +} + +impl UniqueArcUninit { + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it. + #[cfg(not(no_global_oom_handling))] + fn new(for_value: &T, alloc: A) -> UniqueArcUninit { + let layout = Layout::for_value(for_value); + // ignore-tidy-undocumented-unsafe + let ptr = unsafe { + Arc::allocate_for_layout( + layout, + |layout_for_arcinner| alloc.allocate(layout_for_arcinner), + |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner), + ) + }; + Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) } + } + + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it, + /// returning an error if allocation fails. + fn try_new(for_value: &T, alloc: A) -> Result, AllocError> { + let layout = Layout::for_value(for_value); + // ignore-tidy-undocumented-unsafe + let ptr = unsafe { + Arc::try_allocate_for_layout( + layout, + |layout_for_arcinner| alloc.allocate(layout_for_arcinner), + |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner), + )? + }; + Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }) + } + + /// Returns the pointer to be written into to initialize the [`Arc`]. + fn data_ptr(&mut self) -> *mut T { + let offset = data_offset_alignment(self.layout_for_value.alignment()); + // ignore-tidy-undocumented-unsafe + unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T } + } + + /// Upgrade this into a normal [`Arc`]. + /// + /// # Safety + /// + /// The data must have been initialized (by writing to [`Self::data_ptr()`]). + unsafe fn into_arc(self) -> Arc { + let mut this = ManuallyDrop::new(self); + let ptr = this.ptr.as_ptr(); + let alloc = this.alloc.take().unwrap(); + + // SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible + // for having initialized the data. + unsafe { Arc::from_ptr_in(ptr, alloc) } + } +} + +impl Drop for UniqueArcUninit { + fn drop(&mut self) { + // SAFETY: + // * new() produced a pointer safe to deallocate. + // * We own the pointer unless into_arc() was called, which forgets us. + unsafe { + self.alloc.take().unwrap().deallocate( + self.ptr.cast(), + arcinner_layout_for_value_layout(self.layout_for_value), + ); + } + } +} + +#[stable(feature = "arc_error", since = "1.52.0")] +impl core::error::Error for Arc { + #[allow(deprecated)] + fn cause(&self) -> Option<&dyn core::error::Error> { + core::error::Error::cause(&**self) + } + + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + core::error::Error::source(&**self) + } + + fn provide<'a>(&'a self, req: &mut core::error::Request<'a>) { + core::error::Error::provide(&**self, req); + } +} + +/// A uniquely owned [`Arc`]. +/// +/// This represents an `Arc` that is known to be uniquely owned -- that is, have exactly one strong +/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong +/// references will fail unless the `UniqueArc` they point to has been converted into a regular `Arc`. +/// +/// Because it is uniquely owned, the contents of a `UniqueArc` can be freely mutated. A common +/// use case is to have an object be mutable during its initialization phase but then have it become +/// immutable and converted to a normal `Arc`. +/// +/// This can be used as a flexible way to create cyclic data structures, as in the example below. +/// +/// ``` +/// #![feature(unique_rc_arc)] +/// use std::sync::{Arc, Weak, UniqueArc}; +/// +/// struct Gadget { +/// me: Weak, +/// } +/// +/// fn create_gadget() -> Option> { +/// let mut rc = UniqueArc::new(Gadget { +/// me: Weak::new(), +/// }); +/// rc.me = UniqueArc::downgrade(&rc); +/// Some(UniqueArc::into_arc(rc)) +/// } +/// +/// create_gadget().unwrap(); +/// ``` +/// +/// An advantage of using `UniqueArc` over [`Arc::new_cyclic`] to build cyclic data structures is that +/// [`Arc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the +/// previous example, `UniqueArc` allows for more flexibility in the construction of cyclic data, +/// including fallible or async constructors. +#[unstable(feature = "unique_rc_arc", issue = "112566")] +pub struct UniqueArc< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + ptr: NonNull>, + // Define the ownership of `ArcInner` for drop-check + _marker: PhantomData>, + // Invariance is necessary for soundness: once other `Weak` + // references exist, we already have a form of shared mutability! + _marker2: PhantomData<*mut T>, + alloc: A, +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl Send for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl Sync for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +// #[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> + for UniqueArc +{ +} + +//#[unstable(feature = "unique_rc_arc", issue = "112566")] +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Display for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Debug for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Pointer for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&(&raw const **self), f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl borrow::Borrow for UniqueArc { + fn borrow(&self) -> &T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl borrow::BorrowMut for UniqueArc { + fn borrow_mut(&mut self) -> &mut T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl AsRef for UniqueArc { + fn as_ref(&self) -> &T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl AsMut for UniqueArc { + fn as_mut(&mut self) -> &mut T { + self + } +} + +#[cfg(not(no_global_oom_handling))] +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl From for UniqueArc { + #[inline(always)] + fn from(value: T) -> Self { + Self::new(value) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Unpin for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl PartialEq for UniqueArc { + /// Equality for two `UniqueArc`s. + /// + /// Two `UniqueArc`s are equal if their inner values are equal. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five == UniqueArc::new(5)); + /// ``` + #[inline] + fn eq(&self, other: &Self) -> bool { + PartialEq::eq(&**self, &**other) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl PartialOrd for UniqueArc { + /// Partial comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `partial_cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// use std::cmp::Ordering; + /// + /// let five = UniqueArc::new(5); + /// + /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueArc::new(6))); + /// ``` + #[inline(always)] + fn partial_cmp(&self, other: &UniqueArc) -> Option { + (**self).partial_cmp(&**other) + } + + /// Less-than comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `<` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five < UniqueArc::new(6)); + /// ``` + #[inline(always)] + fn lt(&self, other: &UniqueArc) -> bool { + **self < **other + } + + /// 'Less than or equal to' comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `<=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five <= UniqueArc::new(5)); + /// ``` + #[inline(always)] + fn le(&self, other: &UniqueArc) -> bool { + **self <= **other + } + + /// Greater-than comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `>` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five > UniqueArc::new(4)); + /// ``` + #[inline(always)] + fn gt(&self, other: &UniqueArc) -> bool { + **self > **other + } + + /// 'Greater than or equal to' comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `>=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five >= UniqueArc::new(5)); + /// ``` + #[inline(always)] + fn ge(&self, other: &UniqueArc) -> bool { + **self >= **other + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Ord for UniqueArc { + /// Comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// use std::cmp::Ordering; + /// + /// let five = UniqueArc::new(5); + /// + /// assert_eq!(Ordering::Less, five.cmp(&UniqueArc::new(6))); + /// ``` + #[inline] + fn cmp(&self, other: &UniqueArc) -> Ordering { + (**self).cmp(&**other) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Eq for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Hash for UniqueArc { + fn hash(&self, state: &mut H) { + (**self).hash(state); + } +} + +impl UniqueArc { + /// Creates a new `UniqueArc`. + /// + /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading + /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`]. + /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will + /// point to the new [`Arc`]. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn new(value: T) -> Self { + Self::new_in(value, Global) + } + + /// Like [`new`](Self::new), but returns an error if the allocation + /// fails, instead of calling [`handle_alloc_error`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + pub fn try_new(value: T) -> Result { + Self::try_new_in(value, Global) + } +} + +impl UniqueArc { + /// Creates a new `UniqueArc` in the provided allocator. + /// + /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading + /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`]. + /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will + /// point to the new [`Arc`]. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + #[must_use] + pub fn new_in(data: T, alloc: A) -> Self { + let (ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + // keep one weak reference so if all the weak pointers that are created are dropped + // the UniqueArc still stays valid. + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + )); + Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc } + } + + /// Like [`new_in`](Self::new_in), but returns an error if the allocation + /// fails, instead of calling [`handle_alloc_error`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + pub fn try_new_in(data: T, alloc: A) -> Result { + let (ptr, alloc) = Box::into_non_null_with_allocator(Box::try_new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + // keep one weak reference so if all the weak pointers that are created are dropped + // the UniqueArc still stays valid. + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + )?); + Ok(Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }) + } + + /// Consumes the `UniqueArc`, returning its wrapped value and allocator. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + #[must_use] + pub fn unwrap_with_allocator(this: Self) -> (T, A) { + let inner_ptr = this.ptr; + let (data_ptr, alloc) = Self::into_raw_with_allocator(this); + + // SAFETY: Conceptually moves out of the `UniqueRc`. + // We do not use the data inside ever again. + let val = unsafe { data_ptr.read() }; + + // Drop the strong-weak ref + drop(Weak { ptr: inner_ptr, alloc: &alloc }); + + (val, alloc) + } + + /// Consumes the `UniqueArc`, returning its wrapped value. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn unwrap(this: Self) -> T { + Self::unwrap_with_allocator(this).0 + } + + /// Maps the value in a `UniqueArc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `UniqueArc`, and the result is returned, + /// also in a `UniqueArc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `UniqueArc::map(u, f)` instead of `u.map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// + /// use std::sync::UniqueArc; + /// + /// let r = UniqueArc::new(7); + /// let new = UniqueArc::map(r, |i| i + 7); + /// assert_eq!(*new, 14); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + pub fn map(this: Self, f: impl FnOnce(T) -> U) -> UniqueArc { + if size_of::() == size_of::() + && align_of::() == align_of::() + && UniqueArc::weak_count(&this) == 0 + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this); + let value = ptr.read(); + let allocation = + UniqueArc::from_raw_with_allocator(ptr.cast::>(), alloc); + + UniqueArc::write(allocation, f(value)) + } + } else { + let (val, alloc) = UniqueArc::unwrap_with_allocator(this); + UniqueArc::new_in(f(val), alloc) + } + } + + /// Attempts to map the value in a `UniqueArc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `UniqueArc`, and if the operation succeeds, + /// the result is returned, also in a `UniqueArc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `UniqueArc::try_map(u, f)` instead of `u.try_map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(smart_pointer_try_map)] + /// #![feature(unique_rc_arc)] + /// + /// use std::sync::UniqueArc; + /// + /// let b = UniqueArc::new(7); + /// let new = UniqueArc::try_map(b, u32::try_from).unwrap(); + /// assert_eq!(*new, 7); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "smart_pointer_try_map", issue = "144419")] + pub fn try_map( + this: Self, + f: impl FnOnce(T) -> R, + ) -> >>::TryType + where + R: Try, + R::Residual: Residual>, + { + if size_of::() == size_of::() + && align_of::() == align_of::() + && UniqueArc::weak_count(&this) == 0 + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this); + let value = ptr.read(); + let allocation = UniqueArc::from_raw_with_allocator( + ptr.cast::>(), + alloc, + ); + + try { UniqueArc::write(allocation, f(value)?) } + } + } else { + let (val, alloc) = UniqueArc::unwrap_with_allocator(this); + try { UniqueArc::new_in(f(val)?, alloc) } + } + } +} + +impl UniqueArc { + #[cfg(not(no_global_oom_handling))] + unsafe fn from_raw_with_allocator(ptr: *const T, alloc: A) -> Self { + // SAFETY: Upheld by caller. + let offset = unsafe { data_offset(ptr) }; + + // Reverse the offset to find the original ArcInner. + // SAFETY: Upheld by caller. + let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut ArcInner }; + + Self { + // SAFETY: Upheld by caller. + ptr: unsafe { NonNull::new_unchecked(rc_ptr) }, + _marker: PhantomData, + _marker2: PhantomData, + alloc, + } + } + + fn into_raw_with_allocator(this: Self) -> (*const T, A) { + let this = ManuallyDrop::new(this); + // SAFETY: The copy of the allocator stored in `this` is forgotten + (Self::as_ptr(&*this), unsafe { ptr::read(&this.alloc) }) + } + + /// Converts the `UniqueArc` into a regular [`Arc`]. + /// + /// This consumes the `UniqueArc` and returns a regular [`Arc`] that contains the `value` that + /// is passed to `into_arc`. + /// + /// Any weak references created before this method is called can now be upgraded to strong + /// references. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn into_arc(this: Self) -> Arc { + let this = ManuallyDrop::new(this); + + // Move the allocator out. + // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in + // a `ManuallyDrop`. + let alloc: A = unsafe { ptr::read(&this.alloc) }; + + // SAFETY: This pointer was allocated at creation time so we know it is valid. + unsafe { + // Convert our weak reference into a strong reference + (*this.ptr.as_ptr()).strong.store(1, Release); + Arc::from_inner_in(this.ptr, alloc) + } + } + + #[cfg(not(no_global_oom_handling))] + fn weak_count(this: &Self) -> usize { + this.inner().weak.load(Acquire) - 1 + } + + #[cfg(not(no_global_oom_handling))] + fn inner(&self) -> &ArcInner { + // SAFETY: while this UniqueArc is alive we're guaranteed that the inner pointer is valid. + unsafe { self.ptr.as_ref() } + } + + fn as_ptr(this: &Self) -> *const T { + let ptr: *mut ArcInner = NonNull::as_ptr(this.ptr); + + // SAFETY: This cannot go through Deref::deref or UniqueArc::inner because + // this is required to retain raw/mut provenance such that e.g. `get_mut` can + // write through the pointer after the Rc is recovered through `from_raw`. + unsafe { &raw mut (*ptr).data } + } + + #[inline] + fn into_inner_with_allocator(this: Self) -> (NonNull>, A) { + let this = mem::ManuallyDrop::new(this); + // SAFETY: Pointer is valid for reads and only read once. + (this.ptr, unsafe { ptr::read(&this.alloc) }) + } + + #[inline] + unsafe fn from_inner_in(ptr: NonNull>, alloc: A) -> Self { + Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc } + } +} + +impl UniqueArc { + /// Creates a new weak reference to the `UniqueArc`. + /// + /// Attempting to upgrade this weak reference will fail before the `UniqueArc` has been converted + /// to a [`Arc`] using [`UniqueArc::into_arc`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn downgrade(this: &Self) -> Weak { + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object or converting the object to a normal `Arc`. + // + // Note that we don't need to test if the weak counter is locked because there + // are no such operations like `Arc::get_mut` or `Arc::make_mut` that will lock + // the weak counter. + // + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let old_size = unsafe { (*this.ptr.as_ptr()).weak.fetch_add(1, Relaxed) }; + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { + intrinsics::abort_immediate(); + } + + Weak { ptr: this.ptr, alloc: this.alloc.clone() } + } +} + +impl UniqueArc, A> { + /// Writes the value and converts to `UniqueArc`. + /// + /// This method converts similarly to [`assume_init`](Self::assume_init) but + /// writes `value` into it before conversion, thus guaranteeing safety. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn write(mut this: Self, value: T) -> UniqueArc { + // SAFETY: Writing initialises the wrapped value. + unsafe { + this.write(value); + this.assume_init() + } + } + + /// Converts to `UniqueArc`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub unsafe fn assume_init(self) -> UniqueArc { + let (ptr, alloc) = UniqueArc::into_inner_with_allocator(self); + // SAFETY: Upheld by caller. + unsafe { UniqueArc::from_inner_in(ptr.cast(), alloc) } + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Deref for UniqueArc { + type Target = T; + + fn deref(&self) -> &T { + // SAFETY: This pointer was allocated at creation time so we know it is valid. + unsafe { &self.ptr.as_ref().data } + } +} + +// #[unstable(feature = "unique_rc_arc", issue = "112566")] +#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")] +unsafe impl PinSafePointer for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl DerefMut for UniqueArc { + fn deref_mut(&mut self) -> &mut T { + // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we + // have unique ownership and therefore it's safe to make a mutable reference because + // `UniqueArc` owns the only strong reference to itself. + // We also need to be careful to only create a mutable reference to the `data` field, + // as a mutable reference to the entire `ArcInner` would assert uniqueness over the + // ref count fields too, invalidating any attempt by `Weak`s to access the ref count. + unsafe { &mut (*self.ptr.as_ptr()).data } + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +// #[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueArc { + fn drop(&mut self) { + // See `Arc::drop_slow` which drops an `Arc` with a strong count of 0. + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + + // ignore-tidy-undocumented-unsafe + unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) }; + } +} + +#[stable(feature = "allocator_api", since = "1.100.0")] +unsafe impl Allocator for Arc { + #[inline] + fn allocate(&self, layout: Layout) -> Result, AllocError> { + (**self).allocate(layout) + } + + #[inline] + fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { + (**self).allocate_zeroed(layout) + } + + #[inline] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).deallocate(ptr, layout) } + } + + #[inline] + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn grow_zeroed( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn shrink( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).shrink(ptr, old_layout, new_layout) } + } +} + +/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`. +#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] +#[unstable_feature_bound(allocator_ext)] +impl AllocatorNightly for Arc {} + +#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] +unsafe impl AllocatorClone for Arc {} + +#[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::::downcast_unchecked::)] + pub fn check_downcast_unchecked_i32() { + let value: i32 = kani::any(); + let shared: bool = kani::any(); + let erased: Arc = + 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::() }; + assert!(*arc == value); + assert!(Arc::strong_count(&arc) == expected_strong); + drop(extra); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::)] + pub fn check_downcast_unchecked_bool() { + let value: bool = kani::any(); + let erased: Arc = + if kani::any() { Arc::new(value) } else { Arc::new(0u16) }; + let arc = unsafe { erased.downcast_unchecked::() }; + assert!(*arc == value); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::<()>)] + pub fn check_downcast_unchecked_zst() { + let erased: Arc = + 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 = Arc::new(value); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + 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 = Arc::new(other); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + Ok(_) => unreachable!("mismatched concrete type must downcast to Err"), + Err(orig) => { + assert!((*orig).is::()); + assert!(Arc::strong_count(&orig) == expected_strong); + kani::cover(true, "downcast Err branch reached"); + } + } + drop(extra); + } + } +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/original/lib.rs b/verifast-proofs/alloc/rcs/arc.rs/original/lib.rs new file mode 100644 index 0000000000000..08331cfa27538 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/original/lib.rs @@ -0,0 +1,104 @@ +// verifast_options{skip_specless_fns ignore_unwind_paths} + +#![allow(dead_code)] +#![allow(unused_features)] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![no_std] +#![stable(feature = "rust1", since = "1.0.0")] + +#![feature(allocator_api)] +#![feature(allocator_ext)] +#![feature(allow_internal_unstable)] +#![feature(box_into_inner)] +#![feature(cast_maybe_uninit)] +#![feature(cell_get_cloned)] +#![feature(cfg_sanitize)] +#![feature(clone_to_uninit)] +#![feature(coerce_unsized)] +#![feature(const_clone)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_default)] +#![feature(const_destruct)] +#![feature(const_drop_in_place)] +#![feature(const_eval_select)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(core_intrinsics)] +#![feature(deref_pure_trait)] +#![feature(diagnostic_on_move)] +#![feature(dispatch_from_dyn)] +#![feature(dropck_eyepatch)] +#![feature(ergonomic_clones)] +#![feature(error_generic_member_access)] +#![feature(exact_size_is_empty)] +#![feature(extend_one)] +#![feature(generic_atomic)] +#![feature(hasher_prefixfree_extras)] +#![feature(intrinsics)] +#![feature(legacy_receiver_trait)] +#![feature(likely_unlikely)] +#![feature(maybe_uninit_array_assume_init)] +#![feature(maybe_uninit_fill)] +#![feature(min_specialization)] +#![feature(panic_internals)] +#![feature(pin_coerce_unsized_trait)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_array)] +#![feature(ptr_cast_slice)] +#![feature(ptr_internals)] +#![feature(ptr_metadata)] +#![feature(register_tool)] +#![feature(rustc_attrs)] +#![feature(rustdoc_internals)] +#![feature(set_ptr_value)] +#![feature(share_trait)] +#![feature(sized_type_properties)] +#![feature(slice_from_ptr_range)] +#![feature(slice_internals)] +#![feature(slice_ptr_get)] +#![feature(specialization)] +#![feature(staged_api)] +#![feature(std_internals)] +#![feature(temporary_niche_types)] +#![feature(trivial_clone)] +#![feature(trusted_len)] +#![feature(try_blocks)] +#![feature(try_trait_v2)] +#![feature(try_trait_v2_residual)] +#![feature(ub_checks)] +#![feature(unsize)] +#![feature(unsized_fn_params)] +#![register_tool(lint)] + +extern crate alloc as std; + +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::alloc as alloc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::borrow as borrow; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::boxed as boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::collections as collections; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::string as string; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::vec as vec; + +mod rc { + pub(crate) fn is_dangling(ptr: *const T) -> bool { + (ptr.cast::<()>()).addr() == usize::MAX + } + #[rustc_specialization_trait] + pub(crate) trait MarkerEq: Eq {} +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod arc; + +extern crate arc_atomic_cas; +extern crate arc_pin; diff --git a/verifast-proofs/alloc/rcs/arc.rs/update.sh b/verifast-proofs/alloc/rcs/arc.rs/update.sh new file mode 100755 index 0000000000000..d930900b2b430 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/update.sh @@ -0,0 +1,12 @@ +set -x -e + +if ! git diff --quiet .; then + echo "Working directory not clean. Please stash your changes and try again" + false +else + UPSTREAM=../../../../library/alloc/src/rcs/arc.rs + git merge-file --diff3 with-directives/arc.rs original/arc.rs $UPSTREAM + git merge-file --diff3 verified/arc.rs original/arc.rs $UPSTREAM + cp $UPSTREAM original/arc.rs + diff -u original/arc.rs <(sed 's|/\*@~mut@\*/ ||g; s|/\*@~mut@\*/||g' with-directives/arc.rs) | sed '1,2d' > compat.patch || true +fi diff --git a/verifast-proofs/alloc/rcs/arc.rs/verified/arc.rs b/verifast-proofs/alloc/rcs/arc.rs/verified/arc.rs new file mode 100644 index 0000000000000..cda030b0dcb53 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/verified/arc.rs @@ -0,0 +1,10690 @@ +use core::any::Any; +use core::cell::CloneFromCell; +#[cfg(not(no_global_oom_handling))] +use core::clone::TrivialClone; +use core::clone::{CloneToUninit, Share, UseCloned}; +use core::cmp::Ordering; +use core::hash::{Hash, Hasher}; +#[cfg(not(no_global_oom_handling))] +use core::iter; +use core::marker::{PhantomData, Unsize}; +use core::mem::{self, Alignment, ManuallyDrop}; +use core::num::NonZeroUsize; +use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver}; +#[cfg(not(no_global_oom_handling))] +use core::ops::{Residual, Try}; +use core::panic::{RefUnwindSafe, UnwindSafe}; +use core::pin::{Pin, PinSafePointer}; +use core::ptr::{self, NonNull}; +#[cfg(not(no_global_oom_handling))] +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; +use crate::alloc::{ + AllocError, Allocator, AllocatorClone, AllocatorNightly, Global, Layout, StaticAllocator, +}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::rc::is_dangling; +#[cfg(not(no_global_oom_handling))] +use crate::string::String; +#[cfg(not(no_global_oom_handling))] +use crate::vec::Vec; + +/// A soft limit on the amount of references that may be made to an `Arc`. +/// +/// Going above this limit will abort your program (although not +/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references. +/// Trying to go above it might call a `panic` (if not actually going above it). +/// +/// This is a global invariant, and also applies when using a compare-exchange loop. +/// +/// See comment in `Arc::clone`. +const MAX_REFCOUNT: usize = (isize::MAX) as usize; + +#[cold] +#[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] +#[track_caller] +fn panic_arc_overflow() -> ! +//@ req thread_token(?t); +//@ ens false; +//@ on_unwind_ens thread_token(t); +{ + panic!("Arc counter overflow"); +} + +#[cfg(not(sanitize = "thread"))] +macro_rules! acquire { + ($x:expr) => { + atomic::fence(Acquire) + }; +} + +// ThreadSanitizer does not support memory fences. To avoid false positive +// reports in Arc / Weak implementation use atomic loads for synchronization +// instead. +#[cfg(sanitize = "thread")] +macro_rules! acquire { + ($x:expr) => { + $x.load(Acquire) + }; +} + +/// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically +/// Reference Counted'. +/// +/// The type `Arc` provides shared ownership of a value of type `T`, +/// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces +/// a new `Arc` instance, which points to the same allocation on the heap as the +/// source `Arc`, while increasing a reference count. When the last `Arc` +/// pointer to a given allocation is destroyed, the value stored in that allocation (often +/// referred to as "inner value") is also dropped. +/// +/// Shared references in Rust disallow mutation by default, and `Arc` is no +/// exception: you cannot generally obtain a mutable reference to something +/// inside an `Arc`. If you do need to mutate through an `Arc`, you have several options: +/// +/// 1. Use interior mutability with synchronization primitives like [`Mutex`][mutex], +/// [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types. +/// +/// 2. Use clone-on-write semantics with [`Arc::make_mut`] which provides efficient mutation +/// without requiring interior mutability. This approach clones the data only when +/// needed (when there are multiple references) and can be more efficient when mutations +/// are infrequent. +/// +/// 3. Use [`Arc::get_mut`] when you know your `Arc` is not shared (has a reference count of 1), +/// which provides direct mutable access to the inner value without any cloning. +/// +/// ``` +/// use std::sync::Arc; +/// +/// let mut data = Arc::new(vec![1, 2, 3]); +/// +/// // This will clone the vector only if there are other references to it +/// Arc::make_mut(&mut data).push(4); +/// +/// assert_eq!(*data, vec![1, 2, 3, 4]); +/// ``` +/// +/// **Note**: This type is only available on platforms that support atomic +/// loads and stores of pointers, which includes all platforms that support +/// the `std` crate but not all those which only support [`alloc`](crate). +/// This may be detected at compile time using `#[cfg(target_has_atomic = "ptr")]`. +/// +/// ## Thread Safety +/// +/// Unlike [`Rc`], `Arc` uses atomic operations for its reference +/// counting. This means that it is thread-safe. The disadvantage is that +/// atomic operations are more expensive than ordinary memory accesses. If you +/// are not sharing reference-counted allocations between threads, consider using +/// [`Rc`] for lower overhead. [`Rc`] is a safe default, because the +/// compiler will catch any attempt to send an [`Rc`] between threads. +/// However, a library might choose `Arc` in order to give library consumers +/// more flexibility. +/// +/// `Arc` will implement [`Send`] and [`Sync`] as long as the `T` implements +/// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an +/// `Arc` to make it thread-safe? This may be a bit counter-intuitive at +/// first: after all, isn't the point of `Arc` thread safety? The key is +/// this: `Arc` makes it thread safe to have multiple ownership of the same +/// data, but it doesn't add thread safety to its data. Consider +/// Arc<[RefCell\]>. [`RefCell`] isn't [`Sync`], and if `Arc` was always +/// [`Send`], Arc<[RefCell\]> would be as well. But then we'd have a problem: +/// [`RefCell`] is not thread safe; it keeps track of the borrowing count using +/// non-atomic operations. +/// +/// In the end, this means that you may need to pair `Arc` with some sort of +/// [`std::sync`] type, usually [`Mutex`][mutex]. +/// +/// ## Breaking cycles with `Weak` +/// +/// The [`downgrade`][downgrade] method can be used to create a non-owning +/// [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d +/// to an `Arc`, but this will return [`None`] if the value stored in the allocation has +/// already been dropped. In other words, `Weak` pointers do not keep the value +/// inside the allocation alive; however, they *do* keep the allocation +/// (the backing store for the value) alive. +/// +/// A cycle between `Arc` pointers will never be deallocated. For this reason, +/// [`Weak`] is used to break cycles. For example, a tree could have +/// strong `Arc` pointers from parent nodes to children, and [`Weak`] +/// pointers from children back to their parents. +/// +/// # Cloning references +/// +/// Creating a new reference from an existing reference-counted pointer is done using the +/// `Clone` trait implemented for [`Arc`][Arc] and [`Weak`][Weak]. +/// +/// ``` +/// use std::sync::Arc; +/// let foo = Arc::new(vec![1.0, 2.0, 3.0]); +/// // The two syntaxes below are equivalent. +/// let a = foo.clone(); +/// let b = Arc::clone(&foo); +/// // a, b, and foo are all Arcs that point to the same memory location +/// ``` +/// +/// ## `Deref` behavior +/// +/// `Arc` automatically dereferences to `T` (via the [`Deref`] trait), +/// so you can call `T`'s methods on a value of type `Arc`. To avoid name +/// clashes with `T`'s methods, the methods of `Arc` itself are associated +/// functions, called using [fully qualified syntax]: +/// +/// ``` +/// use std::sync::Arc; +/// +/// let my_arc = Arc::new(()); +/// let my_weak = Arc::downgrade(&my_arc); +/// ``` +/// +/// `Arc`'s implementations of traits like `Clone` may also be called using +/// fully qualified syntax. Some people prefer to use fully qualified syntax, +/// while others prefer using method-call syntax. +/// +/// ``` +/// use std::sync::Arc; +/// +/// let arc = Arc::new(()); +/// // Method-call syntax +/// let arc2 = arc.clone(); +/// // Fully qualified syntax +/// let arc3 = Arc::clone(&arc); +/// ``` +/// +/// [`Weak`][Weak] does not auto-dereference to `T`, because the inner value may have +/// already been dropped. +/// +/// [`Rc`]: crate::rc::Rc +/// [clone]: Clone::clone +/// [mutex]: ../../std/sync/struct.Mutex.html +/// [rwlock]: ../../std/sync/struct.RwLock.html +/// [atomic]: core::sync::atomic +/// [downgrade]: Arc::downgrade +/// [upgrade]: Weak::upgrade +/// [RefCell\]: core::cell::RefCell +/// [`RefCell`]: core::cell::RefCell +/// [`std::sync`]: ../../std/sync/index.html +/// [`Arc::clone(&from)`]: Arc::clone +/// [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name +/// +/// # Examples +/// +/// Sharing some immutable data between threads: +/// +/// ```ignore-wasm +/// use std::sync::Arc; +/// use std::thread; +/// +/// let five = Arc::new(5); +/// +/// for _ in 0..10 { +/// let five = Arc::clone(&five); +/// +/// thread::spawn(move || { +/// println!("{five:?}"); +/// }); +/// } +/// ``` +/// +/// Sharing a mutable [`AtomicUsize`]: +/// +/// [`AtomicUsize`]: core::sync::atomic::AtomicUsize "sync::atomic::AtomicUsize" +/// +/// ```ignore-wasm +/// use std::sync::Arc; +/// use std::sync::atomic::{AtomicUsize, Ordering}; +/// use std::thread; +/// +/// let val = Arc::new(AtomicUsize::new(5)); +/// +/// for _ in 0..10 { +/// let val = Arc::clone(&val); +/// +/// thread::spawn(move || { +/// let v = val.fetch_add(1, Ordering::Relaxed); +/// println!("{v:?}"); +/// }); +/// } +/// ``` +/// +/// See the [`rc` documentation][rc_examples] for more examples of reference +/// counting in general. +/// +/// [rc_examples]: crate::rc#examples +#[doc(search_unbox)] +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +#[diagnostic::on_move( + message = "the type `{Self}` does not implement `Copy`", + label = "this move could be avoided by cloning the original `{Self}`, which is inexpensive", + note = "consider using `Arc::clone`" +)] +pub struct Arc< + T: ?Sized, + // FIXME: When stabilizing this parameter, the `AllocatorNightly` + // bound on the `From` impl *must* be weaked to `Allocator`, + // as `Box` is fundamental! + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + ptr: NonNull>, + phantom: PhantomData>, + alloc: A, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Arc {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for Arc {} + +/*@ +// ============================================================================= +// Phase 2 Concurrent 6-State Separation-Logic Model for Arc, Weak, +// and UniqueArc (integrated from `atomic_model/` with `arc_atomic_cas`). +// Supports generic `T: ?Sized` (including `!Send`/`!Sync` via `owner_tid`), +// generic `A: Allocator` (via `alloc_id`), `usize::MAX` weak-lock sentinel, +// and `Weak::new()` dangling `usize::MAX` sentinel. +// ============================================================================= + +fix Narc() -> *u8 { 42 as *u8 } +fix Marc() -> mask_t { MaskSingle(Narc) } + +inductive arc_mode = + | ModeShared(dk: lifetime_t) + | ModeExclusive + | ModeExclusiveLocked + | ModeDataOut + | ModeDataDropped + | ModeDealloced; + +// Strong-reference counting predicate anchored at fixed ghost cell `sgid`. +pred dlft_pred(sgid: i32; dk_opt: option) = + ghost_cell(sgid, dk_opt) &*& + match dk_opt { + some(dk) => lifetime_token(dk), + none => true, + }; + +// Explicit weak-reference counting predicate anchored at fixed ghost cell `wgid`. +pred weak_pred(wgid: i32; dealloced: bool) = + ghost_cell(wgid, dealloced); + +inductive weak_lock_state = + | LockFree + | LockExcl + | LockShared(lf: real); + +pred shared_weak_lock(lock_gid: i32, sgid: i32, dk: lifetime_t, locked: bool) = + [1/2]ghost_cell::(lock_gid, ?ls) &*& + match ls { + LockShared(lf) => locked == true &*& 0 < lf &*& [lf]ghost_cell(sgid, some(dk)), + LockFree => locked == false &*& [1/2]ghost_cell::(lock_gid, LockFree), + LockExcl => false, + }; + +// Polymorphic backing-memory reassembly for `T: ?Sized`: given reclaimed +// `strong`, `weak`, and dropped `data` bytes, reassembles the full allocation +// block + byte array at `alloc_id.lft` for `Allocator::deallocate`. +// Padding + lifetime-token outside `strong`, `weak`, `data` for polymorphic `ArcInner`. +pred ArcInner_padding_at_lft(k: lifetime_t, layout: std::alloc::Layout, ptr: *ArcInner); + +pred ArcInner_backing(alloc_id: std::alloc::alloc_id_t, layout: std::alloc::Layout, ptr: *ArcInner) = + std::alloc::alloc_block_in(alloc_id, ptr as *u8, layout) &*& + ArcInner_padding_at_lft::(alloc_id.lft, layout, ptr); + +lem ArcInner_sized_to_padding_at_lft(k: lifetime_t, ptr: *ArcInner, q: real) + req close_points_to_at_lft_token(1, k, ptr, q) &*& struct_ArcInner_padding::(ptr); + ens ArcInner_padding_at_lft::(k, std::alloc::Layout::new::>(), ptr); +{ + assume(false); // VeriFast lacks open_struct on `?Sized`-generic structs (`struct ArcInner`) +} + +lem ArcInner_reassemble_to_array_at_lft(alloc_id: std::alloc::alloc_id_t, layout: std::alloc::Layout, ptr: *ArcInner) + req ArcInner_backing::(alloc_id, layout, ptr) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, _) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, _) &*& + (*ptr).data |-> _; + ens std::alloc::alloc_block_in(alloc_id, ptr as *u8, layout) &*& + array_at_lft_(alloc_id.lft, ptr as *u8, layout.size(), _); +{ + assume(false); // Inverse of `ArcInner_sized_to_padding_at_lft` / raw layout split for `T: ?Sized` +} + +lem ArcInner_reassemble_uninit_to_array_at_lft(alloc_id: std::alloc::alloc_id_t, layout: std::alloc::Layout, ptr: *ArcInner) + req ArcInner_backing::(alloc_id, layout, ptr) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, _) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, _) &*& + (*ptr).data |-?-> _; + ens std::alloc::alloc_block_in(alloc_id, ptr as *u8, layout) &*& + array_at_lft_(alloc_id.lft, ptr as *u8, layout.size(), _); +{ + assume(false); // Same as `ArcInner_reassemble_to_array_at_lft` when `data` is uninitialized (`UniqueArcUninit`) +} + +lem ArcInner_split_from_array_at_lft(alloc_id: std::alloc::alloc_id_t, layout: std::alloc::Layout, ptr: *ArcInner) + req std::alloc::alloc_block_in(alloc_id, ptr as *u8, layout) &*& + array_at_lft_(alloc_id.lft, ptr as *u8, layout.size(), _) &*& + layout == std::alloc::Layout::for_value(ptr) &*& + (ptr as usize) != 0 &*& (ptr as usize) != usize::MAX; + ens ArcInner_backing::(alloc_id, layout, ptr) &*& + (*ptr).strong |-?-> _ &*& + (*ptr).weak |-?-> _ &*& + (*ptr).data |-?-> _ &*& + pointer_within_limits(&(*ptr).strong) == true &*& + pointer_within_limits(&(*ptr).weak) == true &*& + pointer_within_limits(&(*ptr).data) == true &*& + ptr_within_limits(ptr as pointer) == true &*& + ptr_within_limits(&(*ptr).data as pointer) == true; +{ + assume(false); // Inverse of `ArcInner_reassemble_to_array_at_lft`: raw layout split for `#[repr(C)] ArcInner` +} + +lem MaybeUninit_uninit_to_fbc(t: thread_id_t, p: *std::mem::MaybeUninit) + req *p |-?-> _; + ens (>.full_borrow_content)(t, p)(); +{ + std::mem::MaybeUninit__to_MaybeUninit::(p); + assert *p |-> ?v; + assume(false); // VeriFast prelude omits `close_MaybeUninit_own` (`MaybeUninit` has trivial validity invariant `true`) +} + +lem Slice_MaybeUninit_uninit_to_fbc(t: thread_id_t, p: *[std::mem::MaybeUninit]) + req *p |-?-> _; + ens (<[std::mem::MaybeUninit]>.full_borrow_content)(t, p)(); +{ + assume(false); // Unsized slice equivalent of `array__MaybeUninit_to_array_MaybeUninit` (`[MaybeUninit]` has trivial validity) +} + +// 6-state concurrent separation-logic invariant for `ArcInner`. +pred_ctor Arc_inv( + inv_gid: i32, + sgid: i32, + wgid: i32, + lock_gid: i32, + imp_gid: i32, + alloc_id: std::alloc::alloc_id_t, + layout: std::alloc::Layout, + owner_tid: thread_id_t, + ptr: *ArcInner +)() = + counting(dlft_pred, sgid, ?s_cnt, ?dk_opt) &*& + counting(weak_pred, wgid, ?w_cnt, ?dealloced) &*& + [1/2]ghost_cell::(inv_gid, ?mode) &*& + s_cnt >= 0 &*& w_cnt >= 0 &*& + match mode { + ModeShared(dk) => + [1/2]ghost_cell(inv_gid, ModeShared(dk)) &*& + dk_opt == some(dk) &*& + dealloced == false &*& + s_cnt >= 1 &*& s_cnt <= usize::MAX &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, s_cnt) &*& + shared_weak_lock(lock_gid, sgid, dk, ?locked) &*& + if locked { w_cnt == 0 &*& arc_atomic_cas::AtomicUsize(&(*ptr).weak, usize::MAX) } + else { w_cnt + 1 < usize::MAX &*& arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt + 1) } &*& + ghost_cell(imp_gid, 0) &*& + borrow_end_token(dk, .full_borrow_content(owner_tid, &(*ptr).data)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data) &*& + ArcInner_backing::(alloc_id, layout, ptr), + ModeExclusive => + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + w_cnt == 0 &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 1) &*& + ghost_cell::(lock_gid, LockFree) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, 1) &*& + ghost_cell(imp_gid, 0) &*& + ArcInner_backing::(alloc_id, layout, ptr), + ModeExclusiveLocked => + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + w_cnt == 0 &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 1) &*& + [1/2]ghost_cell::(lock_gid, LockExcl) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, usize::MAX) &*& + ghost_cell(imp_gid, 0) &*& + ArcInner_backing::(alloc_id, layout, ptr), + ModeDataOut => + // `strong == 0`, `weak == w_cnt + 1`, and the holder of `[1/2]ghost_cell(imp_gid, 1)` + // exclusively owns `(*ptr).data` (used by `Arc::drop` / `try_unwrap` / `UniqueArc` / `new_cyclic`). + [1/2]ghost_cell(inv_gid, ModeDataOut) &*& + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + ghost_cell::(lock_gid, LockFree) &*& + w_cnt + 1 < usize::MAX &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt + 1) &*& + [1/2]ghost_cell(imp_gid, 1) &*& + ArcInner_backing::(alloc_id, layout, ptr), + ModeDataDropped => + [1/2]ghost_cell(inv_gid, ModeDataDropped) &*& + dk_opt == none &*& + dealloced == false &*& + s_cnt == 0 &*& + w_cnt >= 1 &*& w_cnt < usize::MAX &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + ghost_cell::(lock_gid, LockFree) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt) &*& + ghost_cell(imp_gid, 2) &*& + (*ptr).data |-> _ &*& + ArcInner_backing::(alloc_id, layout, ptr), + ModeDealloced => + [1/2]ghost_cell(inv_gid, ModeDealloced) &*& + dk_opt == none &*& + dealloced == true &*& + s_cnt == 0 &*& + w_cnt == 0 &*& + ghost_cell::(lock_gid, LockFree) &*& + ghost_cell(imp_gid, 2), + }; + +// Persistent metadata shared by all `Arc`, `Weak`, and `UniqueArc` handles to the same `ArcInner`. +pred ArcInner_meta( + inv_gid: i32, + sgid: i32, + wgid: i32, + lock_gid: i32, + imp_gid: i32, + alloc_id: std::alloc::alloc_id_t, + layout: std::alloc::Layout, + owner_tid: thread_id_t, + ptr: *ArcInner; +) = + [_]atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr)) &*& + pointer_within_limits(&(*ptr).strong) == true &*& + pointer_within_limits(&(*ptr).weak) == true &*& + pointer_within_limits(&(*ptr).data) == true &*& + ptr_within_limits(ptr as pointer) == true &*& + ptr_within_limits(&(*ptr).data as pointer) == true &*& + (ptr as usize) != 0 &*& (ptr as usize) != usize::MAX &*& + layout == std::alloc::Layout::for_value(ptr); + +pred >.own(t, arc) = + [_]std::ptr::NonNull_own(default_tid, arc.ptr) &*& + [_]exists(?ptr) &*& arc.ptr.as_ptr() == ptr &*& + std::alloc::Allocator(t, arc.alloc, ?alloc_id) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + exists::(?exclusive) &*& + if exclusive { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(owner_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(?dk)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data) + }; + +pred Arc_own_in(t: thread_id_t, arc: Arc, alloc_id: std::alloc::alloc_id_t) = + [_]std::ptr::NonNull_own(default_tid, arc.ptr) &*& + [_]exists(?ptr) &*& arc.ptr.as_ptr() == ptr &*& + std::alloc::Allocator(t, arc.alloc, alloc_id) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + exists::(?exclusive) &*& + if exclusive { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(owner_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(?dk)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data) + }; + +lem Arc_own_in_to_own(t: thread_id_t, arc: Arc, alloc_id: std::alloc::alloc_id_t) + req Arc_own_in::(t, arc, alloc_id); + ens Arc_own::(t, arc); +{ + open Arc_own_in::(t, arc, alloc_id); + close Arc_own::(t, arc); +} + +pred_ctor Arc_ptr_bc(l: *Arc, nnp: std::ptr::NonNull>)(;) = + (*l).ptr |-> nnp &*& struct_Arc_padding(l); + +pred_ctor strong_ticket_(sgid: i32, dk: lifetime_t, frac: real)(;) = + ticket(dlft_pred, sgid, frac) &*& [frac]ghost_cell(sgid, some(dk)); + +pred >.share(k, t, l) = + [_]exists(?nnp) &*& + [_]frac_borrow(k, Arc_ptr_bc(l, nnp)) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + pointer_within_limits(&(*l).alloc) == true &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [_]exists(?dk) &*& [_]exists(?frac) &*& + [_]frac_borrow(k, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data); + +// --- Helper arithmetic & concurrent lifetime lemmas --- + +lem mod_eq_minus_one(x: i32, m: i32) + req 1 <= x &*& x <= m; + ens (x + m) % (m + 1) == x - 1; +{ + div_rem_nonneg(x + m, m + 1); + assert x + m == (x + m) / (m + 1) * (m + 1) + (x + m) % (m + 1); + if ((x + m) / (m + 1) < 1) {} else { + if ((x + m) / (m + 1) > 1) { + assert 2 <= (x + m) / (m + 1); + mul_mono_l(2, (x + m) / (m + 1), m + 1); + } else {} + } + assert (x + m) / (m + 1) == 1; +} + +lem mod_eq_plus_one(x: i32, m: i32) + req 0 <= x &*& x < m; + ens (x + 1) % (m + 1) == x + 1; +{ + div_rem_nonneg(x + 1, m + 1); + assert x + 1 == (x + 1) / (m + 1) * (m + 1) + (x + 1) % (m + 1); + if ((x + 1) / (m + 1) >= 1) { + mul_mono_l(1, (x + 1) / (m + 1), m + 1); + } else {} + assert (x + 1) / (m + 1) == 0; +} + +lem close_dlft_pred_some(sgid: i32, dk: lifetime_t) -> real + req [?q]ghost_cell(sgid, some(dk)) &*& [?q1]lifetime_token(dk); + ens [result]dlft_pred(sgid, some(dk)) &*& [q - result]ghost_cell(sgid, some(dk)) &*& [q1 - result]lifetime_token(dk) &*& 0 < result; +{ + lifetime_token_inv(dk); + ghost_cell_fraction_info(sgid); + let r = if q < q1 { q / 2 } else { q1 / 2 }; + close [r]dlft_pred(sgid, some(dk)); + return r; +} + +fix raw_to_arc_inner(ptr: *const T, offset: usize) -> *ArcInner { + (ptr_add(ptr as pointer, -offset) as *T) as *ArcInner +} + +// Concurrent separation-logic ownership of a raw `*const T` pointer obtained from +// `Arc::into_raw` / `Arc::into_raw_with_allocator`, tied to `alloc_id`. +pred Arc_raw_own(t: thread_id_t, ptr: *const T, alloc_id: std::alloc::alloc_id_t) = + is_power_of_2(std::mem::align_of_val(ptr)) == true &*& + std::mem::align_of_val(ptr) <= isize::MAX as usize &*& + arc_data_offset(std::mem::align_of_val(ptr)) <= isize::MAX as usize &*& + arc_data_offset(std::mem::align_of_val(ptr)) < (ptr as usize) &*& + ptr_within_limits(ptr as pointer) == true &*& + ptr_within_limits(ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr)))) == true &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ?arc_ptr) &*& + arc_ptr == raw_to_arc_inner::(ptr, arc_data_offset(std::mem::align_of_val(ptr))) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + exists::(?exclusive) &*& + if exclusive { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(owner_tid, &(*arc_ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(?dk)) &*& + [_](.share)(dk, owner_tid, &(*arc_ptr).data) + }; + +lem Arc_raw_own_facts(t: thread_id_t, ptr: *const T, alloc_id: std::alloc::alloc_id_t) + req Arc_raw_own::(t, ptr, alloc_id); + ens Arc_raw_own::(t, ptr, alloc_id) &*& + is_power_of_2(std::mem::align_of_val(ptr)) == true &*& + std::mem::align_of_val(ptr) <= isize::MAX as usize &*& + arc_data_offset(std::mem::align_of_val(ptr)) <= isize::MAX as usize &*& + arc_data_offset(std::mem::align_of_val(ptr)) < (ptr as usize) &*& + ptr_within_limits(ptr as pointer) == true &*& + ptr_within_limits(ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr)))) == true; +{ + open Arc_raw_own::(t, ptr, alloc_id); + close Arc_raw_own::(t, ptr, alloc_id); +} + +// Concurrent separation-logic ownership of a raw `*const T` pointer obtained from +// `Weak::into_raw` / `Weak::into_raw_with_allocator` (including dangling `usize::MAX`), tied to `alloc_id`. +pred Weak_raw_own(t: thread_id_t, ptr: *const T, alloc_id: std::alloc::alloc_id_t) = + ((ptr as usize) == usize::MAX || ( + is_power_of_2(std::mem::align_of_val(ptr)) == true && + std::mem::align_of_val(ptr) <= isize::MAX as usize && + arc_data_offset(std::mem::align_of_val(ptr)) <= isize::MAX as usize && + arc_data_offset(std::mem::align_of_val(ptr)) < (ptr as usize) && + ptr_within_limits(ptr as pointer) == true && + ptr_within_limits(ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr)))) == true + )) &*& + if (ptr as usize) == usize::MAX { + true + } else { + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ?arc_ptr) &*& + arc_ptr == raw_to_arc_inner::(ptr, arc_data_offset(std::mem::align_of_val(ptr))) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + exists::(?is_implicit) &*& + if is_implicit { + [1/2]ghost_cell(imp_gid, 1) &*& (*arc_ptr).data |-> _ + } else { + ticket(weak_pred, wgid, ?wfrac) &*& [wfrac]weak_pred(wgid, false) + } + }; + +// Helper predicates for `Arc::is_unique` and `Arc::get_mut` (matching `atomic_model/arc_weak_test.rs`). +pred UniqueState(inv_gid: i32, sgid: i32, lock_gid: i32, owner_tid: thread_id_t, ptr: *ArcInner, locked: bool, excl: bool) = + if locked { + if excl { + [1/2]ghost_cell(inv_gid, ModeExclusiveLocked) &*& + [1/2]ghost_cell::(lock_gid, LockExcl) &*& + ((.full_borrow_content)(owner_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + [frac]lifetime_token(?dk) &*& + [frac/2]ghost_cell(sgid, some(dk)) &*& + [1/2]ghost_cell::(lock_gid, LockShared(frac/2)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data) + } + } else { + if excl { + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(owner_tid, &(*ptr).data))() + } else { + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(?dk)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data) + } + }; + +pred ArcPtrFrac(qnnp: real) = true; + +pred SharedLockState(k: lifetime_t, sgid: i32, lock_gid: i32, dk: lifetime_t, frac: real, qs: real, locked: bool) = + [_]frac_borrow(k, strong_ticket_(sgid, dk, frac)) &*& + if locked { + close_frac_borrow_token(?qf, strong_ticket_(sgid, dk, frac), qs, k) &*& + [qf]ticket(dlft_pred, sgid, frac) &*& + [qf * frac / 2]ghost_cell(sgid, some(dk)) &*& + [1/2]ghost_cell::(lock_gid, LockShared(qf * frac / 2)) + } else { + [qs]lifetime_token(k) + }; + +pred Arc_is_unique_req(k: lifetime_t, t: thread_id_t, this: *Arc, owned: bool, qa: real) = + if owned { + (*this).ptr |-> ?nnp &*& + (*this).alloc |-> ?alloc &*& + struct_Arc_padding(this) &*& + Arc_own::(t, Arc:: { ptr: nnp, alloc }) + } else { + [qa]lifetime_token(k) &*& [_]Arc_share::(k, t, this) + }; + +pred Arc_is_unique_ens(k: lifetime_t, t: thread_id_t, this: *Arc, owned: bool, qa: real, res: bool) = + if owned { + (*this).ptr |-> ?nnp &*& + (*this).alloc |-> ?alloc &*& + struct_Arc_padding(this) &*& + if res { + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + std::alloc::Allocator(t, alloc, ?aid) &*& + [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr) &*& + (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [1/2]ghost_cell(ig, ModeExclusive) &*& + ((.full_borrow_content)(ot, &(*ptr).data))() + } else { + Arc_own::(t, Arc:: { ptr: nnp, alloc }) + } + } else { + [qa]lifetime_token(k) + }; + +lem Arc_is_shared_from_borrow(sgid: i32, dk: lifetime_t, frac: real) + req atomic_mask(?mask) &*& mask_le(Nlft, mask) == true &*& + counting(dlft_pred, sgid, ?s_cnt, ?dk_opt) &*& + [_]frac_borrow(?k, strong_ticket_(sgid, dk, frac)) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) &*& + [?q]lifetime_token(k); + ens atomic_mask(mask) &*& counting(dlft_pred, sgid, s_cnt, dk_opt) &*& + [q]lifetime_token(k) &*& dk_opt == some(dk); +{ + open_frac_borrow_m(k, strong_ticket_(sgid, dk, frac), q / 2); + open_frac_borrow_m(k, lifetime_token_(frac, dk), q / 2); + open [?qt]strong_ticket_(sgid, dk, frac)(); + open [?qdk]lifetime_token_(frac, dk)(); + let qp = close_dlft_pred_some(sgid, dk); + counting_match_fraction(dlft_pred, sgid); + open [qp]dlft_pred(sgid, some(dk)); + close [qdk]lifetime_token_(frac, dk)(); + close [qt]strong_ticket_(sgid, dk, frac)(); + close_frac_borrow_m(qdk, lifetime_token_(frac, dk)); + close_frac_borrow_m(qt, strong_ticket_(sgid, dk, frac)); +} + +// VeriFast's `rust_belt/general.rsspec` omits `: ?Sized` on `share_full_borrow_m`. +lem share_full_borrow_m_unsized(k: lifetime_t, t: thread_id_t, l: *_) + req type_interp::() &*& atomic_mask(MaskTop) &*& full_borrow(k, (.full_borrow_content)(t, l)) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(MaskTop) &*& [_](.share)(k, t, l) &*& [q]lifetime_token(k); +{ + assume(false); +} + +lem Arc_exclusive_to_shared( + inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, + alloc_id: std::alloc::alloc_id_t, layout: std::alloc::Layout, owner_tid: thread_id_t, ptr: *ArcInner +) + req type_interp::() &*& atomic_mask(MaskTop) &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr) &*& + [1/2]ghost_cell(inv_gid, ModeExclusive) &*& + ((.full_borrow_content)(owner_tid, &(*ptr).data))(); + ens type_interp::() &*& atomic_mask(MaskTop) &*& + [_]exists(?dk) &*& + ticket(dlft_pred, sgid, ?frac) &*& + [frac]dlft_pred(sgid, some(dk)) &*& + [_](.share)(dk, owner_tid, &(*ptr).data); +{ + open ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr); + let dk = begin_lifetime_m(); + borrow_m(dk, (.full_borrow_content)(owner_tid, &(*ptr).data)); + share_full_borrow_m_unsized::(dk, owner_tid, &(*ptr).data); + open_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr)); + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr)(); + ghost_cell_mutate(inv_gid, ModeShared(dk)); + stop_counting(dlft_pred, sgid); + open dlft_pred(sgid, none); + ghost_cell_mutate(sgid, some(dk)); + close dlft_pred(sgid, some(dk)); + start_counting(dlft_pred, sgid); + let frac = create_ticket(dlft_pred, sgid); + close shared_weak_lock(lock_gid, sgid, dk, false); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr)(); + close_atomic_space(Marc); + leak exists(dk); +} + +lem Arc_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Arc_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Arc_own::(t, Arc:: { ptr: upcast(v.ptr), alloc: upcast(v.alloc) }); +{ + assume(false); // VeriFast issue #610 (same as raw_vec.rs and tests/rust/safe_abstraction/arc.rs) +} + +lem Arc_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(Arc)) == true &*& + Arc_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& Arc_own::(t1, v); +{ + open Arc_own::(t0, v); + std::alloc::Allocator_send::(t1, v.alloc); + close Arc_own::(t1, v); +} + +lem Arc_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Arc) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]Arc_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]Arc_share::(k1, t, l); +{ + open Arc_share::(k, t, l); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ?alloc_id, ?layout, ?owner_tid, ptr) &*& + [_]exists::(?dk) &*& [_]exists::(?frac); + frac_borrow_mono(k, k1, Arc_ptr_bc(l, nnp)); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + frac_borrow_mono(k, k1, strong_ticket_(sgid, dk, frac)); + frac_borrow_mono(k, k1, lifetime_token_(frac, dk)); + close Arc_share::(k1, t, l); + leak Arc_share::(k1, t, l); +} + +// VeriFast 26.10 omits cross-trait `Send` bounds from auto-generated `is_Sync` axioms on +// `unsafe impl Sync for Arc`. +lem Arc_Sync_implies_T_Send_Sync() + req is_Sync(typeid(Arc)) == true; + ens is_Send(typeid(T)) == true &*& is_Sync(typeid(T)) == true &*& is_Send(typeid(A)) == true &*& is_Sync(typeid(A)) == true; +{ + assume(false); +} + +lem Arc_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(Arc)) == true &*& + [_]Arc_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& [_]Arc_share::(k, t1, l); +{ + Arc_Sync_implies_T_Send_Sync::(); + open Arc_share::(k, t0, l); + std::alloc::Allocator_sync::(t1); + close Arc_share::(k, t1, l); + leak Arc_share::(k, t1, l); +} + +lem Arc_share_full(k: lifetime_t, t: thread_id_t, l: *Arc) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + full_borrow(k, Arc_full_borrow_content::(t, l)); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]Arc_share::(k, t, l); +{ + let klong = open_full_borrow_strong_m(k, Arc_full_borrow_content::(t, l), q); + open Arc_full_borrow_content::(t, l)(); + open Arc_own::(t, ?arc); + let nnp = arc.ptr; + assert [_]exists::<*ArcInner>(?ptr) &*& + std::alloc::Allocator(t, arc.alloc, ?alloc_id) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr); + open exists::(?exclusive); + if exclusive { + Arc_exclusive_to_shared::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr); + } else {} + assert ticket(dlft_pred, sgid, ?frac) &*& [frac]dlft_pred(sgid, some(?dk)); + leak exists(dk); + open [frac]dlft_pred(sgid, some(dk)); + points_to_limits(&(*l).alloc); + close Arc_ptr_bc::(l, nnp)(); + std::alloc::close_Allocator_full_borrow_content_::(t, &(*l).alloc); + close strong_ticket_(sgid, dk, frac)(); + close lifetime_token_(frac, dk)(); + close sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))(); + close sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))(); + close sep(Arc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))))(); + { + pred Ctx() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [_]exists(dk) &*& + [_](.share)(dk, owner_tid, &(*ptr).data); + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(Arc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))), + klong, + Arc_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(Arc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))))(); + open Arc_ptr_bc::(l, nnp)(); + open sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))(); + open strong_ticket_(sgid, dk, frac)(); + open lifetime_token_(frac, dk)(); + close [frac]dlft_pred(sgid, some(dk)); + close exists(false); + close Arc_own::(t, *l); + close Arc_full_borrow_content::(t, l)(); + } { + close_full_borrow_strong_m( + klong, + Arc_full_borrow_content::(t, l), + sep(Arc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))) + ); + } + } + full_borrow_mono(klong, k, sep(Arc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))))); + full_borrow_split_m(k, Arc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk))); + full_borrow_split_m(k, strong_ticket_(sgid, dk, frac), lifetime_token_(frac, dk)); + full_borrow_into_frac_m(k, Arc_ptr_bc::(l, nnp)); + std::alloc::share_Allocator_full_borrow_content_m::(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(k, strong_ticket_(sgid, dk, frac)); + full_borrow_into_frac_m(k, lifetime_token_(frac, dk)); + leak exists(nnp); + leak exists(frac); + close Arc_share::(k, t, l); + leak Arc_share::(k, t, l); +} + +lem init_ref_Arc(p: *Arc) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& + [_]Arc_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& + [_]Arc_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + assume(false); // same as tests/rust/safe_abstraction/arc.rs:121 +} +@*/ + +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe + for Arc +{ +} + +#[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> for Arc {} + +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for Arc {} + +// SAFETY: `Arc::clone` doesn't access any `Cell`s which could contain the `Arc` being cloned. +#[unstable(feature = "cell_get_cloned", issue = "145329")] +unsafe impl CloneFromCell for Arc {} + +impl Arc { + unsafe fn from_inner(ptr: NonNull>) -> Self + //@ req true; + //@ ens result.ptr == ptr && result.alloc == std::alloc::Global {}; + //@ on_unwind_ens false; + { + // SAFETY: Upheld by caller. + unsafe { Self::from_inner_in(ptr, Global) } + } + + unsafe fn from_ptr(ptr: *mut ArcInner) -> Self + //@ req ptr as usize != 0; + //@ ens [_]std::ptr::NonNull_own(default_tid, result.ptr) &*& result.ptr == std::ptr::NonNull::new(ptr) && result.ptr.as_ptr() == ptr && result.alloc == std::alloc::Global {}; + //@ on_unwind_ens false; + { + // SAFETY: Upheld by caller. + unsafe { Self::from_ptr_in(ptr, Global) } + } +} + +impl Arc { + #[inline] + fn into_inner_with_allocator(this: Self) -> (NonNull>, A) + //@ req true; + //@ ens result.0 == this.ptr && result.1 == this.alloc; + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, this); + assert [_]exists::<*ArcInner>(?ptr) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open exists::(?ex); + if ex { leak [1/2]ghost_cell(ig, ModeExclusive) &*& ((.full_borrow_content)(ot, &(*ptr).data))(); } + else { leak ticket(dlft_pred, sg, ?f) &*& [f]dlft_pred(sg, some(_)); } + let result = call(); + std::alloc::Allocator_to_own(result.1); + close_NonNull_own_unsized(_t, result.0); + close_tuple_2_own::>, A>(_t, result); + } + @*/ + { + let me = mem::ManuallyDrop::new(this); + //@ let alloc_ref = precreate_ref(&me.alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + // SAFETY: Pointer is valid for reads. + let r = (me.ptr, unsafe { ptr::read(&me.alloc) }); + //@ end_ref_readonly(alloc_ref); + //@ close [1/2]Arc_alloc(&me, _); + r + } + + #[inline] + unsafe fn from_inner_in(ptr: NonNull>, alloc: A) -> Self + //@ req true; + //@ ens result.ptr == ptr && result.alloc == alloc; + //@ on_unwind_ens false; + { + Self { ptr, phantom: PhantomData, alloc } + } + + #[inline] + unsafe fn from_ptr_in(ptr: *mut ArcInner, alloc: A) -> Self + //@ req ptr as usize != 0; + //@ ens [_]std::ptr::NonNull_own(default_tid, result.ptr) &*& result.ptr == std::ptr::NonNull::new(ptr) && result.ptr.as_ptr() == ptr && result.alloc == alloc; + //@ on_unwind_ens false; + { + // SAFETY: Upheld by caller. + unsafe { Self::from_inner_in(NonNull_new_unchecked__VeriFast_wrapper(ptr), alloc) } + } +} + +unsafe fn NonNull_new_unchecked__VeriFast_wrapper(ptr: *mut T) -> NonNull +//@ req ptr as usize != 0; +//@ ens [_]std::ptr::NonNull_own(default_tid, result) &*& result == std::ptr::NonNull::new(ptr) && result.as_ptr() == ptr; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { NonNull::new_unchecked(ptr) } +} + +fn NonNull_as_ptr__VeriFast_wrapper(nn: NonNull) -> *mut T +//@ req true; +//@ ens result == nn.as_ptr(); +//@ on_unwind_ens false; +//@ safety_proof { leak >.own(_t, nn); call(); } +//@ assume_correct +{ + NonNull::as_ptr(nn) +} + +unsafe fn NonNull_ArcInner_data_ref__VeriFast_wrapper<'a, 'b, T: ?Sized>(nn: &'b NonNull>) -> &'a T +//@ req [?q](*nn) |-> ?v &*& pointer_within_limits(&(*v.as_ptr()).data) == true &*& [_](.share)(?k, ?t, &(*v.as_ptr()).data) &*& [?qk]lifetime_token(k); +//@ ens [q](*nn) |-> v &*& [qk]lifetime_token(k) &*& result == &(*v.as_ptr()).data &*& [_](.share)(k, t, result) &*& [_]ref_initialized(result); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { &nn.as_ref().data } +} + +/*@ +// std/lib.rsspec:612 declares `close_NonNull_own(t, v)` without `: ?Sized`; +// NonNull_own holds unconditionally for every NonNull regardless of whether T is Sized. +lem close_NonNull_own_unsized(t: thread_id_t, v: std::ptr::NonNull) + req true; + ens (std::ptr::NonNull_own::())(t, v); +{ + assume(false); +} + +// rust_belt/general.rsspec omits `: ?Sized` on close/open_full_borrow_content. +lem close_full_borrow_content_unsized(t: thread_id_t, l: *T) + req *l |-> ?v &*& (.own)(t, v); + ens (.full_borrow_content)(t, l)(); +{ + assume(false); +} + +lem open_full_borrow_content_unsized(t: thread_id_t, l: *T) + req (.full_borrow_content)(t, l)(); + ens *l |-> ?v &*& (.own)(t, v); +{ + assume(false); +} + +// rust_belt/general.rsspec omits `: ?Sized` on Send::send / Sync::sync / share_mono. +lem Send_send_unsized(t0: thread_id_t, t1: thread_id_t, v: T) + req type_interp::() &*& is_Send(typeid(T)) == true &*& (.own)(t0, v); + ens type_interp::() &*& (.own)(t1, v); +{ + assume(false); +} + +lem Sync_sync_unsized(k: lifetime_t, t0: thread_id_t, t1: thread_id_t, l: *T) + req type_interp::() &*& is_Sync(typeid(T)) == true &*& [_]((.share)(k, t0, l)); + ens type_interp::() &*& [_]((.share)(k, t1, l)); +{ + assume(false); +} + +lem share_mono_unsized(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *T) + req type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]((.share)(k, t, l)); + ens type_interp::() &*& [_]((.share)(k1, t, l)); +{ + assume(false); +} + +lem close_ref_mut_own_unsized<'a, T: ?Sized>(t: thread_id_t, l: *T) + req full_borrow('a, (.full_borrow_content)(t, l)); + ens <&'a mut T>.own(t, l); +{ + assume(false); +} + +// prelude.rsspec:40 provides close_tuple_0_own and close_tuple_4_own, omitting 2-tuples. +lem close_tuple_2_own(t: thread_id_t, v: (T1, T2)) + req .own(t, v.0) &*& .own(t, v.1); + ens <(T1, T2)>.own(t, v); +{ + assume(false); +} + +fix arc_data_offset(align: usize) -> usize { + if std::alloc::Layout::new::>().size() % align == 0 { + std::alloc::Layout::new::>().size() + } else { + std::alloc::Layout::new::>().size() + (align - std::alloc::Layout::new::>().size() % align) + } +} +@*/ + +unsafe fn Layout_padding_needed_for__VeriFast_wrapper<'a>(layout: &'a Layout, align: Alignment) -> usize +//@ req [?f](*layout |-> ?l) &*& std::alloc::is_valid_layout(l.size(), l.align()) == true &*& is_power_of_2(align.as_nonzero_usize().get()) == true; +/*@ +ens [f](*layout |-> l) &*& + result == if l.size() % align.as_nonzero_usize().get() == 0 { + 0 + } else { + align.as_nonzero_usize().get() - l.size() % align.as_nonzero_usize().get() + } &*& + l.size() + result <= usize::MAX; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + layout.padding_needed_for(align) +} + +unsafe fn Alignment_of_val_raw__VeriFast_wrapper(ptr: *const T) -> Alignment +//@ req is_power_of_2(std::mem::align_of_val(ptr)) == true &*& std::mem::align_of_val(ptr) <= isize::MAX as usize; +//@ ens result == std::mem::Alignment::new(std::mem::align_of_val(ptr)) &*& result.as_nonzero_usize().get() == std::mem::align_of_val(ptr); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { Alignment::of_val_raw(ptr) } +} + +unsafe fn ptr_byte_sub__VeriFast_wrapper(ptr: *const T, count: usize) -> *const T +//@ req count <= isize::MAX as usize &*& count <= (ptr as usize) &*& ptr_within_limits(ptr as pointer) == true &*& ptr_within_limits(ptr_add(ptr as pointer, -count)) == true; +//@ ens result == ptr_add(ptr as pointer, -count) as *T &*& (result as usize) == (ptr as usize) - count; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ptr.byte_sub(count) } +} + +unsafe fn ptr_byte_add__VeriFast_wrapper(ptr: *mut T, count: usize) -> *mut T +//@ req count <= isize::MAX as usize &*& (ptr as usize) + count <= usize::MAX &*& ptr_within_limits(ptr as pointer) == true &*& ptr_within_limits(ptr_add(ptr as pointer, count)) == true; +//@ ens result == ptr_add(ptr as pointer, count) as *T &*& (result as usize) == (ptr as usize) + count; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ptr.byte_add(count) } +} + +fn ptr_addr_eq__VeriFast_wrapper(p: *const T, q: *const U) -> bool +//@ req true; +//@ ens result == ((p as usize) == (q as usize)); +//@ on_unwind_ens false; +//@ assume_correct +{ + ptr::addr_eq(p, q) +} + +/*@ +fix arcinner_layout_for(layout: std::alloc::Layout) -> std::alloc::Layout; +fix arcinner_padded_layout(layout: std::alloc::Layout) -> std::alloc::Layout; + +lem_auto(arcinner_padded_layout(layout).size()) arcinner_padded_layout_size(layout: std::alloc::Layout) + req true; + ens arcinner_padded_layout(layout).size() >= 2 * std::mem::size_of::(); +{ + assume(false); // ArcInner starts with two AtomicUsize fields (`strong` and `weak`) +} + +lem pad_to_align_unique(l: std::alloc::Layout, r: std::alloc::Layout) + req r.align() == l.align() &*& if l.size() % l.align() == 0 { r.size() == l.size() } else { l.size() < r.size() }; + ens r == std::alloc::Layout::from_size_align(r.size(), r.align()); +{ + std::alloc::Layout_inv(r); +} +@*/ + +unsafe fn Layout_pad_to_align_arcinner__VeriFast_wrapper<'a>(layout: &'a Layout) -> Layout +//@ req [?f](*layout |-> ?l) &*& exists::(?vlayout) &*& l == arcinner_layout_for(vlayout); +//@ ens [f](*layout |-> l) &*& result == arcinner_padded_layout(vlayout); +//@ on_unwind_ens false; +//@ assume_correct +{ + layout.pad_to_align() +} + +unsafe fn Layout_array_unwrap__VeriFast_wrapper(n: usize) -> Layout +//@ req thread_token(?t); +//@ ens thread_token(t) &*& result == std::alloc::Layout::from_size_align(n * std::mem::size_of::(), std::mem::align_of::()) &*& std::alloc::is_valid_layout(result.size(), result.align()) == true; +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + Layout::array::(n).unwrap() +} + +unsafe fn ptr_cast_sized_arcinner__VeriFast_wrapper(mem: *mut u8) -> *mut ArcInner> +//@ req (mem as usize) != 0 && (mem as usize) != usize::MAX; +//@ ens result as *u8 == mem &*& (result as usize) != 0 && (result as usize) != usize::MAX &*& std::alloc::Layout::for_value(result) == arcinner_padded_layout(std::alloc::Layout::new::()); +//@ on_unwind_ens false; +//@ assume_correct +{ + mem.cast() +} + +unsafe fn ptr_cast_slice_arcinner__VeriFast_wrapper(mem: *mut u8, len: usize) -> *mut ArcInner<[T]> +//@ req (mem as usize) != 0 && (mem as usize) != usize::MAX; +//@ ens result as *u8 == mem &*& (result as usize) != 0 && (result as usize) != usize::MAX &*& std::alloc::Layout::for_value(result) == arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())); +//@ on_unwind_ens false; +//@ assume_correct +{ + mem.cast::().cast_slice(len) as *mut ArcInner<[T]> +} + +unsafe fn ptr_write_atomic__VeriFast_wrapper(dst: *mut atomic::AtomicUsize, val: atomic::AtomicUsize) +//@ req *dst |-?-> _; +//@ ens *dst |-> val; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { dst.write(val) } +} + +unsafe fn NonNull_slice_as_mut_ptr__VeriFast_wrapper(ptr: NonNull<[u8]>) -> *mut u8 +//@ req true; +//@ ens result == ptr.as_ptr() as *u8 &*& (result as usize) != 0; +//@ on_unwind_ens false; +//@ assume_correct +{ + ptr.as_non_null_ptr().as_ptr() +} + +unsafe fn Allocator_allocate__VeriFast_wrapper( + alloc: A, + layout: Layout, +) -> Result, AllocError> +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?alloc_id); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, alloc_id) &*& + match result { + Result::Ok(ptr) => + std::alloc::alloc_block_in(alloc_id, ptr.as_ptr() as *u8, layout) &*& + array_at_lft_(alloc_id.lft, ptr.as_ptr() as *u8, layout.size(), _) &*& + layout.size() <= ptr.len() &*& + std::alloc::is_valid_layout(ptr.len(), layout.align()) == true, + Result::Err(e) => .own(t, e), + }; +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, alloc_id); +//@ assume_correct +{ + alloc.allocate(layout) +} + +unsafe fn Allocator_allocate_zeroed__VeriFast_wrapper( + alloc: A, + layout: Layout, +) -> Result, AllocError> +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?alloc_id); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, alloc_id) &*& + match result { + Result::Ok(ptr) => + std::alloc::alloc_block_in(alloc_id, ptr.as_ptr() as *u8, layout) &*& + array_at_lft(alloc_id.lft, ptr.as_ptr() as *u8, layout.size(), ?bs) &*& forall(bs, (eq)(0)) == true &*& + layout.size() <= ptr.len() &*& + std::alloc::is_valid_layout(ptr.len(), layout.align()) == true, + Result::Err(e) => .own(t, e), + }; +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, alloc_id); +//@ assume_correct +{ + alloc.allocate_zeroed(layout) +} + +unsafe fn Arc_try_alloc_uninit_in__VeriFast_wrapper( + alloc: A, + zeroed: bool, +) -> Result<*mut ArcInner>, AllocError> +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?aid); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid) &*& + match result { + Result::Ok(inner) => + ArcInner_backing::>(aid, arcinner_padded_layout(std::alloc::Layout::new::()), inner) &*& + arc_atomic_cas::AtomicUsize(&(*inner).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*inner).weak, 1) &*& + (*inner).data |-?-> _ &*& + pointer_within_limits(&(*inner).strong) == true &*& + pointer_within_limits(&(*inner).weak) == true &*& + pointer_within_limits(&(*inner).data) == true &*& + ptr_within_limits(inner as pointer) == true &*& + ptr_within_limits(&(*inner).data as pointer) == true &*& + (inner as usize) != 0 &*& (inner as usize) != usize::MAX &*& + arcinner_padded_layout(std::alloc::Layout::new::()) == std::alloc::Layout::for_value(inner), + Result::Err(e) => .own(t, e), + }; +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +{ + let layout = arcinner_layout_for_value_layout(Layout::new::()); + let ptr = if zeroed { + match unsafe { Allocator_allocate_zeroed__VeriFast_wrapper(alloc, layout) } { + Ok(p) => { + //@ array_at_lft_to_array_at_lft_::(p.as_ptr() as *u8); + p + } + Err(e) => return Err(e), + } + } else { + match unsafe { Allocator_allocate__VeriFast_wrapper(alloc, layout) } { + Ok(p) => p, + Err(e) => return Err(e), + } + }; + let mem_ptr = unsafe { NonNull_slice_as_mut_ptr__VeriFast_wrapper(ptr) }; + let inner = unsafe { ptr_cast_sized_arcinner__VeriFast_wrapper::(mem_ptr) }; + //@ ArcInner_split_from_array_at_lft::>(aid, layout, inner); + unsafe { + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).strong, atomic::AtomicUsize::new(1)); + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).weak, atomic::AtomicUsize::new(1)); + } + //@ close arc_atomic_cas::AtomicUsize(&(*inner).strong, 1); + //@ close arc_atomic_cas::AtomicUsize(&(*inner).weak, 1); + Ok(inner) +} + +unsafe fn Arc_alloc_uninit_in__VeriFast_wrapper( + alloc: A, + zeroed: bool, +) -> *mut ArcInner> +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?aid); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid) &*& + ArcInner_backing::>(aid, arcinner_padded_layout(std::alloc::Layout::new::()), result) &*& + arc_atomic_cas::AtomicUsize(&(*result).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*result).weak, 1) &*& + (*result).data |-?-> _ &*& + pointer_within_limits(&(*result).strong) == true &*& + pointer_within_limits(&(*result).weak) == true &*& + pointer_within_limits(&(*result).data) == true &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(&(*result).data as pointer) == true &*& + (result as usize) != 0 &*& (result as usize) != usize::MAX &*& + arcinner_padded_layout(std::alloc::Layout::new::()) == std::alloc::Layout::for_value(result); +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +{ + let layout = arcinner_layout_for_value_layout(Layout::new::()); + let ptr = if zeroed { + match unsafe { Allocator_allocate_zeroed__VeriFast_wrapper(alloc, layout) } { + Ok(p) => { + //@ array_at_lft_to_array_at_lft_::(p.as_ptr() as *u8); + p + } + Err(_) => handle_alloc_error(layout), + } + } else { + match unsafe { Allocator_allocate__VeriFast_wrapper(alloc, layout) } { + Ok(p) => p, + Err(_) => handle_alloc_error(layout), + } + }; + let mem_ptr = unsafe { NonNull_slice_as_mut_ptr__VeriFast_wrapper(ptr) }; + let inner = unsafe { ptr_cast_sized_arcinner__VeriFast_wrapper::(mem_ptr) }; + //@ ArcInner_split_from_array_at_lft::>(aid, layout, inner); + unsafe { + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).strong, atomic::AtomicUsize::new(1)); + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).weak, atomic::AtomicUsize::new(1)); + } + //@ close arc_atomic_cas::AtomicUsize(&(*inner).strong, 1); + //@ close arc_atomic_cas::AtomicUsize(&(*inner).weak, 1); + inner +} + +unsafe fn Arc_alloc_slice_in__VeriFast_wrapper( + len: usize, + alloc: A, + zeroed: bool, +) -> *mut ArcInner<[T]> +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?aid); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid) &*& + ArcInner_backing::<[T]>(aid, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())), result) &*& + arc_atomic_cas::AtomicUsize(&(*result).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*result).weak, 1) &*& + (*result).data |-?-> _ &*& + pointer_within_limits(&(*result).strong) == true &*& + pointer_within_limits(&(*result).weak) == true &*& + pointer_within_limits(&(*result).data) == true &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(&(*result).data as pointer) == true &*& + (result as usize) != 0 &*& (result as usize) != usize::MAX &*& + arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())) == std::alloc::Layout::for_value(result); +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +{ + let val_layout = unsafe { Layout_array_unwrap__VeriFast_wrapper::(len) }; + let layout = arcinner_layout_for_value_layout(val_layout); + let ptr = if zeroed { + match unsafe { Allocator_allocate_zeroed__VeriFast_wrapper(alloc, layout) } { + Ok(p) => { + //@ array_at_lft_to_array_at_lft_::(p.as_ptr() as *u8); + p + } + Err(_) => handle_alloc_error(layout), + } + } else { + match unsafe { Allocator_allocate__VeriFast_wrapper(alloc, layout) } { + Ok(p) => p, + Err(_) => handle_alloc_error(layout), + } + }; + let mem_ptr = unsafe { NonNull_slice_as_mut_ptr__VeriFast_wrapper(ptr) }; + let inner = unsafe { ptr_cast_slice_arcinner__VeriFast_wrapper::(mem_ptr, len) }; + //@ ArcInner_split_from_array_at_lft::<[T]>(aid, layout, inner); + unsafe { + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).strong, atomic::AtomicUsize::new(1)); + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).weak, atomic::AtomicUsize::new(1)); + } + //@ close arc_atomic_cas::AtomicUsize(&(*inner).strong, 1); + //@ close arc_atomic_cas::AtomicUsize(&(*inner).weak, 1); + inner +} + +/*@ +// Unforgeable witness that `ptr` carries valid metadata for an existing value of type `T` +// whose layout is `lay == Layout::for_value(ptr)`. Only produced from a live `&T` or `Box`. +pred ValidValueMetadata(ptr: *T, lay: std::alloc::Layout); +@*/ + +unsafe fn Layout_for_value_ref__VeriFast_wrapper<'a, T: ?Sized>(val: &'a T) -> Layout +//@ req [_](.share)(?k, ?t, val) &*& [?qa]lifetime_token(k); +//@ ens [qa]lifetime_token(k) &*& result == std::alloc::Layout::for_value(val) &*& [_]ValidValueMetadata::(val, result); +//@ on_unwind_ens false; +//@ assume_correct +{ + Layout::for_value(val) +} + +unsafe fn Layout_for_value_ptr__VeriFast_wrapper(ptr: *const T) -> Layout +//@ req [_]ValidValueMetadata::(ptr, ?vlay); +//@ ens result == vlay &*& result == std::alloc::Layout::for_value(ptr); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { Layout::for_value_raw(ptr) } +} + +unsafe fn NonNull_new_unwrap__VeriFast_wrapper(ptr: *mut T) -> NonNull +//@ req (ptr as usize) != 0; +//@ ens [_]std::ptr::NonNull_own(default_tid, result) &*& result == std::ptr::NonNull::new(ptr) && result.as_ptr() == ptr; +//@ on_unwind_ens false; +//@ assume_correct +{ + NonNull::new(ptr).unwrap() +} + +unsafe fn ptr_with_metadata_of_arcinner__VeriFast_wrapper( + mem: *mut u8, + meta: *const ArcInner, +) -> *mut ArcInner +/*@ +req (mem as usize) != 0 && (mem as usize) != usize::MAX &*& + [_]ValidValueMetadata::(?for_val, ?vlay) &*& + meta == for_val as *ArcInner &*& + std::alloc::alloc_block_in(?aid, mem, arcinner_padded_layout(vlay)) &*& + array_at_lft_(aid.lft, mem, arcinner_padded_layout(vlay).size(), ?bs); +@*/ +/*@ +ens std::alloc::alloc_block_in(aid, mem, arcinner_padded_layout(vlay)) &*& + array_at_lft_(aid.lft, mem, arcinner_padded_layout(vlay).size(), bs) &*& + result as *u8 == mem &*& + (result as usize) != 0 && (result as usize) != usize::MAX &*& + std::alloc::Layout::for_value(result) == arcinner_padded_layout(vlay) &*& + arc_data_offset(vlay.align()) <= isize::MAX as usize &*& + (result as usize) + arc_data_offset(vlay.align()) <= usize::MAX &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(ptr_add(result as pointer, arc_data_offset(vlay.align()))) == true; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + mem.with_metadata_of(meta) +} + +unsafe fn Arc_alloc_for_val_in__VeriFast_wrapper( + for_value: *const T, + val_layout: Layout, + alloc: A, +) -> *mut ArcInner +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?aid) &*& [_]ValidValueMetadata::(for_value, val_layout); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid) &*& + ArcInner_backing::(aid, arcinner_padded_layout(val_layout), result) &*& + arc_atomic_cas::AtomicUsize(&(*result).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*result).weak, 1) &*& + (*result).data |-?-> _ &*& + pointer_within_limits(&(*result).strong) == true &*& + pointer_within_limits(&(*result).weak) == true &*& + pointer_within_limits(&(*result).data) == true &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(&(*result).data as pointer) == true &*& + (result as usize) != 0 &*& (result as usize) != usize::MAX &*& + arcinner_padded_layout(val_layout) == std::alloc::Layout::for_value(result) &*& + arc_data_offset(val_layout.align()) <= isize::MAX as usize &*& + (result as usize) + arc_data_offset(val_layout.align()) <= usize::MAX &*& + ptr_within_limits(ptr_add(result as pointer, arc_data_offset(val_layout.align()))) == true; +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +{ + let layout = arcinner_layout_for_value_layout(val_layout); + let ptr = match unsafe { Allocator_allocate__VeriFast_wrapper(alloc, layout) } { + Ok(p) => p, + Err(_) => handle_alloc_error(layout), + }; + let mem_ptr = unsafe { NonNull_slice_as_mut_ptr__VeriFast_wrapper(ptr) }; + let inner = unsafe { ptr_with_metadata_of_arcinner__VeriFast_wrapper::(mem_ptr, for_value as *const ArcInner) }; + //@ ArcInner_split_from_array_at_lft::(aid, layout, inner); + unsafe { + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).strong, atomic::AtomicUsize::new(1)); + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).weak, atomic::AtomicUsize::new(1)); + } + //@ close arc_atomic_cas::AtomicUsize(&(*inner).strong, 1); + //@ close arc_atomic_cas::AtomicUsize(&(*inner).weak, 1); + inner +} + +unsafe fn Arc_try_alloc_for_val_in__VeriFast_wrapper( + for_value: *const T, + val_layout: Layout, + alloc: A, +) -> Result<*mut ArcInner, AllocError> +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?aid) &*& [_]ValidValueMetadata::(for_value, val_layout); +/*@ +ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid) &*& + match result { + Result::Ok(inner) => + ArcInner_backing::(aid, arcinner_padded_layout(val_layout), inner) &*& + arc_atomic_cas::AtomicUsize(&(*inner).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*inner).weak, 1) &*& + (*inner).data |-?-> _ &*& + pointer_within_limits(&(*inner).strong) == true &*& + pointer_within_limits(&(*inner).weak) == true &*& + pointer_within_limits(&(*inner).data) == true &*& + ptr_within_limits(inner as pointer) == true &*& + ptr_within_limits(&(*inner).data as pointer) == true &*& + (inner as usize) != 0 &*& (inner as usize) != usize::MAX &*& + arcinner_padded_layout(val_layout) == std::alloc::Layout::for_value(inner) &*& + arc_data_offset(val_layout.align()) <= isize::MAX as usize &*& + (inner as usize) + arc_data_offset(val_layout.align()) <= usize::MAX &*& + ptr_within_limits(ptr_add(inner as pointer, arc_data_offset(val_layout.align()))) == true, + Result::Err(e) => .own(t, e), + }; +@*/ +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +{ + let layout = arcinner_layout_for_value_layout(val_layout); + let ptr = match unsafe { Allocator_allocate__VeriFast_wrapper(alloc, layout) } { + Ok(p) => p, + Err(e) => return Err(e), + }; + let mem_ptr = unsafe { NonNull_slice_as_mut_ptr__VeriFast_wrapper(ptr) }; + let inner = unsafe { ptr_with_metadata_of_arcinner__VeriFast_wrapper::(mem_ptr, for_value as *const ArcInner) }; + //@ ArcInner_split_from_array_at_lft::(aid, layout, inner); + unsafe { + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).strong, atomic::AtomicUsize::new(1)); + ptr_write_atomic__VeriFast_wrapper(&raw mut (*inner).weak, atomic::AtomicUsize::new(1)); + } + //@ close arc_atomic_cas::AtomicUsize(&(*inner).strong, 1); + //@ close arc_atomic_cas::AtomicUsize(&(*inner).weak, 1); + Ok(inner) +} + +/*@ +pred Vec_shell(aid: std::alloc::alloc_id_t, ptr: *T, cap: usize); +pred Box_shell(aid: std::alloc::alloc_id_t, ptr: *T); +@*/ + +unsafe fn Vec_into_raw_parts_with_allocator__VeriFast_wrapper( + v: Vec, +) -> (*mut T, usize, usize, A) +//@ req thread_token(?t) &*& >.own(t, v); +/*@ +ens thread_token(t) &*& + std::alloc::Allocator(t, result.3, ?aid) &*& + Vec_shell::(aid, result.0, result.2) &*& + result.0[..result.1] |-> ?elems &*& + foreach(elems, own::(t)); +@*/ +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + v.into_raw_parts_with_allocator() +} + +unsafe fn ptr_copy_elems_to_arcinner_slice__VeriFast_wrapper( + src: *const T, + dst: *mut T, + len: usize, +) +//@ req exists::(?t) &*& exists::<*[T]>(?dst_slice) &*& dst_slice as *T == dst &*& src[..len] |-> ?elems &*& foreach(elems, own::(t)) &*& *dst_slice |-?-> _; +//@ ens src[..len] |-?-> _ &*& (<[T]>.full_borrow_content)(t, dst_slice)(); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ptr::copy_nonoverlapping(src, dst, len) } +} + +unsafe fn Vec_drop_empty_in__VeriFast_wrapper( + ptr: *mut T, + cap: usize, + alloc: A, +) +//@ req thread_token(?t) &*& std::alloc::Allocator::(t, alloc, ?aid) &*& Vec_shell::(aid, ptr, cap) &*& ptr[.._] |-?-> _; +//@ ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +//@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::(t, alloc, aid); +//@ assume_correct +{ + let _ = unsafe { Vec::from_raw_parts_in(ptr, 0, cap, alloc) }; +} + +/*@ +// Unforgeable witness that `T: TrivialClone`. Only produced by the Rust-type-checked +// `TrivialClone_slice_identity__VeriFast_wrapper`. +pred TrivialClone_witness(); +@*/ + +unsafe fn TrivialClone_slice_identity__VeriFast_wrapper<'a, T: TrivialClone>(v: &'a [T]) -> &'a [T] +//@ req true; +//@ ens result == v &*& TrivialClone_witness::(); +//@ on_unwind_ens false; +//@ assume_correct +{ + v +} + +unsafe fn ptr_copy_shared_slice_to_arcinner__VeriFast_wrapper( + src: *const T, + dst: *mut T, + len: usize, +) +//@ req TrivialClone_witness::() &*& exists::<*[T]>(?src_slice) &*& src == src_slice as *T &*& [_](<[T]>.share)(?k, ?t, src_slice) &*& [?qa]lifetime_token(k) &*& exists::<*[T]>(?dst_slice) &*& dst_slice as *T == dst &*& len == src_slice.len() &*& *dst_slice |-?-> _; +//@ ens [qa]lifetime_token(k) &*& (<[T]>.full_borrow_content)(t, dst_slice)(); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ptr::copy_nonoverlapping(src, dst, len) } +} + +/*@ +pred Box_unpacked(t: thread_id_t, bptr: *T, aid: std::alloc::alloc_id_t); +@*/ + +unsafe fn Box_size_of_val__VeriFast_wrapper<'a, T: ?Sized, A: Allocator>( + src: &'a Box, +) -> usize +//@ req thread_token(?t) &*& *src |-> ?b &*& >.own(t, b); +//@ ens thread_token(t) &*& *src |-> b &*& Box_unpacked::(t, ?bptr, ?aid) &*& [_]ValidValueMetadata::(bptr, std::alloc::Layout::for_value(bptr)) &*& result == std::mem::size_of_val(bptr); +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + size_of_val(&**src) +} + +unsafe fn Box_deref_const__VeriFast_wrapper<'a, T: ?Sized, A: Allocator>( + src: &'a Box, +) -> &'a T +//@ req *src |-> ?b &*& Box_unpacked::(?t, ?bptr, ?aid); +//@ ens *src |-> b &*& Box_unpacked::(t, bptr, aid) &*& result == bptr; +//@ on_unwind_ens false; +//@ assume_correct +{ + &**src +} + +unsafe fn Box_allocator_ref__VeriFast_wrapper<'a, T: ?Sized, A: Allocator>( + src: &'a Box, +) -> &'a A +//@ req *src |-> ?b &*& Box_unpacked::(?t, ?bptr, ?aid); +//@ ens *src |-> b &*& Box_shell::(aid, bptr) &*& ((.full_borrow_content)(t, bptr))() &*& std::alloc::Allocator::<&'a A>(t, result, aid); +//@ on_unwind_ens false; +//@ assume_correct +{ + Box::allocator(src) +} + +unsafe fn Box_data_ptr_u8__VeriFast_wrapper<'a, T: ?Sized, A: Allocator>( + src: &'a Box, +) -> *const u8 +//@ req *src |-> ?b &*& Box_shell::(?aid, ?bptr); +//@ ens *src |-> b &*& Box_shell::(aid, bptr) &*& result == bptr as *u8; +//@ on_unwind_ens false; +//@ assume_correct +{ + (&raw const **src) as *const u8 +} + +unsafe fn ptr_copy_unsized_data__VeriFast_wrapper( + src: *const u8, + dst: *mut u8, + size: usize, +) +//@ req exists::(?t) &*& exists::<*T>(?src_t) &*& exists::<*T>(?dst_t) &*& src == src_t as *u8 &*& dst == dst_t as *u8 &*& size == std::mem::size_of_val(src_t) &*& ((.full_borrow_content)(t, src_t))() &*& *dst_t |-?-> _; +//@ ens *src_t |-?-> _ &*& ((.full_borrow_content)(t, dst_t))(); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { ptr::copy_nonoverlapping(src, dst, size) } +} + +unsafe fn Box_free_moved_unsized__VeriFast_wrapper( + src: Box, +) -> A +//@ req thread_token(?t) &*& Box_shell::(?aid, ?bptr) &*& *bptr |-?-> _; +//@ ens thread_token(t) &*& std::alloc::Allocator(t, result, aid); +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + let (bptr, alloc) = Box::into_raw_with_allocator(src); + let src = unsafe { Box::from_raw_in(bptr as *mut mem::ManuallyDrop, &alloc) }; + drop(src); + alloc +} + +unsafe fn Layout_extend__VeriFast_wrapper<'a>(layout: &'a Layout, next: Layout) -> Result<(Layout, usize), core::alloc::LayoutError> +//@ req [?f](*layout |-> ?l); +/*@ +ens [f](*layout |-> l) &*& + match result { + Result::Ok(p) => if l == std::alloc::Layout::new::>() { p.0 == arcinner_layout_for(next) } else { true }, + Result::Err(e) => true + }; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + layout.extend(next) +} + +const unsafe fn NonNull_without_provenance_MAX__VeriFast_wrapper() -> NonNull +//@ req true; +//@ ens result.as_ptr() as usize == usize::MAX; +//@ on_unwind_ens false; +//@ assume_correct +{ + NonNull::without_provenance(NonZeroUsize::MAX) +} + +unsafe fn Allocator_deallocate_owned__VeriFast_wrapper( + alloc: A, + ptr: NonNull, + layout: Layout, +) +//@ req thread_token(?t) &*& std::alloc::Allocator(t, alloc, ?alloc_id) &*& std::alloc::alloc_block_in(alloc_id, ptr.as_ptr(), layout) &*& array_at_lft_(alloc_id.lft, ptr.as_ptr(), layout.size(), _); +//@ ens thread_token(t); +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + alloc.deallocate(ptr, layout) +} + +unsafe fn Box_into_non_null__VeriFast_wrapper(b: Box) -> NonNull +//@ req std::boxed::Box::(b, ?value); +/*@ +ens points_to_at_lft(std::alloc::Global_alloc_id.lft, result.as_ptr(), value) &*& + std::alloc::alloc_block_in(std::alloc::Global_alloc_id, result.as_ptr() as *u8, std::alloc::Layout::new::()) &*& + result.as_ptr() as usize != 0; +@*/ +//@ on_unwind_ens false; +//@ assume_correct +{ + Box::into_non_null(b) +} + +unsafe fn Box_try_new__VeriFast_wrapper(x: ArcInner) -> Result>, AllocError> +//@ req thread_token(?t) &*& .own(t, x.data); +/*@ +ens thread_token(t) &*& + match result { + Result::Ok(b) => std::boxed::Box::>(b, x) &*& .own(t, x.data), + Result::Err(e) => .own(t, e), + }; +@*/ +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + Box::try_new(x) +} + +unsafe fn Box_try_new_in__VeriFast_wrapper(x: ArcInner, alloc: A) -> Result, A>, AllocError> +//@ req thread_token(?t) &*& std::alloc::Allocator(t, alloc, ?alloc_id) &*& .own(t, x.data); +/*@ +ens thread_token(t) &*& + match result { + Result::Ok(b) => std::boxed::Box_in::, A>(t, b, alloc_id, x) &*& .own(t, x.data), + Result::Err(e) => .own(t, e), + }; +@*/ +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + Box::try_new_in(x, alloc) +} + +unsafe fn Box_new_uninit__VeriFast_wrapper() -> Box> +//@ req thread_token(?t); +//@ ens thread_token(t) &*& std::boxed::Box::>(result, _); +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + Box::new_uninit() +} + +unsafe fn Box_write__VeriFast_wrapper(boxed: Box>, value: T) -> Box +//@ req std::boxed::Box::>(boxed, _); +//@ ens std::boxed::Box::(result, value); +//@ on_unwind_ens false; +//@ assume_correct +{ + Box::write(boxed, value) +} + +fn Default_default__VeriFast_wrapper() -> T +//@ req thread_token(?t); +//@ ens thread_token(t) &*& .own(t, result); +//@ on_unwind_ens thread_token(t); +//@ assume_correct +{ + T::default() +} + +unsafe fn NonNull_as_ref_ArcInner__VeriFast_wrapper<'a, 'b, T: ?Sized>(nn: &'b NonNull>) -> &'a ArcInner +//@ req [?q](*nn) |-> ?v &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, v.as_ptr()); +//@ ens [q](*nn) |-> v &*& result == v.as_ptr(); +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { nn.as_ref() } +} + +unsafe fn Layout_for_value_raw__VeriFast_wrapper(ptr: *const T) -> Layout +//@ req std::alloc::alloc_block_in(?aid, ptr as *u8, ?lay) &*& lay == std::alloc::Layout::for_value(ptr); +//@ ens std::alloc::alloc_block_in(aid, ptr as *u8, lay) &*& result == lay; +//@ on_unwind_ens false; +//@ assume_correct +{ + unsafe { Layout::for_value_raw(ptr) } +} + +unsafe fn ManuallyDrop_clone_Arc__VeriFast_wrapper<'a, T: ?Sized, A: AllocatorClone>(arc: &'a ManuallyDrop>) -> ManuallyDrop> +//@ req thread_token(?t) &*& exists::>>(?nnp) &*& [_]Arc_share::(?k, t, arc as *Arc) &*& [?qa]lifetime_token(k) &*& [_]frac_borrow(k, Arc_ptr_bc(arc as *Arc, nnp)) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, nnp.as_ptr()) &*& (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)); +//@ ens thread_token(t) &*& [qa]lifetime_token(k) &*& ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)) &*& [_](.share)(dk, ot, &(*nnp.as_ptr()).data); +//@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token(k); +//@ assume_correct +{ + arc.clone() +} + +unsafe fn Allocator_clone_from_share__VeriFast_wrapper<'a, A: AllocatorClone>(alloc: &'a A) -> A +//@ req thread_token(?t) &*& [_]std::alloc::Allocator_share(?k, t, alloc, ?alloc_id) &*& [?qa]lifetime_token(k); +//@ ens thread_token(t) &*& [qa]lifetime_token(k) &*& std::alloc::Allocator(t, result, alloc_id); +//@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token(k); +//@ assume_correct +{ + alloc.clone() +} + +/*@ +fix load_any(r: usize) -> bool { true } +fix load_ge_one(r: usize) -> bool { r >= 1 } +@*/ + +/*@ +// Helper lemma: builds polymorphic `ArcInner_backing` + `Arc_inv` + `ArcInner_meta` +// and produces `Arc_own` from a freshly allocated `Box, A>` (`strong == 1, weak == 1`). +lem init_Arc_from_box_in( + t: thread_id_t, + nnp: std::ptr::NonNull>, + alloc: A, + alloc_id: std::alloc::alloc_id_t +) + req points_to_at_lft(alloc_id.lft, nnp.as_ptr(), ?inner) &*& + inner.strong.inner() == 1 &*& inner.weak.inner() == 1 &*& + .own(t, inner.data) &*& + std::alloc::alloc_block_in(alloc_id, nnp.as_ptr() as *u8, std::alloc::Layout::new::>()) &*& + std::alloc::Allocator(t, alloc, alloc_id) &*& + nnp.as_ptr() as usize != 0; + ens Arc_own::(t, Arc:: { ptr: nnp, alloc: alloc }); +{ + assume(alloc_id.lft == 'static); // same as linked_list.rs:2212 (Global/System allocators are 'static) + produce_lifetime_token_static(); + assert [?qstatic]lifetime_token('static); + let ptr = nnp.as_ptr(); + open_points_to_at_lft(ptr, qstatic); + points_to_limits(ptr); + open_points_to(ptr); + points_to_limits(&(*ptr).strong); + points_to_limits(&(*ptr).weak); + points_to_limits(&(*ptr).data); + close arc_atomic_cas::AtomicUsize(&(*ptr).strong, 1); + close arc_atomic_cas::AtomicUsize(&(*ptr).weak, 1); + close_full_borrow_content::(t, &(*ptr).data); + let layout = std::alloc::Layout::new::>(); + ArcInner_sized_to_padding_at_lft::(alloc_id.lft, ptr, qstatic); + close ArcInner_backing::(alloc_id, layout, ptr); + let inv_gid = create_ghost_cell(ModeExclusive); + let sgid = create_ghost_cell(none); + close dlft_pred(sgid, none); + start_counting(dlft_pred, sgid); + let wgid = create_ghost_cell(false); + close weak_pred(wgid, false); + start_counting(weak_pred, wgid); + let lock_gid = create_ghost_cell::(LockFree); + let imp_gid = create_ghost_cell(0); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)(); + create_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)); + leak atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)); + std::ptr::NonNull_Sized_as_ptr(nnp); + std::alloc::Layout_inv(layout); + close ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr); + leak ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr); + leak exists(ptr); + std::ptr::close_NonNull_own::>()(default_tid, nnp); + leak std::ptr::NonNull_own::>()(default_tid, nnp); + close exists(true); + close Arc_own::(t, Arc:: { ptr: nnp, alloc: alloc }); +} + +lem init_Arc_from_raw_parts_in( + t: thread_id_t, + nnp: std::ptr::NonNull>, + alloc: A, + alloc_id: std::alloc::alloc_id_t, + layout: std::alloc::Layout +) + req [_]std::ptr::NonNull_own(default_tid, nnp) &*& + ArcInner_backing::(alloc_id, layout, nnp.as_ptr()) &*& + arc_atomic_cas::AtomicUsize(&(*nnp.as_ptr()).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*nnp.as_ptr()).weak, 1) &*& + ((.full_borrow_content)(t, &(*nnp.as_ptr()).data))() &*& + std::alloc::Allocator(t, alloc, alloc_id) &*& + pointer_within_limits(&(*nnp.as_ptr()).strong) == true &*& + pointer_within_limits(&(*nnp.as_ptr()).weak) == true &*& + pointer_within_limits(&(*nnp.as_ptr()).data) == true &*& + ptr_within_limits(nnp.as_ptr() as pointer) == true &*& + ptr_within_limits(&(*nnp.as_ptr()).data as pointer) == true &*& + (nnp.as_ptr() as usize) != 0 &*& (nnp.as_ptr() as usize) != usize::MAX &*& + layout == std::alloc::Layout::for_value(nnp.as_ptr()); + ens Arc_own::(t, Arc:: { ptr: nnp, alloc: alloc }); +{ + let ptr = nnp.as_ptr(); + let inv_gid = create_ghost_cell(ModeExclusive); + let sgid = create_ghost_cell(none); + close dlft_pred(sgid, none); + start_counting(dlft_pred, sgid); + let wgid = create_ghost_cell(false); + close weak_pred(wgid, false); + start_counting(weak_pred, wgid); + let lock_gid = create_ghost_cell::(LockFree); + let imp_gid = create_ghost_cell(0); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)(); + create_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)); + leak atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)); + close ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr); + leak ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr); + close exists(ptr); + leak exists(ptr); + close exists(true); + close Arc_own::(t, Arc:: { ptr: nnp, alloc: alloc }); +} + +lem init_UniqueArc_from_box_in( + t: thread_id_t, + nnp: std::ptr::NonNull>, + alloc: A, + alloc_id: std::alloc::alloc_id_t +) + req points_to_at_lft(alloc_id.lft, nnp.as_ptr(), ?inner) &*& + inner.strong.inner() == 0 &*& inner.weak.inner() == 1 &*& + .own(t, inner.data) &*& + std::alloc::alloc_block_in(alloc_id, nnp.as_ptr() as *u8, std::alloc::Layout::new::>()) &*& + std::alloc::Allocator(t, alloc, alloc_id) &*& + nnp.as_ptr() as usize != 0; + ens UniqueArc_own::(t, UniqueArc:: { ptr: nnp, alloc: alloc }); +{ + assume(alloc_id.lft == 'static); // same as linked_list.rs:2212 (Global/System allocators are 'static) + produce_lifetime_token_static(); + assert [?qstatic]lifetime_token('static); + let ptr = nnp.as_ptr(); + open_points_to_at_lft(ptr, qstatic); + points_to_limits(ptr); + open_points_to(ptr); + points_to_limits(&(*ptr).strong); + points_to_limits(&(*ptr).weak); + points_to_limits(&(*ptr).data); + close arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0); + close arc_atomic_cas::AtomicUsize(&(*ptr).weak, 1); + close_full_borrow_content::(t, &(*ptr).data); + let layout = std::alloc::Layout::new::>(); + ArcInner_sized_to_padding_at_lft::(alloc_id.lft, ptr, qstatic); + close ArcInner_backing::(alloc_id, layout, ptr); + let inv_gid = create_ghost_cell(ModeDataOut); + let sgid = create_ghost_cell(none); + close dlft_pred(sgid, none); + start_counting(dlft_pred, sgid); + let wgid = create_ghost_cell(false); + close weak_pred(wgid, false); + start_counting(weak_pred, wgid); + let lock_gid = create_ghost_cell::(LockFree); + let imp_gid = create_ghost_cell(1); + close Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)(); + create_atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)); + leak atomic_space(Marc, Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr)); + std::ptr::NonNull_Sized_as_ptr(nnp); + std::alloc::Layout_inv(layout); + close ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr); + leak ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, t, ptr); + leak exists(ptr); + std::ptr::close_NonNull_own::>()(default_tid, nnp); + leak std::ptr::NonNull_own::>()(default_tid, nnp); + close UniqueArc_own::(t, UniqueArc:: { ptr: nnp, alloc: alloc }); +} +@*/ + +/// `Weak` is a version of [`Arc`] that holds a non-owning reference to the +/// managed allocation. +/// +/// The allocation is accessed by calling [`upgrade`] on the `Weak` +/// pointer, which returns an [Option]<[Arc]\>. +/// +/// Since a `Weak` reference does not count towards ownership, it will not +/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no +/// guarantees about the value still being present. Thus it may return [`None`] +/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation +/// itself (the backing store) from being deallocated. +/// +/// A `Weak` pointer is useful for keeping a temporary reference to the allocation +/// managed by [`Arc`] without preventing its inner value from being dropped. It is also used to +/// prevent circular references between [`Arc`] pointers, since mutual owning references +/// would never allow either [`Arc`] to be dropped. For example, a tree could +/// have strong [`Arc`] pointers from parent nodes to children, and `Weak` +/// pointers from children back to their parents. +/// +/// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`]. +/// +/// [`upgrade`]: Weak::upgrade +#[stable(feature = "arc_weak", since = "1.4.0")] +pub struct Weak< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + // This is a `NonNull` to allow optimizing the size of this type in enums, + // but it is not necessarily a valid pointer. + // `Weak::new` sets this to `usize::MAX` so that it doesn’t need + // to allocate space on the heap. That's not a value a real pointer + // will ever have because ArcInner has alignment at least 2. + ptr: NonNull>, + alloc: A, +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl Send for Weak {} +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl Sync for Weak {} + +/*@ +// Phase 2 Concurrent predicates for Weak (integrated with Arc_inv). +// Supports dangling (ptr == usize::MAX), explicit live weak refs (is_implicit == false), +// and the single implicit weak ref held collectively by strong refs / UniqueArc (is_implicit == true). +pred >.own(t, weak) = + [_]std::ptr::NonNull_own(default_tid, weak.ptr) &*& + [_]exists(?ptr) &*& weak.ptr.as_ptr() == ptr &*& + std::alloc::Allocator(t, weak.alloc, ?alloc_id) &*& + if (ptr as usize) == usize::MAX { + true + } else { + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + exists::(?is_implicit) &*& + if is_implicit { + [1/2]ghost_cell(imp_gid, 1) &*& (*ptr).data |-> _ + } else { + ticket(weak_pred, wgid, ?wfrac) &*& [wfrac]weak_pred(wgid, false) + } + }; + +pred_ctor Weak_ptr_bc(l: *Weak, nnp: std::ptr::NonNull>)(;) = + (*l).ptr |-> nnp &*& struct_Weak_padding(l); + +pred_ctor weak_ticket_(wgid: i32, wfrac: real)(;) = + ticket(weak_pred, wgid, wfrac) &*& [wfrac]weak_pred(wgid, false); + +pred_ctor imp_weak_cell_(imp_gid: i32, ptr: *ArcInner)(;) = + [1/2]ghost_cell(imp_gid, 1) &*& (*ptr).data |-> _; + +pred >.share(k, t, l) = + [_]exists(?nnp) &*& + [_]frac_borrow(k, Weak_ptr_bc(l, nnp)) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + pointer_within_limits(&(*l).alloc) == true &*& + if (ptr as usize) == usize::MAX { + true + } else { + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [_]exists::(?is_implicit) &*& + if is_implicit { + [_]frac_borrow(k, imp_weak_cell_::(imp_gid, ptr)) + } else { + [_]exists(?wfrac) &*& [_]frac_borrow(k, weak_ticket_(wgid, wfrac)) + } + }; + +lem Weak_is_live_from_borrow(wgid: i32, wfrac: real) + req atomic_mask(?mask) &*& mask_le(Nlft, mask) == true &*& + counting(weak_pred, wgid, ?w_cnt, ?dealloced) &*& w_cnt >= 0 &*& + [_]frac_borrow(?k, weak_ticket_(wgid, wfrac)) &*& + [?q]lifetime_token(k); + ens atomic_mask(mask) &*& counting(weak_pred, wgid, w_cnt, dealloced) &*& + [q]lifetime_token(k) &*& dealloced == false &*& w_cnt >= 1; +{ + open_frac_borrow_m(k, weak_ticket_(wgid, wfrac), q); + open [?qw]weak_ticket_(wgid, wfrac)(); + counting_match_fraction(weak_pred, wgid); + if w_cnt == 0 { + open [qw * wfrac]weak_pred(wgid, false); + ghost_cell_fraction_info(wgid); + stop_counting(weak_pred, wgid); + open weak_pred(wgid, false); + merge_fractions ghost_cell::(wgid, _); + ghost_cell_fraction_info(wgid); + } else {} + close [qw]weak_ticket_(wgid, wfrac)(); + close_frac_borrow_m(qw, weak_ticket_(wgid, wfrac)); +} + +lem Weak_implicit_is_data_out(inv_gid: i32, sgid: i32, wgid: i32, lock_gid: i32, imp_gid: i32, alloc_id: std::alloc::alloc_id_t, layout: std::alloc::Layout, owner_tid: thread_id_t, ptr: *ArcInner) + req atomic_mask(?mask) &*& mask_le(Nlft, mask) == true &*& + Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr)() &*& + [_]frac_borrow(?k, imp_weak_cell_::(imp_gid, ptr)) &*& + [?q]lifetime_token(k); + ens atomic_mask(mask) &*& + [q]lifetime_token(k) &*& + [1/2]ghost_cell(inv_gid, ModeDataOut) &*& + [1/2]ghost_cell(inv_gid, ModeDataOut) &*& + counting(dlft_pred, sgid, 0, none) &*& + counting(weak_pred, wgid, ?w_cnt, false) &*& w_cnt >= 0 &*& w_cnt + 1 < usize::MAX &*& + ghost_cell::(lock_gid, LockFree) &*& + [1/2]ghost_cell(imp_gid, 1) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, w_cnt + 1) &*& + ArcInner_backing::(alloc_id, layout, ptr); +{ + open Arc_inv::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr)(); + open_frac_borrow_m(k, imp_weak_cell_::(imp_gid, ptr), q); + open [?qi]imp_weak_cell_::(imp_gid, ptr)(); + assert [1/2]ghost_cell::(inv_gid, ?mode); + match mode { + ModeDataOut => {} + ModeShared(dk) => { + merge_fractions ghost_cell(imp_gid, _); + ghost_cell_fraction_info(imp_gid); + } + ModeExclusive => { + merge_fractions ghost_cell(imp_gid, _); + ghost_cell_fraction_info(imp_gid); + } + ModeExclusiveLocked => { + merge_fractions ghost_cell(imp_gid, _); + ghost_cell_fraction_info(imp_gid); + } + ModeDataDropped => { + merge_fractions ghost_cell(imp_gid, _); + ghost_cell_fraction_info(imp_gid); + } + ModeDealloced => { + merge_fractions ghost_cell(imp_gid, _); + ghost_cell_fraction_info(imp_gid); + } + } + close [qi]imp_weak_cell_::(imp_gid, ptr)(); + close_frac_borrow_m(qi, imp_weak_cell_::(imp_gid, ptr)); +} + +lem Weak_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Weak_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + Weak_own::(t, Weak:: { ptr: upcast(v.ptr), alloc: upcast(v.alloc) }); +{ + assume(false); // VeriFast issue #610 (same as raw_vec.rs and tests/rust/safe_abstraction/arc.rs) +} + +lem Weak_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(Weak)) == true &*& + Weak_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& Weak_own::(t1, v); +{ + open Weak_own::(t0, v); + std::alloc::Allocator_send::(t1, v.alloc); + close Weak_own::(t1, v); +} + +lem Weak_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *Weak) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]Weak_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]Weak_share::(k1, t, l); +{ + open Weak_share::(k, t, l); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + frac_borrow_mono(k, k1, Weak_ptr_bc(l, nnp)); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + if (ptr as usize) == usize::MAX { + } else { + assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ?alloc_id, ?layout, ?owner_tid, ptr) &*& + [_]exists::(?is_implicit); + if is_implicit { + frac_borrow_mono(k, k1, imp_weak_cell_::(imp_gid, ptr)); + } else { + assert [_]exists::(?wfrac); + frac_borrow_mono(k, k1, weak_ticket_(wgid, wfrac)); + } + } + close Weak_share::(k1, t, l); + leak Weak_share::(k1, t, l); +} + +lem Weak_Sync_implies_T_Send_Sync() + req is_Sync(typeid(Weak)) == true; + ens is_Send(typeid(T)) == true &*& is_Sync(typeid(T)) == true &*& is_Send(typeid(A)) == true &*& is_Sync(typeid(A)) == true; +{ + assume(false); +} + +lem Weak_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(Weak)) == true &*& + [_]Weak_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& [_]Weak_share::(k, t1, l); +{ + Weak_Sync_implies_T_Send_Sync::(); + open Weak_share::(k, t0, l); + std::alloc::Allocator_sync::(t1); + close Weak_share::(k, t1, l); + leak Weak_share::(k, t1, l); +} + +lem Weak_share_full(k: lifetime_t, t: thread_id_t, l: *Weak) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + full_borrow(k, Weak_full_borrow_content::(t, l)); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]Weak_share::(k, t, l); +{ + let klong = open_full_borrow_strong_m(k, Weak_full_borrow_content::(t, l), q); + open Weak_full_borrow_content::(t, l)(); + open Weak_own::(t, ?weak); + let nnp = weak.ptr; + assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, weak.alloc, ?alloc_id); + points_to_limits(&(*l).alloc); + close Weak_ptr_bc::(l, nnp)(); + std::alloc::close_Allocator_full_borrow_content_::(t, &(*l).alloc); + if (ptr as usize) == usize::MAX { + close sep(Weak_ptr_bc::(l, nnp), std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id))(); + { + pred Ctx() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& nnp.as_ptr() == ptr &*& + (ptr as usize) == usize::MAX; + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(Weak_ptr_bc::(l, nnp), std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id)), + klong, + Weak_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(Weak_ptr_bc::(l, nnp), std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id))(); + open Weak_ptr_bc::(l, nnp)(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + close Weak_own::(t, *l); + close Weak_full_borrow_content::(t, l)(); + } { + close_full_borrow_strong_m( + klong, + Weak_full_borrow_content::(t, l), + sep(Weak_ptr_bc::(l, nnp), std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id)) + ); + } + } + full_borrow_mono(klong, k, sep(Weak_ptr_bc::(l, nnp), std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id))); + full_borrow_split_m(k, Weak_ptr_bc::(l, nnp), std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id)); + full_borrow_into_frac_m(k, Weak_ptr_bc::(l, nnp)); + std::alloc::share_Allocator_full_borrow_content_m::(k, t, &(*l).alloc, alloc_id); + leak exists(nnp); + close Weak_share::(k, t, l); + leak Weak_share::(k, t, l); + } else { + assert [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr); + open exists::(?is_implicit); + if is_implicit { + close imp_weak_cell_::(imp_gid, ptr)(); + close sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr))(); + close sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr)))(); + { + pred Ctx() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& nnp.as_ptr() == ptr &*& + (ptr as usize) != usize::MAX &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)); + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr))), + klong, + Weak_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr)))(); + open Weak_ptr_bc::(l, nnp)(); + open sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open imp_weak_cell_::(imp_gid, ptr)(); + close exists(true); + close Weak_own::(t, *l); + close Weak_full_borrow_content::(t, l)(); + } { + close_full_borrow_strong_m( + klong, + Weak_full_borrow_content::(t, l), + sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr))) + ); + } + } + full_borrow_mono(klong, k, sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr)))); + full_borrow_split_m(k, Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), imp_weak_cell_::(imp_gid, ptr)); + full_borrow_into_frac_m(k, Weak_ptr_bc::(l, nnp)); + std::alloc::share_Allocator_full_borrow_content_m::(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(k, imp_weak_cell_::(imp_gid, ptr)); + leak exists(nnp); + leak exists(true); + close Weak_share::(k, t, l); + leak Weak_share::(k, t, l); + } else { + assert ticket(weak_pred, wgid, ?wfrac); + close weak_ticket_(wgid, wfrac)(); + close sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac))(); + close sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac)))(); + { + pred Ctx() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& nnp.as_ptr() == ptr &*& + (ptr as usize) != usize::MAX &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)); + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac))), + klong, + Weak_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac)))(); + open Weak_ptr_bc::(l, nnp)(); + open sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open weak_ticket_(wgid, wfrac)(); + close exists(false); + close Weak_own::(t, *l); + close Weak_full_borrow_content::(t, l)(); + } { + close_full_borrow_strong_m( + klong, + Weak_full_borrow_content::(t, l), + sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac))) + ); + } + } + full_borrow_mono(klong, k, sep(Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac)))); + full_borrow_split_m(k, Weak_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), weak_ticket_(wgid, wfrac)); + full_borrow_into_frac_m(k, Weak_ptr_bc::(l, nnp)); + std::alloc::share_Allocator_full_borrow_content_m::(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(k, weak_ticket_(wgid, wfrac)); + leak exists(nnp); + leak exists(false); + leak exists(wfrac); + close Weak_share::(k, t, l); + leak Weak_share::(k, t, l); + } + } +} + +lem init_ref_Weak(p: *Weak) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& + [_]Weak_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& + [_]Weak_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + assume(false); // same as tests/rust/safe_abstraction/arc.rs:121 +} +@*/ + +#[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> for Weak {} +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for Weak {} + +// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned. +#[unstable(feature = "cell_get_cloned", issue = "145329")] +unsafe impl CloneFromCell for Weak {} + +#[stable(feature = "arc_weak", since = "1.4.0")] +impl fmt::Debug for Weak { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "(Weak)") + } +} + +// This is repr(C) to future-proof against possible field-reordering, which +// would interfere with otherwise safe [into|from]_raw() of transmutable +// inner types. +// Unlike RcInner, repr(align(2)) is not strictly required because atomic types +// have the alignment same as its size, but we use it for consistency and clarity. +#[repr(C, align(2))] +struct ArcInner { + strong: Atomic, + + // the value usize::MAX acts as a sentinel for temporarily "locking" the + // weak count, preventing `Arc::downgrade` from racing to create new + // `Weak` references. `Arc::is_unique` (which backs `Arc::get_mut`) + // needs to observe both the strong and weak counts as indicating + // uniqueness in one logical atomic step; since they live in separate + // atomic words, it locks the weak count while reading the strong + // count to keep the two reads consistent. + weak: Atomic, + + data: T, +} + +/// Calculate layout for `ArcInner` using the inner value's layout +fn arcinner_layout_for_value_layout(layout: Layout) -> Layout +//@ req thread_token(?t); +//@ ens thread_token(t) &*& result == arcinner_padded_layout(layout); +//@ on_unwind_ens thread_token(t); +/*@ +safety_proof { + leak .own(_t, layout); + let r = call(); + std::alloc::close_Layout_own(_t, r); +} +@*/ +{ + // Calculate layout using the given value layout. + // Previously, layout was calculated on the expression + // `&*(ptr as *const ArcInner)`, but this created a misaligned + // reference (see #54908). + let base = Layout::new::>(); + let ext = unsafe { Layout_extend__VeriFast_wrapper(&base, layout) }; //~ignore_ref_creation + let p = match ext { + Ok(p) => p, + Err(_) => panic!("capacity overflow"), + }; + //@ close exists(layout); + let r = unsafe { Layout_pad_to_align_arcinner__VeriFast_wrapper(&p.0) }; //~ignore_ref_creation + r +} + +unsafe impl Send for ArcInner {} +unsafe impl Sync for ArcInner {} + +/*@ +pred >.own(t, v) = + >.own(t, v.strong) &*& + >.own(t, v.weak) &*& + (.own)(t, v.data); + +pred >.share(k, t, l) = + [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, l) &*& + (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)); + +lem ArcInner_own_mono() + req type_interp::() &*& type_interp::() &*& ArcInner_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& ArcInner_own::(t, ArcInner:: { strong: upcast(v.strong), weak: upcast(v.weak), data: upcast(v.data) }); +{ + assume(false); +} + +lem ArcInner_drop() + req ArcInner_own::(?t, ?v); + ens (.own)(t, v.data) &*& >.own(t, v.strong) &*& >.own(t, v.weak); +{ + open ArcInner_own::(t, v); +} + +lem ArcInner_send(t1: thread_id_t) + req type_interp::() &*& is_Send(typeid(ArcInner)) == true &*& ArcInner_own::(?t0, ?v); + ens type_interp::() &*& ArcInner_own::(t1, v); +{ + assume(false); // ArcInner is private and Atomic is trivially Send (opaque in extern_spec) +} + +lem ArcInner_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *ArcInner) + req type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]ArcInner_share::(k, t, l); + ens type_interp::() &*& [_]ArcInner_share::(k1, t, l); +{ + open ArcInner_share::(k, t, l); + close ArcInner_share::(k1, t, l); + leak ArcInner_share::(k1, t, l); +} + +lem ArcInner_Sync_implies_T_Send_Sync() + req is_Sync(typeid(ArcInner)) == true; + ens is_Send(typeid(T)) == true &*& is_Sync(typeid(T)) == true; +{ + assume(false); +} + +lem ArcInner_sync(t1: thread_id_t) + req type_interp::() &*& is_Sync(typeid(ArcInner)) == true &*& [_]ArcInner_share::(?k, ?t0, ?l); + ens type_interp::() &*& [_]ArcInner_share::(k, t1, l); +{ + ArcInner_Sync_implies_T_Send_Sync::(); + open ArcInner_share::(k, t0, l); + close ArcInner_share::(k, t1, l); + leak ArcInner_share::(k, t1, l); +} + +lem ArcInner_share_full(k: lifetime_t, t: thread_id_t, l: *ArcInner) + req type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + full_borrow(k, ArcInner_full_borrow_content::(t, l)); + ens type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]ArcInner_share::(k, t, l); +{ + assume(false); // ArcInner is private and only shared via Arc::inner / UniqueArc::inner +} + +lem init_ref_ArcInner(p: *ArcInner) + req type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& + [_]ArcInner_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& + [_]ArcInner_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + assume(false); +} +@*/ + +impl Arc { + /// Constructs a new `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn new(data: T) -> Arc + //@ req thread_token(?t) &*& .own(t, data); + //@ ens thread_token(t) &*& Arc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let inner = ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }; + //@ close drop_perm::>(false, True, t, inner); + let x: Box<_> = Box::new(inner); + //@ open drop_perm::>(false, True, t, inner); + let ptr = unsafe { Box_into_non_null__VeriFast_wrapper(x) }; + // SAFETY: Pointer is valid. + let r = unsafe { Self::from_inner(ptr) }; + //@ std::alloc::produce_Allocator_Global(t); + //@ init_Arc_from_box_in::(t, ptr, std::alloc::Global {}, std::alloc::Global_alloc_id); + r + } + + /// Constructs a new `Arc` while giving you a `Weak` to the allocation, + /// to allow you to construct a `T` which holds a weak pointer to itself. + /// + /// Generally, a structure circularly referencing itself, either directly or + /// indirectly, should not hold a strong reference to itself to prevent a memory leak. + /// Using this function, you get access to the weak pointer during the + /// initialization of `T`, before the `Arc` is created, such that you can + /// clone and store it inside the `T`. + /// + /// `new_cyclic` first allocates the managed allocation for the `Arc`, + /// then calls your closure, giving it a `Weak` to this allocation, + /// and only afterwards completes the construction of the `Arc` by placing + /// the `T` returned from your closure into the allocation. + /// + /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic` + /// returns, calling [`upgrade`] on the weak reference inside your closure will + /// fail and result in a `None` value. + /// + /// # Panics + /// + /// If `data_fn` panics, the panic is propagated to the caller, and the + /// temporary [`Weak`] is dropped normally. + /// + /// # Example + /// + /// ``` + /// # #![allow(dead_code)] + /// use std::sync::{Arc, Weak}; + /// + /// struct Gadget { + /// me: Weak, + /// } + /// + /// impl Gadget { + /// /// Constructs a reference counted Gadget. + /// fn new() -> Arc { + /// // `me` is a `Weak` pointing at the new allocation of the + /// // `Arc` we're constructing. + /// Arc::new_cyclic(|me| { + /// // Create the actual struct here. + /// Gadget { me: me.clone() } + /// }) + /// } + /// + /// /// Returns a reference counted pointer to Self. + /// fn me(&self) -> Arc { + /// self.me.upgrade().unwrap() + /// } + /// } + /// ``` + /// [`upgrade`]: Weak::upgrade + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "arc_new_cyclic", since = "1.60.0")] + pub fn new_cyclic(data_fn: F) -> Arc + where + F: FnOnce(&Weak) -> T, + { + Self::new_cyclic_in(data_fn, Global) + } + + /// Constructs a new `Arc` with uninitialized contents. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut five = Arc::::new_uninit(); + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use] + pub fn new_uninit() -> Arc> + //@ req thread_token(?t); + //@ ens thread_token(t) &*& Arc_own::, std::alloc::Global>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let inner = Arc_alloc_uninit_in__VeriFast_wrapper::(Global, false); + let a = Arc::from_ptr(inner); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::new::())); + a + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let zero = Arc::::new_zeroed(); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_zeroed_alloc", since = "1.92.0")] + #[must_use] + pub fn new_zeroed() -> Arc> + //@ req thread_token(?t); + //@ ens thread_token(t) &*& Arc_own::, std::alloc::Global>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let inner = Arc_alloc_uninit_in__VeriFast_wrapper::(Global, true); + let a = Arc::from_ptr(inner); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::new::())); + a + } + } + + /// Constructs a new `Pin>`. If `T` does not implement `Unpin`, then + /// `data` will be pinned in memory and unable to be moved. + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "pin", since = "1.33.0")] + #[must_use] + pub fn pin(data: T) -> Pin> + //@ req thread_token(?t) &*& .own(t, data); + //@ ens thread_token(t) &*& >>.own(t, result); + //@ on_unwind_ens thread_token(t); + { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::new(data)) } + } + + /// Constructs a new `Pin>`, return an error if allocation fails. + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_pin(data: T) -> Result>, AllocError> + //@ req thread_token(?t) &*& .own(t, data); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(p) => arc_pin::Pin_own::>(t, p), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::>, std::alloc::AllocError>(_t, r); + } + @*/ + { + // SAFETY: We own and create the pinned pointer. + unsafe { Ok(Pin::new_unchecked(Arc::try_new(data)?)) } + } + + /// Constructs a new `Arc`, returning an error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// + /// let five = Arc::try_new(5)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new(data: T) -> Result, AllocError> + //@ req thread_token(?t) &*& .own(t, data); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(a) => Arc_own::(t, a), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::AllocError>(_t, r); + } + @*/ + { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x: Box<_> = unsafe { + Box_try_new__VeriFast_wrapper(ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }) + }?; + // SAFETY: Pointer is valid. + let ptr = unsafe { Box_into_non_null__VeriFast_wrapper(x) }; + let a = unsafe { Self::from_inner(ptr) }; + //@ std::alloc::produce_Allocator_Global(t); + //@ init_Arc_from_box_in::(t, ptr, std::alloc::Global {}, std::alloc::Global_alloc_id); + Ok(a) + } + + /// Constructs a new `Arc` with uninitialized contents, returning an error + /// if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// + /// let mut five = Arc::::try_new_uninit()?; + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_new_uninit() -> Result>, AllocError> + //@ req thread_token(?t); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(a) => Arc_own::, std::alloc::Global>(t, a), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::Global>, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let inner = match Arc_try_alloc_uninit_in__VeriFast_wrapper::(Global, false) { + Ok(p) => p, + Err(e) => { + //@ leak std::alloc::Allocator(t, std::alloc::Global {}, std::alloc::Global_alloc_id); + return Err(e); + } + }; + let a = Arc::from_ptr(inner); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::new::())); + Ok(a) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, returning an error if allocation fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature( allocator_ext)] + /// + /// use std::sync::Arc; + /// + /// let zero = Arc::::try_new_zeroed()?; + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_new_zeroed() -> Result>, AllocError> + //@ req thread_token(?t); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(a) => Arc_own::, std::alloc::Global>(t, a), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::Global>, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let inner = match Arc_try_alloc_uninit_in__VeriFast_wrapper::(Global, true) { + Ok(p) => p, + Err(e) => { + //@ leak std::alloc::Allocator(t, std::alloc::Global {}, std::alloc::Global_alloc_id); + return Err(e); + } + }; + let a = Arc::from_ptr(inner); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::new::())); + Ok(a) + } + } +} + +impl Arc { + /// Constructs a new `Arc` in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// ``` + #[inline] + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_in(data: T, alloc: A) -> Arc + //@ req thread_token(?t) &*& .own(t, data) &*& .own(t, alloc); + //@ ens thread_token(t) &*& Arc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::open_Allocator_own(alloc); + //@ assert std::alloc::Allocator(t, alloc, ?aid); + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let inner = ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }; + //@ close drop_perm::>(false, True, t, inner); + let x = Box::new_in(inner, alloc); + //@ open drop_perm::>(false, True, t, inner); + let (ptr, alloc) = Box::into_non_null_with_allocator(x); + // SAFETY: Pointer is valid. + let r = unsafe { Self::from_inner_in(ptr, alloc) }; + //@ init_Arc_from_box_in::(t, ptr, r.alloc, aid); + r + } + + /// Constructs a new `Arc` with uninitialized contents in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut five = Arc::::new_uninit_in(System); + /// + /// let five = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); + /// + /// five.assume_init() + /// }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_uninit_in(mut alloc: A) -> Arc, A> + //@ req thread_token(?t) &*& .own(t, alloc); + //@ ens thread_token(t) &*& Arc_own::, A>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let inner; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + inner = unsafe { Arc_alloc_uninit_in__VeriFast_wrapper::(&alloc, false) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr_in(inner, alloc); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::new::())); + a + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, in the provided allocator. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let zero = Arc::::new_zeroed_in(System); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_zeroed_in(mut alloc: A) -> Arc, A> + //@ req thread_token(?t) &*& .own(t, alloc); + //@ ens thread_token(t) &*& Arc_own::, A>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let inner; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + inner = unsafe { Arc_alloc_uninit_in__VeriFast_wrapper::(&alloc, true) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr_in(inner, alloc); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::new::())); + a + } + } + + /// Constructs a new `Arc` in the given allocator while giving you a `Weak` to the allocation, + /// to allow you to construct a `T` which holds a weak pointer to itself. + /// + /// Generally, a structure circularly referencing itself, either directly or + /// indirectly, should not hold a strong reference to itself to prevent a memory leak. + /// Using this function, you get access to the weak pointer during the + /// initialization of `T`, before the `Arc` is created, such that you can + /// clone and store it inside the `T`. + /// + /// `new_cyclic_in` first allocates the managed allocation for the `Arc`, + /// then calls your closure, giving it a `Weak` to this allocation, + /// and only afterwards completes the construction of the `Arc` by placing + /// the `T` returned from your closure into the allocation. + /// + /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic_in` + /// returns, calling [`upgrade`] on the weak reference inside your closure will + /// fail and result in a `None` value. + /// + /// # Panics + /// + /// If `data_fn` panics, the panic is propagated to the caller, and the + /// temporary [`Weak`] is dropped normally. + /// + /// # Example + /// + /// See [`new_cyclic`] + /// + /// [`new_cyclic`]: Arc::new_cyclic + /// [`upgrade`]: Weak::upgrade + #[cfg(not(no_global_oom_handling))] + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_cyclic_in(data_fn: F, alloc: A) -> Arc + where + F: FnOnce(&Weak) -> T, + { + // Construct the inner in the "uninitialized" state with a single + // weak reference. + let (uninit_ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + weak: atomic::AtomicUsize::new(1), + data: mem::MaybeUninit::::uninit(), + }, + alloc, + )); + let init_ptr: NonNull> = uninit_ptr.cast(); + + let weak = Weak { ptr: init_ptr, alloc }; + + // It's important we don't give up ownership of the weak pointer, or + // else the memory might be freed by the time `data_fn` returns. If + // we really wanted to pass ownership, we could create an additional + // weak pointer for ourselves, but this would result in additional + // updates to the weak reference count which might not be necessary + // otherwise. + let data = data_fn(&weak); + + // Now we can properly initialize the inner value and turn our weak + // reference into a strong reference. + let inner = init_ptr.as_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::write(&raw mut (*inner).data, data); + + // The above write to the data field must be visible to any threads which + // observe a non-zero strong count. Therefore we need at least "Release" ordering + // in order to synchronize with the `compare_exchange_weak` in `Weak::upgrade`. + // + // "Acquire" ordering is not required. When considering the possible behaviors + // of `data_fn` we only need to look at what it could do with a reference to a + // non-upgradeable `Weak`: + // - It can *clone* the `Weak`, increasing the weak reference count. + // - It can drop those clones, decreasing the weak reference count (but never to zero). + // + // These side effects do not impact us in any way, and no other side effects are + // possible with safe code alone. + let prev_value = (*inner).strong.fetch_add(1, Release); + debug_assert_eq!(prev_value, 0, "No prior strong references should exist"); + + // Strong references should collectively own a shared weak reference, + // so don't run the destructor for our old weak reference. + // Calling into_raw_with_allocator has the double effect of giving us back the allocator, + // and forgetting the weak reference. + let alloc = weak.into_raw_with_allocator().1; + + Arc::from_inner_in(init_ptr, alloc) + } + } + + /// Constructs a new `Pin>` in the provided allocator. If `T` does not implement `Unpin`, + /// then `data` will be pinned in memory and unable to be moved. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn pin_in(data: T, alloc: A) -> Pin> + where + A: StaticAllocator, + //@ req thread_token(?t) &*& .own(t, data) &*& .own(t, alloc); + //@ ens thread_token(t) &*& >>.own(t, result); + //@ on_unwind_ens thread_token(t); + { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::new_in(data, alloc)) } + } + + /// Constructs a new `Pin>` in the provided allocator, return an error if allocation + /// fails. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_pin_in(data: T, alloc: A) -> Result>, AllocError> + where + A: StaticAllocator, + //@ req thread_token(?t) &*& .own(t, data) &*& .own(t, alloc); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(p) => arc_pin::Pin_own::>(t, p), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::>, std::alloc::AllocError>(_t, r); + } + @*/ + { + // SAFETY: We own and create the pinned pointer. + unsafe { Ok(Pin::new_unchecked(Arc::try_new_in(data, alloc)?)) } + } + + /// Constructs a new `Arc` in the provided allocator, returning an error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::try_new_in(5, System)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_in(data: T, alloc: A) -> Result, AllocError> + //@ req thread_token(?t) &*& .own(t, data) &*& .own(t, alloc); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(a) => Arc_own::(t, a), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ std::alloc::open_Allocator_own(alloc); + //@ assert std::alloc::Allocator(t, alloc, ?aid); + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x = unsafe { + Box_try_new_in__VeriFast_wrapper( + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + ) + }?; + let (ptr, alloc) = Box::into_non_null_with_allocator(x); + // SAFETY: Pointer is valid since we created it. + let a = unsafe { Self::from_inner_in(ptr, alloc) }; + //@ init_Arc_from_box_in::(t, ptr, a.alloc, aid); + Ok(a) + } + + /// Constructs a new `Arc` with uninitialized contents, in the provided allocator, returning an + /// error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut five = Arc::::try_new_uninit_in(System)?; + /// + /// let five = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); + /// + /// five.assume_init() + /// }; + /// + /// assert_eq!(*five, 5); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_uninit_in(mut alloc: A) -> Result, A>, AllocError> + //@ req thread_token(?t) &*& .own(t, alloc); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(a) => Arc_own::, A>(t, a), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, A>, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let inner_res; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + inner_res = unsafe { Arc_try_alloc_uninit_in__VeriFast_wrapper::(&alloc, false) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + let inner = match inner_res { + Ok(p) => p, + Err(e) => { + //@ assert *(&alloc) |-> ?alloc_val2; + //@ std::alloc::Allocator_to_own(alloc_val2); + return Err(e); + } + }; + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr_in(inner, alloc); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::new::())); + Ok(a) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, in the provided allocator, returning an error if allocation + /// fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let zero = Arc::::try_new_zeroed_in(System)?; + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_zeroed_in(mut alloc: A) -> Result, A>, AllocError> + //@ req thread_token(?t) &*& .own(t, alloc); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(a) => Arc_own::, A>(t, a), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, A>, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let inner_res; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + inner_res = unsafe { Arc_try_alloc_uninit_in__VeriFast_wrapper::(&alloc, true) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + let inner = match inner_res { + Ok(p) => p, + Err(e) => { + //@ assert *(&alloc) |-> ?alloc_val2; + //@ std::alloc::Allocator_to_own(alloc_val2); + return Err(e); + } + }; + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr_in(inner, alloc); + //@ MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::, A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::new::())); + Ok(a) + } + } + /// Returns the inner value, if the `Arc` has exactly one strong reference. + /// + /// Otherwise, an [`Err`] is returned with the same `Arc` that was + /// passed in. + /// + /// This will succeed even if there are outstanding weak references. + /// + /// It is strongly recommended to use [`Arc::into_inner`] instead if you don't + /// keep the `Arc` in the [`Err`] case. + /// Immediately dropping the [`Err`]-value, as the expression + /// `Arc::try_unwrap(this).ok()` does, can cause the strong count to + /// drop to zero and the inner value of the `Arc` to be dropped. + /// For instance, if two threads execute such an expression in parallel, + /// there is a race condition without the possibility of unsafety: + /// The threads could first both check whether they own the last instance + /// in `Arc::try_unwrap`, determine that they both do not, and then both + /// discard and drop their instance in the call to [`ok`][`Result::ok`]. + /// In this scenario, the value inside the `Arc` is safely destroyed + /// by exactly one of the threads, but neither thread will ever be able + /// to use the value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// assert_eq!(Arc::try_unwrap(x), Ok(3)); + /// + /// let x = Arc::new(4); + /// let _y = Arc::clone(&x); + /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn try_unwrap(mut this: Self) -> Result + //@ req thread_token(?t) &*& Arc_own::(t, this); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(v) => .own(t, v), + Result::Err(a) => Arc_own::(t, a), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::>(_t, r); + } + @*/ + { + //@ open Arc_own::(t, ?this_val); + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, ?alloc_val, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open exists::(?exclusive); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if exclusive { + [1/2]ghost_cell(ig, ModeExclusive) &*& + ((.full_borrow_content)(ot, &(*ptr).data))() + } else { + ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)) &*& + [_](.share)(dk, ot, &(*ptr).data) + }; + pred PostOk(rv: usize) = + [1/2]ghost_cell(img, 1) &*& + ((.full_borrow_content)(ot, &(*ptr).data))(); + pred PostErrAcq(rv: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_ghop(&(*ptr).strong, 1, 0, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_op(?op, _, _, _, _, ?Q); + if exclusive { + op(); + assert Q(?rv); + match rv { + Result::Ok(v_ok) => { + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDataOut); + ghost_cell_mutate(img, 1); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => {} + } + } else { + assert ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk_val)); + counting_match_fraction(dlft_pred, sg); + op(); + assert Q(?rv); + match rv { + Result::Ok(v_ok) => { + destroy_ticket(dlft_pred, sg); + stop_counting(dlft_pred, sg); + open dlft_pred(sg, some(dk_val)); + assert shared_weak_lock(lg, sg, dk_val, ?locked); + open shared_weak_lock(lg, sg, dk_val, locked); + if locked { + merge_fractions ghost_cell::>(sg, _); + ghost_cell_fraction_info(sg); + } else {} + end_lifetime_m(dk_val); + borrow_end_m(dk_val, (.full_borrow_content)(ot, &(*ptr).data)); + ghost_cell_mutate(sg, none); + close dlft_pred(sg, none); + start_counting(dlft_pred, sg); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDataOut); + ghost_cell_mutate(img, 1); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + } + }; + @*/ + //@ close Pre(); + //@ let this_ref = precreate_ref(&this); + //@ init_ref_readonly(this_ref, 1/2); + //@ assert [?f_tr](*this_ref |-> _); + //@ open_points_to(this_ref); + let inner_ref = this.inner(); + //@ close_points_to(this_ref, f_tr); + //@ end_ref_readonly(this_ref); + //@ open_points_to(&this); + let cas_res = inner_ref.strong.compare_exchange(1, 0, Relaxed, Relaxed); //~ignore_ref_creation + let is_err = cas_res.is_err(); //~ignore_ref_creation + /*@ + match cas_res { + Result::Ok(v_res) => {} + Result::Err(v_err_res) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_err_res)); + } + } + @*/ + if is_err { + //@ close exists(exclusive); + //@ close Arc_own::(t, this_val); + let err_res = Err(this); + //@ close Arc_ptr_(&this, _); + return err_res; + } + acquire!(this.inner().strong); + /*@ + match cas_res { + Result::Ok(v_res) => { + open arc_atomic_cas::app_usize(PostOk, v_res)(); + open PostOk(v_res); + } + Result::Err(v_err_res) => {} + } + @*/ + } + + //@ open_full_borrow_content::(ot, &(*ptr).data); + //@ assert (*ptr).data |-> ?val; + //@ if ot != t { produce_type_interp::(); Send::send::(ot, t, val); leak type_interp::(); } else {} + let md = ManuallyDrop::new(this); + //@ close Arc_ptr_(&this, _); + // SAFETY: Pointer is valid for reads, contains initialised memory, + // and not dropped multiple times (we return it). + //@ let ptr_ref = precreate_ref(&md.ptr); + //@ init_ref_readonly(ptr_ref, 1/2); + let inner_p = unsafe { NonNull_as_ref_ArcInner__VeriFast_wrapper(&md.ptr) }; + let elem: T = unsafe { ptr::read(&inner_p.data) }; //~ignore_ref_creation + //@ close ArcInner_data(ptr, val); + //@ end_ref_readonly(ptr_ref); + //@ close [1/2]Arc_ptr(&md, _); + // SAFETY: As above, but we explicitly drop the allocator only once + // upon creating and dropping a weak pointer. + //@ let alloc_ref = precreate_ref(&md.alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + let alloc: A = unsafe { ptr::read(&md.alloc) }; // copy the allocator + //@ end_ref_readonly(alloc_ref); + //@ close [1/2]Arc_alloc(&md, _); + + // Make a weak pointer to clean up the implicit strong-weak reference + let _weak = Weak { ptr: md.ptr, alloc }; + //@ close exists(true); + //@ close Weak_own::(t, _weak); + + Ok(elem) + } + + /// Returns the inner value, if the `Arc` has exactly one strong reference. + /// + /// Otherwise, [`None`] is returned and the `Arc` is dropped. + /// + /// This will succeed even if there are outstanding weak references. + /// + /// If `Arc::into_inner` is called on every clone of this `Arc`, + /// it is guaranteed that exactly one of the calls returns the inner value. + /// This means in particular that the inner value is not dropped. + /// + /// [`Arc::try_unwrap`] is conceptually similar to `Arc::into_inner`, but it + /// is meant for different use-cases. If used as a direct replacement + /// for `Arc::into_inner` anyway, such as with the expression + /// [Arc::try_unwrap]\(this).[ok][Result::ok](), then it does + /// **not** give the same guarantee as described in the previous paragraph. + /// For more information, see the examples below and read the documentation + /// of [`Arc::try_unwrap`]. + /// + /// # Examples + /// + /// Minimal example demonstrating the guarantee that `Arc::into_inner` gives. + /// ```ignore-wasm + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// let y = Arc::clone(&x); + /// + /// // Two threads calling `Arc::into_inner` on both clones of an `Arc`: + /// let x_thread = std::thread::spawn(|| Arc::into_inner(x)); + /// let y_thread = std::thread::spawn(|| Arc::into_inner(y)); + /// + /// let x_inner_value = x_thread.join().unwrap(); + /// let y_inner_value = y_thread.join().unwrap(); + /// + /// // One of the threads is guaranteed to receive the inner value: + /// assert!(matches!( + /// (x_inner_value, y_inner_value), + /// (None, Some(3)) | (Some(3), None) + /// )); + /// // The result could also be `(None, None)` if the threads called + /// // `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead. + /// ``` + /// + /// A more practical example demonstrating the need for `Arc::into_inner`: + /// ```ignore-wasm + /// use std::sync::Arc; + /// + /// // Definition of a simple singly linked list using `Arc`: + /// #[derive(Clone)] + /// struct LinkedList(Option>>); + /// struct Node(T, Option>>); + /// + /// // Dropping a long `LinkedList` relying on the destructor of `Arc` + /// // can cause a stack overflow. To prevent this, we can provide a + /// // manual `Drop` implementation that does the destruction in a loop: + /// impl Drop for LinkedList { + /// fn drop(&mut self) { + /// let mut link = self.0.take(); + /// while let Some(arc_node) = link.take() { + /// if let Some(Node(_value, next)) = Arc::into_inner(arc_node) { + /// link = next; + /// } + /// } + /// } + /// } + /// + /// // Implementation of `new` and `push` omitted + /// impl LinkedList { + /// /* ... */ + /// # fn new() -> Self { + /// # LinkedList(None) + /// # } + /// # fn push(&mut self, x: T) { + /// # self.0 = Some(Arc::new(Node(x, self.0.take()))); + /// # } + /// } + /// + /// // The following code could have still caused a stack overflow + /// // despite the manual `Drop` impl if that `Drop` impl had used + /// // `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`. + /// + /// // Create a long list and clone it + /// let mut x = LinkedList::new(); + /// let size = 100000; + /// # let size = if cfg!(miri) { 100 } else { size }; + /// for i in 0..size { + /// x.push(i); // Adds i to the front of x + /// } + /// let y = x.clone(); + /// + /// // Drop the clones in parallel + /// let x_thread = std::thread::spawn(|| drop(x)); + /// let y_thread = std::thread::spawn(|| drop(y)); + /// x_thread.join().unwrap(); + /// y_thread.join().unwrap(); + /// ``` + #[inline] + #[stable(feature = "arc_into_inner", since = "1.70.0")] + pub fn into_inner(this: Self) -> Option + //@ req thread_token(?t) &*& Arc_own::(t, this); + //@ ens thread_token(t) &*& >.own(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ open Arc_own::(t, ?this_val); + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, ?alloc_val, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open exists::(?exclusive); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + // Make sure that the ordinary `Drop` implementation isn’t called as well + let mut md = mem::ManuallyDrop::new(this); + + // Following the implementation of `drop` and `drop_slow` + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if exclusive { + [1/2]ghost_cell(ig, ModeExclusive) &*& + ((.full_borrow_content)(ot, &(*ptr).data))() + } else { + ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)) + }; + pred Post(rv: usize) = if rv == 1 { + [1/2]ghost_cell(img, 1) &*& + ((.full_borrow_content)(ot, &(*ptr).data))() + } else { true }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_sub_ghop(&(*ptr).strong, 1, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_fetch_sub_op(?op, _, _, _, ?Q); + if exclusive { + mod_eq_minus_one(1, usize::MAX); + op(); + assert Q(?rv); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDataOut); + ghost_cell_mutate(img, 1); + } else { + assert ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)); + counting_match_fraction(dlft_pred, sg); + assert arc_atomic_cas::AtomicUsize(&(*ptr).strong, ?v0); + destroy_ticket(dlft_pred, sg); + mod_eq_minus_one(v0, usize::MAX); + op(); + assert Q(?rv); + if rv == 1 { + stop_counting(dlft_pred, sg); + open dlft_pred(sg, some(dk)); + assert shared_weak_lock(lg, sg, dk, ?locked); + open shared_weak_lock(lg, sg, dk, locked); + if locked { + merge_fractions ghost_cell::>(sg, _); + ghost_cell_fraction_info(sg); + } else {} + end_lifetime_m(dk); + borrow_end_m(dk, (.full_borrow_content)(ot, &(*ptr).data)); + ghost_cell_mutate(sg, none); + close dlft_pred(sg, none); + start_counting(dlft_pred, sg); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDataOut); + ghost_cell_mutate(img, 1); + } else {} + } + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?res_r); + close Post(res_r); + }; + @*/ + //@ close Pre(); + //@ close_points_to(&md); + //@ let md_ref = precreate_ref(&md as *Arc); + //@ init_ref_readonly(md_ref, 1/2); + //@ open_points_to(md_ref); + let inner_ref = Self::inner(&*md); + //@ close_points_to(md_ref, 1/2); + //@ end_ref_readonly(md_ref); + //@ open_points_to(&md); + let old_strong = inner_ref.strong.fetch_sub(1, Release); //~ignore_ref_creation + if old_strong != 1 { + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(Post, old_strong)); + // Note: upstream `into_inner` wraps `this` in `ManuallyDrop` and returns early here + // without dropping `this.alloc` (memory-safe leak in Rust). + //@ leak std::alloc::Allocator(t, _, aid); + //@ close std::option::Option_own::(t, std::option::Option::None); + return None; + } + acquire!(md.inner().strong); + //@ open arc_atomic_cas::app_usize(Post, old_strong)(); + //@ open Post(old_strong); + } + + //@ if ot != t { open_full_borrow_content::(ot, &(*ptr).data); assert (*ptr).data |-> ?v0; produce_type_interp::(); Send::send::(ot, t, v0); leak type_interp::(); close_full_borrow_content::(t, &(*ptr).data); } else {} + // SAFETY: This mirrors the line + // + // unsafe { ptr::drop_in_place(Self::get_mut_unchecked(self)) }; + // + // in `drop_slow`. Instead of dropping the value behind the pointer, + // it is read and eventually returned; `ptr::read` has the same + // safety conditions as `ptr::drop_in_place`. + //@ close exists(t); + let data_ref = unsafe { Self::get_mut_unchecked(&mut md) }; //~ignore_ref_creation + //@ open_full_borrow_content::(t, data_ref); + //@ assert (*ptr).data |-> ?val; + let inner = unsafe { ptr::read(data_ref) }; + //@ close ArcInner_data(ptr, val); + // SAFETY: Pointer is valid for reads. + //@ close_points_to(&md); + //@ let md_ref2 = precreate_ref(&md as *Arc); + //@ init_ref_readonly(md_ref2, 1/2); + //@ open_points_to(md_ref2); + //@ let alloc_ref = precreate_ref(&(*md_ref2).alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + let alloc = unsafe { ptr::read(&md.alloc) }; + //@ end_ref_readonly(alloc_ref); + //@ close_points_to(md_ref2, 1/2); + //@ end_ref_readonly(md_ref2); + //@ let md_ref3 = precreate_ref(&md as *Arc); + //@ init_ref_readonly(md_ref3, 1/2); + //@ open_points_to(md_ref3); + let w = Weak { ptr: md.ptr, alloc }; + //@ close_points_to(md_ref3, 1/2); + //@ end_ref_readonly(md_ref3); + //@ open_points_to(&md); + //@ close exists(true); + //@ close Weak_own::(t, w); + drop(w); + + let ret = Some(inner); + //@ close std::option::Option_own::(t, ret); + ret + } + + /// Maps the value in an `Arc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `Arc`, and the result is returned, also in + /// an `Arc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::map(a, f)` instead of `r.map(a)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let r = Arc::new(7); + /// let new = Arc::map(r, |i| i + 7); + /// assert_eq!(*new, 14); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "smart_pointer_map", since = "1.100.0")] + pub fn map(this: Self, f: impl FnOnce(&T) -> U) -> Arc { + if size_of::() == size_of::() + && align_of::() == align_of::() + && Arc::is_unique(&this) + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + let value = ptr.read(); + let mut allocation = Arc::from_raw_in(ptr.cast::>(), alloc); + + Arc::get_mut_unchecked(&mut allocation).write(f(&value)); + allocation.assume_init() + } + } else { + let output = f(&*this); + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::decrement_strong_count_in(ptr, &alloc) } + + Arc::new_in(output, alloc) + } + } + + /// Attempts to map the value in an `Arc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `Arc`, and if the operation succeeds, the + /// result is returned, also in an `Arc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::try_map(a, f)` instead of `a.try_map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(smart_pointer_try_map)] + /// + /// use std::sync::Arc; + /// + /// let b = Arc::new(7); + /// let new = Arc::try_map(b, |&i| u32::try_from(i)).unwrap(); + /// assert_eq!(*new, 7); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "smart_pointer_try_map", issue = "144419")] + pub fn try_map( + this: Self, + f: impl FnOnce(&T) -> R, + ) -> >>::TryType + where + R: Try, + R::Residual: Residual>, + { + if size_of::() == size_of::() + && align_of::() == align_of::() + && Arc::is_unique(&this) + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + let value = ptr.read(); + let mut allocation = + Arc::from_raw_in(ptr.cast::>(), alloc); + + Arc::get_mut_unchecked(&mut allocation).write(f(&value)?); + try { allocation.assume_init() } + } + } else { + let output = f(&*this)?; + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::decrement_strong_count_in(ptr, &alloc) } + + try { Arc::new_in(output, alloc) } + } + } +} + +impl Arc<[T]> { + /// Constructs a new atomically reference-counted slice with uninitialized contents. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut values = Arc::<[u32]>::new_uninit_slice(3); + /// + /// // Deferred initialization: + /// let data = Arc::get_mut(&mut values).unwrap(); + /// data[0].write(1); + /// data[1].write(2); + /// data[2].write(3); + /// + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use] + pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit]> + //@ req thread_token(?t); + //@ ens thread_token(t) &*& Arc_own::<[std::mem::MaybeUninit], std::alloc::Global>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr(Arc::allocate_for_slice(len)); + //@ Slice_MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::<[std::mem::MaybeUninit], std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::>(), std::mem::align_of::>()))); + a + } + } + + /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being + /// filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and + /// incorrect usage of this method. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let values = Arc::<[u32]>::new_zeroed_slice(3); + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_zeroed_alloc", since = "1.92.0")] + #[must_use] + pub fn new_zeroed_slice(len: usize) -> Arc<[mem::MaybeUninit]> + //@ req thread_token(?t); + //@ ens thread_token(t) &*& Arc_own::<[std::mem::MaybeUninit], std::alloc::Global>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let inner = Arc_alloc_slice_in__VeriFast_wrapper::, Global>(len, Global, true); + let a = Arc::from_ptr(inner); + //@ Slice_MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::<[std::mem::MaybeUninit], std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::>(), std::mem::align_of::>()))); + a + } + } +} + +impl Arc<[T], A> { + /// Constructs a new atomically reference-counted slice with uninitialized contents in the + /// provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut values = Arc::<[u32], _>::new_uninit_slice_in(3, System); + /// + /// let values = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1); + /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2); + /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3); + /// + /// values.assume_init() + /// }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_uninit_slice_in(len: usize, mut alloc: A) -> Arc<[mem::MaybeUninit], A> + //@ req thread_token(?t) &*& .own(t, alloc); + //@ ens thread_token(t) &*& Arc_own::<[std::mem::MaybeUninit], A>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let inner; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + inner = unsafe { Arc::allocate_for_slice_in/*@::, A, 'a>@*/(len, &alloc) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr_in(inner, alloc); + //@ Slice_MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::<[std::mem::MaybeUninit], A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::>(), std::mem::align_of::>()))); + a + } + } + + /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being + /// filled with `0` bytes, in the provided allocator. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and + /// incorrect usage of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let values = Arc::<[u32], _>::new_zeroed_slice_in(3, System); + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_zeroed_slice_in(len: usize, mut alloc: A) -> Arc<[mem::MaybeUninit], A> + //@ req thread_token(?t) &*& .own(t, alloc); + //@ ens thread_token(t) &*& Arc_own::<[std::mem::MaybeUninit], A>(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let inner; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + inner = unsafe { Arc_alloc_slice_in__VeriFast_wrapper::, &A>(len, &alloc, true) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + // ignore-tidy-undocumented-unsafe + unsafe { + let a = Arc::from_ptr_in(inner, alloc); + //@ Slice_MaybeUninit_uninit_to_fbc::(t, &(*a.ptr.as_ptr()).data); + //@ init_Arc_from_raw_parts_in::<[std::mem::MaybeUninit], A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::>(), std::mem::align_of::>()))); + a + } + } + + /// Converts the reference-counted slice into a reference-counted array. + /// + /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type. + /// + /// # Errors + /// + /// Returns the original `Arc<[T]>` in the `Err` variant if `self.len()` does not equal `N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(alloc_slice_into_array)] + /// use std::sync::Arc; + /// + /// let arc_slice: Arc<[i32]> = Arc::new([1, 2, 3]); + /// + /// let arc_array: Arc<[i32; 3]> = arc_slice.into_array().unwrap(); + /// ``` + #[unstable(feature = "alloc_slice_into_array", issue = "148082")] + #[inline] + pub fn into_array(self) -> Result, Self> { + if self.len() == N { + let (ptr, alloc) = Self::into_raw_with_allocator(self); + let ptr = ptr as *const [T; N]; + + // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length. + let me = unsafe { Arc::from_raw_in(ptr, alloc) }; + Ok(me) + } else { + Err(self) + } + } +} + +impl Arc, A> { + /// Converts to `Arc`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the inner value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut five = Arc::::new_uninit(); + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub unsafe fn assume_init(self) -> Arc + //@ req Arc_own::(?t, Arc:: { ptr: std::ptr::NonNull::new(self.ptr.as_ptr() as *ArcInner), alloc: self.alloc }); + //@ ens Arc_own::(t, result) &*& result.ptr.as_ptr() == self.ptr.as_ptr() as *ArcInner && result.alloc == self.alloc; + //@ on_unwind_ens false; + { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + //@ std::ptr::NonNull_Sized_as_ptr(ptr); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_inner_in(ptr.cast(), alloc) } + } +} + +impl Arc { + /// Constructs a new `Arc` with a clone of `value`. + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// use std::sync::Arc; + /// + /// let hello: Arc = Arc::clone_from_ref("hello"); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "clone_from_ref", issue = "149075")] + pub fn clone_from_ref(value: &T) -> Arc { + Arc::clone_from_ref_in(value, Global) + } + + /// Constructs a new `Arc` with a clone of `value`, returning an error if allocation fails + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// use std::sync::Arc; + /// + /// let hello: Arc = Arc::try_clone_from_ref("hello")?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_clone_from_ref(value: &T) -> Result, AllocError> { + Arc::try_clone_from_ref_in(value, Global) + } +} + +impl Arc { + /// Constructs a new `Arc` with a clone of `value` in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let hello: Arc = Arc::clone_from_ref_in("hello", System); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn clone_from_ref_in(value: &T, alloc: A) -> Arc { + // `in_progress` drops the allocation if we panic before finishing initializing it. + let mut in_progress: UniqueArcUninit = UniqueArcUninit::new(value, alloc); + + // Initialize with clone of value. + // ignore-tidy-undocumented-unsafe + unsafe { + // Clone. If the clone panics, `in_progress` will be dropped and clean up. + value.clone_to_uninit(in_progress.data_ptr().cast()); + // Cast type of pointer, now that it is initialized. + in_progress.into_arc() + } + } + + /// Constructs a new `Arc` with a clone of `value` in the provided allocator, returning an error if allocation fails + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let hello: Arc = Arc::try_clone_from_ref_in("hello", System)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_clone_from_ref_in(value: &T, alloc: A) -> Result, AllocError> { + // `in_progress` drops the allocation if we panic before finishing initializing it. + let mut in_progress: UniqueArcUninit = UniqueArcUninit::try_new(value, alloc)?; + + // Initialize with clone of value. + // ignore-tidy-undocumented-unsafe + let initialized_clone = unsafe { + // Clone. If the clone panics, `in_progress` will be dropped and clean up. + value.clone_to_uninit(in_progress.data_ptr().cast()); + // Cast type of pointer, now that it is initialized. + in_progress.into_arc() + }; + + Ok(initialized_clone) + } +} + +impl Arc<[mem::MaybeUninit], A> { + /// Converts to `Arc<[T]>`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the inner value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut values = Arc::<[u32]>::new_uninit_slice(3); + /// + /// // Deferred initialization: + /// let data = Arc::get_mut(&mut values).unwrap(); + /// data[0].write(1); + /// data[1].write(2); + /// data[2].write(3); + /// + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub unsafe fn assume_init(self) -> Arc<[T], A> + //@ req Arc_own::<[T], A>(?t, Arc::<[T], A> { ptr: std::ptr::NonNull::new(self.ptr.as_ptr() as *ArcInner<[T]>), alloc: self.alloc }); + //@ ens Arc_own::<[T], A>(t, result) &*& result.ptr.as_ptr() == self.ptr.as_ptr() as *ArcInner<[T]> && result.alloc == self.alloc; + //@ on_unwind_ens false; + { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + // SAFETY: Upheld by caller. + unsafe { Arc::from_ptr_in(NonNull_as_ptr__VeriFast_wrapper(ptr) as _, alloc) } + } +} + +impl Arc { + /// Constructs an `Arc` from a raw pointer. + /// + /// The raw pointer must have been previously returned by a call to + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator]. + /// + /// # Safety + /// + /// * Creating a `Arc` from a pointer other than one returned from + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator] + /// is undefined behavior. + /// * If `U` is sized, it must have the same size and alignment as `T`. This + /// is trivially true if `U` is `T`. + /// * If `U` is unsized, its data pointer must have the same size and + /// alignment as `T`. This is trivially true if `Arc` was constructed + /// through `Arc` and then converted to `Arc` through an [unsized + /// coercion]. + /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size + /// and alignment, this is basically like transmuting references of + /// different types. See [`mem::transmute`][transmute] for more information + /// on what restrictions apply in this case. + /// * The raw pointer must point to a block of memory allocated by the global allocator. + /// * The user of `from_raw` has to make sure a specific value of `T` is only + /// dropped once. + /// + /// This function is unsafe because improper use may lead to memory unsafety, + /// even if the returned `Arc` is never accessed. + /// + /// [into_raw]: Arc::into_raw + /// [into_raw_with_allocator]: Arc::into_raw_with_allocator + /// [transmute]: core::mem::transmute + /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let x_ptr = Arc::into_raw(x); + /// + /// unsafe { + /// // Convert back to an `Arc` to prevent leak. + /// let x = Arc::from_raw(x_ptr); + /// assert_eq!(&*x, "hello"); + /// + /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. + /// } + /// + /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! + /// ``` + /// + /// Convert a slice back into its original array: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x: Arc<[u32]> = Arc::new([1, 2, 3]); + /// let x_ptr: *const [u32] = Arc::into_raw(x); + /// + /// unsafe { + /// let x: Arc<[u32; 3]> = Arc::from_raw(x_ptr.cast::<[u32; 3]>()); + /// assert_eq!(&*x, &[1, 2, 3]); + /// } + /// ``` + #[inline] + #[stable(feature = "rc_raw", since = "1.17.0")] + pub unsafe fn from_raw(ptr: *const T) -> Self + //@ req Arc_raw_own::(?t, ptr, std::alloc::Global_alloc_id); + //@ ens Arc_own::(t, result) &*& result.ptr.as_ptr() == (ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr))) as *T) as *ArcInner && result.alloc == std::alloc::Global {}; + //@ on_unwind_ens false; + { + //@ std::alloc::produce_Allocator_Global(t); + // SAFETY: Upheld by caller. + let r = unsafe { Arc::from_raw_in(ptr, Global) }; + //@ Arc_own_in_to_own::(t, r, std::alloc::Global_alloc_id); + r + } + + /// Consumes the `Arc`, returning the wrapped pointer. + /// + /// To avoid a memory leak the pointer must be converted back to an `Arc` using + /// [`Arc::from_raw`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let x_ptr = Arc::into_raw(x); + /// assert_eq!(unsafe { &*x_ptr }, "hello"); + /// # // Prevent leaks for Miri. + /// # drop(unsafe { Arc::from_raw(x_ptr) }); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "rc_raw", since = "1.17.0")] + #[lint::never_returns_null_ptr] + pub fn into_raw(this: Self) -> *const T + //@ req pointer_within_limits(&(*this.ptr.as_ptr()).data) == true; + //@ ens result == &(*this.ptr.as_ptr()).data; + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, this); + assert [_]exists::<*ArcInner>(?ptr) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open exists::(?ex); + if ex { leak [1/2]ghost_cell(ig, ModeExclusive) &*& ((.full_borrow_content)(ot, &(*ptr).data))(); } + else { leak ticket(dlft_pred, sg, ?f) &*& [f]dlft_pred(sg, some(_)); } + leak std::alloc::Allocator(_t, this.alloc, aid); + call(); + } + @*/ + { + let mut me = ManuallyDrop::new(this); + //@ close_points_to(&me.alloc); + //@ close Arc_alloc(&me, std::alloc::Global {}); + //@ close_points_to(&me); + //@ let me_ref = precreate_ref(&me as *Arc); + //@ init_ref_readonly(me_ref, 1/2); + //@ open_points_to(me_ref); + let r = Self::as_ptr(&*me); + //@ close_points_to(me_ref, 1/2); + //@ end_ref_readonly(me_ref); + //@ open_points_to(&me); + //@ open Arc_alloc(&me, _); + //@ open_points_to(&me.alloc); + r + } + + /// Increments the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory + /// allocated by the global allocator. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// unsafe { + /// let ptr = Arc::into_raw(five); + /// Arc::increment_strong_count(ptr); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// # // Prevent leaks for Miri. + /// # Arc::decrement_strong_count(ptr); + /// } + /// ``` + #[inline] + #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] + pub unsafe fn increment_strong_count(ptr: *const T) + //@ req thread_token(?t) &*& Arc_raw_own::(t, ptr, std::alloc::Global_alloc_id); + //@ ens thread_token(t) &*& Arc_raw_own::(t, ptr, std::alloc::Global_alloc_id) &*& Arc_raw_own::(t, ptr, std::alloc::Global_alloc_id); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // SAFETY: Upheld by caller. + unsafe { Arc::increment_strong_count_in(ptr, Global) } + } + + /// Decrements the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) when invoking this method, and `ptr` must point to a block of memory + /// allocated by the global allocator. This method can be used to release the final + /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been + /// released. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// unsafe { + /// let ptr = Arc::into_raw(five); + /// Arc::increment_strong_count(ptr); + /// + /// // Those assertions are deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// Arc::decrement_strong_count(ptr); + /// assert_eq!(1, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] + pub unsafe fn decrement_strong_count(ptr: *const T) + //@ req thread_token(?t) &*& Arc_raw_own::(t, ptr, std::alloc::Global_alloc_id); + //@ ens thread_token(t); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // SAFETY: Upheld by caller. + unsafe { Arc::decrement_strong_count_in(ptr, Global) } + } + + /// Gets the number of strong (`Arc`) pointers to the allocation behind the given raw + /// pointer. + /// + /// This method does not consume or drop the `Arc` behind this pointer. + /// + /// # Safety + /// + /// The pointer must point to (and have valid metadata for) the value inside a live `Arc` + /// allocation, such as a pointer returned by [`Arc::into_raw`], + /// [`Arc::into_raw_with_allocator`], or [`Arc::as_ptr`]. + /// `T` must have the same alignment as that value. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method. + /// + /// Using this method correctly also requires extra care: another thread can change the + /// strong count at any time, including between calling this method and acting on the + /// result. + /// + /// # Examples + /// + /// ``` + /// #![feature(arc_raw_get_strong)] + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _also_five = Arc::clone(&five); + /// let ptr = Arc::into_raw(five); + /// + /// unsafe { + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// assert_eq!(2, Arc::strong_count_from_raw(ptr)); + /// + /// // Convert back to an `Arc` to avoid leaking memory. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[must_use] + #[unstable(feature = "arc_raw_get_strong", issue = "157021")] + pub unsafe fn strong_count_from_raw(ptr: *const T) -> usize { + // SAFETY: Upheld by caller. + let offset = unsafe { data_offset(ptr) }; + // Reverse the offset to find the original ArcInner. + // SAFETY: Caller ensures this pointer was to an `Arc` allocation, + // so offsetting must be inbounds. + let arc_ptr = unsafe { ptr.byte_sub(offset) as *mut ArcInner }; + // SAFETY: Per the above, an `ArcInner` is stored here. + unsafe { (*arc_ptr).strong.load(Relaxed) } + } +} + +impl Arc { + /// Returns a reference to the underlying allocator. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::allocator(&a)` instead of `a.allocator()`. This + /// is so that there is no conflict with a method on the inner type. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn allocator<'a>(this: &'a Self) -> &'a A + //@ req [?qa]lifetime_token('a) &*& [_]Arc_share::('a, ?t, this); + //@ ens [qa]lifetime_token('a) &*& [_](.share)('a, t, result); + //@ on_unwind_ens false; + { + //@ open Arc_share::('a, t, this); + //@ std::alloc::close_Allocator_share::('a, t, &(*this).alloc); + //@ let alloc_ref = precreate_ref(&(*this).alloc); + //@ produce_type_interp::(); + //@ init_ref_share::('a, t, alloc_ref); + //@ leak type_interp::(); + //@ open_frac_borrow('a, ref_initialized_(alloc_ref), qa); + //@ open [?f]ref_initialized_::(alloc_ref)(); + let r = &this.alloc; + //@ close [f]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f, ref_initialized_(alloc_ref)); + r + } + + /// Consumes the `Arc`, returning the wrapped pointer and allocator. + /// + /// To avoid a memory leak the pointer must be converted back to an `Arc` using + /// [`Arc::from_raw_in`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x = Arc::new_in("hello".to_owned(), System); + /// let (ptr, alloc) = Arc::into_raw_with_allocator(x); + /// assert_eq!(unsafe { &*ptr }, "hello"); + /// let x = unsafe { Arc::from_raw_in(ptr, alloc) }; + /// assert_eq!(&*x, "hello"); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn into_raw_with_allocator(this: Self) -> (*const T, A) + //@ req pointer_within_limits(&(*this.ptr.as_ptr()).data) == true; + //@ ens result.0 == &(*this.ptr.as_ptr()).data && result.1 == this.alloc; + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, this); + assert [_]exists::<*ArcInner>(?ptr) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open exists::(?ex); + if ex { leak [1/2]ghost_cell(ig, ModeExclusive) &*& ((.full_borrow_content)(ot, &(*ptr).data))(); } + else { leak ticket(dlft_pred, sg, ?f) &*& [f]dlft_pred(sg, some(_)); } + let r = call(); + std::alloc::Allocator_to_own(r.1); + close raw_ptr_own::()(_t, r.0); + close_tuple_2_own::<*const T, A>(_t, r); + } + @*/ + { + let mut me = mem::ManuallyDrop::new(this); + //@ close_points_to(&me); + //@ let me_ref = precreate_ref(&me as *Arc); + //@ init_ref_readonly(me_ref, 1/2); + //@ open_points_to(me_ref); + let ptr = Self::as_ptr(&me); + //@ close_points_to(me_ref, 1/2); + //@ end_ref_readonly(me_ref); + //@ let me_ref2 = precreate_ref(&me as *Arc); + //@ init_ref_readonly(me_ref2, 1/2); + //@ open_points_to(me_ref2); + //@ let alloc_ref = precreate_ref(&(*me_ref2).alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped + let alloc = unsafe { ptr::read(&me.alloc) }; + //@ end_ref_readonly(alloc_ref); + //@ close_points_to(me_ref2, 1/2); + //@ end_ref_readonly(me_ref2); + //@ open_points_to(&me); + (ptr, alloc) + } + + /// Provides a raw pointer to the data. + /// + /// The counts are not affected in any way and the `Arc` is not consumed. The pointer is valid for + /// as long as there are strong counts in the `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let y = Arc::clone(&x); + /// let x_ptr = Arc::as_ptr(&x); + /// assert_eq!(x_ptr, Arc::as_ptr(&y)); + /// assert_eq!(unsafe { &*x_ptr }, "hello"); + /// ``` + #[must_use] + #[stable(feature = "rc_as_ptr", since = "1.45.0")] + #[lint::never_returns_null_ptr] + pub fn as_ptr<'a>(this: &'a Self) -> *const T + //@ req [?f](*this).ptr |-> ?nnp &*& pointer_within_limits(&(*nnp.as_ptr()).data) == true; + //@ ens [f](*this).ptr |-> nnp &*& result == &(*nnp.as_ptr()).data; + //@ on_unwind_ens false; + /*@ + safety_proof { + open Arc_share::('a, _t, this); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& + [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open_frac_borrow('a, Arc_ptr_bc(this, nnp), _q_a); + open [?f]Arc_ptr_bc::(this, nnp)(); + let r = call(); + close [f]Arc_ptr_bc::(this, nnp)(); + close_frac_borrow(f, Arc_ptr_bc(this, nnp)); + } + @*/ + { + let ptr: *mut ArcInner = NonNull_as_ptr__VeriFast_wrapper(this.ptr); + + // SAFETY: This cannot go through Deref::deref or ArcInnerPtr::inner because + // this is required to retain raw/mut provenance such that e.g. `get_mut` can + // write through the pointer after the Arc is recovered through `from_raw`. + unsafe { &raw mut (*ptr).data } + } + + /// Constructs an `Arc` from a raw pointer. + /// + /// The raw pointer must have been previously returned by a call to [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator]. + /// + /// # Safety + /// + /// * Creating a `Arc` from a pointer other than one returned from + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator] + /// is undefined behavior. + /// * If `U` is sized, it must have the same size and alignment as `T`. This + /// is trivially true if `U` is `T`. + /// * If `U` is unsized, its data pointer must have the same size and + /// alignment as `T`. This is trivially true if `Arc` was constructed + /// through `Arc` and then converted to `Arc` through an [unsized + /// coercion]. + /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size + /// and alignment, this is basically like transmuting references of + /// different types. See [`mem::transmute`][transmute] for more information + /// on what restrictions apply in this case. + /// * The raw pointer must point to a block of memory allocated by `alloc` + /// * The user of `from_raw` has to make sure a specific value of `T` is only + /// dropped once. + /// + /// This function is unsafe because improper use may lead to memory unsafety, + /// even if the returned `Arc` is never accessed. + /// + /// [into_raw]: Arc::into_raw + /// [into_raw_with_allocator]: Arc::into_raw_with_allocator + /// [transmute]: core::mem::transmute + /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x = Arc::new_in("hello".to_owned(), System); + /// let (x_ptr, alloc) = Arc::into_raw_with_allocator(x); + /// + /// unsafe { + /// // Convert back to an `Arc` to prevent leak. + /// let x = Arc::from_raw_in(x_ptr, System); + /// assert_eq!(&*x, "hello"); + /// + /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. + /// } + /// + /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! + /// ``` + /// + /// Convert a slice back into its original array: + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x: Arc<[u32], _> = Arc::new_in([1, 2, 3], System); + /// let x_ptr: *const [u32] = Arc::into_raw_with_allocator(x).0; + /// + /// unsafe { + /// let x: Arc<[u32; 3], _> = Arc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System); + /// assert_eq!(&*x, &[1, 2, 3]); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self + //@ req Arc_raw_own::(?t, ptr, ?aid) &*& std::alloc::Allocator(t, alloc, aid); + //@ ens Arc_own_in::(t, result, aid) &*& result.ptr.as_ptr() == (ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr))) as *T) as *ArcInner && result.alloc == alloc; + //@ on_unwind_ens false; + { + //@ open Arc_raw_own::(t, ptr, aid); + // SAFETY: Upheld by caller. + unsafe { + let offset = data_offset(ptr); + + // Reverse the offset to find the original ArcInner. + let arc_ptr = ptr_byte_sub__VeriFast_wrapper(ptr, offset) as *mut ArcInner; + + let r = Self::from_ptr_in(arc_ptr, alloc); + //@ close exists::<*ArcInner>(arc_ptr); + //@ leak exists::<*ArcInner>(arc_ptr); + //@ close Arc_own_in::(t, r, aid); + r + } + } + + /// Creates a new [`Weak`] pointer to this allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let weak_five = Arc::downgrade(&five); + /// ``` + #[must_use = "this returns a new `Weak` pointer, \ + without modifying the original `Arc`"] + #[stable(feature = "arc_weak", since = "1.4.0")] + pub fn downgrade<'a>(this: &'a Self) -> Weak + where + A: AllocatorClone, + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_]Arc_share::('a, t, this); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& Weak_own::(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ open Arc_share::('a, t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]std::alloc::Allocator_share('a, t, &(*this).alloc, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, Arc_ptr_bc(this, nnp), qa / 2); + //@ open [?qnnp]Arc_ptr_bc::(this, nnp)(); + // This Relaxed is OK because we're checking the value in the CAS + // below. + let mut cur; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).weak, Frame, load_any, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + Arc_is_shared_from_borrow(sg, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame(); + close PostAcq(r); + }; + @*/ + //@ close Frame(); + cur = this.inner().weak.load(Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, cur)); + } + + loop { + /*@ + inv thread_token(t) &*& + [qa / 2]lifetime_token('a) &*& + [qnnp]((*this).ptr |-> nnp) &*& + [qnnp]struct_Arc_padding(this) &*& + close_frac_borrow_token(qnnp, Arc_ptr_bc(this, nnp), qa / 2, 'a) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& + [_]std::alloc::Allocator_share('a, t, &(*this).alloc, aid) &*& + pointer_within_limits(&(*this).alloc) == true &*& + [_]ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + @*/ + // check if the weak counter is currently "locked"; if so, spin. + if cur == usize::MAX { + hint::spin_loop(); + { + /*@ + pred Frame2() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq2(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).weak, Frame2, load_any, PostAcq2)() { + open Frame2(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + Arc_is_shared_from_borrow(sg, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame2(); + close PostAcq2(r); + }; + @*/ + //@ close Frame2(); + cur = this.inner().weak.load(Relaxed); //~ignore_ref_creation + //@ open Frame2(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq2, cur)); + } + continue; + } + + // We can't allow the refcount to increase much past `MAX_REFCOUNT`. + if cur > MAX_REFCOUNT { + //@ close [qnnp]Arc_ptr_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_ptr_bc(this, nnp)); + panic_arc_overflow(); + } + + // Unlike with Clone(), we need this to be an Acquire read to + // synchronize with the write coming from `is_unique`, so that the + // events prior to that write happen before this read. + let cas_res; + { + /*@ + pred Pre() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostOk(pv: usize) = [qa / 2]lifetime_token('a) &*& + ticket(weak_pred, wg, ?wfrac) &*& [wfrac]weak_pred(wg, false); + pred PostErrAcq(pv: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_weak_ghop(&(*ptr).weak, cur, cur + 1, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + Arc_is_shared_from_borrow(sg, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_weak_op(?op, _, _, _, ?spurious, _, ?Q); + op(); + assert Q(?r); + match r { + Result::Ok(v_ok) => { + create_ticket(weak_pred, wg); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + }; + @*/ + //@ close Pre(); + cas_res = this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed); //~ignore_ref_creation + /*@ + match cas_res { + Result::Ok(v_res) => { open PostOk(v_res); } + Result::Err(v_err) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_err)); + } + } + @*/ + match cas_res { + Ok(_) => { + // Make sure we do not create a dangling Weak + if cfg!(debug_assertions) { + if !(!is_dangling(NonNull_as_ptr__VeriFast_wrapper(this.ptr))) { + core::panicking::panic("assertion failed: !is_dangling(this.ptr.as_ptr())"); + } + } + let ptr_val = this.ptr; + //@ close [qnnp]Arc_ptr_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_ptr_bc(this, nnp)); + let a_clone = unsafe { Allocator_clone_from_share__VeriFast_wrapper(&this.alloc) }; //~ignore_ref_creation + let w = Weak { ptr: ptr_val, alloc: a_clone }; + //@ close exists(false); + //@ close Weak_own::(t, w); + return w; + } + Err(old) => { + cur = old; + } + } + } + } + } + + /// Gets the number of [`Weak`] pointers to this allocation. + /// + /// # Safety + /// + /// This method by itself is safe, but using it correctly requires extra care. + /// Another thread can change the weak count at any time, + /// including potentially between calling this method and acting on the result. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _weak_five = Arc::downgrade(&five); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` or `Weak` between threads. + /// assert_eq!(1, Arc::weak_count(&five)); + /// ``` + #[inline] + #[must_use] + #[stable(feature = "arc_counts", since = "1.15.0")] + pub fn weak_count<'a>(this: &'a Self) -> usize + //@ req [?qa]lifetime_token('a) &*& [_]Arc_share::('a, ?t, this); + //@ ens [qa]lifetime_token('a); + //@ on_unwind_ens false; + { + //@ open Arc_share::('a, t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, Arc_ptr_bc(this, nnp), qa / 2); + //@ open [?qnnp]Arc_ptr_bc::(this, nnp)(); + let cnt; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq(r: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).weak, Frame, load_ge_one, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + Arc_is_shared_from_borrow(sg, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?r); + close Frame(); + close PostAcq(r); + }; + @*/ + //@ close Frame(); + cnt = this.inner().weak.load(Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, cnt)); + } + //@ close [qnnp]Arc_ptr_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_ptr_bc(this, nnp)); + // If the weak count is currently locked, the value of the + // count was 0 just before taking the lock. + if cnt == usize::MAX { 0 } else { cnt - 1 } + } + + /// Gets the number of strong (`Arc`) pointers to this allocation. + /// + /// # Safety + /// + /// This method by itself is safe, but using it correctly requires extra care. + /// Another thread can change the strong count at any time, + /// including potentially between calling this method and acting on the result. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _also_five = Arc::clone(&five); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// assert_eq!(2, Arc::strong_count(&five)); + /// ``` + #[inline] + #[must_use] + #[stable(feature = "arc_counts", since = "1.15.0")] + pub fn strong_count<'a>(this: &'a Self) -> usize + //@ req [?qa]lifetime_token('a) &*& [_]Arc_share::('a, ?t, this); + //@ ens [qa]lifetime_token('a); + //@ on_unwind_ens false; + { + //@ open Arc_share::('a, t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, Arc_ptr_bc(this, nnp), qa / 2); + //@ open [?qnnp]Arc_ptr_bc::(this, nnp)(); + let r; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred PostAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).strong, Frame, load_any, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + Arc_is_shared_from_borrow(sg, dk, frac); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?v); + close Frame(); + close PostAcq(v); + }; + @*/ + //@ close Frame(); + r = this.inner().strong.load(Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, r)); + } + //@ close [qnnp]Arc_ptr_bc::(this, nnp)(); + //@ close_frac_borrow(qnnp, Arc_ptr_bc(this, nnp)); + r + } + + /// Increments the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory + /// allocated by `alloc`. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// + /// unsafe { + /// let (ptr, _alloc) = Arc::into_raw_with_allocator(five); + /// Arc::increment_strong_count_in(ptr, System); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw_in(ptr, System); + /// assert_eq!(2, Arc::strong_count(&five)); + /// # // Prevent leaks for Miri. + /// # Arc::decrement_strong_count_in(ptr, System); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A) + where + A: AllocatorClone, + //@ req thread_token(?t) &*& Arc_raw_own::(t, ptr, ?aid) &*& std::alloc::Allocator(t, alloc, aid); + //@ ens thread_token(t) &*& Arc_raw_own::(t, ptr, aid) &*& Arc_raw_own::(t, ptr, aid); + //@ on_unwind_ens thread_token(t); + { + //@ Arc_raw_own_facts::(t, ptr, aid); + // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop + // SAFETY: Upheld by caller. + let mut arc = unsafe { mem::ManuallyDrop::new(Arc::from_raw_in(ptr, alloc)) }; + //@ open Arc_own_in::(t, ?r_orig, aid); + //@ let nnp = r_orig.ptr; + //@ assert [_]exists::<*ArcInner>(?arc_p) &*& std::alloc::Allocator(t, r_orig.alloc, aid) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, arc_p); + //@ open exists::(?exclusive); + //@ let k = begin_lifetime(); + //@ let arc_addr = &arc as *Arc; + //@ points_to_limits(&(*arc_addr).alloc); + //@ close Arc_ptr_bc::(arc_addr, nnp)(); + //@ borrow(k, Arc_ptr_bc::(arc_addr, nnp)); + //@ std::alloc::close_Allocator_full_borrow_content_::(t, &(*arc_addr).alloc); + //@ borrow(k, std::alloc::Allocator_full_borrow_content_::(t, &(*arc_addr).alloc, aid)); + { + /*@ + pred Pre() = + type_interp::() &*& type_interp::() &*& + [_]ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, arc_p) &*& + [1/2]lifetime_token(k) &*& + full_borrow(k, Arc_ptr_bc::(arc_addr, nnp)) &*& + full_borrow(k, std::alloc::Allocator_full_borrow_content_::(t, &(*arc_addr).alloc, aid)) &*& + if exclusive { + [1/2]ghost_cell(ig, ModeExclusive) &*& + ((.full_borrow_content)(ot, &(*arc_p).data))() + } else { + ticket(dlft_pred, sg, ?f0) &*& [f0]dlft_pred(sg, some(?dk0)) &*& + [_](.share)(dk0, ot, &(*arc_p).data) + }; + pred Post() = + [1/2]lifetime_token(k) &*& + [_]frac_borrow(k, Arc_ptr_bc::(arc_addr, nnp)) &*& + [_]std::alloc::Allocator_share(k, t, &(*arc_addr).alloc, aid) &*& + [_]exists::(?dk1) &*& [_]exists::(?f1) &*& + [_]frac_borrow(k, strong_ticket_(sg, dk1, f1)) &*& + [_]frac_borrow(k, lifetime_token_(f1, dk1)) &*& + [_](.share)(dk1, ot, &(*arc_p).data) &*& + borrow_end_token(k, strong_ticket_(sg, dk1, f1)) &*& + borrow_end_token(k, lifetime_token_(f1, dk1)); + @*/ + //@ produce_type_interp::(); + //@ produce_type_interp::(); + //@ close Pre(); + /*@ + produce_lem_ptr_chunk atomic_block(Pre, Post)() { + open Pre(); + if exclusive { + Arc_exclusive_to_shared::(ig, sg, wg, lg, img, aid, lay, ot, arc_p); + } else {} + assert ticket(dlft_pred, sg, ?f1) &*& [f1]dlft_pred(sg, some(?dk1)); + open [f1]dlft_pred(sg, some(dk1)); + full_borrow_into_frac_m(k, Arc_ptr_bc::(arc_addr, nnp)); + std::alloc::share_Allocator_full_borrow_content_m::(k, t, &(*arc_addr).alloc, aid); + close strong_ticket_(sg, dk1, f1)(); + borrow_m(k, strong_ticket_(sg, dk1, f1)); + full_borrow_into_frac_m(k, strong_ticket_(sg, dk1, f1)); + close lifetime_token_(f1, dk1)(); + borrow_m(k, lifetime_token_(f1, dk1)); + full_borrow_into_frac_m(k, lifetime_token_(f1, dk1)); + close exists(dk1); + leak exists(dk1); + close exists(f1); + leak exists(f1); + leak type_interp::(); + leak type_interp::(); + close Post(); + } { + perform_atomically(); + } + @*/ + //@ open Post(); + } + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ close exists(nnp); + //@ leak exists(nnp); + //@ close Arc_share::(k, t, arc_addr); + //@ leak Arc_share::(k, t, arc_addr); + //@ close exists::>>(nnp); + // Now increase refcount, but don't drop new refcount either + let _arc_clone: mem::ManuallyDrop<_> = unsafe { ManuallyDrop_clone_Arc__VeriFast_wrapper(&arc) }; //~ignore_ref_creation + //@ close exists::(false); + //@ close Arc_raw_own::(t, ptr, aid); + //@ end_lifetime(k); + //@ borrow_end(k, Arc_ptr_bc::(arc_addr, nnp)); + //@ open Arc_ptr_bc::(arc_addr, nnp)(); + //@ borrow_end(k, std::alloc::Allocator_full_borrow_content_::(t, &(*arc_addr).alloc, aid)); + //@ std::alloc::open_Allocator_full_borrow_content_::(t, &(*arc_addr).alloc, aid); + //@ close Arc_alloc(arc_addr, _); + //@ borrow_end(k, strong_ticket_(sg, dk, frac)); + //@ open strong_ticket_(sg, dk, frac)(); + //@ borrow_end(k, lifetime_token_(frac, dk)); + //@ open lifetime_token_(frac, dk)(); + //@ close [frac]dlft_pred(sg, some(dk)); + //@ leak std::alloc::Allocator(t, _, aid); + //@ close exists::(false); + //@ close Arc_raw_own::(t, ptr, aid); + } + + /// Decrements the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) when invoking this method, and `ptr` must point to a block of memory + /// allocated by `alloc`. This method can be used to release the final + /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been + /// released. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// + /// unsafe { + /// let (ptr, _alloc) = Arc::into_raw_with_allocator(five); + /// Arc::increment_strong_count_in(ptr, System); + /// + /// // Those assertions are deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw_in(ptr, System); + /// assert_eq!(2, Arc::strong_count(&five)); + /// Arc::decrement_strong_count_in(ptr, System); + /// assert_eq!(1, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A) + //@ req thread_token(?t) &*& Arc_raw_own::(t, ptr, ?aid) &*& std::alloc::Allocator(t, alloc, aid); + //@ ens thread_token(t); + //@ on_unwind_ens thread_token(t); + { + // SAFETY: Upheld by caller. + unsafe { + let a = Arc::from_raw_in(ptr, alloc); + //@ Arc_own_in_to_own::(t, a, aid); + drop(a) + }; + } + + #[inline] + fn inner<'a>(&'a self) -> &'a ArcInner + //@ req [?f](*self).ptr |-> ?nnp &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, nnp.as_ptr()); + //@ ens [f](*self).ptr |-> nnp &*& result == nnp.as_ptr(); + //@ on_unwind_ens false; + /*@ + safety_proof { + open Arc_share::('a, _t, self); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + open_frac_borrow('a, Arc_ptr_bc(self, nnp), _q_a); + open [?f]Arc_ptr_bc::(self, nnp)(); + let r = call(); + close [f]Arc_ptr_bc::(self, nnp)(); + close_frac_borrow(f, Arc_ptr_bc(self, nnp)); + close ArcInner_share::('a, _t, r); + leak ArcInner_share::('a, _t, r); + } + @*/ + { + //@ points_to_limits(&(*self).ptr); + // SAFETY: While this arc is alive we're guaranteed + // that the inner pointer is valid. Furthermore, we know that the + // `ArcInner` structure itself is `Sync` if the inner data is + // `Sync` as well, so we're ok loaning out an immutable pointer to these + // contents. + unsafe { NonNull_as_ref_ArcInner__VeriFast_wrapper(&self.ptr) } //~ignore_ref_creation + } + + // Non-inlined part of `drop`. + #[inline(never)] + unsafe fn drop_slow(&mut self) + /*@ + req thread_token(?t) &*& + (*self).ptr |-> ?nnp &*& + (*self).alloc |-> ?alloc &*& + std::alloc::Allocator(t, alloc, ?aid) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr) &*& + (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [1/2]ghost_cell(img, 1) &*& + ((.full_borrow_content)(ot, &(*ptr).data))(); + @*/ + //@ ens thread_token(t) &*& (*self).ptr |-> nnp &*& (*self).alloc |-> ?alloc1 &*& std::alloc::Allocator(t, alloc1, aid); + //@ on_unwind_ens thread_token(t); + { + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ points_to_limits(&(*self).alloc); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k_alloc = begin_lifetime(); + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + // Drop the weak ref collectively held by all strong references when this + // variable goes out of scope. This ensures that the memory is deallocated + // even if the destructor of `T` panics. + // Take a reference to `self.alloc` instead of cloning because 1. it'll last long + // enough, and 2. you should be able to drop `Arc`s with unclonable allocators + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + + // Destroy the data at this time, even though we must not free the box + // allocation itself (there might still be weak pointers lying around). + // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed. + // ignore-tidy-undocumented-unsafe + //@ open_full_borrow_content_unsized::(ot, &(*ptr).data); + //@ assert (*ptr).data |-> ?val; + //@ if ot != t { produce_type_interp::(); Send_send_unsized::(ot, t, val); leak type_interp::(); } else {} + unsafe { ptr::drop_in_place(&mut (*NonNull_as_ptr__VeriFast_wrapper(self.ptr)).data) }; + //@ close exists(true); + //@ close Weak_own::(t, _weak); + drop/*@::>@*/(_weak); + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + } + + /// Returns `true` if the two `Arc`s point to the same allocation in a vein similar to + /// [`ptr::eq`]. This function ignores the metadata of `dyn Trait` pointers. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let same_five = Arc::clone(&five); + /// let other_five = Arc::new(5); + /// + /// assert!(Arc::ptr_eq(&five, &same_five)); + /// assert!(!Arc::ptr_eq(&five, &other_five)); + /// ``` + /// + /// [`ptr::eq`]: core::ptr::eq "ptr::eq" + #[inline] + #[must_use] + #[stable(feature = "ptr_eq", since = "1.17.0")] + pub fn ptr_eq<'a, 'b>(this: &'a Self, other: &'b Self) -> bool + //@ req [?f1](*this).ptr |-> ?nnp1 &*& [?f2](*other).ptr |-> ?nnp2; + //@ ens [f1](*this).ptr |-> nnp1 &*& [f2](*other).ptr |-> nnp2 &*& result == ((nnp1.as_ptr() as usize) == (nnp2.as_ptr() as usize)); + //@ on_unwind_ens false; + /*@ + safety_proof { + open Arc_share::('a, _t, this); + assert [_]exists::>>(?nnp1); + open_frac_borrow('a, Arc_ptr_bc(this, nnp1), _q_a); + open [?f1]Arc_ptr_bc::(this, nnp1)(); + open Arc_share::('b, _t, other); + assert [_]exists::>>(?nnp2); + open_frac_borrow('b, Arc_ptr_bc(other, nnp2), _q_b); + open [?f2]Arc_ptr_bc::(other, nnp2)(); + let r = call(); + close [f2]Arc_ptr_bc::(other, nnp2)(); + close_frac_borrow(f2, Arc_ptr_bc(other, nnp2)); + close [f1]Arc_ptr_bc::(this, nnp1)(); + close_frac_borrow(f1, Arc_ptr_bc(this, nnp1)); + } + @*/ + { + ptr_addr_eq__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(this.ptr), NonNull_as_ptr__VeriFast_wrapper(other.ptr)) + } +} + +impl Arc { + /// Allocates an `ArcInner` with sufficient space for + /// a possibly-unsized inner value where the value has the layout provided. + /// + /// The function `mem_to_arcinner` is called with the data pointer + /// and must return back a (potentially fat)-pointer for the `ArcInner`. + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_layout( + value_layout: Layout, + allocate: impl FnOnce(Layout) -> Result, AllocError>, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> *mut ArcInner { + let layout = arcinner_layout_for_value_layout(value_layout); + + let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)); + + // ignore-tidy-undocumented-unsafe + unsafe { Self::initialize_arcinner(ptr, layout, mem_to_arcinner) } + } + + /// Allocates an `ArcInner` with sufficient space for + /// a possibly-unsized inner value where the value has the layout provided, + /// returning an error if allocation fails. + /// + /// The function `mem_to_arcinner` is called with the data pointer + /// and must return back a (potentially fat)-pointer for the `ArcInner`. + unsafe fn try_allocate_for_layout( + value_layout: Layout, + allocate: impl FnOnce(Layout) -> Result, AllocError>, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> Result<*mut ArcInner, AllocError> { + let layout = arcinner_layout_for_value_layout(value_layout); + + let ptr = allocate(layout)?; + + // ignore-tidy-undocumented-unsafe + let inner = unsafe { Self::initialize_arcinner(ptr, layout, mem_to_arcinner) }; + + Ok(inner) + } + + unsafe fn initialize_arcinner( + ptr: NonNull<[u8]>, + layout: Layout, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> *mut ArcInner { + let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr()); + // SAFETY: Upheld by caller. + debug_assert_eq!(unsafe { Layout::for_value_raw(inner) }, layout); + + // ignore-tidy-undocumented-unsafe + unsafe { + (&raw mut (*inner).strong).write(atomic::AtomicUsize::new(1)); + (&raw mut (*inner).weak).write(atomic::AtomicUsize::new(1)); + } + + inner + } +} + +impl Arc { + /// Allocates an `ArcInner` with sufficient space for an unsized inner value. + #[inline] + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_ptr_in<'a>(ptr: *const T, alloc: &'a A) -> *mut ArcInner + //@ req thread_token(?t) &*& std::alloc::Allocator::<&'a A>(t, alloc, ?aid) &*& [_]ValidValueMetadata::(ptr, std::alloc::Layout::for_value(ptr)); + /*@ + ens thread_token(t) &*& std::alloc::Allocator::<&'a A>(t, alloc, aid) &*& + ArcInner_backing::(aid, arcinner_padded_layout(std::alloc::Layout::for_value(ptr)), result) &*& + arc_atomic_cas::AtomicUsize(&(*result).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*result).weak, 1) &*& + (*result).data |-?-> _ &*& + pointer_within_limits(&(*result).strong) == true &*& + pointer_within_limits(&(*result).weak) == true &*& + pointer_within_limits(&(*result).data) == true &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(&(*result).data as pointer) == true &*& + (result as usize) != 0 &*& (result as usize) != usize::MAX &*& + arcinner_padded_layout(std::alloc::Layout::for_value(ptr)) == std::alloc::Layout::for_value(result); + @*/ + //@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::<&'a A>(t, alloc, aid); + { + // Allocate for the `ArcInner` using the given value. + // ignore-tidy-undocumented-unsafe + unsafe { + let layout = Layout_for_value_ptr__VeriFast_wrapper(ptr); + Arc_alloc_for_val_in__VeriFast_wrapper::(ptr, layout, alloc) //~ignore_ref_creation + } + } + + #[cfg(not(no_global_oom_handling))] + fn from_box_in(mut src: Box) -> Arc + //@ req thread_token(?t) &*& >.own(t, src); + //@ ens thread_token(t) &*& Arc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + // ignore-tidy-undocumented-unsafe + unsafe { + let value_size = Box_size_of_val__VeriFast_wrapper(&src); //~ignore_ref_creation + //@ assert Box_unpacked::(t, ?val_ptr, ?aid); + let ptr; + //@ let k_box = begin_lifetime(); + { + //@ let_lft 'a = k_box; + ptr = Self::allocate_for_ptr_in/*@::@*/( + Box_deref_const__VeriFast_wrapper(&src), //~ignore_ref_creation + Box_allocator_ref__VeriFast_wrapper/*@::@*/(&src), //~ignore_ref_creation + ); //~ignore_ref_creation + //@ leak std::alloc::Allocator::<&'a A>(t, _, aid); + } + //@ end_lifetime(k_box); + //@ close exists::(t); + //@ close exists::<*T>(val_ptr); + //@ close exists::<*T>(&(*ptr).data); + // Copy value as bytes + ptr_copy_unsized_data__VeriFast_wrapper::( + Box_data_ptr_u8__VeriFast_wrapper(&src), //~ignore_ref_creation + (&raw mut (*ptr).data) as *mut u8, + value_size, + ); + + // Free the allocation without dropping its contents + let alloc = Box_free_moved_unsized__VeriFast_wrapper(src); + let a = Self::from_ptr_in(ptr, alloc); + //@ init_Arc_from_raw_parts_in::(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::for_value(val_ptr))); + a + } + } +} + +impl Arc<[T]> { + /// Allocates an `ArcInner<[T]>` with the given length. + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> + //@ req thread_token(?t); + /*@ + ens thread_token(t) &*& + ArcInner_backing::<[T]>(std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())), result) &*& + arc_atomic_cas::AtomicUsize(&(*result).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*result).weak, 1) &*& + (*result).data |-?-> _ &*& + pointer_within_limits(&(*result).strong) == true &*& + pointer_within_limits(&(*result).weak) == true &*& + pointer_within_limits(&(*result).data) == true &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(&(*result).data as pointer) == true &*& + (result as usize) != 0 &*& (result as usize) != usize::MAX &*& + arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())) == std::alloc::Layout::for_value(result); + @*/ + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + let r = unsafe { Arc_alloc_slice_in__VeriFast_wrapper::(len, Global, false) }; + //@ leak std::alloc::Allocator(t, std::alloc::Global {}, std::alloc::Global_alloc_id); + r + } + + /// Copy elements from slice into newly allocated `Arc<[T]>` + /// + /// Unsafe because the caller must either take ownership, bind `T: Copy` or + /// bind `T: TrivialClone`. + #[cfg(not(no_global_oom_handling))] + unsafe fn copy_from_slice<'a>(v: &'a [T]) -> Arc<[T]> + //@ req thread_token(?t) &*& TrivialClone_witness::() &*& [?qa]lifetime_token('a) &*& [_](<[T]>.share)('a, t, v); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& Arc_own::<[T], std::alloc::Global>(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ std::alloc::produce_Allocator_Global(t); + // ignore-tidy-undocumented-unsafe + unsafe { + let ptr = Self::allocate_for_slice(v.len()); + //@ close exists::<*[T]>(v); + //@ close exists::<*[T]>(&(*ptr).data); + ptr_copy_shared_slice_to_arcinner__VeriFast_wrapper(v.as_ptr(), (&raw mut (*ptr).data) as *mut T, v.len()); + + let a = Self::from_ptr(ptr); + //@ init_Arc_from_raw_parts_in::<[T], std::alloc::Global>(t, a.ptr, a.alloc, std::alloc::Global_alloc_id, arcinner_padded_layout(std::alloc::Layout::from_size_align(v.len() * std::mem::size_of::(), std::mem::align_of::()))); + a + } + } + + /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size. + /// + /// Behavior is undefined should the size be wrong. + #[cfg(not(no_global_oom_handling))] + unsafe fn from_iter_exact(iter: impl Iterator, len: usize) -> Arc<[T]> { + // Panic guard while cloning T elements. + // In the event of a panic, elements that have been written + // into the new ArcInner will be dropped, then the memory freed. + struct Guard { + mem: NonNull, + elems: *mut T, + layout: Layout, + n_elems: usize, + } + + impl Drop for Guard { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + let slice = from_raw_parts_mut(self.elems, self.n_elems); + ptr::drop_in_place(slice); + + Global.deallocate(self.mem, self.layout); + } + } + } + + // ignore-tidy-undocumented-unsafe + unsafe { + let ptr = Self::allocate_for_slice(len); + + let mem = ptr as *mut _ as *mut u8; + let layout = Layout::for_value_raw(ptr); + + // Pointer to first element + let elems = (&raw mut (*ptr).data) as *mut T; + + let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 }; + + for (i, item) in iter.enumerate() { + ptr::write(elems.add(i), item); + guard.n_elems += 1; + } + + // All clear. Forget the guard so it doesn't free the new ArcInner. + mem::forget(guard); + + Self::from_ptr(ptr) + } + } +} + +impl Arc<[T], A> { + /// Allocates an `ArcInner<[T]>` with the given length. + #[inline] + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_slice_in<'a>(len: usize, alloc: &'a A) -> *mut ArcInner<[T]> + //@ req thread_token(?t) &*& std::alloc::Allocator::<&'a A>(t, alloc, ?aid); + /*@ + ens thread_token(t) &*& std::alloc::Allocator::<&'a A>(t, alloc, aid) &*& + ArcInner_backing::<[T]>(aid, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())), result) &*& + arc_atomic_cas::AtomicUsize(&(*result).strong, 1) &*& + arc_atomic_cas::AtomicUsize(&(*result).weak, 1) &*& + (*result).data |-?-> _ &*& + pointer_within_limits(&(*result).strong) == true &*& + pointer_within_limits(&(*result).weak) == true &*& + pointer_within_limits(&(*result).data) == true &*& + ptr_within_limits(result as pointer) == true &*& + ptr_within_limits(&(*result).data as pointer) == true &*& + (result as usize) != 0 &*& (result as usize) != usize::MAX &*& + arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::())) == std::alloc::Layout::for_value(result); + @*/ + //@ on_unwind_ens thread_token(t) &*& std::alloc::Allocator::<&'a A>(t, alloc, aid); + { + // ignore-tidy-undocumented-unsafe + unsafe { Arc_alloc_slice_in__VeriFast_wrapper::(len, alloc, false) } //~ignore_ref_creation + } +} + +/// Specialization trait used for `From<&[T]>`. +#[cfg(not(no_global_oom_handling))] +trait ArcFromSlice { + fn from_slice(slice: &[T]) -> Self; +} + +#[cfg(not(no_global_oom_handling))] +impl ArcFromSlice for Arc<[T]> { + #[inline] + default fn from_slice(v: &[T]) -> Self { + // ignore-tidy-undocumented-unsafe + unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } + } +} + +#[cfg(not(no_global_oom_handling))] +impl ArcFromSlice for Arc<[T]> { + #[inline] + fn from_slice<'a>(v: &'a [T]) -> Self + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_](<[T]>.share)('a, t, v); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& Arc_own::<[T], std::alloc::Global>(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + // SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent + // to the above. + unsafe { Arc::copy_from_slice/*@::@*/(TrivialClone_slice_identity__VeriFast_wrapper(v)) } //~ignore_ref_creation + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Clone for Arc { + /// Makes a clone of the `Arc` pointer. + /// + /// This creates another pointer to the same allocation, increasing the + /// strong reference count. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let _ = Arc::clone(&five); + /// ``` + #[inline] + fn clone<'a>(&'a self) -> Arc + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_]Arc_share::('a, t, self); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& Arc_own::(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ open Arc_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]std::alloc::Allocator_share('a, t, &(*self).alloc, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, Arc_ptr_bc(self, nnp), qa / 2); + //@ open [?qnnp]Arc_ptr_bc::(self, nnp)(); + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object. + let old_size; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [_]frac_borrow('a, strong_ticket_(sg, dk, frac)) &*& + [_]frac_borrow('a, lifetime_token_(frac, dk)); + pred GhostPost(rv: usize) = + ticket(dlft_pred, sg, ?frac1) &*& [frac1]dlft_pred(sg, some(dk)); + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_add_relaxed_ghop(&(*ptr).strong, 1, Frame, GhostPost)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + Arc_is_shared_from_borrow(sg, dk, frac); + assert arc_atomic_cas::AtomicUsize(&(*ptr).strong, ?v0); + if v0 > isize::MAX as usize { + // Documented Rust Arc overflow assumption (arc.rs L2536, TRUSTED-MODEL.md §3.3): + // fewer than isize::MAX concurrent threads execute fetch_add before hitting abort(). + assume(v0 < usize::MAX); + } else {} + mod_eq_plus_one(v0, usize::MAX); + assert arc_atomic_cas::is_AtomicUsize_fetch_add_op(?op, _, _, _, ?Q); + op(); + assert Q(?rv); + create_ticket(dlft_pred, sg); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Frame(); + close GhostPost(rv); + }; + @*/ + //@ close Frame(); + old_size = self.inner().strong.fetch_add(1, Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ open GhostPost(old_size); + } + + if old_size > MAX_REFCOUNT { + intrinsics::abort(); + } + + let ptr_val = self.ptr; + //@ close [qnnp]Arc_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Arc_ptr_bc(self, nnp)); + let a_clone = unsafe { Allocator_clone_from_share__VeriFast_wrapper(&self.alloc) }; //~ignore_ref_creation + // SAFETY: Pointer is valid & allocator corresponds to the one used to allocate it. + let r = unsafe { Self::from_inner_in(ptr_val, a_clone) }; + //@ close exists(false); + //@ close Arc_own::(t, r); + r + } +} + +#[unstable(feature = "ergonomic_clones", issue = "132290")] +impl UseCloned for Arc {} + +#[unstable(feature = "share_trait", issue = "156756")] +impl Share for Arc {} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Deref for Arc { + type Target = T; + + #[inline] + fn deref<'a>(&'a self) -> &'a T + //@ req [?qa]lifetime_token('a) &*& [_]Arc_share::('a, ?t, self); + //@ ens [qa]lifetime_token('a) &*& [_](.share)('a, t, result); + //@ on_unwind_ens false; + { + //@ open Arc_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ assert [_]exists::(?dk) &*& [_]exists::(?frac); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, Arc_ptr_bc(self, nnp), qa / 2); + //@ open [?qnnp]Arc_ptr_bc::(self, nnp)(); + //@ frac_borrow_lft_incl('a, frac, dk); + //@ produce_type_interp::(); + //@ share_mono_unsized::(dk, 'a, ot, &(*ptr).data); + //@ if ot != t { Sync_sync_unsized::('a, ot, t, &(*ptr).data); } else {} + //@ leak type_interp::(); + let r = &self.inner().data; //~ignore_ref_creation + //@ close [qnnp]Arc_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Arc_ptr_bc(self, nnp)); + r //~ignore_ref_creation + } +} + +// The API of this pointer type enforces that if the `T` is pinned, then *all* +// clones of this `Arc` are wrapped as `Pin>`. Since an `&Arc` +// could be used to obtain an `Arc` that is not wrapped in `Pin` (and later +// used with `Arc::get_mut`), this means that this type treats `&Arc` as +// evidence that the `T` is not pinned. The implementations of various traits +// are written accordingly. Since this type is not fundamental, downstream +// crates cannot provide malicious implementations of any of the traits relevant +// for `Pin`. +#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")] +unsafe impl PinSafePointer for Arc {} + +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for Arc {} + +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Arc {} + +#[cfg(not(no_global_oom_handling))] +impl Arc { + /// Makes a mutable reference into the given `Arc`. + /// + /// If there are other `Arc` pointers to the same allocation, then `make_mut` will + /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also + /// referred to as clone-on-write. + /// + /// However, if there are no other `Arc` pointers to this allocation, but some [`Weak`] + /// pointers, then the [`Weak`] pointers will be dissociated and the inner value will not + /// be cloned. + /// + /// See also [`get_mut`], which will fail rather than cloning the inner value + /// or dissociating [`Weak`] pointers. + /// + /// [`clone`]: Clone::clone + /// [`get_mut`]: Arc::get_mut + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut data = Arc::new(5); + /// + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// let mut other_data = Arc::clone(&data); // Won't clone inner data + /// *Arc::make_mut(&mut data) += 1; // Clones inner data + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything + /// + /// // Now `data` and `other_data` point to different allocations. + /// assert_eq!(*data, 8); + /// assert_eq!(*other_data, 12); + /// ``` + /// + /// [`Weak`] pointers will be dissociated: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut data = Arc::new(75); + /// let weak = Arc::downgrade(&data); + /// + /// assert!(75 == *data); + /// assert!(75 == *weak.upgrade().unwrap()); + /// + /// *Arc::make_mut(&mut data) += 1; + /// + /// assert!(76 == *data); + /// assert!(weak.upgrade().is_none()); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn make_mut(this: &mut Self) -> &mut T { + let size_of_val = size_of_val::(&**this); + + // Note that we hold both a strong reference and a weak reference. + // Thus, releasing our strong reference only will not, by itself, cause + // the memory to be deallocated. + // + // Use Acquire to ensure that we see any writes to `weak` that happen + // before release writes (i.e., decrements) to `strong`. Since we hold a + // weak count, there's no chance the ArcInner itself could be + // deallocated. + if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() { + // Another strong pointer exists, so we must clone. + *this = Arc::clone_from_ref_in(&**this, this.alloc.clone()); + } else if this.inner().weak.load(Relaxed) != 1 { + // Relaxed suffices in the above because this is fundamentally an + // optimization: we are always racing with weak pointers being + // dropped. Worst case, we end up allocated a new Arc unnecessarily. + + // We removed the last strong ref, but there are additional weak + // refs remaining. We'll move the contents to a new Arc, and + // invalidate the other weak refs. + + // Note that it is not possible for the read of `weak` to yield + // usize::MAX (i.e., locked), since the weak count can only be + // locked by a thread with a strong reference. + + // Guard against panics while using the allocator. + // If we unwind before the Arc is overwritten, we expose a strong + // count of 0, resulting in a UAF (#155746, #157203). + // Until the new Arc is written, the old Arc must remain valid + struct Guard<'a, T: ?Sized> { + inner: &'a ArcInner, + } + impl<'a, T: ?Sized> Drop for Guard<'a, T> { + fn drop(&mut self) { + self.inner.strong.store(1, Release); + } + } + let guard = Guard { inner: this.inner() }; + + // Can just steal the data, all that's left is Weaks + // Note that this can panic in two ways: + // - The allocation can fail + // - The allocator clone can fail + let mut in_progress: UniqueArcUninit = + UniqueArcUninit::new(&**this, this.alloc.clone()); + + // ignore-tidy-undocumented-unsafe + unsafe { + // Initialize `in_progress` with move of **this. + // We have to express this in terms of bytes because `T: ?Sized`; there is no + // operation that just copies a value based on its `size_of_val()`. + ptr::copy_nonoverlapping( + ptr::from_ref(&**this).cast::(), + in_progress.data_ptr().cast::(), + size_of_val, + ); + + // We are now safe from panics. + mem::forget(guard); + + // Materialize our own implicit weak pointer, so that it can clean + // up the ArcInner as needed. + // Make sure the allocator is not leaked when the Arc is overwritten. + // Only drop at the end of the scope to avoid panics. + let _weak = Weak { ptr: this.ptr, alloc: ptr::read(&this.alloc) }; + + ptr::write(this, in_progress.into_arc()); + } + } else { + // We were the sole reference of either kind; bump back up the + // strong ref count. + this.inner().strong.store(1, Release); + } + + // SAFETY: As with `get_mut()`, our reference was + // either unique to begin with, or became one upon cloning the contents. + unsafe { Self::get_mut_unchecked(this) } + } +} + +impl Arc { + /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the + /// clone. + /// + /// Assuming `arc_t` is of type `Arc`, this function is functionally equivalent to + /// `(*arc_t).clone()`, but will avoid cloning the inner value where possible. + /// + /// # Examples + /// + /// ``` + /// # use std::{ptr, sync::Arc}; + /// let inner = String::from("test"); + /// let ptr = inner.as_ptr(); + /// + /// let arc = Arc::new(inner); + /// let inner = Arc::unwrap_or_clone(arc); + /// // The inner value was not cloned + /// assert!(ptr::eq(ptr, inner.as_ptr())); + /// + /// let arc = Arc::new(inner); + /// let arc2 = arc.clone(); + /// let inner = Arc::unwrap_or_clone(arc); + /// // Because there were 2 references, we had to clone the inner value. + /// assert!(!ptr::eq(ptr, inner.as_ptr())); + /// // `arc2` is the last reference, so when we unwrap it we get back + /// // the original `String`. + /// let inner = Arc::unwrap_or_clone(arc2); + /// assert!(ptr::eq(ptr, inner.as_ptr())); + /// ``` + #[inline] + #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")] + pub fn unwrap_or_clone(this: Self) -> T { + Arc::try_unwrap(this).unwrap_or_else(|arc| (*arc).clone()) + } +} + +impl Arc { + /// Returns a mutable reference into the given `Arc`, if there are + /// no other `Arc` or [`Weak`] pointers to the same allocation. + /// + /// Returns [`None`] otherwise, because it is not safe to + /// mutate a shared value. + /// + /// See also [`make_mut`][make_mut], which will [`clone`][clone] + /// the inner value when there are other `Arc` pointers. + /// + /// [make_mut]: Arc::make_mut + /// [clone]: Clone::clone + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut x = Arc::new(3); + /// *Arc::get_mut(&mut x).unwrap() = 4; + /// assert_eq!(*x, 4); + /// + /// let _y = Arc::clone(&x); + /// assert!(Arc::get_mut(&mut x).is_none()); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn get_mut<'a>(this: &'a mut Self) -> Option<&'a mut T> + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& full_borrow('a, Arc_full_borrow_content::(t, this)); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& >.own(t, result); + //@ on_unwind_ens false; + { + //@ let klong = open_full_borrow_strong('a, Arc_full_borrow_content::(t, this), qa); + //@ open Arc_full_borrow_content::(t, this)(); + //@ close Arc_is_unique_req::('a, t, this, true, 0); + if Self::is_unique(this) { //~ignore_ref_creation + //@ open Arc_is_unique_ens::('a, t, this, true, 0, true); + //@ assert (*this).ptr |-> ?nnp &*& (*this).alloc |-> ?alloc &*& [_]exists::<*ArcInner>(?ptr); + //@ assert std::alloc::Allocator(t, alloc, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ produce_type_interp::(); + //@ if ot != t { open_full_borrow_content_unsized::(ot, &(*ptr).data); assert (*ptr).data |-> ?v0; Send_send_unsized::(ot, t, v0); close_full_borrow_content_unsized::(t, &(*ptr).data); } else {} + // SAFETY: We're guaranteed that the pointer + // returned is the *only* pointer that will ever be returned to T. Our + // reference count is guaranteed to be 1 at this point, and we required + // the Arc itself to be `mut`, so we're returning the only possible + // reference to the inner data. + //@ close exists(t); + let data_ref = unsafe { Arc::get_mut_unchecked(this) }; //~ignore_ref_creation + /*@ + { + pred Ctx() = + type_interp::() &*& + (*this).ptr |-> nnp &*& + (*this).alloc |-> alloc &*& + struct_Arc_padding::(this) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& + std::alloc::Allocator(t, alloc, aid) &*& + [_]ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr) &*& + (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [1/2]ghost_cell(ig, ModeExclusive); + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + (.full_borrow_content)(t, data_ref), + klong, + Arc_full_borrow_content::(t, this) + )() { + open Ctx(); + if ot != t { + open_full_borrow_content_unsized::(t, data_ref); + assert *data_ref |-> ?v1; + Send_send_unsized::(t, ot, v1); + close_full_borrow_content_unsized::(ot, &(*ptr).data); + } else {} + leak type_interp::(); + close exists(true); + close Arc_own::(t, Arc:: { ptr: nnp, alloc }); + close Arc_full_borrow_content::(t, this)(); + } { + close_full_borrow_strong(klong, Arc_full_borrow_content::(t, this), (.full_borrow_content)(t, data_ref)); + } + } + @*/ + //@ full_borrow_mono(klong, 'a, (.full_borrow_content)(t, data_ref)); + //@ close_ref_mut_own_unsized::<'a, T>(t, data_ref); + let ret = Some(data_ref); + //@ close std::option::Option_own::<&'a mut T>(t, ret); + ret + } else { + //@ open Arc_is_unique_ens::('a, t, this, true, 0, false); + //@ close Arc_full_borrow_content::(t, this)(); + /*@ + { + pred Ctx() = true; + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + Arc_full_borrow_content::(t, this), + klong, + Arc_full_borrow_content::(t, this) + )() { + open Ctx(); + } { + close_full_borrow_strong(klong, Arc_full_borrow_content::(t, this), Arc_full_borrow_content::(t, this)); + } + } + @*/ + //@ leak full_borrow(klong, Arc_full_borrow_content::(t, this)); + //@ close std::option::Option_own::<&'a mut T>(t, std::option::Option::None); + None + } + } + + /// Returns a mutable reference into the given `Arc`, + /// without any check. + /// + /// See also [`get_mut`], which is safe and does appropriate checks. + /// + /// [`get_mut`]: Arc::get_mut + /// + /// # Safety + /// + /// If any other `Arc` or [`Weak`] pointers to the same allocation exist, then + /// they must not be dereferenced or have active borrows for the duration + /// of the returned borrow, and their inner type must be exactly the same as the + /// inner type of this Arc (including lifetimes). This is trivially the case if no + /// such pointers exist, for example immediately after `Arc::new`. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let mut x = Arc::new(String::new()); + /// unsafe { + /// Arc::get_mut_unchecked(&mut x).push_str("foo") + /// } + /// assert_eq!(*x, "foo"); + /// ``` + /// Other `Arc` pointers to the same allocation must be to the same type. + /// ```no_run + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let x: Arc = Arc::from("Hello, world!"); + /// let mut y: Arc<[u8]> = x.clone().into(); + /// unsafe { + /// // this is Undefined Behavior, because x's inner type is str, not [u8] + /// Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8 + /// } + /// println!("{}", &*x); // Invalid UTF-8 in a str + /// ``` + /// Other `Arc` pointers to the same allocation must be to the exact same type, including lifetimes. + /// ```no_run + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let x: Arc<&str> = Arc::new("Hello, world!"); + /// { + /// let s = String::from("Oh, no!"); + /// let mut y: Arc<&str> = x.clone(); + /// unsafe { + /// // this is Undefined Behavior, because x's inner type + /// // is &'long str, not &'short str + /// *Arc::get_mut_unchecked(&mut y) = &s; + /// } + /// } + /// println!("{}", &*x); // Use-after-free + /// ``` + #[inline] + #[unstable(feature = "get_mut_unchecked", issue = "63292")] + pub unsafe fn get_mut_unchecked<'a>(this: &'a mut Self) -> &'a mut T + //@ req [?f](*this).ptr |-> ?nnp &*& pointer_within_limits(&(*nnp.as_ptr()).data) == true &*& exists::(?t) &*& ((.full_borrow_content)(t, &(*nnp.as_ptr()).data))(); + //@ ens [f](*this).ptr |-> nnp &*& result == &(*nnp.as_ptr()).data &*& ((.full_borrow_content)(t, result))(); + //@ on_unwind_ens false; + { + // We are careful to *not* create a reference covering the "count" fields, as + // this would alias with concurrent access to the reference counts (e.g. by `Weak`). + // ignore-tidy-undocumented-unsafe + unsafe { &mut (*NonNull_as_ptr__VeriFast_wrapper(this.ptr)).data } //~ignore_ref_creation + } + + /// Determine whether this is the unique reference to the underlying data. + /// + /// Returns `true` if there are no other `Arc` or [`Weak`] pointers to the same allocation; + /// returns `false` otherwise. + /// + /// If this function returns `true`, then it is guaranteed to be safe to call [`get_mut_unchecked`] + /// on this `Arc`, as long as no clones occur in between. + /// + /// The result can become stale if another thread can call `clone` or + /// `downgrade` through a shared reference. Make sure you have exclusive + /// access to the `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// assert!(Arc::is_unique(&x)); + /// + /// let y = Arc::clone(&x); + /// assert!(!Arc::is_unique(&x)); + /// drop(y); + /// + /// // Weak references also count, because they could be upgraded at any time. + /// let z = Arc::downgrade(&x); + /// assert!(!Arc::is_unique(&x)); + /// ``` + /// + /// # Pointer invalidation + /// + /// This function will always return the same value as `Arc::get_mut(arc).is_some()`. However, + /// unlike that operation it does not produce any mutable references to the underlying data, + /// meaning no pointers to the data inside the `Arc` are invalidated by the call. Thus, the + /// following code is valid: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let arc = Arc::new(5); + /// let pointer: *const i32 = &*arc; + /// assert!(Arc::is_unique(&arc)); + /// assert_eq!(unsafe { *pointer }, 5); + /// ``` + /// + /// The following changes would make the example unsound: + /// + /// - Using `Arc::get_mut` to create a mutable reference while also accessing the value + /// through `pointer`. + /// - Dropping `arc` before dereferencing `pointer`, leaving it dangling. + /// + /// # Atomic orderings + /// + /// Concurrent drops to other `Arc` pointers to the same allocation will synchronize with this + /// call - that is, this call performs an `Acquire` operation on the underlying strong and weak + /// ref counts. This ensures that calling `get_mut_unchecked` is safe. + /// + /// Note that this operation requires locking the weak ref count, so concurrent calls to + /// `downgrade` may spin-loop for a short period of time. + /// + /// [`get_mut_unchecked`]: Self::get_mut_unchecked + #[inline] + #[stable(feature = "arc_is_unique", since = "1.101.0")] + pub fn is_unique<'a>(this: &'a Self) -> bool + //@ req Arc_is_unique_req::(?k, ?t, this, ?owned, ?qa); + //@ ens Arc_is_unique_ens::(k, t, this, owned, qa, result); + //@ on_unwind_ens false; + /*@ + safety_proof { + close Arc_is_unique_req::('a, _t, this, false, _q_a); + let r = call(); + open Arc_is_unique_ens::('a, _t, this, false, _q_a, r); + } + @*/ + { + //@ open Arc_is_unique_req::(k, t, this, owned, qa); + /*@ + if owned { + open Arc_own::(t, _); + assert (*this).ptr |-> ?nnp &*& (*this).alloc |-> ?alloc &*& [_]exists::<*ArcInner>(?ptr); + assert std::alloc::Allocator(t, alloc, ?aid); + assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + open exists::(?exclusive); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + close UniqueState::(ig, sg, lg, ot, ptr, false, exclusive); + close exists(exclusive); + close exists(nnp); + close exists(ptr); + close exists(aid); + close exists(ig); + close exists(sg); + close exists(wg); + close exists(lg); + close exists(img); + close exists(lay); + close exists(ot); + } else { + open Arc_share::(k, t, this); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + assert [_]exists::(?dk) &*& [_]exists::(?frac); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open_frac_borrow(k, Arc_ptr_bc(this, nnp), qa / 2); + open [?qnnp]Arc_ptr_bc::(this, nnp)(); + close SharedLockState(k, sg, lg, dk, frac, qa / 2, false); + close ArcPtrFrac(qnnp); + close exists(dk); + close exists(frac); + close exists(nnp); + close exists(ptr); + close exists(aid); + close exists(ig); + close exists(sg); + close exists(wg); + close exists(lg); + close exists(img); + close exists(lay); + close exists(ot); + } + @*/ + //@ open exists::(?ot); + //@ open exists::(?lay); + //@ open exists::(?img); + //@ open exists::(?lg); + //@ open exists::(?wg); + //@ open exists::(?sg); + //@ open exists::(?ig); + //@ open exists::(?aid); + //@ open exists::<*ArcInner>(?ptr); + //@ open exists::>>(?nnp); + // lock the weak pointer count if we appear to be the sole weak pointer + // holder. + // + // The acquire label here ensures a happens-before relationship with any + // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements + // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded + // weak ref was never dropped, the CAS here will fail so we do not care to synchronize. + let locked_ok; + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if owned { + exists::(?excl) &*& UniqueState::(ig, sg, lg, ot, ptr, false, excl) + } else { + exists::(?frac) &*& exists::(?dk) &*& + SharedLockState(k, sg, lg, dk, frac, qa / 2, false) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) + }; + pred PostOk(rv: usize) = + if owned { + exists::(?excl) &*& UniqueState::(ig, sg, lg, ot, ptr, true, excl) + } else { + exists::(?frac) &*& exists::(?dk) &*& + SharedLockState(k, sg, lg, dk, frac, qa / 2, true) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) + }; + pred PostErrAcq(rv: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_ghop(&(*ptr).weak, 1, usize::MAX, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_op(?op, _, _, _, _, ?Q); + if owned { + open exists::(?excl); + open UniqueState::(ig, sg, lg, ot, ptr, false, excl); + if excl { + op(); + assert Q(?rv); + match rv { + Result::Ok(v_ok) => { + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeExclusiveLocked); + ghost_cell_mutate::(lg, LockExcl); + close UniqueState::(ig, sg, lg, ot, ptr, true, true); + close exists(true); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => {} + } + } else { + assert ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)); + counting_match_fraction(dlft_pred, sg); + assert shared_weak_lock(lg, sg, dk, ?locked); + open shared_weak_lock(lg, sg, dk, locked); + op(); + assert Q(?rv); + match rv { + Result::Ok(v_ok) => { + open [frac]dlft_pred(sg, some(dk)); + ghost_cell_fraction_info(sg); + ghost_cell_mutate::(lg, LockShared(frac / 2)); + close shared_weak_lock(lg, sg, dk, true); + close UniqueState::(ig, sg, lg, ot, ptr, true, false); + close exists(false); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close shared_weak_lock(lg, sg, dk, locked); + close UniqueState::(ig, sg, lg, ot, ptr, false, false); + close exists(false); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + } + } else { + open exists::(?frac); + open exists::(?dk); + open SharedLockState(k, sg, lg, dk, frac, qa / 2, false); + Arc_is_shared_from_borrow(sg, dk, frac); + assert shared_weak_lock(lg, sg, dk, ?locked); + open shared_weak_lock(lg, sg, dk, locked); + op(); + assert Q(?rv); + match rv { + Result::Ok(v_ok) => { + open_frac_borrow_m(k, strong_ticket_(sg, dk, frac), qa / 2); + open [?qf]strong_ticket_(sg, dk, frac)(); + ghost_cell_fraction_info(sg); + ghost_cell_mutate::(lg, LockShared(qf * frac / 2)); + close shared_weak_lock(lg, sg, dk, true); + close SharedLockState(k, sg, lg, dk, frac, qa / 2, true); + close exists(dk); + close exists(frac); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close shared_weak_lock(lg, sg, dk, locked); + close SharedLockState(k, sg, lg, dk, frac, qa / 2, false); + close exists(dk); + close exists(frac); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + } + }; + @*/ + //@ close Pre(); + let lock_res = this.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed); //~ignore_ref_creation + locked_ok = lock_res.is_ok(); //~ignore_ref_creation + /*@ + match lock_res { + Result::Ok(v_res) => { open PostOk(v_res); } + Result::Err(v_res) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_res)); + } + } + @*/ + } + + if locked_ok { + // This needs to be an `Acquire` to synchronize with the decrement of the `strong` + // counter in `drop` -- the only access that happens when any but the last reference + // is being dropped. + let s_val; + { + /*@ + pred Pre2() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if owned { + exists::(?excl) &*& UniqueState::(ig, sg, lg, ot, ptr, true, excl) + } else { + exists::(?frac) &*& exists::(?dk) &*& + SharedLockState(k, sg, lg, dk, frac, qa / 2, true) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) + }; + pred Post2(rv: usize) = + if owned { + UniqueState::(ig, sg, lg, ot, ptr, true, rv == 1) + } else { + exists::(?frac) &*& exists::(?dk) &*& + SharedLockState(k, sg, lg, dk, frac, qa / 2, true) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) + }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_ghop(&(*ptr).strong, Pre2, Post2)() { + open Pre2(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + if owned { + open exists::(?excl); + open UniqueState::(ig, sg, lg, ot, ptr, true, excl); + if excl { + op(); + assert Q(?rv); + close UniqueState::(ig, sg, lg, ot, ptr, true, true); + } else { + assert ticket(dlft_pred, sg, ?frac) &*& [frac]lifetime_token(?dk); + let qp = close_dlft_pred_some(sg, dk); + counting_match_fraction(dlft_pred, sg); + open [qp]dlft_pred(sg, some(dk)); + assert shared_weak_lock(lg, sg, dk, ?locked); + open shared_weak_lock(lg, sg, dk, locked); + op(); + assert Q(?rv); + if rv == 1 { + close [frac]dlft_pred(sg, some(dk)); + destroy_ticket(dlft_pred, sg); + stop_counting(dlft_pred, sg); + open dlft_pred(sg, some(dk)); + end_lifetime_m(dk); + borrow_end_m(dk, (.full_borrow_content)(ot, &(*ptr).data)); + ghost_cell_mutate(sg, none); + close dlft_pred(sg, none); + start_counting(dlft_pred, sg); + ghost_cell_mutate::(lg, LockExcl); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeExclusiveLocked); + close UniqueState::(ig, sg, lg, ot, ptr, true, true); + } else { + close shared_weak_lock(lg, sg, dk, true); + close UniqueState::(ig, sg, lg, ot, ptr, true, false); + } + } + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?res_r); + close Post2(res_r); + } else { + open exists::(?frac); + open exists::(?dk); + open SharedLockState(k, sg, lg, dk, frac, qa / 2, true); + assert [?qf]ticket(dlft_pred, sg, frac); + assert [1/2]ghost_cell::(ig, ?mode); + match mode { + ModeShared(dk0) => { + assert shared_weak_lock(lg, sg, dk0, ?locked); + open shared_weak_lock(lg, sg, dk0, locked); + merge_fractions ghost_cell::>(sg, _); + op(); + assert Q(?rv); + close shared_weak_lock(lg, sg, dk, true); + close SharedLockState(k, sg, lg, dk, frac, qa / 2, true); + close exists(dk); + close exists(frac); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Post2(rv); + } + ModeExclusive => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeExclusiveLocked => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeDataOut => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeDataDropped => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeDealloced => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + } + } + }; + @*/ + //@ close Pre2(); + s_val = this.inner().strong.load(Acquire); //~ignore_ref_creation + //@ open Post2(s_val); + } + let unique = s_val == 1; + + // The release write here synchronizes with a read in `downgrade`, + // effectively preventing the above read of `strong` from happening + // after the write. + { + /*@ + pred Pre3() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if owned { + UniqueState::(ig, sg, lg, ot, ptr, true, unique) + } else { + exists::(?frac) &*& exists::(?dk) &*& + SharedLockState(k, sg, lg, dk, frac, qa / 2, true) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) + }; + pred Post3() = + if owned { + UniqueState::(ig, sg, lg, ot, ptr, false, unique) + } else { + exists::(?frac) &*& exists::(?dk) &*& + SharedLockState(k, sg, lg, dk, frac, qa / 2, false) &*& + [_]frac_borrow(k, lifetime_token_(frac, dk)) + }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_store_ghop(&(*ptr).weak, 1, Pre3, Post3)() { + open Pre3(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_store_op(?op, _, _, _, ?Q); + if owned { + open UniqueState::(ig, sg, lg, ot, ptr, true, unique); + if unique { + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeExclusive); + ghost_cell_mutate::(lg, LockFree); + op(); + close UniqueState::(ig, sg, lg, ot, ptr, false, true); + } else { + assert ticket(dlft_pred, sg, ?frac) &*& [frac]lifetime_token(?dk); + let qp = close_dlft_pred_some(sg, dk); + counting_match_fraction(dlft_pred, sg); + open [qp]dlft_pred(sg, some(dk)); + assert shared_weak_lock(lg, sg, dk, ?locked); + open shared_weak_lock(lg, sg, dk, locked); + ghost_cell_mutate::(lg, LockFree); + close shared_weak_lock(lg, sg, dk, false); + close [frac]dlft_pred(sg, some(dk)); + op(); + close UniqueState::(ig, sg, lg, ot, ptr, false, false); + } + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Post3(); + } else { + open exists::(?frac); + open exists::(?dk); + open SharedLockState(k, sg, lg, dk, frac, qa / 2, true); + assert [?qf]ticket(dlft_pred, sg, frac); + assert [1/2]ghost_cell::(ig, ?mode); + match mode { + ModeShared(dk0) => { + assert shared_weak_lock(lg, sg, dk0, ?locked); + open shared_weak_lock(lg, sg, dk0, locked); + merge_fractions ghost_cell::>(sg, _); + ghost_cell_mutate::(lg, LockFree); + close shared_weak_lock(lg, sg, dk, false); + close [qf]strong_ticket_(sg, dk, frac)(); + close_frac_borrow_m(qf, strong_ticket_(sg, dk, frac)); + op(); + close SharedLockState(k, sg, lg, dk, frac, qa / 2, false); + close exists(dk); + close exists(frac); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Post3(); + } + ModeExclusive => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeExclusiveLocked => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeDataOut => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeDataDropped => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + ModeDealloced => { merge_fractions ghost_cell::(lg, _); ghost_cell_fraction_info(lg); } + } + } + }; + @*/ + //@ close Pre3(); + this.inner().weak.store(1, Release); //~ignore_ref_creation + //@ open Post3(); + } + /*@ + if owned { + open UniqueState::(ig, sg, lg, ot, ptr, false, unique); + if unique { + close Arc_is_unique_ens::(k, t, this, true, qa, true); + } else { + close exists(false); + close Arc_own::(t, Arc:: { ptr: nnp, alloc: (*this).alloc }); + close Arc_is_unique_ens::(k, t, this, true, qa, false); + } + } else { + open SharedLockState(k, sg, lg, ?dk, ?frac, qa / 2, false); + open ArcPtrFrac(?qnnp); + close [qnnp]Arc_ptr_bc::(this, nnp)(); + close_frac_borrow(qnnp, Arc_ptr_bc(this, nnp)); + close Arc_is_unique_ens::(k, t, this, false, qa, unique); + } + @*/ + unique + } else { + /*@ + if owned { + open UniqueState::(ig, sg, lg, ot, ptr, false, ?excl); + close exists(excl); + close Arc_own::(t, Arc:: { ptr: nnp, alloc: (*this).alloc }); + close Arc_is_unique_ens::(k, t, this, true, qa, false); + } else { + open SharedLockState(k, sg, lg, ?dk, ?frac, qa / 2, false); + open ArcPtrFrac(?qnnp); + close [qnnp]Arc_ptr_bc::(this, nnp)(); + close_frac_borrow(qnnp, Arc_ptr_bc(this, nnp)); + close Arc_is_unique_ens::(k, t, this, false, qa, false); + } + @*/ + false + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Arc { + /// Drops the `Arc`. + /// + /// This will decrement the strong reference count. If the strong reference + /// count reaches zero then the only other references (if any) are + /// [`Weak`], so we `drop` the inner value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// struct Foo; + /// + /// impl Drop for Foo { + /// fn drop(&mut self) { + /// println!("dropped!"); + /// } + /// } + /// + /// let foo = Arc::new(Foo); + /// let foo2 = Arc::clone(&foo); + /// + /// drop(foo); // Doesn't print anything + /// drop(foo2); // Prints "dropped!" + /// ``` + #[inline] + fn drop(&mut self) + //@ req thread_token(?t) &*& Arc_full_borrow_content::(t, self)(); + //@ ens thread_token(t) &*& (*self).ptr |-> ?p &*& std::ptr::NonNull_own(t, p) &*& (*self).alloc |-> ?a &*& .own(t, a) &*& struct_Arc_padding(self); + //@ on_unwind_ens thread_token(t); + { + //@ open Arc_full_borrow_content::(t, self)(); + //@ open_points_to(self); + //@ open Arc_own::(t, ?arc); + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, arc.alloc, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open exists::(?exclusive); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + // Because `fetch_sub` is already atomic, we do not need to synchronize + // with other threads unless we are going to delete the object. This + // same logic applies to the below `fetch_sub` to the `weak` count. + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if exclusive { + [1/2]ghost_cell(ig, ModeExclusive) &*& + ((.full_borrow_content)(ot, &(*ptr).data))() + } else { + ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)) + }; + pred Post(rv: usize) = if rv == 1 { + [1/2]ghost_cell(img, 1) &*& + ((.full_borrow_content)(ot, &(*ptr).data))() + } else { true }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_sub_ghop(&(*ptr).strong, 1, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_fetch_sub_op(?op, _, _, _, ?Q); + if exclusive { + mod_eq_minus_one(1, usize::MAX); + op(); + assert Q(?rv); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDataOut); + ghost_cell_mutate(img, 1); + } else { + assert ticket(dlft_pred, sg, ?frac) &*& [frac]dlft_pred(sg, some(?dk)); + counting_match_fraction(dlft_pred, sg); + assert arc_atomic_cas::AtomicUsize(&(*ptr).strong, ?v0); + destroy_ticket(dlft_pred, sg); + mod_eq_minus_one(v0, usize::MAX); + op(); + assert Q(?rv); + if rv == 1 { + stop_counting(dlft_pred, sg); + open dlft_pred(sg, some(dk)); + assert shared_weak_lock(lg, sg, dk, ?locked); + open shared_weak_lock(lg, sg, dk, locked); + if locked { + merge_fractions ghost_cell::>(sg, _); + ghost_cell_fraction_info(sg); + } else {} + end_lifetime_m(dk); + borrow_end_m(dk, (.full_borrow_content)(ot, &(*ptr).data)); + ghost_cell_mutate(sg, none); + close dlft_pred(sg, none); + start_counting(dlft_pred, sg); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDataOut); + ghost_cell_mutate(img, 1); + } else {} + } + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + assert Q(?res_r); + close Post(res_r); + }; + @*/ + //@ close Pre(); + let old_strong = self.inner().strong.fetch_sub(1, Release); //~ignore_ref_creation + if old_strong != 1 { + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(Post, old_strong)); + //@ close_NonNull_own_unsized(t, (*self).ptr); + //@ std::alloc::Allocator_to_own((*self).alloc); + return; + } + + acquire!(self.inner().strong); + //@ open arc_atomic_cas::app_usize(Post, old_strong)(); + //@ open Post(old_strong); + } + + // Make sure we aren't trying to "drop" the shared static for empty slices + // used by Default::default. + debug_assert!( + !ptr_addr_eq__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr), &STATIC_INNER_SLICE.inner), //~ignore_ref_creation + "Arcs backed by a static should never reach a strong count of 0. \ + Likely decrement_strong_count or from_raw were called too many times.", + ); + //@ leak <&'static SliceArcInnerForStatic>.own(t, _); + + // ignore-tidy-undocumented-unsafe + unsafe { + self.drop_slow(); + } + //@ close_NonNull_own_unsized(t, (*self).ptr); + //@ std::alloc::Allocator_to_own((*self).alloc); + } +} + +impl Arc { + /// Attempts to downcast the `Arc` to a concrete type. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// fn print_if_string(value: Arc) { + /// if let Ok(string) = value.downcast::() { + /// println!("String ({}): {}", string.len(), string); + /// } + /// } + /// + /// let my_string = "Hello World".to_string(); + /// print_if_string(Arc::new(my_string)); + /// print_if_string(Arc::new(0i8)); + /// ``` + #[inline] + #[stable(feature = "rc_downcast", since = "1.29.0")] + pub fn downcast(self) -> Result, Self> + where + T: Any + Send + Sync, + { + if (*self).is::() { + // SAFETY: Check ensures the typecast is okay. + unsafe { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + Ok(Arc::from_inner_in(ptr.cast(), alloc)) + } + } else { + Err(self) + } + } + + /// Downcasts the `Arc` to a concrete type. + /// + /// For a safe alternative see [`downcast`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(downcast_unchecked)] + /// + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// let x: Arc = Arc::new(1_usize); + /// + /// unsafe { + /// assert_eq!(*x.downcast_unchecked::(), 1); + /// } + /// ``` + /// + /// # Safety + /// + /// The contained value must be of type `T`. Calling this method + /// with the incorrect type is *undefined behavior*. + /// + /// + /// [`downcast`]: Self::downcast + #[inline] + #[unstable(feature = "downcast_unchecked", issue = "90850")] + #[cfg_attr(kani, requires((*self).is::()))] + #[cfg_attr(kani, ensures(|result| ub_checks::can_dereference(&**result as *const T)))] + pub unsafe fn downcast_unchecked(self) -> Arc + where + T: Any + Send + Sync, + { + // SAFETY: Upheld by caller. + unsafe { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + Arc::from_inner_in(ptr.cast(), alloc) + } + } +} + +impl Weak { + /// Constructs a new `Weak`, without allocating any memory. + /// Calling [`upgrade`] on the return value always gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// use std::sync::Weak; + /// + /// let empty: Weak = Weak::new(); + /// assert!(empty.upgrade().is_none()); + /// ``` + #[inline] + #[stable(feature = "downgraded_weak", since = "1.10.0")] + #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")] + #[must_use] + pub const fn new() -> Weak + //@ req true; + //@ ens result.ptr.as_ptr() as usize == usize::MAX && result.alloc == std::alloc::Global {}; + //@ on_unwind_ens false; + /*@ + safety_proof { + let r = call(); + std::ptr::close_NonNull_own(default_tid, r.ptr); + leak std::ptr::NonNull_own(default_tid, r.ptr); + leak exists(r.ptr.as_ptr()); + std::alloc::produce_Allocator_Global(_t); + close >.own(_t, r); + } + @*/ + { + Weak { ptr: unsafe { NonNull_without_provenance_MAX__VeriFast_wrapper() }, alloc: Global } + } +} + +impl Weak { + /// Constructs a new `Weak`, without allocating any memory, technically in the provided + /// allocator. + /// Calling [`upgrade`] on the return value always gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Weak; + /// use std::alloc::System; + /// + /// let empty: Weak = Weak::new_in(System); + /// assert!(empty.upgrade().is_none()); + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_in(alloc: A) -> Weak + //@ req true; + //@ ens result.ptr.as_ptr() as usize == usize::MAX && result.alloc == alloc; + //@ on_unwind_ens false; + /*@ + safety_proof { + let r = call(); + std::ptr::close_NonNull_own(default_tid, r.ptr); + leak std::ptr::NonNull_own(default_tid, r.ptr); + leak exists(r.ptr.as_ptr()); + std::alloc::open_Allocator_own(r.alloc); + close >.own(_t, r); + } + @*/ + { + Weak { ptr: unsafe { NonNull_without_provenance_MAX__VeriFast_wrapper() }, alloc } + } +} + +/// Helper type to allow accessing the reference counts without +/// making any assertions about the data field. +struct WeakInner<'a> { + weak: &'a Atomic, + strong: &'a Atomic, +} + +/*@ +pred<'a> >.own(t, wi) = true; + +lem WeakInner_own_mono<'a0, 'a1>() + req WeakInner_own::<'a0>(?t, ?v) &*& lifetime_inclusion('a1, 'a0) == true; + ens WeakInner_own::<'a1>(t, WeakInner::<'a1> { weak: v.weak, strong: v.strong }); +{ + open WeakInner_own::<'a0>(t, v); + close WeakInner_own::<'a1>(t, WeakInner::<'a1> { weak: v.weak, strong: v.strong }); +} +@*/ + +impl Weak { + /// Converts a raw pointer previously created by [`into_raw`] back into `Weak`. + /// + /// This can be used to safely get a strong reference (by calling [`upgrade`] + /// later) or to deallocate the weak count by dropping the `Weak`. + /// + /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], + /// as these don't own anything; the method still works on them). + /// + /// # Safety + /// + /// The pointer must have originated from the [`into_raw`] and must still own its potential + /// weak reference, and must point to a block of memory allocated by global allocator. + /// + /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this + /// takes ownership of one weak reference currently represented as a raw pointer (the weak + /// count is not modified by this operation) and therefore it must be paired with a previous + /// call to [`into_raw`]. + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// + /// let raw_1 = Arc::downgrade(&strong).into_raw(); + /// let raw_2 = Arc::downgrade(&strong).into_raw(); + /// + /// assert_eq!(2, Arc::weak_count(&strong)); + /// + /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); + /// assert_eq!(1, Arc::weak_count(&strong)); + /// + /// drop(strong); + /// + /// // Decrement the last weak count. + /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); + /// ``` + /// + /// [`new`]: Weak::new + /// [`into_raw`]: Weak::into_raw + /// [`upgrade`]: Weak::upgrade + #[inline] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub unsafe fn from_raw(ptr: *const T) -> Self + //@ req Weak_raw_own::(?t, ptr, std::alloc::Global_alloc_id); + /*@ + ens Weak_own::(t, result) &*& + result.ptr.as_ptr() == (if (ptr as usize) == usize::MAX { + ptr as *ArcInner + } else { + (ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr))) as *T) as *ArcInner + }) && result.alloc == std::alloc::Global {}; + @*/ + //@ on_unwind_ens false; + { + //@ std::alloc::produce_Allocator_Global(t); + // SAFETY: Upheld by caller. + unsafe { Weak::from_raw_in(ptr, Global) } + } + + /// Consumes the `Weak` and turns it into a raw pointer. + /// + /// This converts the weak pointer into a raw pointer, while still preserving the ownership of + /// one weak reference (the weak count is not modified by this operation). It can be turned + /// back into the `Weak` with [`from_raw`]. + /// + /// The same restrictions of accessing the target of the pointer as with + /// [`as_ptr`] apply. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// let weak = Arc::downgrade(&strong); + /// let raw = weak.into_raw(); + /// + /// assert_eq!(1, Arc::weak_count(&strong)); + /// assert_eq!("hello", unsafe { &*raw }); + /// + /// drop(unsafe { Weak::from_raw(raw) }); + /// assert_eq!(0, Arc::weak_count(&strong)); + /// ``` + /// + /// [`from_raw`]: Weak::from_raw + /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub fn into_raw(self) -> *const T + //@ req self.ptr.as_ptr() as usize == usize::MAX || pointer_within_limits(&(*self.ptr.as_ptr()).data) == true; + //@ ens result == (if self.ptr.as_ptr() as usize == usize::MAX { self.ptr.as_ptr() as *T } else { &(*self.ptr.as_ptr()).data }); + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, self); + assert [_]exists::<*ArcInner>(?ptr); + if (ptr as usize) != usize::MAX { + assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open exists::(?is_imp); + if is_imp { + leak [1/2]ghost_cell(img, 1) &*& (*ptr).data |-> _; + } else { + leak ticket(weak_pred, wg, ?wf) &*& [wf]weak_pred(wg, false); + } + } else {} + leak std::alloc::Allocator(_t, self.alloc, _); + call(); + } + @*/ + { + let me = ManuallyDrop::new(self); + Self::as_ptr(&*me) //~ignore_ref_creation + } +} + +impl Weak { + /// Returns a reference to the underlying allocator. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn allocator<'a>(&'a self) -> &'a A + //@ req [?qa]lifetime_token('a) &*& [_]Weak_share::('a, ?t, self); + //@ ens [qa]lifetime_token('a) &*& [_](.share)('a, t, result); + //@ on_unwind_ens false; + { + //@ open Weak_share::('a, t, self); + //@ std::alloc::close_Allocator_share::('a, t, &(*self).alloc); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ produce_type_interp::(); + //@ init_ref_share::('a, t, alloc_ref); + //@ leak type_interp::(); + //@ open_frac_borrow('a, ref_initialized_(alloc_ref), qa); + //@ open [?f]ref_initialized_::(alloc_ref)(); + let r = &self.alloc; + //@ close [f]ref_initialized_::(alloc_ref)(); + //@ close_frac_borrow(f, ref_initialized_(alloc_ref)); + r + } + + /// Returns a raw pointer to the object `T` pointed to by this `Weak`. + /// + /// The pointer is valid only if there are some strong references. The pointer may be dangling, + /// unaligned or even [`null`] otherwise. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::ptr; + /// + /// let strong = Arc::new("hello".to_owned()); + /// let weak = Arc::downgrade(&strong); + /// // Both point to the same object + /// assert!(ptr::eq(&*strong, weak.as_ptr())); + /// // The strong here keeps it alive, so we can still access the object. + /// assert_eq!("hello", unsafe { &*weak.as_ptr() }); + /// + /// drop(strong); + /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to + /// // undefined behavior. + /// // assert_eq!("hello", unsafe { &*weak.as_ptr() }); + /// ``` + /// + /// [`null`]: core::ptr::null "ptr::null" + #[must_use] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub fn as_ptr<'a>(&'a self) -> *const T + //@ req [?f](*self).ptr |-> ?nnp &*& (nnp.as_ptr() as usize == usize::MAX || pointer_within_limits(&(*nnp.as_ptr()).data) == true); + //@ ens [f](*self).ptr |-> nnp &*& result == (if nnp.as_ptr() as usize == usize::MAX { nnp.as_ptr() as *T } else { &(*nnp.as_ptr()).data }); + //@ on_unwind_ens false; + /*@ + safety_proof { + open Weak_share::('a, _t, self); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + if (ptr as usize) != usize::MAX { + assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else {} + open_frac_borrow('a, Weak_ptr_bc(self, nnp), _q_a); + open [?f]Weak_ptr_bc::(self, nnp)(); + let r = call(); + close [f]Weak_ptr_bc::(self, nnp)(); + close_frac_borrow(f, Weak_ptr_bc(self, nnp)); + } + @*/ + { + let ptr: *mut ArcInner = NonNull_as_ptr__VeriFast_wrapper(self.ptr); + + if is_dangling(ptr) { + // If the pointer is dangling, we return the sentinel directly. This cannot be + // a valid payload address, as the payload is at least as aligned as ArcInner (usize). + ptr as *const T + } else { + // SAFETY: if is_dangling returns false, then the pointer is dereferenceable. + // The payload may be dropped at this point, and we have to maintain provenance, + // so use raw pointer manipulation. + unsafe { &raw mut (*ptr).data } + } + } + + /// Consumes the `Weak`, returning the wrapped pointer and allocator. + /// + /// This converts the weak pointer into a raw pointer, while still preserving the ownership of + /// one weak reference (the weak count is not modified by this operation). It can be turned + /// back into the `Weak` with [`from_raw_in`]. + /// + /// The same restrictions of accessing the target of the pointer as with + /// [`as_ptr`] apply. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::{Arc, Weak}; + /// use std::alloc::System; + /// + /// let strong = Arc::new_in("hello".to_owned(), System); + /// let weak = Arc::downgrade(&strong); + /// let (raw, alloc) = weak.into_raw_with_allocator(); + /// + /// assert_eq!(1, Arc::weak_count(&strong)); + /// assert_eq!("hello", unsafe { &*raw }); + /// + /// drop(unsafe { Weak::from_raw_in(raw, alloc) }); + /// assert_eq!(0, Arc::weak_count(&strong)); + /// ``` + /// + /// [`from_raw_in`]: Weak::from_raw_in + /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn into_raw_with_allocator(self) -> (*const T, A) + //@ req self.ptr.as_ptr() as usize == usize::MAX || pointer_within_limits(&(*self.ptr.as_ptr()).data) == true; + //@ ens result.0 == (if self.ptr.as_ptr() as usize == usize::MAX { self.ptr.as_ptr() as *T } else { &(*self.ptr.as_ptr()).data }) && result.1 == self.alloc; + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, self); + assert [_]exists::<*ArcInner>(?ptr); + if (ptr as usize) != usize::MAX { + assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open exists::(?is_imp); + if is_imp { + leak [1/2]ghost_cell(img, 1) &*& (*ptr).data |-> _; + } else { + leak ticket(weak_pred, wg, ?wf) &*& [wf]weak_pred(wg, false); + } + } else {} + let r = call(); + std::alloc::Allocator_to_own(r.1); + close raw_ptr_own::()(_t, r.0); + close_tuple_2_own::<*const T, A>(_t, r); + } + @*/ + { + let mut me = mem::ManuallyDrop::new(self); + //@ close_points_to(&me); + //@ let me_ref = precreate_ref(&me as *Weak); + //@ init_ref_readonly(me_ref, 1/2); + //@ open_points_to(me_ref); + let result = Self::as_ptr(&me); + //@ close_points_to(me_ref, 1/2); + //@ end_ref_readonly(me_ref); + //@ let me_ref2 = precreate_ref(&me as *Weak); + //@ init_ref_readonly(me_ref2, 1/2); + //@ open_points_to(me_ref2); + //@ let alloc_ref = precreate_ref(&(*me_ref2).alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped + let alloc = unsafe { ptr::read(&me.alloc) }; + //@ end_ref_readonly(alloc_ref); + //@ close_points_to(me_ref2, 1/2); + //@ end_ref_readonly(me_ref2); + //@ open_points_to(&me); + (result, alloc) + } + + /// Converts a raw pointer previously created by [`into_raw`] back into `Weak` in the provided + /// allocator. + /// + /// This can be used to safely get a strong reference (by calling [`upgrade`] + /// later) or to deallocate the weak count by dropping the `Weak`. + /// + /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], + /// as these don't own anything; the method still works on them). + /// + /// # Safety + /// + /// The pointer must have originated from the [`into_raw`] and must still own its potential + /// weak reference, and must point to a block of memory allocated by `alloc`. + /// + /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this + /// takes ownership of one weak reference currently represented as a raw pointer (the weak + /// count is not modified by this operation) and therefore it must be paired with a previous + /// call to [`into_raw`]. + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// + /// let raw_1 = Arc::downgrade(&strong).into_raw(); + /// let raw_2 = Arc::downgrade(&strong).into_raw(); + /// + /// assert_eq!(2, Arc::weak_count(&strong)); + /// + /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); + /// assert_eq!(1, Arc::weak_count(&strong)); + /// + /// drop(strong); + /// + /// // Decrement the last weak count. + /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); + /// ``` + /// + /// [`new`]: Weak::new + /// [`into_raw`]: Weak::into_raw + /// [`upgrade`]: Weak::upgrade + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self + //@ req Weak_raw_own::(?t, ptr, ?aid) &*& std::alloc::Allocator(t, alloc, aid); + /*@ + ens Weak_own::(t, result) &*& + result.ptr.as_ptr() == (if (ptr as usize) == usize::MAX { + ptr as *ArcInner + } else { + (ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr))) as *T) as *ArcInner + }) && result.alloc == alloc; + @*/ + //@ on_unwind_ens false; + { + //@ open Weak_raw_own::(t, ptr, aid); + // See Weak::as_ptr for context on how the input pointer is derived. + + let ptr = if is_dangling(ptr) { + // This is a dangling Weak. + ptr as *mut ArcInner + } else { + // Otherwise, we're guaranteed the pointer came from a nondangling Weak. + // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T. + let offset = unsafe { data_offset(ptr) }; + // Thus, we reverse the offset to get the whole ArcInner. + // SAFETY: the pointer originated from a Weak, so this offset is safe. + unsafe { ptr_byte_sub__VeriFast_wrapper(ptr, offset) as *mut ArcInner } + }; + + // SAFETY: we now have recovered the original Weak pointer, so can create the Weak. + let r = Weak { ptr: unsafe { NonNull_new_unchecked__VeriFast_wrapper(ptr) }, alloc }; + //@ let inner_p = if (ptr as usize) == usize::MAX { ptr as *ArcInner } else { raw_to_arc_inner::(ptr, arc_data_offset(std::mem::align_of_val(ptr))) }; + //@ close exists::<*ArcInner>(inner_p); + //@ leak exists::<*ArcInner>(inner_p); + //@ close Weak_own::(t, r); + r + } +} + +impl Weak { + /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying + /// dropping of the inner value if successful. + /// + /// Returns [`None`] in the following cases: + /// + /// 1. The inner value has since been dropped or moved out. + /// + /// 2. This `Weak` does not point to an allocation. + /// + /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let weak_five = Arc::downgrade(&five); + /// + /// let strong_five: Option> = weak_five.upgrade(); + /// assert!(strong_five.is_some()); + /// + /// // Destroy all strong pointers. + /// drop(strong_five); + /// drop(five); + /// + /// assert!(weak_five.upgrade().is_none()); + /// ``` + #[must_use = "this returns a new `Arc`, \ + without modifying the original weak pointer"] + #[stable(feature = "arc_weak", since = "1.4.0")] + pub fn upgrade<'a>(&'a self) -> Option> + where + A: AllocatorClone, + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_]Weak_share::('a, t, self); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& >>.own(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ open Weak_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]std::alloc::Allocator_share('a, t, &(*self).alloc, ?aid); + //@ open_frac_borrow('a, Weak_ptr_bc(self, nnp), qa / 2); + //@ open [?qnnp]Weak_ptr_bc::(self, nnp)(); + //@ if (ptr as usize) != usize::MAX { open ArcInner_meta::(_, _, _, _, _, _, _, _, ptr); } else {} + let inner = match self.inner() { //~ignore_ref_creation + Some(inner) => inner, + None => { + //@ close [qnnp]Weak_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_ptr_bc(self, nnp)); + //@ close std::option::Option_own::>(t, std::option::Option::None); + return None; + } + }; + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ assert [_]exists::(?is_implicit); + // Inline `inner.strong.try_update(Acquire, Relaxed, checked_increment)` as its exact + // `load(Relaxed)` + `compare_exchange_weak(Acquire, Relaxed)` CAS loop (VeriFast 26.10 + // does not support `fn`-item operands in rvalues). + let strong = inner.strong; + let mut n; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + pred PostAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).strong, Frame, load_any, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + if is_implicit { + Weak_implicit_is_data_out::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else { + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [_]exists::(?wfrac); + Weak_is_live_from_borrow(wg, wfrac); + } + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + assert Q(?v); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Frame(); + close PostAcq(v); + }; + @*/ + //@ close Frame(); + n = strong.load(Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, n)); + } + //@ close [qnnp]Weak_ptr_bc::(self, nnp)(); + loop { + /*@ + inv thread_token(t) &*& + [qa / 2]lifetime_token('a) &*& + [qnnp]Weak_ptr_bc::(self, nnp)() &*& + close_frac_borrow_token(qnnp, Weak_ptr_bc(self, nnp), qa / 2, 'a) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& + [_]std::alloc::Allocator_share('a, t, &(*self).alloc, aid) &*& + [_]ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + @*/ + if n == 0 { + //@ close_frac_borrow(qnnp, Weak_ptr_bc(self, nnp)); + //@ close std::option::Option_own::>(t, std::option::Option::None); + return None; + } + if n > MAX_REFCOUNT { + panic_arc_overflow(); + } + let cas_res; + { + /*@ + pred Pre() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + pred PostOk(v: usize) = [qa / 2]lifetime_token('a) &*& + [_]exists(?dk) &*& + ticket(dlft_pred, sg, ?sfrac) &*& + [sfrac]dlft_pred(sg, some(dk)) &*& + [_](.share)(dk, ot, &(*ptr).data); + pred PostErrAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_compare_exchange_weak_ghop(&(*ptr).strong, n, n + 1, Pre, PostOk, PostErrAcq)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + if is_implicit { + Weak_implicit_is_data_out::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else { + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [_]exists::(?wfrac); + Weak_is_live_from_borrow(wg, wfrac); + } + assert arc_atomic_cas::is_AtomicUsize_compare_exchange_weak_op(?op, _, _, _, ?spurious, _, ?Q); + op(); + assert Q(?rv); + match rv { + Result::Ok(v_ok) => { + assert [1/2]ghost_cell(ig, ModeShared(?dk)); + create_ticket(dlft_pred, sg); + leak exists(dk); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close PostOk(v_ok); + } + Result::Err(v_err) => { + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Pre(); + close PostErrAcq(v_err); + } + } + }; + @*/ + //@ close Pre(); + cas_res = strong.compare_exchange_weak(n, n + 1, Acquire, Relaxed); //~ignore_ref_creation + /*@ + match cas_res { + Result::Ok(v_res) => { open PostOk(v_res); } + Result::Err(v_err_res) => { + open Pre(); + arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostErrAcq, v_err_res)); + } + } + @*/ + match cas_res { + Ok(_) => { + //@ open [qnnp]Weak_ptr_bc::(self, nnp)(); + let ptr_val = self.ptr; + //@ close [qnnp]Weak_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_ptr_bc(self, nnp)); + let a_clone = unsafe { Allocator_clone_from_share__VeriFast_wrapper(&self.alloc) }; //~ignore_ref_creation + // SAFETY: pointer is not null, verified in checked_increment + let a = unsafe { Arc::from_inner_in(ptr_val, a_clone) }; + //@ close exists(false); + //@ close Arc_own::(t, a); + let ret = Some(a); + //@ close std::option::Option_own::>(t, ret); + return ret; + } + Err(prev) => { + n = prev; + } + } + } + } + } + + /// Gets the number of strong (`Arc`) pointers pointing to this allocation. + /// + /// If `self` was created using [`Weak::new`], this will return 0. + #[must_use] + #[stable(feature = "weak_counts", since = "1.41.0")] + pub fn strong_count<'a>(&'a self) -> usize + //@ req [?qa]lifetime_token('a) &*& [_]Weak_share::('a, ?t, self); + //@ ens [qa]lifetime_token('a); + //@ on_unwind_ens false; + { + //@ open Weak_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ open_frac_borrow('a, Weak_ptr_bc(self, nnp), qa / 2); + //@ open [?qnnp]Weak_ptr_bc::(self, nnp)(); + //@ if (ptr as usize) != usize::MAX { open ArcInner_meta::(_, _, _, _, _, _, _, _, ptr); } else {} + let r = if let Some(inner) = self.inner() { //~ignore_ref_creation + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ assert [_]exists::(?is_implicit); + let cnt; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + pred PostAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).strong, Frame, load_any, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + if is_implicit { + Weak_implicit_is_data_out::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else { + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [_]exists::(?wfrac); + Weak_is_live_from_borrow(wg, wfrac); + } + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + assert Q(?v); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Frame(); + close PostAcq(v); + }; + @*/ + //@ close Frame(); + cnt = inner.strong.load(Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, cnt)); + } + cnt + } else { + 0 + }; + //@ close [qnnp]Weak_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_ptr_bc(self, nnp)); + r + } + + /// Gets an approximation of the number of `Weak` pointers pointing to this + /// allocation. + /// + /// If `self` was created using [`Weak::new`], or if there are no remaining + /// strong pointers, this will return 0. + /// + /// # Accuracy + /// + /// Due to implementation details, the returned value can be off by 1 in + /// either direction when other threads are manipulating any `Arc`s or + /// `Weak`s pointing to the same allocation. + #[must_use] + #[stable(feature = "weak_counts", since = "1.41.0")] + pub fn weak_count<'a>(&'a self) -> usize + //@ req [?qa]lifetime_token('a) &*& [_]Weak_share::('a, ?t, self); + //@ ens [qa]lifetime_token('a); + //@ on_unwind_ens false; + { + //@ open Weak_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ open_frac_borrow('a, Weak_ptr_bc(self, nnp), qa / 2); + //@ open [?qnnp]Weak_ptr_bc::(self, nnp)(); + //@ if (ptr as usize) != usize::MAX { open ArcInner_meta::(_, _, _, _, _, _, _, _, ptr); } else {} + let r = if let Some(inner) = self.inner() { //~ignore_ref_creation + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ assert [_]exists::(?is_implicit); + let weak; + { + /*@ + pred Pre() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + pred Post(v: usize) = [qa / 2]lifetime_token('a) &*& v >= 1; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_ghop(&(*ptr).weak, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + if is_implicit { + Weak_implicit_is_data_out::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else { + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [_]exists::(?wfrac); + Weak_is_live_from_borrow(wg, wfrac); + } + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + assert Q(?v); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Post(v); + }; + @*/ + //@ close Pre(); + weak = inner.weak.load(Acquire); //~ignore_ref_creation + //@ open Post(weak); + } + let strong; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + pred PostAcq(v: usize) = true; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_relaxed_ghop(&(*ptr).strong, Frame, load_any, PostAcq)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + if is_implicit { + Weak_implicit_is_data_out::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else { + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [_]exists::(?wfrac); + Weak_is_live_from_borrow(wg, wfrac); + } + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, _, _, ?Q); + op(); + assert Q(?v); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Frame(); + close PostAcq(v); + }; + @*/ + //@ close Frame(); + strong = inner.strong.load(Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(PostAcq, strong)); + } + if strong == 0 { + 0 + } else { + // Since we observed that there was at least one strong pointer + // after reading the weak count, we know that the implicit weak + // reference (present whenever any strong references are alive) + // was still around when we observed the weak count, and can + // therefore safely subtract it. + weak - 1 + } + } else { + 0 + }; + //@ close [qnnp]Weak_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_ptr_bc(self, nnp)); + r + } + + /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`, + /// (i.e., when this `Weak` was created by `Weak::new`). + #[inline] + fn inner<'a>(&'a self) -> Option> + //@ req [?f](*self).ptr |-> ?nnp &*& (nnp.as_ptr() as usize == usize::MAX || (pointer_within_limits(&(*nnp.as_ptr()).strong) == true && pointer_within_limits(&(*nnp.as_ptr()).weak) == true)); + /*@ + ens [f](*self).ptr |-> nnp &*& + if nnp.as_ptr() as usize == usize::MAX { + result == std::option::Option::None + } else { + result == std::option::Option::Some(WeakInner::<'a> { + strong: &(*nnp.as_ptr()).strong, + weak: &(*nnp.as_ptr()).weak + }) + }; + @*/ + //@ on_unwind_ens false; + /*@ + safety_proof { + open Weak_share::('a, _t, self); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + open_frac_borrow('a, Weak_ptr_bc(self, nnp), _q_a); + open [?f]Weak_ptr_bc::(self, nnp)(); + if (ptr as usize) != usize::MAX { + open ArcInner_meta::(_, _, _, _, _, _, _, _, ptr); + } else {} + let r = call(); + close [f]Weak_ptr_bc::(self, nnp)(); + close_frac_borrow(f, Weak_ptr_bc(self, nnp)); + match r { + Option::None => {} + Option::Some(wi) => { close >.own(_t, wi); } + } + close std::option::Option_own::>(_t, r); + } + @*/ + { + let ptr = NonNull_as_ptr__VeriFast_wrapper(self.ptr); + if is_dangling(ptr) { + None + } else { + // We are careful to *not* create a reference covering the "data" field, as + // the field may be mutated concurrently (for example, if the last `Arc` + // is dropped, the data field will be dropped in-place). + // ignore-tidy-undocumented-unsafe + Some(unsafe { WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } }) //~ignore_ref_creation + } + } + + /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if + /// both don't point to any allocation (because they were created with `Weak::new()`). However, + /// this function ignores the metadata of `dyn Trait` pointers. + /// + /// # Notes + /// + /// Since this compares pointers it means that `Weak::new()` will equal each + /// other, even though they don't point to any allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let first_rc = Arc::new(5); + /// let first = Arc::downgrade(&first_rc); + /// let second = Arc::downgrade(&first_rc); + /// + /// assert!(first.ptr_eq(&second)); + /// + /// let third_rc = Arc::new(5); + /// let third = Arc::downgrade(&third_rc); + /// + /// assert!(!first.ptr_eq(&third)); + /// ``` + /// + /// Comparing `Weak::new`. + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let first = Weak::new(); + /// let second = Weak::new(); + /// assert!(first.ptr_eq(&second)); + /// + /// let third_rc = Arc::new(()); + /// let third = Arc::downgrade(&third_rc); + /// assert!(!first.ptr_eq(&third)); + /// ``` + /// + /// [`ptr::eq`]: core::ptr::eq "ptr::eq" + #[inline] + #[must_use] + #[stable(feature = "weak_ptr_eq", since = "1.39.0")] + pub fn ptr_eq<'a, 'b>(&'a self, other: &'b Self) -> bool + //@ req [?f1](*self).ptr |-> ?nnp1 &*& [?f2](*other).ptr |-> ?nnp2; + //@ ens [f1](*self).ptr |-> nnp1 &*& [f2](*other).ptr |-> nnp2 &*& result == ((nnp1.as_ptr() as usize) == (nnp2.as_ptr() as usize)); + //@ on_unwind_ens false; + /*@ + safety_proof { + open Weak_share::('a, _t, self); + assert [_]exists::>>(?nnp1); + open_frac_borrow('a, Weak_ptr_bc(self, nnp1), _q_a); + open [?f1]Weak_ptr_bc::(self, nnp1)(); + open Weak_share::('b, _t, other); + assert [_]exists::>>(?nnp2); + open_frac_borrow('b, Weak_ptr_bc(other, nnp2), _q_b); + open [?f2]Weak_ptr_bc::(other, nnp2)(); + let r = call(); + close [f2]Weak_ptr_bc::(other, nnp2)(); + close_frac_borrow(f2, Weak_ptr_bc(other, nnp2)); + close [f1]Weak_ptr_bc::(self, nnp1)(); + close_frac_borrow(f1, Weak_ptr_bc(self, nnp1)); + } + @*/ + { + ptr_addr_eq__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr), NonNull_as_ptr__VeriFast_wrapper(other.ptr)) + } +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +impl Clone for Weak { + /// Makes a clone of the `Weak` pointer that points to the same allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let weak_five = Arc::downgrade(&Arc::new(5)); + /// + /// let _ = Weak::clone(&weak_five); + /// ``` + #[inline] + fn clone<'a>(&'a self) -> Weak + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_]Weak_share::('a, t, self); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& Weak_own::(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ open Weak_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]std::alloc::Allocator_share('a, t, &(*self).alloc, ?aid); + //@ open_frac_borrow('a, Weak_ptr_bc(self, nnp), qa / 2); + //@ open [?qnnp]Weak_ptr_bc::(self, nnp)(); + //@ if (ptr as usize) != usize::MAX { open ArcInner_meta::(_, _, _, _, _, _, _, _, ptr); } else {} + if let Some(inner) = self.inner() { //~ignore_ref_creation + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ assert [_]exists::(?is_implicit); + // See comments in Arc::clone() for why this is relaxed. This can use a + // fetch_add (ignoring the lock) because the weak count is only locked + // where are *no other* weak pointers in existence. (So we can't be + // running this code in that case). + let old_size; + { + /*@ + pred Frame() = [qa / 2]lifetime_token('a) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [_]frac_borrow('a, imp_weak_cell_::(img, ptr)) + } else { + [_]exists::(?wfrac) &*& [_]frac_borrow('a, weak_ticket_(wg, wfrac)) + }; + pred GhostPost(rv: usize) = + ticket(weak_pred, wg, ?wfrac1) &*& [wfrac1]weak_pred(wg, false); + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_add_relaxed_ghop(&(*ptr).weak, 1, Frame, GhostPost)() { + open Frame(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + if is_implicit { + Weak_implicit_is_data_out::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + } else { + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [_]exists::(?wfrac); + Weak_is_live_from_borrow(wg, wfrac); + } + assert arc_atomic_cas::AtomicUsize(&(*ptr).weak, ?v0); + if v0 > isize::MAX as usize { + // Documented Rust Arc/Weak overflow assumption (arc.rs L3529, TRUSTED-MODEL.md §3.3): + // fewer than isize::MAX - 1 concurrent threads pause between fetch_add and abort(). + assume(v0 < usize::MAX - 1); + } else {} + mod_eq_plus_one(v0, usize::MAX); + assert arc_atomic_cas::is_AtomicUsize_fetch_add_op(?op, _, _, _, ?Q); + op(); + assert Q(?rv); + create_ticket(weak_pred, wg); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Frame(); + close GhostPost(rv); + }; + @*/ + //@ close Frame(); + old_size = inner.weak.fetch_add(1, Relaxed); //~ignore_ref_creation + //@ open Frame(); + //@ open GhostPost(old_size); + } + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { + intrinsics::abort(); + } + } + + let ptr_val = self.ptr; + //@ close [qnnp]Weak_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(qnnp, Weak_ptr_bc(self, nnp)); + let a_clone = unsafe { Allocator_clone_from_share__VeriFast_wrapper(&self.alloc) }; //~ignore_ref_creation + let w = Weak { ptr: ptr_val, alloc: a_clone }; + //@ if (ptr as usize) != usize::MAX { close exists(false); } else {} + //@ close Weak_own::(t, w); + w + } +} + +#[unstable(feature = "ergonomic_clones", issue = "132290")] +impl UseCloned for Weak {} + +#[stable(feature = "downgraded_weak", since = "1.10.0")] +impl Default for Weak { + /// Constructs a new `Weak`, without allocating memory. + /// Calling [`upgrade`] on the return value always + /// gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// use std::sync::Weak; + /// + /// let empty: Weak = Default::default(); + /// assert!(empty.upgrade().is_none()); + /// ``` + fn default() -> Weak + //@ req true; + //@ ens result.ptr.as_ptr() as usize == usize::MAX && result.alloc == std::alloc::Global {}; + //@ on_unwind_ens false; + /*@ + safety_proof { + let r = call(); + std::ptr::close_NonNull_own(default_tid, r.ptr); + leak std::ptr::NonNull_own(default_tid, r.ptr); + leak exists(r.ptr.as_ptr()); + std::alloc::produce_Allocator_Global(_t); + close >.own(_t, r); + } + @*/ + { + Weak::new() + } +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak { + /// Drops the `Weak` pointer. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// struct Foo; + /// + /// impl Drop for Foo { + /// fn drop(&mut self) { + /// println!("dropped!"); + /// } + /// } + /// + /// let foo = Arc::new(Foo); + /// let weak_foo = Arc::downgrade(&foo); + /// let other_weak_foo = Weak::clone(&weak_foo); + /// + /// drop(weak_foo); // Doesn't print anything + /// drop(foo); // Prints "dropped!" + /// + /// assert!(other_weak_foo.upgrade().is_none()); + /// ``` + fn drop(&mut self) + //@ req thread_token(?t) &*& Weak_full_borrow_content::(t, self)(); + //@ ens thread_token(t) &*& (*self).ptr |-> ?p &*& std::ptr::NonNull_own(t, p) &*& (*self).alloc |-> ?a &*& .own(t, a) &*& struct_Weak_padding(self); + //@ on_unwind_ens thread_token(t); + { + //@ open Weak_full_borrow_content::(t, self)(); + //@ open_points_to(self); + //@ open Weak_own::(t, ?weak); + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, weak.alloc, ?aid); + //@ if (ptr as usize) != usize::MAX { open ArcInner_meta::(_, _, _, _, _, _, _, _, ptr); } else {} + // If we find out that we were the last weak pointer, then its time to + // deallocate the data entirely. See the discussion in Arc::drop() about + // the memory orderings + // + // It's not necessary to check for the locked state here, because the + // weak count can only be locked if there was precisely one weak ref, + // meaning that drop could only subsequently run ON that remaining weak + // ref, which can only happen after the lock is released. + let inner = if let Some(inner) = self.inner() { inner } else { //~ignore_ref_creation + //@ close_NonNull_own_unsized(t, weak.ptr); + //@ std::alloc::Allocator_to_own(weak.alloc); + return; + }; + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open exists::(?is_implicit); + + let old_weak; + let drop_res; + { + /*@ + pred Pre() = [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + if is_implicit { + [1/2]ghost_cell(img, 1) &*& (*ptr).data |-> _ + } else { + ticket(weak_pred, wg, ?wfrac) &*& [wfrac]weak_pred(wg, false) + }; + pred Post(rv: usize) = if rv == 1 { + arc_atomic_cas::AtomicUsize(&(*ptr).strong, 0) &*& + arc_atomic_cas::AtomicUsize(&(*ptr).weak, 0) &*& + (*ptr).data |-> _ &*& + ArcInner_backing::(aid, lay, ptr) + } else { true }; + @*/ + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_sub_ghop(&(*ptr).weak, 1, Pre, Post)() { + open Pre(); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert arc_atomic_cas::is_AtomicUsize_fetch_sub_op(?op, _, _, _, ?Q); + if is_implicit { + assert [1/2]ghost_cell::(ig, ?mode); + match mode { + ModeDataOut => {} + ModeShared(dk) => { merge_fractions ghost_cell(img, _); ghost_cell_fraction_info(img); } + ModeExclusive => { merge_fractions ghost_cell(img, _); ghost_cell_fraction_info(img); } + ModeExclusiveLocked => { merge_fractions ghost_cell(img, _); ghost_cell_fraction_info(img); } + ModeDataDropped => { merge_fractions ghost_cell(img, _); ghost_cell_fraction_info(img); } + ModeDealloced => { merge_fractions ghost_cell(img, _); ghost_cell_fraction_info(img); } + } + assert arc_atomic_cas::AtomicUsize(&(*ptr).weak, ?v0); + mod_eq_minus_one(v0, usize::MAX); + op(); + assert Q(?rv); + merge_fractions ghost_cell(img, _); + ghost_cell_mutate(img, 2); + merge_fractions ghost_cell::(ig, _); + if rv == 1 { + stop_counting(weak_pred, wg); + open weak_pred(wg, false); + ghost_cell_mutate(wg, true); + close weak_pred(wg, true); + start_counting(weak_pred, wg); + ghost_cell_mutate(ig, ModeDealloced); + } else { + ghost_cell_mutate(ig, ModeDataDropped); + } + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Post(rv); + } else { + counting_match_fraction(weak_pred, wg); + assert counting(weak_pred, wg, ?w_cnt, false); + if w_cnt == 0 { + assert [?wf]weak_pred(wg, false); + open [wf]weak_pred(wg, false); + ghost_cell_fraction_info(wg); + stop_counting(weak_pred, wg); + open weak_pred(wg, false); + merge_fractions ghost_cell::(wg, _); + ghost_cell_fraction_info(wg); + } else {} + destroy_ticket(weak_pred, wg); + assert arc_atomic_cas::AtomicUsize(&(*ptr).weak, ?v0); + mod_eq_minus_one(v0, usize::MAX); + op(); + assert Q(?rv); + if rv == 1 { + stop_counting(weak_pred, wg); + open weak_pred(wg, false); + ghost_cell_mutate(wg, true); + close weak_pred(wg, true); + start_counting(weak_pred, wg); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeDealloced); + } else {} + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close Post(rv); + } + }; + @*/ + //@ close Pre(); + old_weak = inner.weak.fetch_sub(1, Release); //~ignore_ref_creation + drop_res = if old_weak == 1 { + acquire!(inner.weak); + //@ open arc_atomic_cas::app_usize(Post, old_weak)(); + //@ open Post(old_weak); + //@ ArcInner_reassemble_to_array_at_lft::(aid, lay, ptr); + + // Make sure we aren't trying to "deallocate" the shared static for empty slices + // used by Default::default. + debug_assert!( + !ptr_addr_eq__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr), &STATIC_INNER_SLICE.inner), //~ignore_ref_creation + "Arc/Weaks backed by a static should never be deallocated. \ + Likely decrement_strong_count or from_raw were called too many times.", + ); + //@ leak <&'static SliceArcInnerForStatic>.own(t, _); + + // ignore-tidy-undocumented-unsafe + //@ points_to_limits(&(*self).alloc); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k1 = begin_lifetime(); + let r; + unsafe { + //@ let_lft 'a = k1; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + r = self.alloc.deallocate/*@::@*/(self.ptr.cast(), Layout_for_value_raw__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr))); + } + //@ end_lifetime(k1); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + r + } else { + //@ arc_atomic_cas::discard_pending_acquire(arc_atomic_cas::app_usize(Post, old_weak)); + }; + } + //@ close_NonNull_own_unsized(t, (*self).ptr); + //@ std::alloc::Allocator_to_own((*self).alloc); + drop_res + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +trait ArcEqIdent { + fn eq(&self, other: &Arc) -> bool; + fn ne(&self, other: &Arc) -> bool; +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + default fn eq(&self, other: &Arc) -> bool { + **self == **other + } + #[inline] + default fn ne(&self, other: &Arc) -> bool { + **self != **other + } +} + +/// We're doing this specialization here, and not as a more general optimization on `&T`, because it +/// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to +/// store large values, that are slow to clone, but also heavy to check for equality, causing this +/// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to +/// the same value, than two `&T`s. +/// +/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + fn eq(&self, other: &Arc) -> bool { + ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other + } + + #[inline] + fn ne(&self, other: &Arc) -> bool { + !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialEq for Arc { + /// Equality for two `Arc`s. + /// + /// Two `Arc`s are equal if their inner values are equal, even if they are + /// stored in different allocation. + /// + /// If `T` also implements `Eq` (implying reflexivity of equality), + /// two `Arc`s that point to the same allocation are always equal. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five == Arc::new(5)); + /// ``` + #[inline] + fn eq(&self, other: &Arc) -> bool { + ArcEqIdent::eq(self, other) + } + + /// Inequality for two `Arc`s. + /// + /// Two `Arc`s are not equal if their inner values are not equal. + /// + /// If `T` also implements `Eq` (implying reflexivity of equality), + /// two `Arc`s that point to the same value are always equal. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five != Arc::new(6)); + /// ``` + #[inline] + fn ne(&self, other: &Arc) -> bool { + ArcEqIdent::ne(self, other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialOrd for Arc { + /// Partial comparison for two `Arc`s. + /// + /// The two are compared by calling `partial_cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::cmp::Ordering; + /// + /// let five = Arc::new(5); + /// + /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); + /// ``` + fn partial_cmp(&self, other: &Arc) -> Option { + (**self).partial_cmp(&**other) + } + + /// Less-than comparison for two `Arc`s. + /// + /// The two are compared by calling `<` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five < Arc::new(6)); + /// ``` + fn lt(&self, other: &Arc) -> bool { + *(*self) < *(*other) + } + + /// 'Less than or equal to' comparison for two `Arc`s. + /// + /// The two are compared by calling `<=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five <= Arc::new(5)); + /// ``` + fn le(&self, other: &Arc) -> bool { + *(*self) <= *(*other) + } + + /// Greater-than comparison for two `Arc`s. + /// + /// The two are compared by calling `>` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five > Arc::new(4)); + /// ``` + fn gt(&self, other: &Arc) -> bool { + *(*self) > *(*other) + } + + /// 'Greater than or equal to' comparison for two `Arc`s. + /// + /// The two are compared by calling `>=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five >= Arc::new(5)); + /// ``` + fn ge(&self, other: &Arc) -> bool { + *(*self) >= *(*other) + } +} +#[stable(feature = "rust1", since = "1.0.0")] +impl Ord for Arc { + /// Comparison for two `Arc`s. + /// + /// The two are compared by calling `cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::cmp::Ordering; + /// + /// let five = Arc::new(5); + /// + /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6))); + /// ``` + fn cmp(&self, other: &Arc) -> Ordering { + (**self).cmp(&**other) + } +} +#[stable(feature = "rust1", since = "1.0.0")] +impl Eq for Arc {} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Pointer for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&(&raw const **self), f) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Default for Arc { + /// Creates a new `Arc`, with the `Default` value for `T`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x: Arc = Default::default(); + /// assert_eq!(*x, 0); + /// ``` + fn default() -> Arc + //@ req thread_token(?t); + //@ ens thread_token(t) &*& Arc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + // ignore-tidy-undocumented-unsafe + unsafe { + let b = Box_new_uninit__VeriFast_wrapper(); + let bx = Box_write__VeriFast_wrapper( + b, + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: Default_default__VeriFast_wrapper(), + }, + ); + let ptr = Box_into_non_null__VeriFast_wrapper(bx); + let r = Self::from_inner(ptr); + //@ std::alloc::produce_Allocator_Global(t); + //@ init_Arc_from_box_in::(t, ptr, std::alloc::Global {}, std::alloc::Global_alloc_id); + r + } + } +} + +/// Struct to hold the static `ArcInner` used for empty `Arc` as +/// returned by `Default::default`. +/// +/// Layout notes: +/// * `repr(align(16))` so we can use it for `[T]` with `align_of::() <= 16`. +/// * `repr(C)` so `inner` is at offset 0 (and thus guaranteed to actually be aligned to 16). +/// * `[u8; 1]` (to be initialized with 0) so it can be used for `Arc`. +#[repr(C, align(16))] +struct SliceArcInnerForStatic { + inner: ArcInner<[u8; 1]>, +} +#[cfg(not(no_global_oom_handling))] +const MAX_STATIC_INNER_SLICE_ALIGNMENT: usize = 16; + +static STATIC_INNER_SLICE: SliceArcInnerForStatic = SliceArcInnerForStatic { + inner: ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: [0], + }, +}; + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc { + /// Creates an empty str inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + let arc: Arc<[u8]> = Default::default(); + debug_assert!(core::str::from_utf8(&arc).is_ok()); + let (ptr, alloc) = Arc::into_inner_with_allocator(arc); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr_in(ptr.as_ptr() as *mut ArcInner, alloc) } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc { + /// Creates an empty CStr inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + use core::ffi::CStr; + let inner: NonNull> = NonNull::from(&STATIC_INNER_SLICE.inner); + let inner: NonNull> = + NonNull::new(inner.as_ptr() as *mut ArcInner).unwrap(); + // `this` semantically is the Arc "owned" by the static, so make sure not to drop it. + let this: mem::ManuallyDrop> = + // ignore-tidy-undocumented-unsafe + unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) }; + (*this).clone() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc<[T]> { + /// Creates an empty `[T]` inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + if align_of::() <= MAX_STATIC_INNER_SLICE_ALIGNMENT { + // We take a reference to the whole struct instead of the ArcInner<[u8; 1]> inside it so + // we don't shrink the range of bytes the ptr is allowed to access under Stacked Borrows. + // (Miri complains on 32-bit targets with Arc<[Align16]> otherwise.) + // (Note that NonNull::from(&STATIC_INNER_SLICE.inner) is fine under Tree Borrows.) + let inner: NonNull = NonNull::from(&STATIC_INNER_SLICE); + let inner: NonNull> = inner.cast(); + // `this` semantically is the Arc "owned" by the static, so make sure not to drop it. + let this: mem::ManuallyDrop> = + // ignore-tidy-undocumented-unsafe + unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) }; + return (*this).clone(); + } + + // If T's alignment is too large for the static, make a new unique allocation. + let arr: [T; 0] = []; + Arc::from(arr) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "pin_default_impls", since = "1.91.0")] +impl Default for Pin> +where + T: ?Sized, + Arc: Default, +{ + #[inline] + fn default() -> Self { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::::default()) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Hash for Arc { + fn hash(&self, state: &mut H) { + (**self).hash(state) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "from_for_ptrs", since = "1.6.0")] +impl From for Arc { + /// Converts a `T` into an `Arc` + /// + /// The conversion moves the value into a + /// newly allocated `Arc`. It is equivalent to + /// calling `Arc::new(t)`. + /// + /// # Example + /// ```rust + /// # use std::sync::Arc; + /// let x = 5; + /// let arc = Arc::new(5); + /// + /// assert_eq!(Arc::from(x), arc); + /// ``` + fn from(t: T) -> Self { + Arc::new(t) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_array", since = "1.74.0")] +impl From<[T; N]> for Arc<[T]> { + /// Converts a [`[T; N]`](prim@array) into an `Arc<[T]>`. + /// + /// The conversion moves the array into a newly allocated `Arc`. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let original: [i32; 3] = [1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: [T; N]) -> Arc<[T]> { + Arc::<[T; N]>::from(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From<&[T]> for Arc<[T]> { + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let original: &[i32] = &[1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: &[T]) -> Arc<[T]> { + >::from_slice(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_mut_slice", since = "1.84.0")] +impl From<&mut [T]> for Arc<[T]> { + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let mut original = [1, 2, 3]; + /// let original: &mut [i32] = &mut original; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: &mut [T]) -> Arc<[T]> { + Arc::from(&*v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From<&str> for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let shared: Arc = Arc::from("eggplant"); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: &str) -> Arc { + let arc = Arc::<[u8]>::from(v.as_bytes()); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_mut_slice", since = "1.84.0")] +impl From<&mut str> for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let mut original = String::from("eggplant"); + /// let original: &mut str = &mut original; + /// let shared: Arc = Arc::from(original); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: &mut str) -> Arc { + Arc::from(&*v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: String = "eggplant".to_owned(); + /// let shared: Arc = Arc::from(unique); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: String) -> Arc { + Arc::from(&v[..]) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From> for Arc { + /// Move a boxed object to a new, reference-counted allocation. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: Box = Box::from("eggplant"); + /// let shared: Arc = Arc::from(unique); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: Box) -> Arc { + Arc::from_box_in(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From> for Arc<[T], A> { + /// Allocates a reference-counted slice and moves `v`'s items into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: Vec = vec![1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(unique); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: Vec) -> Arc<[T], A> + //@ req thread_token(?t) &*& >.own(t, v); + //@ ens thread_token(t) &*& Arc_own::<[T], A>(t, result); + //@ on_unwind_ens thread_token(t); + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (vec_ptr, len, cap, mut alloc) = Vec_into_raw_parts_with_allocator__VeriFast_wrapper(v); + //@ assert *(&alloc) |-> ?alloc_val &*& std::alloc::Allocator(t, alloc_val, ?aid); + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let rc_ptr; + { + //@ let_lft 'a = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'a, A>(alloc_ref); + let alloc_borrow = &alloc; + rc_ptr = Self::allocate_for_slice_in/*@::@*/(len, alloc_borrow); //~ignore_ref_creation + //@ close exists::(t); + //@ close exists::<*[T]>(&(*rc_ptr).data); + ptr_copy_elems_to_arcinner_slice__VeriFast_wrapper(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len); + + // Create a `Vec` with length 0, to deallocate the buffer + // without dropping its contents or the allocator + Vec_drop_empty_in__VeriFast_wrapper(vec_ptr, cap, alloc_borrow); //~ignore_ref_creation + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + + let a = Self::from_ptr_in(rc_ptr, alloc); + //@ init_Arc_from_raw_parts_in::<[T], A>(t, a.ptr, a.alloc, aid, arcinner_padded_layout(std::alloc::Layout::from_size_align(len * std::mem::size_of::(), std::mem::align_of::()))); + a + } + } +} + +#[stable(feature = "shared_from_cow", since = "1.45.0")] +impl<'a, B> From> for Arc +where + B: ToOwned + ?Sized, + Arc: From<&'a B> + From, +{ + /// Creates an atomically reference-counted pointer from a clone-on-write + /// pointer by copying its content. + /// + /// # Example + /// + /// ```rust + /// # use std::sync::Arc; + /// # use std::borrow::Cow; + /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant"); + /// let shared: Arc = Arc::from(cow); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(cow: Cow<'a, B>) -> Arc { + match cow { + Cow::Borrowed(s) => Arc::from(s), + Cow::Owned(s) => Arc::from(s), + } + } +} + +#[stable(feature = "shared_from_str", since = "1.62.0")] +impl From> for Arc<[u8]> { + /// Converts an atomically reference-counted string slice into a byte slice. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let string: Arc = Arc::from("eggplant"); + /// let bytes: Arc<[u8]> = Arc::from(string); + /// assert_eq!("eggplant".as_bytes(), bytes.as_ref()); + /// ``` + #[inline] + fn from(rc: Arc) -> Self { + // SAFETY: `str` has the same layout as `[u8]`. + unsafe { Arc::from_raw(Arc::into_raw(rc) as *const [u8]) } + } +} + +#[stable(feature = "boxed_slice_try_from", since = "1.43.0")] +impl TryFrom> for Arc<[T; N], A> { + type Error = Arc<[T], A>; + + fn try_from(boxed_slice: Arc<[T], A>) -> Result { + if boxed_slice.len() == N { + let (ptr, alloc) = Arc::into_inner_with_allocator(boxed_slice); + // ignore-tidy-undocumented-unsafe + Ok(unsafe { Arc::from_inner_in(ptr.cast(), alloc) }) + } else { + Err(boxed_slice) + } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_iter", since = "1.37.0")] +impl FromIterator for Arc<[T]> { + /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`. + /// + /// # Performance characteristics + /// + /// ## The general case + /// + /// In the general case, collecting into `Arc<[T]>` is done by first + /// collecting into a `Vec`. That is, when writing the following: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect(); + /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); + /// ``` + /// + /// this behaves as if we wrote: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0) + /// .collect::>() // The first set of allocations happens here. + /// .into(); // A second allocation for `Arc<[T]>` happens here. + /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); + /// ``` + /// + /// This will allocate as many times as needed for constructing the `Vec` + /// and then it will allocate once for turning the `Vec` into the `Arc<[T]>`. + /// + /// ## Iterators of known length + /// + /// When your `Iterator` implements `TrustedLen` and is of an exact size, + /// a single allocation will be made for the `Arc<[T]>`. For example: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here. + /// # assert_eq!(&*evens, &*(0..10).collect::>()); + /// ``` + fn from_iter>(iter: I) -> Self { + ToArcSlice::to_arc_slice(iter.into_iter()) + } +} + +#[cfg(not(no_global_oom_handling))] +/// Specialization trait used for collecting into `Arc<[T]>`. +trait ToArcSlice: Iterator + Sized { + fn to_arc_slice(self) -> Arc<[T]>; +} + +#[cfg(not(no_global_oom_handling))] +impl> ToArcSlice for I { + default fn to_arc_slice(self) -> Arc<[T]> { + self.collect::>().into() + } +} + +#[cfg(not(no_global_oom_handling))] +impl> ToArcSlice for I { + fn to_arc_slice(self) -> Arc<[T]> { + // This is the case for a `TrustedLen` iterator. + let (low, high) = self.size_hint(); + if let Some(high) = high { + debug_assert_eq!( + low, + high, + "TrustedLen iterator's size hint is not exact: {:?}", + (low, high) + ); + + // SAFETY: We need to ensure that the iterator has an exact length and we have. + unsafe { Arc::from_iter_exact(self, low) } + } else { + // TrustedLen contract guarantees that `upper_bound == None` implies an iterator + // length exceeding `usize::MAX`. + // The default implementation would collect into a vec which would panic. + // Thus we panic here immediately without invoking `Vec` code. + panic!("capacity overflow"); + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl borrow::Borrow for Arc { + fn borrow(&self) -> &T { + self + } +} + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsRef for Arc { + fn as_ref(&self) -> &T { + self + } +} + +#[stable(feature = "pin", since = "1.33.0")] +impl Unpin for Arc {} + +/// Gets the offset within an `ArcInner` for the payload behind a pointer. +/// +/// # Safety +/// +/// The pointer must point to (and have valid metadata for) a previously +/// valid instance of T, but the T is allowed to be dropped. +unsafe fn data_offset(ptr: *const T) -> usize +//@ req is_power_of_2(std::mem::align_of_val(ptr)) == true &*& std::mem::align_of_val(ptr) <= isize::MAX as usize; +//@ ens result == arc_data_offset(std::mem::align_of_val(ptr)); +//@ on_unwind_ens false; +{ + // Align the unsized value to the end of the ArcInner. + // Because ArcInner is repr(C), it will always be the last field in memory. + // SAFETY: since the only unsized types possible are slices, trait objects, + // and extern types, the input safety requirement is currently enough to + // satisfy the requirements of Alignment::of_val_raw; this is an implementation + // detail of the language that must not be relied upon outside of std. + unsafe { data_offset_alignment(Alignment_of_val_raw__VeriFast_wrapper(ptr)) } +} + +#[inline] +fn data_offset_alignment(alignment: Alignment) -> usize +//@ req true; +//@ ens result == arc_data_offset(alignment.as_nonzero_usize().get()); +//@ on_unwind_ens false; +//@ safety_proof { leak .own(_t, alignment); call(); } +{ + let mut layout = Layout::new::>(); + //@ std::alloc::Layout_inv(layout); + //@ std::mem::Alignment_is_power_of_2(alignment); + //@ let l_ref1 = precreate_ref(&layout); + //@ init_ref_readonly(l_ref1, 1/2); + let sz = layout.size(); + //@ end_ref_readonly(l_ref1); + //@ let l_ref2 = precreate_ref(&layout); + //@ init_ref_readonly(l_ref2, 1/2); + let pad = unsafe { Layout_padding_needed_for__VeriFast_wrapper(&layout, alignment) }; + //@ end_ref_readonly(l_ref2); + sz + pad +} + +/// A unique owning pointer to an [`ArcInner`] **that does not imply the contents are initialized,** +/// but will deallocate it (without dropping the value) when dropped. +/// +/// This is a helper for [`Arc::make_mut()`] to ensure correct cleanup on panic. +struct UniqueArcUninit { + ptr: NonNull>, + layout_for_value: Layout, + alloc: Option, +} + +/*@ +pred >.own(t, u) = + [_]std::ptr::NonNull_own(default_tid, u.ptr) &*& + arc_data_offset(u.layout_for_value.align()) <= isize::MAX as usize &*& + (u.ptr.as_ptr() as usize) + arc_data_offset(u.layout_for_value.align()) <= usize::MAX &*& + ptr_within_limits(u.ptr.as_ptr() as pointer) == true &*& + ptr_within_limits(ptr_add(u.ptr.as_ptr() as pointer, arc_data_offset(u.layout_for_value.align()))) == true &*& + match u.alloc { + Option::Some(a) => + std::alloc::Allocator(t, a, ?alloc_id) &*& + std::alloc::alloc_block_in(alloc_id, u.ptr.as_ptr() as *u8, arcinner_padded_layout(u.layout_for_value)) &*& + array_at_lft_(alloc_id.lft, u.ptr.as_ptr() as *u8, arcinner_padded_layout(u.layout_for_value).size(), _), + Option::None => false + }; + +lem UniqueArcUninit_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + UniqueArcUninit_own::(?t, ?v) &*& is_subtype_of::() == true &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& type_interp::() &*& + UniqueArcUninit_own::(t, UniqueArcUninit:: { ptr: upcast(v.ptr), layout_for_value: upcast(v.layout_for_value), alloc: upcast(v.alloc) }); +{ + assume(false); // VeriFast issue #610 +} +@*/ + +impl UniqueArcUninit { + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it. + #[cfg(not(no_global_oom_handling))] + fn new<'a>(for_value: &'a T, mut alloc: A) -> UniqueArcUninit + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_](.share)('a, t, for_value) &*& .own(t, alloc); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& UniqueArcUninit_own::(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + let layout = unsafe { Layout_for_value_ref__VeriFast_wrapper(for_value) }; //~ignore_ref_creation + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let ptr; + { + //@ let_lft 'b = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'b, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + ptr = unsafe { Arc_alloc_for_val_in__VeriFast_wrapper::(for_value, layout, &alloc) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + //@ ArcInner_reassemble_uninit_to_array_at_lft::(aid, arcinner_padded_layout(layout), ptr); + let nnp = unsafe { NonNull_new_unwrap__VeriFast_wrapper(ptr) }; + let r = Self { ptr: nnp, layout_for_value: layout, alloc: Some(alloc) }; + //@ close UniqueArcUninit_own::(t, r); + r + } + + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it, + /// returning an error if allocation fails. + fn try_new<'a>(for_value: &'a T, mut alloc: A) -> Result, AllocError> + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_](.share)('a, t, for_value) &*& .own(t, alloc); + /*@ + ens thread_token(t) &*& [qa]lifetime_token('a) &*& + match result { + Result::Ok(u) => UniqueArcUninit_own::(t, u), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ assert *(&alloc) |-> ?alloc_val; + //@ std::alloc::open_Allocator_own(alloc_val); + //@ assert std::alloc::Allocator(t, alloc_val, ?aid); + let layout = unsafe { Layout_for_value_ref__VeriFast_wrapper(for_value) }; //~ignore_ref_creation + //@ let alloc_ref = precreate_ref(&alloc); + //@ let k_alloc = begin_lifetime(); + let ptr_res; + { + //@ let_lft 'b = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'b, A>(alloc_ref); + // ignore-tidy-undocumented-unsafe + ptr_res = unsafe { Arc_try_alloc_for_val_in__VeriFast_wrapper::(for_value, layout, &alloc) }; + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + let ptr = match ptr_res { + Ok(p) => p, + Err(e) => { + //@ assert *(&alloc) |-> ?alloc_val2; + //@ std::alloc::Allocator_to_own(alloc_val2); + return Err(e); + } + }; + //@ ArcInner_reassemble_uninit_to_array_at_lft::(aid, arcinner_padded_layout(layout), ptr); + let nnp = unsafe { NonNull_new_unwrap__VeriFast_wrapper(ptr) }; + let r = Self { ptr: nnp, layout_for_value: layout, alloc: Some(alloc) }; + //@ close UniqueArcUninit_own::(t, r); + Ok(r) + } + + /// Returns the pointer to be written into to initialize the [`Arc`]. + fn data_ptr<'a>(&'a mut self) -> *mut T + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& full_borrow('a, UniqueArcUninit_full_borrow_content::(t, self)); + //@ ens thread_token(t) &*& [qa]lifetime_token('a); + //@ on_unwind_ens false; + { + //@ let klong = open_full_borrow_strong('a, UniqueArcUninit_full_borrow_content::(t, self), qa); + //@ open UniqueArcUninit_full_borrow_content::(t, self)(); + //@ open UniqueArcUninit_own::(t, ?u); + //@ points_to_limits(&(*self).layout_for_value); + //@ let l_ref = precreate_ref(&(*self).layout_for_value); + //@ init_ref_readonly(l_ref, 1/2); + let align = self.layout_for_value.alignment(); + //@ end_ref_readonly(l_ref); + let offset = data_offset_alignment(align); + // ignore-tidy-undocumented-unsafe + let r = unsafe { ptr_byte_add__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr), offset) as *mut T }; + //@ close [1/2]UniqueArcUninit_layout_for_value(self, _); + //@ close UniqueArcUninit_own::(t, u); + //@ close UniqueArcUninit_full_borrow_content::(t, self)(); + /*@ + { + pred Ctx() = true; + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + UniqueArcUninit_full_borrow_content::(t, self), + klong, + UniqueArcUninit_full_borrow_content::(t, self) + )() { + open Ctx(); + } { + close_full_borrow_strong(klong, UniqueArcUninit_full_borrow_content::(t, self), UniqueArcUninit_full_borrow_content::(t, self)); + } + } + @*/ + //@ leak full_borrow(klong, UniqueArcUninit_full_borrow_content::(t, self)); + r + } + + /// Upgrade this into a normal [`Arc`]. + /// + /// # Safety + /// + /// The data must have been initialized (by writing to [`Self::data_ptr()`]). + unsafe fn into_arc(self) -> Arc + //@ req self.alloc == std::option::Option::Some(?a); + //@ ens result.ptr.as_ptr() == self.ptr.as_ptr() && result.alloc == a; + //@ on_unwind_ens false; + { + let mut me = ManuallyDrop::new(self); + //@ close_points_to(&me); + //@ let me_ref = precreate_ref(&me as *UniqueArcUninit); + //@ init_ref_readonly(me_ref, 1/2); + //@ open_points_to(me_ref); + let ptr = NonNull_as_ptr__VeriFast_wrapper(me.ptr); + //@ close_points_to(me_ref, 1/2); + //@ end_ref_readonly(me_ref); + //@ open_points_to(&me); + let alloc = me.alloc.take().unwrap(); + //@ close UniqueArcUninit_alloc(&me, _); + + // SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible + // for having initialized the data. + unsafe { Arc::from_ptr_in(ptr, alloc) } + } +} + +impl Drop for UniqueArcUninit { + fn drop(&mut self) + //@ req thread_token(?t) &*& UniqueArcUninit_full_borrow_content::(t, self)(); + //@ ens thread_token(t) &*& (*self).ptr |-> ?p &*& std::ptr::NonNull_own(t, p) &*& (*self).layout_for_value |-> ?l &*& std::alloc::Layout_own(t, l) &*& (*self).alloc |-> ?a &*& >.own(t, a) &*& struct_UniqueArcUninit_padding(self); + //@ on_unwind_ens thread_token(t); + { + //@ open UniqueArcUninit_full_borrow_content::(t, self)(); + //@ open UniqueArcUninit_own::(t, ?u); + //@ assert u.alloc == std::option::Option::Some(?alloc_val); + // SAFETY: + // * new() produced a pointer safe to deallocate. + // * We own the pointer unless into_arc() was called, which forgets us. + unsafe { + Allocator_deallocate_owned__VeriFast_wrapper( + self.alloc.take().unwrap(), + self.ptr.cast(), + arcinner_layout_for_value_layout(self.layout_for_value), + ); + } + //@ close_NonNull_own_unsized(t, (*self).ptr); + //@ std::alloc::close_Layout_own(t, (*self).layout_for_value); + //@ close >.own(t, std::option::Option::None); + } +} + +#[stable(feature = "arc_error", since = "1.52.0")] +impl core::error::Error for Arc { + #[allow(deprecated)] + fn cause(&self) -> Option<&dyn core::error::Error> { + core::error::Error::cause(&**self) + } + + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + core::error::Error::source(&**self) + } + + fn provide<'a>(&'a self, req: &mut core::error::Request<'a>) { + core::error::Error::provide(&**self, req); + } +} + +/// A uniquely owned [`Arc`]. +/// +/// This represents an `Arc` that is known to be uniquely owned -- that is, have exactly one strong +/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong +/// references will fail unless the `UniqueArc` they point to has been converted into a regular `Arc`. +/// +/// Because it is uniquely owned, the contents of a `UniqueArc` can be freely mutated. A common +/// use case is to have an object be mutable during its initialization phase but then have it become +/// immutable and converted to a normal `Arc`. +/// +/// This can be used as a flexible way to create cyclic data structures, as in the example below. +/// +/// ``` +/// #![feature(unique_rc_arc)] +/// use std::sync::{Arc, Weak, UniqueArc}; +/// +/// struct Gadget { +/// me: Weak, +/// } +/// +/// fn create_gadget() -> Option> { +/// let mut rc = UniqueArc::new(Gadget { +/// me: Weak::new(), +/// }); +/// rc.me = UniqueArc::downgrade(&rc); +/// Some(UniqueArc::into_arc(rc)) +/// } +/// +/// create_gadget().unwrap(); +/// ``` +/// +/// An advantage of using `UniqueArc` over [`Arc::new_cyclic`] to build cyclic data structures is that +/// [`Arc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the +/// previous example, `UniqueArc` allows for more flexibility in the construction of cyclic data, +/// including fallible or async constructors. +#[unstable(feature = "unique_rc_arc", issue = "112566")] +pub struct UniqueArc< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + ptr: NonNull>, + // Define the ownership of `ArcInner` for drop-check + _marker: PhantomData>, + // Invariance is necessary for soundness: once other `Weak` + // references exist, we already have a form of shared mutability! + _marker2: PhantomData<*mut T>, + alloc: A, +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl Send for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl Sync for UniqueArc {} + +/*@ +// Phase 2 Concurrent predicates for UniqueArc: +// Shares `ArcInner_meta` with `Arc_inv` in `ModeDataOut` (`strong == 0`, `weak == w_cnt + 1`), +// holding `[1/2]ghost_cell(imp_gid, 1)` + exclusive ownership of `(*ptr).data`. +pred >.own(t, ua) = + [_]std::ptr::NonNull_own(default_tid, ua.ptr) &*& + [_]exists(?ptr) &*& ua.ptr.as_ptr() == ptr &*& + std::alloc::Allocator(t, ua.alloc, ?alloc_id) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [1/2]ghost_cell(imp_gid, 1) &*& + ((.full_borrow_content)(owner_tid, &(*ptr).data))(); + +pred_ctor UniqueArc_ptr_bc(l: *UniqueArc, nnp: std::ptr::NonNull>)(;) = + (*l).ptr |-> nnp &*& struct_UniqueArc_padding(l); + +pred_ctor imp_token_(imp_gid: i32)(;) = [1/2]ghost_cell(imp_gid, 1); + +pred >.share(k, t, l) = + [_]exists(?nnp) &*& + [_]frac_borrow(k, UniqueArc_ptr_bc(l, nnp)) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(?ptr) &*& nnp.as_ptr() == ptr &*& + [_]std::alloc::Allocator_share(k, t, &(*l).alloc, ?alloc_id) &*& + pointer_within_limits(&(*l).alloc) == true &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [_]frac_borrow(k, imp_token_(imp_gid)) &*& + [_](.share)(k, owner_tid, &(*ptr).data); + +lem UniqueArc_own_mono() + req type_interp::() &*& type_interp::() &*& type_interp::() &*& + UniqueArc_own::(?t, ?v) &*& is_subtype_of::() == true; + ens type_interp::() &*& type_interp::() &*& type_interp::() &*& + UniqueArc_own::(t, UniqueArc:: { ptr: upcast(v.ptr), alloc: upcast(v.alloc) }); +{ + assume(false); // VeriFast issue #610 +} + +lem UniqueArc_send(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Send(typeid(UniqueArc)) == true &*& + UniqueArc_own::(?t0, ?v); + ens type_interp::() &*& type_interp::() &*& UniqueArc_own::(t1, v); +{ + open UniqueArc_own::(t0, v); + std::alloc::Allocator_send::(t1, v.alloc); + close UniqueArc_own::(t1, v); +} + +lem UniqueArc_share_mono(k: lifetime_t, k1: lifetime_t, t: thread_id_t, l: *UniqueArc) + req type_interp::() &*& type_interp::() &*& lifetime_inclusion(k1, k) == true &*& [_]UniqueArc_share::(k, t, l); + ens type_interp::() &*& type_interp::() &*& [_]UniqueArc_share::(k1, t, l); +{ + open UniqueArc_share::(k, t, l); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, ?alloc_id, ?layout, ?owner_tid, ptr); + frac_borrow_mono(k, k1, UniqueArc_ptr_bc(l, nnp)); + std::alloc::Allocator_share_mono::(k, k1, t, &(*l).alloc); + frac_borrow_mono(k, k1, imp_token_(imp_gid)); + share_mono::(k, k1, owner_tid, &(*ptr).data); + close UniqueArc_share::(k1, t, l); + leak UniqueArc_share::(k1, t, l); +} + +lem UniqueArc_Sync_implies_T_Send_Sync() + req is_Sync(typeid(UniqueArc)) == true; + ens is_Send(typeid(T)) == true &*& is_Sync(typeid(T)) == true &*& is_Send(typeid(A)) == true &*& is_Sync(typeid(A)) == true; +{ + assume(false); +} + +lem UniqueArc_sync(t1: thread_id_t) + req type_interp::() &*& type_interp::() &*& + is_Sync(typeid(UniqueArc)) == true &*& + [_]UniqueArc_share::(?k, ?t0, ?l); + ens type_interp::() &*& type_interp::() &*& [_]UniqueArc_share::(k, t1, l); +{ + UniqueArc_Sync_implies_T_Send_Sync::(); + open UniqueArc_share::(k, t0, l); + std::alloc::Allocator_sync::(t1); + close UniqueArc_share::(k, t1, l); + leak UniqueArc_share::(k, t1, l); +} + +lem UniqueArc_share_full(k: lifetime_t, t: thread_id_t, l: *UniqueArc) + req type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [?q]lifetime_token(k) &*& + full_borrow(k, UniqueArc_full_borrow_content::(t, l)); + ens type_interp::() &*& type_interp::() &*& atomic_mask(MaskTop) &*& [q]lifetime_token(k) &*& + [_]UniqueArc_share::(k, t, l); +{ + let klong = open_full_borrow_strong_m(k, UniqueArc_full_borrow_content::(t, l), q); + open UniqueArc_full_borrow_content::(t, l)(); + open UniqueArc_own::(t, ?ua); + let nnp = ua.ptr; + assert [_]exists::<*ArcInner>(?ptr) &*& + std::alloc::Allocator(t, ua.alloc, ?alloc_id) &*& + [_]ArcInner_meta::(?inv_gid, ?sgid, ?wgid, ?lock_gid, ?imp_gid, alloc_id, ?layout, ?owner_tid, ptr); + points_to_limits(&(*l).alloc); + close UniqueArc_ptr_bc::(l, nnp)(); + std::alloc::close_Allocator_full_borrow_content_::(t, &(*l).alloc); + close imp_token_(imp_gid)(); + close sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data))(); + close sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data)))(); + close sep(UniqueArc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data))))(); + { + pred Ctx() = + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& nnp.as_ptr() == ptr &*& + [_]ArcInner_meta::(inv_gid, sgid, wgid, lock_gid, imp_gid, alloc_id, layout, owner_tid, ptr) &*& + (owner_tid == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)); + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + sep(UniqueArc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data)))), + klong, + UniqueArc_full_borrow_content::(t, l) + )() { + open Ctx(); + open sep(UniqueArc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data))))(); + open UniqueArc_ptr_bc::(l, nnp)(); + open sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data)))(); + std::alloc::open_Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id); + open sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data))(); + open imp_token_(imp_gid)(); + close UniqueArc_own::(t, *l); + close UniqueArc_full_borrow_content::(t, l)(); + } { + close_full_borrow_strong_m( + klong, + UniqueArc_full_borrow_content::(t, l), + sep(UniqueArc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data)))) + ); + } + } + full_borrow_mono(klong, k, sep(UniqueArc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data))))); + full_borrow_split_m(k, UniqueArc_ptr_bc::(l, nnp), sep(std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data)))); + full_borrow_split_m(k, std::alloc::Allocator_full_borrow_content_::(t, &(*l).alloc, alloc_id), sep(imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data))); + full_borrow_split_m(k, imp_token_(imp_gid), .full_borrow_content(owner_tid, &(*ptr).data)); + full_borrow_into_frac_m(k, UniqueArc_ptr_bc::(l, nnp)); + std::alloc::share_Allocator_full_borrow_content_m::(k, t, &(*l).alloc, alloc_id); + full_borrow_into_frac_m(k, imp_token_(imp_gid)); + share_full_borrow_m::(k, owner_tid, &(*ptr).data); + leak exists(nnp); + close UniqueArc_share::(k, t, l); + leak UniqueArc_share::(k, t, l); +} + +lem init_ref_UniqueArc(p: *UniqueArc) + req type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& ref_init_perm(p, ?x) &*& + [_]UniqueArc_share::(?k, ?t, x) &*& [?q]lifetime_token(k); + ens type_interp::() &*& type_interp::() &*& atomic_mask(Nlft) &*& [q]lifetime_token(k) &*& + [_]UniqueArc_share::(k, t, p) &*& [_]frac_borrow(k, ref_initialized_(p)); +{ + assume(false); +} +@*/ + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +// #[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> + for UniqueArc +{ +} + +//#[unstable(feature = "unique_rc_arc", issue = "112566")] +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Display for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Debug for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Pointer for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&(&raw const **self), f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl borrow::Borrow for UniqueArc { + fn borrow(&self) -> &T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl borrow::BorrowMut for UniqueArc { + fn borrow_mut(&mut self) -> &mut T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl AsRef for UniqueArc { + fn as_ref(&self) -> &T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl AsMut for UniqueArc { + fn as_mut(&mut self) -> &mut T { + self + } +} + +#[cfg(not(no_global_oom_handling))] +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl From for UniqueArc { + #[inline(always)] + fn from(value: T) -> Self { + Self::new(value) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Unpin for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl PartialEq for UniqueArc { + /// Equality for two `UniqueArc`s. + /// + /// Two `UniqueArc`s are equal if their inner values are equal. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five == UniqueArc::new(5)); + /// ``` + #[inline] + fn eq(&self, other: &Self) -> bool { + PartialEq::eq(&**self, &**other) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl PartialOrd for UniqueArc { + /// Partial comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `partial_cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// use std::cmp::Ordering; + /// + /// let five = UniqueArc::new(5); + /// + /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueArc::new(6))); + /// ``` + #[inline(always)] + fn partial_cmp(&self, other: &UniqueArc) -> Option { + (**self).partial_cmp(&**other) + } + + /// Less-than comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `<` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five < UniqueArc::new(6)); + /// ``` + #[inline(always)] + fn lt(&self, other: &UniqueArc) -> bool { + **self < **other + } + + /// 'Less than or equal to' comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `<=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five <= UniqueArc::new(5)); + /// ``` + #[inline(always)] + fn le(&self, other: &UniqueArc) -> bool { + **self <= **other + } + + /// Greater-than comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `>` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five > UniqueArc::new(4)); + /// ``` + #[inline(always)] + fn gt(&self, other: &UniqueArc) -> bool { + **self > **other + } + + /// 'Greater than or equal to' comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `>=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five >= UniqueArc::new(5)); + /// ``` + #[inline(always)] + fn ge(&self, other: &UniqueArc) -> bool { + **self >= **other + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Ord for UniqueArc { + /// Comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// use std::cmp::Ordering; + /// + /// let five = UniqueArc::new(5); + /// + /// assert_eq!(Ordering::Less, five.cmp(&UniqueArc::new(6))); + /// ``` + #[inline] + fn cmp(&self, other: &UniqueArc) -> Ordering { + (**self).cmp(&**other) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Eq for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Hash for UniqueArc { + fn hash(&self, state: &mut H) { + (**self).hash(state); + } +} + +impl UniqueArc { + /// Creates a new `UniqueArc`. + /// + /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading + /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`]. + /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will + /// point to the new [`Arc`]. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn new(value: T) -> Self + //@ req thread_token(?t) &*& .own(t, value); + //@ ens thread_token(t) &*& UniqueArc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::produce_Allocator_Global(t); + //@ std::alloc::Allocator_to_own(std::alloc::Global {}); + Self::new_in(value, Global) + } + + /// Like [`new`](Self::new), but returns an error if the allocation + /// fails, instead of calling [`handle_alloc_error`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + pub fn try_new(value: T) -> Result + //@ req thread_token(?t) &*& .own(t, value); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(u) => UniqueArc_own::(t, u), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ std::alloc::produce_Allocator_Global(t); + //@ std::alloc::Allocator_to_own(std::alloc::Global {}); + Self::try_new_in(value, Global) + } +} + +impl UniqueArc { + /// Creates a new `UniqueArc` in the provided allocator. + /// + /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading + /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`]. + /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will + /// point to the new [`Arc`]. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + #[must_use] + pub fn new_in(data: T, alloc: A) -> Self + //@ req thread_token(?t) &*& .own(t, data) &*& .own(t, alloc); + //@ ens thread_token(t) &*& UniqueArc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ std::alloc::open_Allocator_own(alloc); + //@ assert std::alloc::Allocator(t, alloc, ?aid); + let inner = ArcInner { + strong: atomic::AtomicUsize::new(0), + // keep one weak reference so if all the weak pointers that are created are dropped + // the UniqueArc still stays valid. + weak: atomic::AtomicUsize::new(1), + data, + }; + //@ close drop_perm::>(false, True, t, inner); + let b = Box::new_in(inner, alloc); + //@ open drop_perm::>(false, True, t, inner); + let (ptr, alloc) = Box::into_non_null_with_allocator(b); + let r = Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }; + //@ init_UniqueArc_from_box_in::(t, ptr, r.alloc, aid); + r + } + + /// Like [`new_in`](Self::new_in), but returns an error if the allocation + /// fails, instead of calling [`handle_alloc_error`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + pub fn try_new_in(data: T, alloc: A) -> Result + //@ req thread_token(?t) &*& .own(t, data) &*& .own(t, alloc); + /*@ + ens thread_token(t) &*& + match result { + Result::Ok(u) => UniqueArc_own::(t, u), + Result::Err(e) => .own(t, e), + }; + @*/ + //@ on_unwind_ens thread_token(t); + /*@ + safety_proof { + let r = call(); + close arc_atomic_cas::Result_own::, std::alloc::AllocError>(_t, r); + } + @*/ + { + //@ std::alloc::open_Allocator_own(alloc); + //@ assert std::alloc::Allocator(t, alloc, ?aid); + let (ptr, alloc) = Box::into_non_null_with_allocator(unsafe { + Box_try_new_in__VeriFast_wrapper( + ArcInner { + strong: atomic::AtomicUsize::new(0), + // keep one weak reference so if all the weak pointers that are created are dropped + // the UniqueArc still stays valid. + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + ) + }?); + let ua = Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }; + //@ init_UniqueArc_from_box_in::(t, ptr, ua.alloc, aid); + Ok(ua) + } + + /// Consumes the `UniqueArc`, returning its wrapped value and allocator. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + #[must_use] + pub fn unwrap_with_allocator(this: Self) -> (T, A) { + let inner_ptr = this.ptr; + let (data_ptr, alloc) = Self::into_raw_with_allocator(this); + + // SAFETY: Conceptually moves out of the `UniqueRc`. + // We do not use the data inside ever again. + let val = unsafe { data_ptr.read() }; + + // Drop the strong-weak ref + drop(Weak { ptr: inner_ptr, alloc: &alloc }); + + (val, alloc) + } + + /// Consumes the `UniqueArc`, returning its wrapped value. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn unwrap(this: Self) -> T { + Self::unwrap_with_allocator(this).0 + } + + /// Maps the value in a `UniqueArc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `UniqueArc`, and the result is returned, + /// also in a `UniqueArc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `UniqueArc::map(u, f)` instead of `u.map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// + /// use std::sync::UniqueArc; + /// + /// let r = UniqueArc::new(7); + /// let new = UniqueArc::map(r, |i| i + 7); + /// assert_eq!(*new, 14); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + pub fn map(this: Self, f: impl FnOnce(T) -> U) -> UniqueArc { + if size_of::() == size_of::() + && align_of::() == align_of::() + && UniqueArc::weak_count(&this) == 0 + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this); + let value = ptr.read(); + let allocation = + UniqueArc::from_raw_with_allocator(ptr.cast::>(), alloc); + + UniqueArc::write(allocation, f(value)) + } + } else { + let (val, alloc) = UniqueArc::unwrap_with_allocator(this); + UniqueArc::new_in(f(val), alloc) + } + } + + /// Attempts to map the value in a `UniqueArc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `UniqueArc`, and if the operation succeeds, + /// the result is returned, also in a `UniqueArc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `UniqueArc::try_map(u, f)` instead of `u.try_map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(smart_pointer_try_map)] + /// #![feature(unique_rc_arc)] + /// + /// use std::sync::UniqueArc; + /// + /// let b = UniqueArc::new(7); + /// let new = UniqueArc::try_map(b, u32::try_from).unwrap(); + /// assert_eq!(*new, 7); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "smart_pointer_try_map", issue = "144419")] + pub fn try_map( + this: Self, + f: impl FnOnce(T) -> R, + ) -> >>::TryType + where + R: Try, + R::Residual: Residual>, + { + if size_of::() == size_of::() + && align_of::() == align_of::() + && UniqueArc::weak_count(&this) == 0 + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this); + let value = ptr.read(); + let allocation = UniqueArc::from_raw_with_allocator( + ptr.cast::>(), + alloc, + ); + + try { UniqueArc::write(allocation, f(value)?) } + } + } else { + let (val, alloc) = UniqueArc::unwrap_with_allocator(this); + try { UniqueArc::new_in(f(val)?, alloc) } + } + } +} + +impl UniqueArc { + #[cfg(not(no_global_oom_handling))] + unsafe fn from_raw_with_allocator(ptr: *const T, alloc: A) -> Self + //@ req is_power_of_2(std::mem::align_of_val(ptr)) == true &*& std::mem::align_of_val(ptr) <= isize::MAX as usize &*& arc_data_offset(std::mem::align_of_val(ptr)) <= isize::MAX as usize &*& arc_data_offset(std::mem::align_of_val(ptr)) < (ptr as usize) &*& ptr_within_limits(ptr as pointer) == true &*& ptr_within_limits(ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr)))) == true; + //@ ens result.ptr.as_ptr() == (ptr_add(ptr as pointer, -arc_data_offset(std::mem::align_of_val(ptr))) as *T) as *ArcInner && result.alloc == alloc; + //@ on_unwind_ens false; + { + // SAFETY: Upheld by caller. + let offset = unsafe { data_offset(ptr) }; + + // Reverse the offset to find the original ArcInner. + // SAFETY: Upheld by caller. + let rc_ptr = unsafe { ptr_byte_sub__VeriFast_wrapper(ptr, offset) as *mut ArcInner }; + + Self { + // SAFETY: Upheld by caller. + ptr: unsafe { NonNull_new_unchecked__VeriFast_wrapper(rc_ptr) }, + _marker: PhantomData, + _marker2: PhantomData, + alloc, + } + } + + fn into_raw_with_allocator(this: Self) -> (*const T, A) + //@ req pointer_within_limits(&(*this.ptr.as_ptr()).data) == true; + //@ ens result.0 == &(*this.ptr.as_ptr()).data && result.1 == this.alloc; + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, this); + assert [_]exists::<*ArcInner>(?ptr) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + leak [1/2]ghost_cell(img, 1) &*& ((.full_borrow_content)(ot, &(*ptr).data))(); + let r = call(); + std::alloc::Allocator_to_own(r.1); + close raw_ptr_own::()(_t, r.0); + close_tuple_2_own::<*const T, A>(_t, r); + } + @*/ + { + let mut me = ManuallyDrop::new(this); + //@ close_points_to(&me); + //@ let me_ref = precreate_ref(&me as *UniqueArc); + //@ init_ref_readonly(me_ref, 1/2); + //@ open_points_to(me_ref); + let ptr = Self::as_ptr(&*me); + //@ close_points_to(me_ref, 1/2); + //@ end_ref_readonly(me_ref); + //@ let me_ref2 = precreate_ref(&me as *UniqueArc); + //@ init_ref_readonly(me_ref2, 1/2); + //@ open_points_to(me_ref2); + //@ let alloc_ref = precreate_ref(&(*me_ref2).alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + // SAFETY: The copy of the allocator stored in `this` is forgotten + let alloc = unsafe { ptr::read(&me.alloc) }; + //@ end_ref_readonly(alloc_ref); + //@ close_points_to(me_ref2, 1/2); + //@ end_ref_readonly(me_ref2); + //@ open_points_to(&me); + (ptr, alloc) + } + + /// Converts the `UniqueArc` into a regular [`Arc`]. + /// + /// This consumes the `UniqueArc` and returns a regular [`Arc`] that contains the `value` that + /// is passed to `into_arc`. + /// + /// Any weak references created before this method is called can now be upgraded to strong + /// references. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn into_arc(this: Self) -> Arc + //@ req thread_token(?t) &*& UniqueArc_own::(t, this); + //@ ens thread_token(t) &*& Arc_own::(t, result); + //@ on_unwind_ens thread_token(t); + { + //@ open UniqueArc_own::(t, ?this_val); + //@ let nnp = this_val.ptr; + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, this_val.alloc, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + let md = ManuallyDrop::new(this); + + // Move the allocator out. + // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in + // a `ManuallyDrop`. + //@ let alloc_ref = precreate_ref(&md.alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + let alloc: A = unsafe { ptr::read(&md.alloc) }; + //@ end_ref_readonly(alloc_ref); + //@ close [1/2]UniqueArc_alloc(&md, _); + + // SAFETY: This pointer was allocated at creation time so we know it is valid. + unsafe { + // Convert our weak reference into a strong reference + { + /*@ + pred Pre() = + type_interp::() &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)) &*& + [1/2]ghost_cell(img, 1) &*& + ((.full_borrow_content)(ot, &(*ptr).data))(); + pred Post() = + ticket(dlft_pred, sg, ?frac) &*& + [frac]dlft_pred(sg, some(?dk)) &*& + [_](.share)(dk, ot, &(*ptr).data); + @*/ + //@ produce_type_interp::(); + //@ close Pre(); + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_store_ghop(&(*ptr).strong, 1, Pre, Post)() { + open Pre(); + let dk = begin_lifetime_m(); + borrow_m(dk, (.full_borrow_content)(ot, &(*ptr).data)); + share_full_borrow_m_unsized::(dk, ot, &(*ptr).data); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [1/2]ghost_cell::(ig, ?mode); + match mode { + ModeShared(dk0) => { merge_fractions ghost_cell(img, _); } + ModeExclusive => { merge_fractions ghost_cell(img, _); } + ModeExclusiveLocked => { merge_fractions ghost_cell(img, _); } + ModeDataOut => { + assert arc_atomic_cas::is_AtomicUsize_store_op(?op, &(*ptr).strong, 1, ?P, ?Q); + op(); + merge_fractions ghost_cell(img, _); + ghost_cell_mutate(img, 0); + merge_fractions ghost_cell::(ig, _); + ghost_cell_mutate(ig, ModeShared(dk)); + stop_counting(dlft_pred, sg); + open dlft_pred(sg, none); + ghost_cell_mutate(sg, some(dk)); + close dlft_pred(sg, some(dk)); + start_counting(dlft_pred, sg); + let frac = create_ticket(dlft_pred, sg); + close shared_weak_lock(lg, sg, dk, false); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + leak type_interp::(); + close Post(); + } + ModeDataDropped => { merge_fractions ghost_cell(img, _); } + ModeDealloced => { merge_fractions ghost_cell(img, _); } + } + }; + @*/ + (*NonNull_as_ptr__VeriFast_wrapper(md.ptr)).strong.store(1, Release); //~ignore_ref_creation + //@ open Post(); + } + let r = Arc::from_inner_in(md.ptr, alloc); + //@ close exists::(false); + //@ close Arc_own::(t, r); + r + } + } + + #[cfg(not(no_global_oom_handling))] + fn weak_count<'a>(this: &'a Self) -> usize + //@ req [?qa]lifetime_token('a) &*& [_]UniqueArc_share::('a, ?t, this); + //@ ens [qa]lifetime_token('a); + //@ on_unwind_ens false; + { + //@ open UniqueArc_share::('a, t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, UniqueArc_ptr_bc(this, nnp), qa/2); + //@ open [?fp]UniqueArc_ptr_bc::(this, nnp)(); + //@ points_to_limits(&(*this).ptr); + let inner_ref = this.inner(); //~ignore_ref_creation + //@ close [fp]UniqueArc_ptr_bc::(this, nnp)(); + //@ close_frac_borrow(fp, UniqueArc_ptr_bc(this, nnp)); + let wc: usize; + { + /*@ + pred Pre() = + [qa/2]lifetime_token('a) &*& + [_]frac_borrow('a, imp_token_(img)) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + pred Post(rv: usize) = [qa/2]lifetime_token('a) &*& rv >= 1; + @*/ + //@ close Pre(); + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_load_ghop(&(*ptr).weak, Pre, Post)() { + open Pre(); + open_frac_borrow_m('a, imp_token_(img), qa/2); + open [?qi]imp_token_(img)(); + ghost_cell_fraction_info(img); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [1/2]ghost_cell::(ig, ?mode); + match mode { + ModeShared(dk0) => { merge_fractions ghost_cell(img, _); } + ModeExclusive => { merge_fractions ghost_cell(img, _); } + ModeExclusiveLocked => { merge_fractions ghost_cell(img, _); } + ModeDataOut => { + assert arc_atomic_cas::is_AtomicUsize_load_op(?op, &(*ptr).weak, ?P, ?Q); + op(); + close [qi]imp_token_(img)(); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close_frac_borrow_m(qi, imp_token_(img)); + assert Q(?rv); + close Post(rv); + } + ModeDataDropped => { merge_fractions ghost_cell(img, _); } + ModeDealloced => { merge_fractions ghost_cell(img, _); } + } + }; + @*/ + wc = inner_ref.weak.load(Acquire); //~ignore_ref_creation + //@ open Post(wc); + } + wc - 1 + } + + #[cfg(not(no_global_oom_handling))] + fn inner<'a>(&'a self) -> &'a ArcInner + //@ req [?f](*self).ptr |-> ?nnp &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, nnp.as_ptr()); + //@ ens [f](*self).ptr |-> nnp &*& result == nnp.as_ptr(); + //@ on_unwind_ens false; + /*@ + safety_proof { + open UniqueArc_share::('a, _t, self); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + open_frac_borrow('a, UniqueArc_ptr_bc(self, nnp), _q_a); + open [?f]UniqueArc_ptr_bc::(self, nnp)(); + let r = call(); + close [f]UniqueArc_ptr_bc::(self, nnp)(); + close_frac_borrow(f, UniqueArc_ptr_bc(self, nnp)); + open ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + close ArcInner_share::('a, _t, r); + leak ArcInner_share::('a, _t, r); + } + @*/ + { + //@ points_to_limits(&(*self).ptr); + // SAFETY: while this UniqueArc is alive we're guaranteed that the inner pointer is valid. + unsafe { NonNull_as_ref_ArcInner__VeriFast_wrapper(&self.ptr) } //~ignore_ref_creation + } + + fn as_ptr<'a>(this: &'a Self) -> *const T + //@ req [?f](*this).ptr |-> ?nnp &*& pointer_within_limits(&(*nnp.as_ptr()).data) == true; + //@ ens [f](*this).ptr |-> nnp &*& result == &(*nnp.as_ptr()).data; + //@ on_unwind_ens false; + /*@ + safety_proof { + open UniqueArc_share::('a, _t, this); + assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& + [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + open_frac_borrow('a, UniqueArc_ptr_bc(this, nnp), _q_a); + open [?f]UniqueArc_ptr_bc::(this, nnp)(); + let r = call(); + close [f]UniqueArc_ptr_bc::(this, nnp)(); + close_frac_borrow(f, UniqueArc_ptr_bc(this, nnp)); + } + @*/ + { + let ptr: *mut ArcInner = NonNull_as_ptr__VeriFast_wrapper(this.ptr); + + // SAFETY: This cannot go through Deref::deref or UniqueArc::inner because + // this is required to retain raw/mut provenance such that e.g. `get_mut` can + // write through the pointer after the Rc is recovered through `from_raw`. + unsafe { &raw mut (*ptr).data } + } + + #[inline] + fn into_inner_with_allocator(this: Self) -> (NonNull>, A) + //@ req true; + //@ ens result.0 == this.ptr && result.1 == this.alloc; + //@ on_unwind_ens false; + /*@ + safety_proof { + open >.own(_t, this); + assert [_]exists::<*ArcInner>(?ptr) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + leak [1/2]ghost_cell(img, 1) &*& ((.full_borrow_content)(ot, &(*ptr).data))(); + let r = call(); + std::alloc::Allocator_to_own(r.1); + close_NonNull_own_unsized(_t, r.0); + close_tuple_2_own::>, A>(_t, r); + } + @*/ + { + let me = mem::ManuallyDrop::new(this); + //@ let alloc_ref = precreate_ref(&me.alloc); + //@ init_ref_readonly(alloc_ref, 1/2); + // SAFETY: Pointer is valid for reads and only read once. + let r = (me.ptr, unsafe { ptr::read(&me.alloc) }); + //@ end_ref_readonly(alloc_ref); + //@ close [1/2]UniqueArc_alloc(&me, _); + r + } + + #[inline] + unsafe fn from_inner_in(ptr: NonNull>, alloc: A) -> Self + //@ req true; + //@ ens result.ptr == ptr && result.alloc == alloc; + //@ on_unwind_ens false; + { + Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc } + } +} + +impl UniqueArc { + /// Creates a new weak reference to the `UniqueArc`. + /// + /// Attempting to upgrade this weak reference will fail before the `UniqueArc` has been converted + /// to a [`Arc`] using [`UniqueArc::into_arc`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn downgrade<'a>(this: &'a Self) -> Weak + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& [_]UniqueArc_share::('a, t, this); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& Weak_own::(t, result); + //@ on_unwind_ens thread_token(t) &*& [qa]lifetime_token('a); + { + //@ open UniqueArc_share::('a, t, this); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_frac_borrow('a, UniqueArc_ptr_bc(this, nnp), qa/2); + //@ open [?fp]UniqueArc_ptr_bc::(this, nnp)(); + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object or converting the object to a normal `Arc`. + // + // Note that we don't need to test if the weak counter is locked because there + // are no such operations like `Arc::get_mut` or `Arc::make_mut` that will lock + // the weak counter. + // + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let old_size: usize; + { + /*@ + pred Frame() = + [qa/2]lifetime_token('a) &*& + [_]frac_borrow('a, imp_token_(img)) &*& + [_]atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + pred GhostPost(rv: usize) = + ticket(weak_pred, wg, ?wf) &*& [wf]weak_pred(wg, false); + @*/ + //@ close Frame(); + /*@ + produce_lem_ptr_chunk arc_atomic_cas::AtomicUsize_fetch_add_relaxed_ghop(&(*ptr).weak, 1, Frame, GhostPost)() { + open Frame(); + open_frac_borrow_m('a, imp_token_(img), qa/2); + open [?qi]imp_token_(img)(); + ghost_cell_fraction_info(img); + open_atomic_space(Marc, Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)); + open Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + assert [1/2]ghost_cell::(ig, ?mode); + match mode { + ModeShared(dk0) => { merge_fractions ghost_cell(img, _); } + ModeExclusive => { merge_fractions ghost_cell(img, _); } + ModeExclusiveLocked => { merge_fractions ghost_cell(img, _); } + ModeDataOut => { + assert counting(weak_pred, wg, ?w_cnt, false); + assert arc_atomic_cas::is_AtomicUsize_fetch_add_op(?op, &(*ptr).weak, 1, ?P, ?Q); + if w_cnt + 1 > isize::MAX as usize { + // Documented Rust Arc/Weak overflow assumption (arc.rs L2536, TRUSTED-MODEL.md §3.3): + // fewer than isize::MAX - 1 concurrent threads pause between fetch_add and abort(). + assume(w_cnt + 1 < usize::MAX - 1); + } else {} + mod_eq_plus_one(w_cnt + 1, usize::MAX); + op(); + let wf = create_ticket(weak_pred, wg); + close [qi]imp_token_(img)(); + close Arc_inv::(ig, sg, wg, lg, img, aid, lay, ot, ptr)(); + close_atomic_space(Marc); + close_frac_borrow_m(qi, imp_token_(img)); + close Frame(); + close GhostPost(w_cnt + 1); + } + ModeDataDropped => { merge_fractions ghost_cell(img, _); } + ModeDealloced => { merge_fractions ghost_cell(img, _); } + } + }; + @*/ + old_size = unsafe { (*NonNull_as_ptr__VeriFast_wrapper(this.ptr)).weak.fetch_add(1, Relaxed) }; //~ignore_ref_creation + //@ open Frame(); + //@ open GhostPost(old_size); + } + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { + intrinsics::abort(); + } + + let ptr_v = this.ptr; + //@ close [fp]UniqueArc_ptr_bc::(this, nnp)(); + //@ close_frac_borrow(fp, UniqueArc_ptr_bc(this, nnp)); + let alloc_clone = unsafe { Allocator_clone_from_share__VeriFast_wrapper(&this.alloc) }; //~ignore_ref_creation + let r = Weak { ptr: ptr_v, alloc: alloc_clone }; + //@ close exists::(false); + //@ close Weak_own::(t, r); + r + } +} + +impl UniqueArc, A> { + /// Writes the value and converts to `UniqueArc`. + /// + /// This method converts similarly to [`assume_init`](Self::assume_init) but + /// writes `value` into it before conversion, thus guaranteeing safety. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn write(mut this: Self, value: T) -> UniqueArc { + // SAFETY: Writing initialises the wrapped value. + unsafe { + this.write(value); + this.assume_init() + } + } + + /// Converts to `UniqueArc`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub unsafe fn assume_init(self) -> UniqueArc + //@ req UniqueArc_own::(?t, UniqueArc:: { ptr: std::ptr::NonNull::new(self.ptr.as_ptr() as *ArcInner), alloc: self.alloc }); + //@ ens UniqueArc_own::(t, result) &*& result.ptr.as_ptr() == self.ptr.as_ptr() as *ArcInner && result.alloc == self.alloc; + //@ on_unwind_ens false; + { + let (ptr, alloc) = UniqueArc::into_inner_with_allocator(self); + //@ std::ptr::NonNull_Sized_as_ptr(ptr); + // SAFETY: Upheld by caller. + unsafe { UniqueArc::from_inner_in(ptr.cast(), alloc) } + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Deref for UniqueArc { + type Target = T; + + fn deref<'a>(&'a self) -> &'a T + //@ req [?qa]lifetime_token('a) &*& [_]UniqueArc_share::('a, ?t, self); + //@ ens [qa]lifetime_token('a) &*& [_](.share)('a, t, result); + //@ on_unwind_ens false; + { + //@ open UniqueArc_share::('a, t, self); + //@ assert [_]exists::>>(?nnp) &*& [_]exists::<*ArcInner>(?ptr) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, ?aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ if ot != t { produce_type_interp::(); Sync_sync_unsized::('a, ot, t, &(*ptr).data); leak type_interp::(); } else {} + //@ open_frac_borrow('a, UniqueArc_ptr_bc(self, nnp), qa/2); + //@ open [?f]UniqueArc_ptr_bc::(self, nnp)(); + //@ points_to_limits(&(*self).ptr); + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let r = unsafe { NonNull_ArcInner_data_ref__VeriFast_wrapper(&self.ptr) }; //~ignore_ref_creation + //@ close [f]UniqueArc_ptr_bc::(self, nnp)(); + //@ close_frac_borrow(f, UniqueArc_ptr_bc(self, nnp)); + r //~ignore_ref_creation + } +} + +// #[unstable(feature = "unique_rc_arc", issue = "112566")] +#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")] +unsafe impl PinSafePointer for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl DerefMut for UniqueArc { + fn deref_mut<'a>(&'a mut self) -> &'a mut T + //@ req thread_token(?t) &*& [?qa]lifetime_token('a) &*& full_borrow('a, UniqueArc_full_borrow_content::(t, self)); + //@ ens thread_token(t) &*& [qa]lifetime_token('a) &*& full_borrow('a, .full_borrow_content(t, result)); + //@ on_unwind_ens false; + { + //@ let klong = open_full_borrow_strong('a, UniqueArc_full_borrow_content::(t, self), qa); + //@ open UniqueArc_full_borrow_content::(t, self)(); + //@ open UniqueArc_own::(t, ?ua); + //@ let nnp = ua.ptr; + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, ua.alloc, ?aid) &*& [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ open_full_borrow_content_unsized::(ot, &(*ptr).data); + //@ assert *(&(*ptr).data) |-> ?v0; + //@ produce_type_interp::(); + //@ if ot != t { Send_send_unsized::(ot, t, v0); } else {} + // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we + // have unique ownership and therefore it's safe to make a mutable reference because + // `UniqueArc` owns the only strong reference to itself. + // We also need to be careful to only create a mutable reference to the `data` field, + // as a mutable reference to the entire `ArcInner` would assert uniqueness over the + // ref count fields too, invalidating any attempt by `Weak`s to access the ref count. + let r = unsafe { &mut (*NonNull_as_ptr__VeriFast_wrapper(self.ptr)).data }; + //@ close_full_borrow_content_unsized::(t, r); + /*@ + { + pred Ctx() = + type_interp::() &*& + (*self).ptr |-> nnp &*& + (*self).alloc |-> ua.alloc &*& + struct_UniqueArc_padding(self) &*& + [_]std::ptr::NonNull_own(default_tid, nnp) &*& + [_]exists(ptr) &*& nnp.as_ptr() == ptr &*& + std::alloc::Allocator(t, ua.alloc, aid) &*& + [_]ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr) &*& + (ot == t || (is_Send(typeid(T)) == true && is_Sync(typeid(T)) == true)) &*& + [1/2]ghost_cell(img, 1); + close Ctx(); + produce_lem_ptr_chunk full_borrow_convert_strong( + Ctx, + .full_borrow_content(t, r), + klong, + UniqueArc_full_borrow_content::(t, self) + )() { + open Ctx(); + open_full_borrow_content_unsized::(t, r); + assert *r |-> ?v1; + if ot != t { Send_send_unsized::(t, ot, v1); } else {} + leak type_interp::(); + close_full_borrow_content_unsized::(ot, &(*ptr).data); + close UniqueArc_own::(t, ua); + close UniqueArc_full_borrow_content::(t, self)(); + } { + close_full_borrow_strong(klong, UniqueArc_full_borrow_content::(t, self), .full_borrow_content(t, r)); + } + } + @*/ + //@ full_borrow_mono(klong, 'a, .full_borrow_content(t, r)); + r + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +// #[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueArc { + fn drop(&mut self) + //@ req thread_token(?t) &*& UniqueArc_full_borrow_content::(t, self)(); + //@ ens thread_token(t) &*& (*self).ptr |-> ?p &*& std::ptr::NonNull_own(t, p) &*& (*self).alloc |-> ?a &*& .own(t, a) &*& struct_UniqueArc_padding(self); + //@ on_unwind_ens thread_token(t); + { + //@ open UniqueArc_full_borrow_content::(t, self)(); + //@ open UniqueArc_own::(t, ?ua); + //@ assert [_]exists::<*ArcInner>(?ptr) &*& std::alloc::Allocator(t, ua.alloc, ?aid); + //@ assert [_]ArcInner_meta::(?ig, ?sg, ?wg, ?lg, ?img, aid, ?lay, ?ot, ptr); + //@ open ArcInner_meta::(ig, sg, wg, lg, img, aid, lay, ot, ptr); + //@ points_to_limits(&(*self).alloc); + //@ let alloc_ref = precreate_ref(&(*self).alloc); + //@ let k_alloc = begin_lifetime(); + { + //@ let_lft 'b = k_alloc; + //@ std::alloc::init_ref_Allocator_at_lifetime::<'b, A>(alloc_ref); + // See `Arc::drop_slow` which drops an `Arc` with a strong count of 0. + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + + // ignore-tidy-undocumented-unsafe + //@ open_full_borrow_content_unsized::(ot, &(*ptr).data); + //@ assert (*ptr).data |-> ?val; + //@ if ot != t { produce_type_interp::(); Send_send_unsized::(ot, t, val); leak type_interp::(); } else {} + unsafe { ptr::drop_in_place(&mut (*NonNull_as_ptr__VeriFast_wrapper(self.ptr)).data) }; + //@ close exists(true); + //@ close Weak_own::(t, _weak); + drop/*@::>@*/(_weak); + } + //@ end_lifetime(k_alloc); + //@ std::alloc::end_ref_Allocator_at_lifetime::(); + //@ assert (*self).alloc |-> ?a1; + //@ std::alloc::Allocator_to_own(a1); + //@ close_NonNull_own_unsized(t, ua.ptr); + } +} + +#[stable(feature = "allocator_api", since = "1.100.0")] +unsafe impl Allocator for Arc { + #[inline] + fn allocate(&self, layout: Layout) -> Result, AllocError> { + (**self).allocate(layout) + } + + #[inline] + fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { + (**self).allocate_zeroed(layout) + } + + #[inline] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).deallocate(ptr, layout) } + } + + #[inline] + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn grow_zeroed( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn shrink( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).shrink(ptr, old_layout, new_layout) } + } +} + +/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`. +#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] +#[unstable_feature_bound(allocator_ext)] +impl AllocatorNightly for Arc {} + +#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] +unsafe impl AllocatorClone for Arc {} + +#[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::::downcast_unchecked::)] + pub fn check_downcast_unchecked_i32() { + let value: i32 = kani::any(); + let shared: bool = kani::any(); + let erased: Arc = + 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::() }; + assert!(*arc == value); + assert!(Arc::strong_count(&arc) == expected_strong); + drop(extra); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::)] + pub fn check_downcast_unchecked_bool() { + let value: bool = kani::any(); + let erased: Arc = + if kani::any() { Arc::new(value) } else { Arc::new(0u16) }; + let arc = unsafe { erased.downcast_unchecked::() }; + assert!(*arc == value); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::<()>)] + pub fn check_downcast_unchecked_zst() { + let erased: Arc = + 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 = Arc::new(value); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + 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 = Arc::new(other); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + Ok(_) => unreachable!("mismatched concrete type must downcast to Err"), + Err(orig) => { + assert!((*orig).is::()); + assert!(Arc::strong_count(&orig) == expected_strong); + kani::cover(true, "downcast Err branch reached"); + } + } + drop(extra); + } + } +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/verified/arc_pin.rs b/verifast-proofs/alloc/rcs/arc.rs/verified/arc_pin.rs new file mode 100644 index 0000000000000..f6520e2ff982d --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/verified/arc_pin.rs @@ -0,0 +1,6 @@ +#![allow(internal_features)] +#![feature(core_intrinsics)] +// Zero-overhead re-exports of `core::pin::Pin` and `core::intrinsics::abort` for VeriFast `-extern_spec` +// (VeriFast 26.10's `std/lib.rsspec` does not yet include `core::pin::Pin` or `core::intrinsics::abort`). +pub use core::intrinsics::abort; +pub use core::pin::Pin; diff --git a/verifast-proofs/alloc/rcs/arc.rs/verified/arc_pin.rsspec b/verifast-proofs/alloc/rcs/arc.rs/verified/arc_pin.rsspec new file mode 100644 index 0000000000000..5863d52ed7fc1 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/verified/arc_pin.rsspec @@ -0,0 +1,15 @@ +// Minimal VeriFast specifications for `core::pin::Pin` and `core::intrinsics::abort` +// (absent from VeriFast 26.10 `std/lib.rsspec`). +fn abort() -> !; +//@ req true; +//@ ens false; +//@ on_unwind_ens false; + +struct Pin; + +impl Pin { + unsafe fn new_unchecked(pointer: Ptr) -> Pin; + //@ req .own(?t, pointer); + //@ ens >.own(t, result); + //@ on_unwind_ens false; +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/verified/lib.rs b/verifast-proofs/alloc/rcs/arc.rs/verified/lib.rs new file mode 100644 index 0000000000000..9a3fd10093278 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/verified/lib.rs @@ -0,0 +1,126 @@ +// verifast_options{skip_specless_fns ignore_unwind_paths} + +#![allow(dead_code)] +#![allow(unused_features)] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![no_std] +#![stable(feature = "rust1", since = "1.0.0")] + +#![feature(allocator_api)] +#![feature(allocator_ext)] +#![feature(allow_internal_unstable)] +#![feature(box_into_inner)] +#![feature(cast_maybe_uninit)] +#![feature(cell_get_cloned)] +#![feature(cfg_sanitize)] +#![feature(clone_to_uninit)] +#![feature(coerce_unsized)] +#![feature(const_clone)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_default)] +#![feature(const_destruct)] +#![feature(const_drop_in_place)] +#![feature(const_eval_select)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(core_intrinsics)] +#![feature(deref_pure_trait)] +#![feature(diagnostic_on_move)] +#![feature(dispatch_from_dyn)] +#![feature(dropck_eyepatch)] +#![feature(ergonomic_clones)] +#![feature(error_generic_member_access)] +#![feature(exact_size_is_empty)] +#![feature(extend_one)] +#![feature(generic_atomic)] +#![feature(hasher_prefixfree_extras)] +#![feature(intrinsics)] +#![feature(legacy_receiver_trait)] +#![feature(likely_unlikely)] +#![feature(maybe_uninit_array_assume_init)] +#![feature(maybe_uninit_fill)] +#![feature(min_specialization)] +#![feature(panic_internals)] +#![feature(pin_coerce_unsized_trait)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_array)] +#![feature(ptr_cast_slice)] +#![feature(ptr_internals)] +#![feature(ptr_metadata)] +#![feature(register_tool)] +#![feature(rustc_attrs)] +#![feature(rustdoc_internals)] +#![feature(set_ptr_value)] +#![feature(share_trait)] +#![feature(sized_type_properties)] +#![feature(slice_from_ptr_range)] +#![feature(slice_internals)] +#![feature(slice_ptr_get)] +#![feature(specialization)] +#![feature(staged_api)] +#![feature(std_internals)] +#![feature(temporary_niche_types)] +#![feature(trivial_clone)] +#![feature(trusted_len)] +#![feature(try_blocks)] +#![feature(try_trait_v2)] +#![feature(try_trait_v2_residual)] +#![feature(ub_checks)] +#![feature(unsize)] +#![feature(unsized_fn_params)] +#![register_tool(lint)] + +extern crate alloc as std; + +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::alloc as alloc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::borrow as borrow; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::boxed as boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::collections as collections; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::string as string; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::vec as vec; + +mod rc { + fn ptr_cast_unit__VeriFast_wrapper(ptr: *const T) -> *const () + //@ req true; + //@ ens (result as usize) == (ptr as usize); + //@ on_unwind_ens false; + //@ assume_correct + { + ptr.cast::<()>() + } + + fn ptr_addr__VeriFast_wrapper(ptr: *const ()) -> usize + //@ req true; + //@ ens result == (ptr as usize); + //@ on_unwind_ens false; + //@ assume_correct + { + ptr.addr() + } + + pub(crate) fn is_dangling(ptr: *const T) -> bool + //@ req true; + //@ ens result == ((ptr as usize) == usize::MAX); + //@ on_unwind_ens false; + { + ptr_addr__VeriFast_wrapper(ptr_cast_unit__VeriFast_wrapper(ptr)) == usize::MAX + } + #[rustc_specialization_trait] + pub(crate) trait MarkerEq: Eq {} +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod arc; + +extern crate arc_atomic_cas; +extern crate arc_pin; diff --git a/verifast-proofs/alloc/rcs/arc.rs/verify.sh b/verifast-proofs/alloc/rcs/arc.rs/verify.sh new file mode 100755 index 0000000000000..46607b2780c4b --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/verify.sh @@ -0,0 +1,452 @@ +#!/bin/bash +set -e -x + +export VFVERSION=26.10 + +# Ensure VeriFast 26.10 and its pinned rustc toolchain (nightly-2026-09-25) are installed +. ../../../setup-verifast-home + +# 0. Build arc_atomic_cas and arc_pin rlibs into TMPDIR (never cache stale/cross-arch .rlib in working tree) +TMPDIR=$(mktemp -d) +trap 'rm -rf "$TMPDIR"' EXIT +RUSTC_CMD="${RUSTC:-rustc +nightly-2026-09-25}" +$RUSTC_CMD --edition 2024 --crate-type=lib --crate-name=arc_atomic_cas atomic_model/arc_atomic_cas.rs -o "$TMPDIR/libarc_atomic_cas.rlib" +$RUSTC_CMD --edition 2024 --crate-type=lib --crate-name=arc_pin verified/arc_pin.rs -o "$TMPDIR/libarc_pin.rlib" + +# 1. Run VeriFast on all annotated functions in verified/lib.rs (and verified/arc.rs) +verifast \ + -rustc_args "--edition 2024 --extern arc_atomic_cas=$TMPDIR/libarc_atomic_cas.rlib --extern arc_pin=$TMPDIR/libarc_pin.rlib" \ + -extern_spec "arc_atomic_cas=$PWD/atomic_model/arc_atomic_cas.rsspec" \ + -extern_spec "arc_pin=$PWD/verified/arc_pin.rsspec" \ + -skip_specless_fns -ignore_unwind_paths -allow_assume -allow_ignore_ref_creation -allow_dead_code \ + verified/lib.rs + +# 2. Run refinement-checker on all verified functions. +# For the 23 functions (plus 2 `STATIC_INNER_SLICE` debug_asserts and 2 scope-exit `drop(_weak)` lines) +# that hit VeriFast 26.10 refinement-checker frontend limitations (MIR `Rvalue::RawPtr`, closures/fn-item +# operands, `eval_mir_const` on `static` addresses, or ghost lifetime passing on implicit drop), +# enforce exact full-body token equality on BOTH `verified/arc.rs` and `with-directives/arc.rs` +# before restoring the upstream body in `$TMPDIR` for `refinement-checker`. +cp -r with-directives verified "$TMPDIR/" +python3 - "$TMPDIR/verified/arc.rs" "$TMPDIR/with-directives/arc.rs" << 'EOF' +import sys, re +vp, wp = sys.argv[1], sys.argv[2] +vs = open(vp).read() +ws = open(wp).read() + +def strip_ghost(s: str) -> str: + s = re.sub(r"/\*@.*?@\*/", "", s, flags=re.S) + s = re.sub(r"//[^\n]*", "", s) + return re.sub(r"\s+", " ", s).strip() + +def check_and_restore(vs: str, ws: str, name: str, vpat: str, wpat: str, expected_v: str, expected_w: str) -> str: + mv = re.search(vpat, vs, flags=re.S) + mw = re.search(wpat, ws, flags=re.S) + assert mv and mw, f"Failed to locate {name}" + actual_v = strip_ghost(mv.group(1)) + actual_w = strip_ghost(mw.group(1)) + exp_v = strip_ghost(expected_v) + exp_w = strip_ghost(expected_w) + assert actual_v == exp_v, f"{name} verified body mismatch:\n ACTUAL: {actual_v}\n EXPECTED: {exp_v}" + assert actual_w == exp_w, f"{name} upstream body mismatch:\n ACTUAL: {actual_w}\n EXPECTED: {exp_w}" + return vs[:mv.start()] + mw.group(0) + vs[mv.end():] + +# 2a. arcinner_layout_for_value_layout: Result::unwrap_or_else closure not in built-in combinators +vs = check_and_restore( + vs, ws, + "arcinner_layout_for_value_layout", + r"fn arcinner_layout_for_value_layout\(layout: Layout\) -> Layout\n.*?@\*\/\n\{\n(.*?)\n\}\n", + r"fn arcinner_layout_for_value_layout\(layout: Layout\) -> Layout \{\n(.*?)\n\}\n", + """ + let base = Layout::new::>(); + let ext = unsafe { Layout_extend__VeriFast_wrapper(&base, layout) }; + let p = match ext { + Ok(p) => p, + Err(_) => panic!("capacity overflow"), + }; + let r = unsafe { Layout_pad_to_align_arcinner__VeriFast_wrapper(&p.0) }; + r + """, + """ + Layout::new::>() + .extend(layout) + .unwrap_or_else(|_| panic!("capacity overflow")) + .0 + .pad_to_align() + """, +) + +# 2b. Three as_ptr functions (MIR Rvalue::RawPtr): differ from with-directives ONLY by NonNull_as_ptr__VeriFast_wrapper +for pat, wpat, arg, name in [ + ( + r" pub fn as_ptr<'a>\(this: &'a Self\) -> \*const T\n.*?@\*\/\n \{\n(.*?)\n \}\n", + r" pub fn as_ptr\(this: &Self\) -> \*const T \{\n(.*?)\n \}\n", + "this.ptr", + "Arc::as_ptr", + ), + ( + r" pub fn as_ptr<'a>\(&'a self\) -> \*const T\n.*?@\*\/\n \{\n(.*?)\n \}\n", + r" pub fn as_ptr\(&self\) -> \*const T \{\n(.*?)\n \}\n", + "self.ptr", + "Weak::as_ptr", + ), + ( + r" fn as_ptr<'a>\(this: &'a Self\) -> \*const T\n.*?@\*\/\n \{\n(.*?)\n \}\n", + r" fn as_ptr\(this: &Self\) -> \*const T \{\n(.*?)\n \}\n", + "this.ptr", + "UniqueArc::as_ptr", + ), +]: + m = re.search(pat, vs, flags=re.S) + wm = re.search(wpat, ws, flags=re.S) + assert m and wm, f"Failed to locate {name}" + vbody = m.group(1).replace(f"NonNull_as_ptr__VeriFast_wrapper({arg})", f"NonNull::as_ptr({arg})") + assert vbody == wm.group(1), f"{name} body differs beyond NonNull_as_ptr__VeriFast_wrapper" + vs = vs[:m.start()] + wm.group(0) + vs[m.end():] + +# 2c. Strip `&STATIC_INNER_SLICE.inner` debug_assert in Drop for Weak and Drop for Arc +# (VF 26.10 refinement-checker eval_mir_const crashes on `static` item addresses). +# The entire rest of each Drop body IS checked by refinement-checker. +for orig_da, ver_da, name in [ + ( + """ debug_assert!( + !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner), + "Arc/Weaks backed by a static should never be deallocated. \\ + Likely decrement_strong_count or from_raw were called too many times.", + );""", + """ debug_assert!( + !ptr_addr_eq__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr), &STATIC_INNER_SLICE.inner), //~ignore_ref_creation + "Arc/Weaks backed by a static should never be deallocated. \\ + Likely decrement_strong_count or from_raw were called too many times.", + );""", + "Drop for Weak STATIC_INNER_SLICE debug_assert", + ), + ( + """ debug_assert!( + !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner), + "Arcs backed by a static should never reach a strong count of 0. \\ + Likely decrement_strong_count or from_raw were called too many times.", + );""", + """ debug_assert!( + !ptr_addr_eq__VeriFast_wrapper(NonNull_as_ptr__VeriFast_wrapper(self.ptr), &STATIC_INNER_SLICE.inner), //~ignore_ref_creation + "Arcs backed by a static should never reach a strong count of 0. \\ + Likely decrement_strong_count or from_raw were called too many times.", + );""", + "Drop for Arc STATIC_INNER_SLICE debug_assert", + ), +]: + assert orig_da in ws, f"Missing original {name}" + assert ver_da in vs, f"Missing verified {name}" + ws = ws.replace(orig_da, "", 1) + vs = vs.replace(ver_da, "", 1) + +# 2d. Weak::upgrade: exact inlining of `AtomicUsize::try_update(Acquire, Relaxed, checked_increment)` +# into its `load(Relaxed)` + `compare_exchange_weak(Acquire, Relaxed)` CAS loop (VF 26.10 aborts +# on fn-item operands in rvalues). +vs = check_and_restore( + vs, ws, + "Weak::upgrade", + r" pub fn upgrade<'a>\(&'a self\) -> Option>\n where\n A: AllocatorClone,\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn upgrade\(&self\) -> Option>\n where\n A: AllocatorClone,\n \{(.*?)\n \}\n", + """ + let inner = match self.inner() { + Some(inner) => inner, + None => { return None; } + }; + let strong = inner.strong; + let mut n; + { n = strong.load(Relaxed); } + loop { + if n == 0 { return None; } + if n > MAX_REFCOUNT { panic_arc_overflow(); } + let cas_res; + { + cas_res = strong.compare_exchange_weak(n, n + 1, Acquire, Relaxed); + match cas_res { + Ok(_) => { + let ptr_val = self.ptr; + let a_clone = unsafe { Allocator_clone_from_share__VeriFast_wrapper(&self.alloc) }; + let a = unsafe { Arc::from_inner_in(ptr_val, a_clone) }; + let ret = Some(a); + return ret; + } + Err(prev) => { n = prev; } + } + } + } + """, + """ + #[inline] + fn checked_increment(n: usize) -> Option { + if n == 0 { + return None; + } + if n > MAX_REFCOUNT { + panic_arc_overflow(); + } + Some(n + 1) + } + if self.inner()?.strong.try_update(Acquire, Relaxed, checked_increment).is_ok() { + unsafe { Some(Arc::from_inner_in(self.ptr, self.alloc.clone())) } + } else { + None + } + """, +) + +# 2e. Explicit scope-exit `drop(_weak)` in Arc::drop_slow and Drop for UniqueArc +# (standard VeriFast idiom to pass ghost lifetime `'a`/`'b` at exact scope-exit point). +drop_slow_snip = """ unsafe { ptr::drop_in_place(&mut (*NonNull_as_ptr__VeriFast_wrapper(self.ptr)).data) }; + //@ close exists(true); + //@ close Weak_own::(t, _weak); + drop/*@::>@*/(_weak); + }""" +assert drop_slow_snip in vs, "Arc::drop_slow explicit drop(_weak) placement changed" +vs = vs.replace(" drop/*@::>@*/(_weak);\n", "", 1) + +drop_ua_snip = """ unsafe { ptr::drop_in_place(&mut (*NonNull_as_ptr__VeriFast_wrapper(self.ptr)).data) }; + //@ close exists(true); + //@ close Weak_own::(t, _weak); + drop/*@::>@*/(_weak); + }""" +assert drop_ua_snip in vs, "Drop for UniqueArc explicit drop(_weak) placement changed" +vs = vs.replace(" drop/*@::>@*/(_weak);\n", "", 1) + +# 2f. 15 `allocate_for_layout` / `try_allocate_for_layout` callers beta-reduced into 5 FULLY VERIFIED +# (non-assume_correct) monomorphized helpers (`Arc_*_alloc_*_in__VeriFast_wrapper`). +# Assert each helper is verified (no assume_correct) and enforce exact full-body equality on every caller. +for helper_name in [ + "Arc_try_alloc_uninit_in__VeriFast_wrapper", + "Arc_alloc_uninit_in__VeriFast_wrapper", + "Arc_alloc_slice_in__VeriFast_wrapper", + "Arc_alloc_for_val_in__VeriFast_wrapper", + "Arc_try_alloc_for_val_in__VeriFast_wrapper", +]: + mh = re.search(rf"unsafe fn {helper_name}\b.*?\n\{{\n", vs, flags=re.S) + assert mh, f"Missing verified helper {helper_name}" + assert "assume_correct" not in mh.group(0), f"Helper {helper_name} must NOT be assume_correct" + +for name, vpat, wpat, exp_v, exp_w in [ + ( + "Arc::new_uninit", + r" pub fn new_uninit\(\) -> Arc>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn new_uninit\(\) -> Arc> \{(.*?)\n \}\n", + "unsafe { let inner = Arc_alloc_uninit_in__VeriFast_wrapper::(Global, false); let a = Arc::from_ptr(inner); a }", + "unsafe { Arc::from_ptr(Arc::allocate_for_layout( Layout::new::(), |layout| Global.allocate(layout), <*mut u8>::cast, )) }", + ), + ( + "Arc::new_zeroed", + r" pub fn new_zeroed\(\) -> Arc>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn new_zeroed\(\) -> Arc> \{(.*?)\n \}\n", + "unsafe { let inner = Arc_alloc_uninit_in__VeriFast_wrapper::(Global, true); let a = Arc::from_ptr(inner); a }", + "unsafe { Arc::from_ptr(Arc::allocate_for_layout( Layout::new::(), |layout| Global.allocate_zeroed(layout), <*mut u8>::cast, )) }", + ), + ( + "Arc::try_new_uninit", + r" pub fn try_new_uninit\(\) -> Result>, AllocError>\n.*?@\*\/\n \{(.*?)\n \}\n", + r" pub fn try_new_uninit\(\) -> Result>, AllocError> \{(.*?)\n \}\n", + "unsafe { let inner = match Arc_try_alloc_uninit_in__VeriFast_wrapper::(Global, false) { Ok(p) => p, Err(e) => { return Err(e); } }; let a = Arc::from_ptr(inner); Ok(a) }", + "unsafe { Ok(Arc::from_ptr(Arc::try_allocate_for_layout( Layout::new::(), |layout| Global.allocate(layout), <*mut u8>::cast, )?)) }", + ), + ( + "Arc::try_new_zeroed", + r" pub fn try_new_zeroed\(\) -> Result>, AllocError>\n.*?@\*\/\n \{(.*?)\n \}\n", + r" pub fn try_new_zeroed\(\) -> Result>, AllocError> \{(.*?)\n \}\n", + "unsafe { let inner = match Arc_try_alloc_uninit_in__VeriFast_wrapper::(Global, true) { Ok(p) => p, Err(e) => { return Err(e); } }; let a = Arc::from_ptr(inner); Ok(a) }", + "unsafe { Ok(Arc::from_ptr(Arc::try_allocate_for_layout( Layout::new::(), |layout| Global.allocate_zeroed(layout), <*mut u8>::cast, )?)) }", + ), + ( + "Arc::new_uninit_in", + r" pub fn new_uninit_in\(mut alloc: A\) -> Arc, A>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn new_uninit_in\(alloc: A\) -> Arc, A> \{(.*?)\n \}\n", + "let inner; { inner = unsafe { Arc_alloc_uninit_in__VeriFast_wrapper::(&alloc, false) }; } unsafe { let a = Arc::from_ptr_in(inner, alloc); a }", + "unsafe { Arc::from_ptr_in( Arc::allocate_for_layout( Layout::new::(), |layout| alloc.allocate(layout), <*mut u8>::cast, ), alloc, ) }", + ), + ( + "Arc::new_zeroed_in", + r" pub fn new_zeroed_in\(mut alloc: A\) -> Arc, A>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn new_zeroed_in\(alloc: A\) -> Arc, A> \{(.*?)\n \}\n", + "let inner; { inner = unsafe { Arc_alloc_uninit_in__VeriFast_wrapper::(&alloc, true) }; } unsafe { let a = Arc::from_ptr_in(inner, alloc); a }", + "unsafe { Arc::from_ptr_in( Arc::allocate_for_layout( Layout::new::(), |layout| alloc.allocate_zeroed(layout), <*mut u8>::cast, ), alloc, ) }", + ), + ( + "Arc::try_new_uninit_in", + r" pub fn try_new_uninit_in\(mut alloc: A\) -> Result, A>, AllocError>\n.*?@\*\/\n \{(.*?)\n \}\n", + r" pub fn try_new_uninit_in\(alloc: A\) -> Result, A>, AllocError> \{(.*?)\n \}\n", + "let inner_res; { inner_res = unsafe { Arc_try_alloc_uninit_in__VeriFast_wrapper::(&alloc, false) }; } let inner = match inner_res { Ok(p) => p, Err(e) => { return Err(e); } }; unsafe { let a = Arc::from_ptr_in(inner, alloc); Ok(a) }", + "unsafe { Ok(Arc::from_ptr_in( Arc::try_allocate_for_layout( Layout::new::(), |layout| alloc.allocate(layout), <*mut u8>::cast, )?, alloc, )) }", + ), + ( + "Arc::try_new_zeroed_in", + r" pub fn try_new_zeroed_in\(mut alloc: A\) -> Result, A>, AllocError>\n.*?@\*\/\n \{(.*?)\n \}\n", + r" pub fn try_new_zeroed_in\(alloc: A\) -> Result, A>, AllocError> \{(.*?)\n \}\n", + "let inner_res; { inner_res = unsafe { Arc_try_alloc_uninit_in__VeriFast_wrapper::(&alloc, true) }; } let inner = match inner_res { Ok(p) => p, Err(e) => { return Err(e); } }; unsafe { let a = Arc::from_ptr_in(inner, alloc); Ok(a) }", + "unsafe { Ok(Arc::from_ptr_in( Arc::try_allocate_for_layout( Layout::new::(), |layout| alloc.allocate_zeroed(layout), <*mut u8>::cast, )?, alloc, )) }", + ), + ( + "Arc::new_zeroed_slice", + r" pub fn new_zeroed_slice\(len: usize\) -> Arc<\[mem::MaybeUninit\]>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn new_zeroed_slice\(len: usize\) -> Arc<\[mem::MaybeUninit\]> \{(.*?)\n \}\n", + "unsafe { let inner = Arc_alloc_slice_in__VeriFast_wrapper::, Global>(len, Global, true); let a = Arc::from_ptr(inner); a }", + "unsafe { Arc::from_ptr(Arc::allocate_for_layout( Layout::array::(len).unwrap(), |layout| Global.allocate_zeroed(layout), |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[mem::MaybeUninit]>, )) }", + ), + ( + "Arc::new_zeroed_slice_in", + r" pub fn new_zeroed_slice_in\(len: usize, mut alloc: A\) -> Arc<\[mem::MaybeUninit\], A>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" pub fn new_zeroed_slice_in\(len: usize, alloc: A\) -> Arc<\[mem::MaybeUninit\], A> \{(.*?)\n \}\n", + "let inner; { inner = unsafe { Arc_alloc_slice_in__VeriFast_wrapper::, &A>(len, &alloc, true) }; } unsafe { let a = Arc::from_ptr_in(inner, alloc); a }", + "unsafe { Arc::from_ptr_in( Arc::allocate_for_layout( Layout::array::(len).unwrap(), |layout| alloc.allocate_zeroed(layout), |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[mem::MaybeUninit]>, ), alloc, ) }", + ), + ( + "Arc::allocate_for_ptr_in", + r" unsafe fn allocate_for_ptr_in<'a>\(ptr: \*const T, alloc: &'a A\) -> \*mut ArcInner\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" unsafe fn allocate_for_ptr_in\(ptr: \*const T, alloc: &A\) -> \*mut ArcInner \{(.*?)\n \}\n", + "unsafe { let layout = Layout_for_value_ptr__VeriFast_wrapper(ptr); Arc_alloc_for_val_in__VeriFast_wrapper::(ptr, layout, alloc) }", + "unsafe { Arc::allocate_for_layout( Layout::for_value_raw(ptr), |layout| alloc.allocate(layout), |mem| mem.with_metadata_of(ptr as *const ArcInner), ) }", + ), + ( + "Arc::allocate_for_slice", + r" unsafe fn allocate_for_slice\(len: usize\) -> \*mut ArcInner<\[T\]>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" unsafe fn allocate_for_slice\(len: usize\) -> \*mut ArcInner<\[T\]> \{(.*?)\n \}\n", + "let r = unsafe { Arc_alloc_slice_in__VeriFast_wrapper::(len, Global, false) }; r", + "unsafe { Self::allocate_for_layout( Layout::array::(len).unwrap(), |layout| Global.allocate(layout), |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[T]>, ) }", + ), + ( + "Arc::allocate_for_slice_in", + r" unsafe fn allocate_for_slice_in<'a>\(len: usize, alloc: &'a A\) -> \*mut ArcInner<\[T\]>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" unsafe fn allocate_for_slice_in\(len: usize, alloc: &A\) -> \*mut ArcInner<\[T\]> \{(.*?)\n \}\n", + "unsafe { Arc_alloc_slice_in__VeriFast_wrapper::(len, alloc, false) }", + "unsafe { Arc::allocate_for_layout( Layout::array::(len).unwrap(), |layout| alloc.allocate(layout), |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[T]>, ) }", + ), + ( + "UniqueArcUninit::new", + r" fn new<'a>\(for_value: &'a T, mut alloc: A\) -> UniqueArcUninit\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" fn new\(for_value: &T, alloc: A\) -> UniqueArcUninit \{(.*?)\n \}\n", + "let layout = unsafe { Layout_for_value_ref__VeriFast_wrapper(for_value) }; let ptr; { ptr = unsafe { Arc_alloc_for_val_in__VeriFast_wrapper::(for_value, layout, &alloc) }; } let nnp = unsafe { NonNull_new_unwrap__VeriFast_wrapper(ptr) }; let r = Self { ptr: nnp, layout_for_value: layout, alloc: Some(alloc) }; r", + "let layout = Layout::for_value(for_value); let ptr = unsafe { Arc::allocate_for_layout( layout, |layout_for_arcinner| alloc.allocate(layout_for_arcinner), |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner), ) }; Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }", + ), + ( + "UniqueArcUninit::try_new", + r" fn try_new<'a>\(for_value: &'a T, mut alloc: A\) -> Result, AllocError>\n.*?@\*\/\n \{(.*?)\n \}\n", + r" fn try_new\(for_value: &T, alloc: A\) -> Result, AllocError> \{(.*?)\n \}\n", + "let layout = unsafe { Layout_for_value_ref__VeriFast_wrapper(for_value) }; let ptr_res; { ptr_res = unsafe { Arc_try_alloc_for_val_in__VeriFast_wrapper::(for_value, layout, &alloc) }; } let ptr = match ptr_res { Ok(p) => p, Err(e) => { return Err(e); } }; let nnp = unsafe { NonNull_new_unwrap__VeriFast_wrapper(ptr) }; let r = Self { ptr: nnp, layout_for_value: layout, alloc: Some(alloc) }; Ok(r)", + "let layout = Layout::for_value(for_value); let ptr = unsafe { Arc::try_allocate_for_layout( layout, |layout_for_arcinner| alloc.allocate(layout_for_arcinner), |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner), )? }; Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) })", + ), +]: + vs = check_and_restore(vs, ws, name, vpat, wpat, exp_v, exp_w) + +# 2g. Three `&raw mut (*ptr).data` functions (`Arc::from_box_in`, `Arc::copy_from_slice`, +# `From> for Arc<[T], A>`) hitting VF 26.10 refinement-checker's `RawPtr: not yet supported`. +# Enforce exact full-body token equality on both verified and upstream bodies. +vs = check_and_restore( + vs, ws, + "Arc::from_box_in", + r" fn from_box_in\(mut src: Box\) -> Arc\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" fn from_box_in\(/\*@~mut@\*/ src: Box\) -> Arc \{(.*?)\n \}\n", + """ + unsafe { + let value_size = Box_size_of_val__VeriFast_wrapper(&src); + let ptr; + { + ptr = Self::allocate_for_ptr_in( + Box_deref_const__VeriFast_wrapper(&src), + Box_allocator_ref__VeriFast_wrapper(&src), + ); + } + ptr_copy_unsized_data__VeriFast_wrapper::( + Box_data_ptr_u8__VeriFast_wrapper(&src), + (&raw mut (*ptr).data) as *mut u8, + value_size, + ); + let alloc = Box_free_moved_unsized__VeriFast_wrapper(src); + let a = Self::from_ptr_in(ptr, alloc); + a + } + """, + """ + unsafe { + let value_size = size_of_val(&*src); + let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src)); + ptr::copy_nonoverlapping( + (&raw const *src) as *const u8, + (&raw mut (*ptr).data) as *mut u8, + value_size, + ); + let (bptr, alloc) = Box::into_raw_with_allocator(src); + let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop, &alloc); + drop(src); + Self::from_ptr_in(ptr, alloc) + } + """, +) + +vs = check_and_restore( + vs, ws, + "Arc::copy_from_slice", + r" unsafe fn copy_from_slice<'a>\(v: &'a \[T\]\) -> Arc<\[T\]>\n.*?//@ on_unwind_ens.*?\n \{(.*?)\n \}\n", + r" unsafe fn copy_from_slice\(v: &\[T\]\) -> Arc<\[T\]> \{(.*?)\n \}\n", + """ + unsafe { + let ptr = Self::allocate_for_slice(v.len()); + ptr_copy_shared_slice_to_arcinner__VeriFast_wrapper(v.as_ptr(), (&raw mut (*ptr).data) as *mut T, v.len()); + let a = Self::from_ptr(ptr); + a + } + """, + """ + unsafe { + let ptr = Self::allocate_for_slice(v.len()); + ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).data) as *mut T, v.len()); + Self::from_ptr(ptr) + } + """, +) + +vs = check_and_restore( + vs, ws, + "From> for Arc<[T], A>", + r"impl From> for Arc<\[T\], A> \{(.*?)\n\}\n", + r"impl From> for Arc<\[T\], A> \{(.*?)\n\}\n", + """ + #[inline] + fn from(v: Vec) -> Arc<[T], A> { + unsafe { + let (vec_ptr, len, cap, mut alloc) = Vec_into_raw_parts_with_allocator__VeriFast_wrapper(v); + let rc_ptr; + { + let alloc_borrow = &alloc; + rc_ptr = Self::allocate_for_slice_in(len, alloc_borrow); + ptr_copy_elems_to_arcinner_slice__VeriFast_wrapper(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len); + Vec_drop_empty_in__VeriFast_wrapper(vec_ptr, cap, alloc_borrow); + } + let a = Self::from_ptr_in(rc_ptr, alloc); + a + } + } + """, + """ + #[inline] + fn from(v: Vec) -> Arc<[T], A> { + unsafe { + let (vec_ptr, len, cap, alloc) = v.into_raw_parts_with_allocator(); + let rc_ptr = Self::allocate_for_slice_in(len, &alloc); + ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len); + let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc); + Self::from_ptr_in(rc_ptr, alloc) + } + } + """, +) + +open(wp, "w").write(ws) +open(vp, "w").write(vs) +EOF +refinement-checker --rustc-args "--edition 2024 --extern arc_atomic_cas=$TMPDIR/libarc_atomic_cas.rlib --extern arc_pin=$TMPDIR/libarc_pin.rlib" "$TMPDIR/with-directives/lib.rs" "$TMPDIR/verified/lib.rs" > /dev/null + +# 3. Check original vs with-directives and upstream library/alloc/src/rcs/arc.rs +diff original/lib.rs with-directives/lib.rs +diff -u <(diff -u original/arc.rs <(sed 's|/\*@~mut@\*/ ||g; s|/\*@~mut@\*/||g' with-directives/arc.rs) | sed '1,2d' || true) compat.patch +if ! diff original/arc.rs ../../../../library/alloc/src/rcs/arc.rs; then + echo "::error title=Please run verifast-proofs/patch-verifast-proofs.sh::Some VeriFast proofs are out of date; please chdir to verifast-proofs and run patch-verifast-proofs.sh to update them." + false +fi diff --git a/verifast-proofs/alloc/rcs/arc.rs/with-directives/arc.rs b/verifast-proofs/alloc/rcs/arc.rs/with-directives/arc.rs new file mode 100644 index 0000000000000..9a0e20f3a3802 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/with-directives/arc.rs @@ -0,0 +1,5309 @@ +use core::any::Any; +use core::cell::CloneFromCell; +#[cfg(not(no_global_oom_handling))] +use core::clone::TrivialClone; +use core::clone::{CloneToUninit, Share, UseCloned}; +use core::cmp::Ordering; +use core::hash::{Hash, Hasher}; +#[cfg(not(no_global_oom_handling))] +use core::iter; +use core::marker::{PhantomData, Unsize}; +use core::mem::{self, Alignment, ManuallyDrop}; +use core::num::NonZeroUsize; +use core::ops::{CoerceUnsized, Deref, DerefMut, DerefPure, DispatchFromDyn, LegacyReceiver}; +#[cfg(not(no_global_oom_handling))] +use core::ops::{Residual, Try}; +use core::panic::{RefUnwindSafe, UnwindSafe}; +use core::pin::{Pin, PinSafePointer}; +use core::ptr::{self, NonNull}; +#[cfg(not(no_global_oom_handling))] +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; +use crate::alloc::{ + AllocError, Allocator, AllocatorClone, AllocatorNightly, Global, Layout, StaticAllocator, +}; +use crate::borrow::{Cow, ToOwned}; +use crate::boxed::Box; +use crate::rc::is_dangling; +#[cfg(not(no_global_oom_handling))] +use crate::string::String; +#[cfg(not(no_global_oom_handling))] +use crate::vec::Vec; + +/// A soft limit on the amount of references that may be made to an `Arc`. +/// +/// Going above this limit will abort your program (although not +/// necessarily) at _exactly_ `MAX_REFCOUNT + 1` references. +/// Trying to go above it might call a `panic` (if not actually going above it). +/// +/// This is a global invariant, and also applies when using a compare-exchange loop. +/// +/// See comment in `Arc::clone`. +const MAX_REFCOUNT: usize = (isize::MAX) as usize; + +#[cold] +#[cfg_attr(not(panic = "immediate-abort"), inline(never))] +#[cfg_attr(panic = "immediate-abort", inline)] +#[track_caller] +fn panic_arc_overflow() -> ! { + panic!("Arc counter overflow"); +} + +#[cfg(not(sanitize = "thread"))] +macro_rules! acquire { + ($x:expr) => { + atomic::fence(Acquire) + }; +} + +// ThreadSanitizer does not support memory fences. To avoid false positive +// reports in Arc / Weak implementation use atomic loads for synchronization +// instead. +#[cfg(sanitize = "thread")] +macro_rules! acquire { + ($x:expr) => { + $x.load(Acquire) + }; +} + +/// A thread-safe reference-counting pointer. 'Arc' stands for 'Atomically +/// Reference Counted'. +/// +/// The type `Arc` provides shared ownership of a value of type `T`, +/// allocated in the heap. Invoking [`clone`][clone] on `Arc` produces +/// a new `Arc` instance, which points to the same allocation on the heap as the +/// source `Arc`, while increasing a reference count. When the last `Arc` +/// pointer to a given allocation is destroyed, the value stored in that allocation (often +/// referred to as "inner value") is also dropped. +/// +/// Shared references in Rust disallow mutation by default, and `Arc` is no +/// exception: you cannot generally obtain a mutable reference to something +/// inside an `Arc`. If you do need to mutate through an `Arc`, you have several options: +/// +/// 1. Use interior mutability with synchronization primitives like [`Mutex`][mutex], +/// [`RwLock`][rwlock], or one of the [`Atomic`][atomic] types. +/// +/// 2. Use clone-on-write semantics with [`Arc::make_mut`] which provides efficient mutation +/// without requiring interior mutability. This approach clones the data only when +/// needed (when there are multiple references) and can be more efficient when mutations +/// are infrequent. +/// +/// 3. Use [`Arc::get_mut`] when you know your `Arc` is not shared (has a reference count of 1), +/// which provides direct mutable access to the inner value without any cloning. +/// +/// ``` +/// use std::sync::Arc; +/// +/// let mut data = Arc::new(vec![1, 2, 3]); +/// +/// // This will clone the vector only if there are other references to it +/// Arc::make_mut(&mut data).push(4); +/// +/// assert_eq!(*data, vec![1, 2, 3, 4]); +/// ``` +/// +/// **Note**: This type is only available on platforms that support atomic +/// loads and stores of pointers, which includes all platforms that support +/// the `std` crate but not all those which only support [`alloc`](crate). +/// This may be detected at compile time using `#[cfg(target_has_atomic = "ptr")]`. +/// +/// ## Thread Safety +/// +/// Unlike [`Rc`], `Arc` uses atomic operations for its reference +/// counting. This means that it is thread-safe. The disadvantage is that +/// atomic operations are more expensive than ordinary memory accesses. If you +/// are not sharing reference-counted allocations between threads, consider using +/// [`Rc`] for lower overhead. [`Rc`] is a safe default, because the +/// compiler will catch any attempt to send an [`Rc`] between threads. +/// However, a library might choose `Arc` in order to give library consumers +/// more flexibility. +/// +/// `Arc` will implement [`Send`] and [`Sync`] as long as the `T` implements +/// [`Send`] and [`Sync`]. Why can't you put a non-thread-safe type `T` in an +/// `Arc` to make it thread-safe? This may be a bit counter-intuitive at +/// first: after all, isn't the point of `Arc` thread safety? The key is +/// this: `Arc` makes it thread safe to have multiple ownership of the same +/// data, but it doesn't add thread safety to its data. Consider +/// Arc<[RefCell\]>. [`RefCell`] isn't [`Sync`], and if `Arc` was always +/// [`Send`], Arc<[RefCell\]> would be as well. But then we'd have a problem: +/// [`RefCell`] is not thread safe; it keeps track of the borrowing count using +/// non-atomic operations. +/// +/// In the end, this means that you may need to pair `Arc` with some sort of +/// [`std::sync`] type, usually [`Mutex`][mutex]. +/// +/// ## Breaking cycles with `Weak` +/// +/// The [`downgrade`][downgrade] method can be used to create a non-owning +/// [`Weak`] pointer. A [`Weak`] pointer can be [`upgrade`][upgrade]d +/// to an `Arc`, but this will return [`None`] if the value stored in the allocation has +/// already been dropped. In other words, `Weak` pointers do not keep the value +/// inside the allocation alive; however, they *do* keep the allocation +/// (the backing store for the value) alive. +/// +/// A cycle between `Arc` pointers will never be deallocated. For this reason, +/// [`Weak`] is used to break cycles. For example, a tree could have +/// strong `Arc` pointers from parent nodes to children, and [`Weak`] +/// pointers from children back to their parents. +/// +/// # Cloning references +/// +/// Creating a new reference from an existing reference-counted pointer is done using the +/// `Clone` trait implemented for [`Arc`][Arc] and [`Weak`][Weak]. +/// +/// ``` +/// use std::sync::Arc; +/// let foo = Arc::new(vec![1.0, 2.0, 3.0]); +/// // The two syntaxes below are equivalent. +/// let a = foo.clone(); +/// let b = Arc::clone(&foo); +/// // a, b, and foo are all Arcs that point to the same memory location +/// ``` +/// +/// ## `Deref` behavior +/// +/// `Arc` automatically dereferences to `T` (via the [`Deref`] trait), +/// so you can call `T`'s methods on a value of type `Arc`. To avoid name +/// clashes with `T`'s methods, the methods of `Arc` itself are associated +/// functions, called using [fully qualified syntax]: +/// +/// ``` +/// use std::sync::Arc; +/// +/// let my_arc = Arc::new(()); +/// let my_weak = Arc::downgrade(&my_arc); +/// ``` +/// +/// `Arc`'s implementations of traits like `Clone` may also be called using +/// fully qualified syntax. Some people prefer to use fully qualified syntax, +/// while others prefer using method-call syntax. +/// +/// ``` +/// use std::sync::Arc; +/// +/// let arc = Arc::new(()); +/// // Method-call syntax +/// let arc2 = arc.clone(); +/// // Fully qualified syntax +/// let arc3 = Arc::clone(&arc); +/// ``` +/// +/// [`Weak`][Weak] does not auto-dereference to `T`, because the inner value may have +/// already been dropped. +/// +/// [`Rc`]: crate::rc::Rc +/// [clone]: Clone::clone +/// [mutex]: ../../std/sync/struct.Mutex.html +/// [rwlock]: ../../std/sync/struct.RwLock.html +/// [atomic]: core::sync::atomic +/// [downgrade]: Arc::downgrade +/// [upgrade]: Weak::upgrade +/// [RefCell\]: core::cell::RefCell +/// [`RefCell`]: core::cell::RefCell +/// [`std::sync`]: ../../std/sync/index.html +/// [`Arc::clone(&from)`]: Arc::clone +/// [fully qualified syntax]: https://doc.rust-lang.org/book/ch19-03-advanced-traits.html#fully-qualified-syntax-for-disambiguation-calling-methods-with-the-same-name +/// +/// # Examples +/// +/// Sharing some immutable data between threads: +/// +/// ```ignore-wasm +/// use std::sync::Arc; +/// use std::thread; +/// +/// let five = Arc::new(5); +/// +/// for _ in 0..10 { +/// let five = Arc::clone(&five); +/// +/// thread::spawn(move || { +/// println!("{five:?}"); +/// }); +/// } +/// ``` +/// +/// Sharing a mutable [`AtomicUsize`]: +/// +/// [`AtomicUsize`]: core::sync::atomic::AtomicUsize "sync::atomic::AtomicUsize" +/// +/// ```ignore-wasm +/// use std::sync::Arc; +/// use std::sync::atomic::{AtomicUsize, Ordering}; +/// use std::thread; +/// +/// let val = Arc::new(AtomicUsize::new(5)); +/// +/// for _ in 0..10 { +/// let val = Arc::clone(&val); +/// +/// thread::spawn(move || { +/// let v = val.fetch_add(1, Ordering::Relaxed); +/// println!("{v:?}"); +/// }); +/// } +/// ``` +/// +/// See the [`rc` documentation][rc_examples] for more examples of reference +/// counting in general. +/// +/// [rc_examples]: crate::rc#examples +#[doc(search_unbox)] +#[stable(feature = "rust1", since = "1.0.0")] +#[rustc_insignificant_dtor] +#[diagnostic::on_move( + message = "the type `{Self}` does not implement `Copy`", + label = "this move could be avoided by cloning the original `{Self}`, which is inexpensive", + note = "consider using `Arc::clone`" +)] +pub struct Arc< + T: ?Sized, + // FIXME: When stabilizing this parameter, the `AllocatorNightly` + // bound on the `From` impl *must* be weaked to `Allocator`, + // as `Box` is fundamental! + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + ptr: NonNull>, + phantom: PhantomData>, + alloc: A, +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Send for Arc {} +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl Sync for Arc {} + +#[stable(feature = "catch_unwind", since = "1.9.0")] +impl UnwindSafe + for Arc +{ +} + +#[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> for Arc {} + +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for Arc {} + +// SAFETY: `Arc::clone` doesn't access any `Cell`s which could contain the `Arc` being cloned. +#[unstable(feature = "cell_get_cloned", issue = "145329")] +unsafe impl CloneFromCell for Arc {} + +impl Arc { + unsafe fn from_inner(ptr: NonNull>) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_inner_in(ptr, Global) } + } + + unsafe fn from_ptr(ptr: *mut ArcInner) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_ptr_in(ptr, Global) } + } +} + +impl Arc { + #[inline] + fn into_inner_with_allocator(this: Self) -> (NonNull>, A) { + let this = mem::ManuallyDrop::new(this); + // SAFETY: Pointer is valid for reads. + (this.ptr, unsafe { ptr::read(&this.alloc) }) + } + + #[inline] + unsafe fn from_inner_in(ptr: NonNull>, alloc: A) -> Self { + Self { ptr, phantom: PhantomData, alloc } + } + + #[inline] + unsafe fn from_ptr_in(ptr: *mut ArcInner, alloc: A) -> Self { + // SAFETY: Upheld by caller. + unsafe { Self::from_inner_in(NonNull::new_unchecked(ptr), alloc) } + } +} + +/// `Weak` is a version of [`Arc`] that holds a non-owning reference to the +/// managed allocation. +/// +/// The allocation is accessed by calling [`upgrade`] on the `Weak` +/// pointer, which returns an [Option]<[Arc]\>. +/// +/// Since a `Weak` reference does not count towards ownership, it will not +/// prevent the value stored in the allocation from being dropped, and `Weak` itself makes no +/// guarantees about the value still being present. Thus it may return [`None`] +/// when [`upgrade`]d. Note however that a `Weak` reference *does* prevent the allocation +/// itself (the backing store) from being deallocated. +/// +/// A `Weak` pointer is useful for keeping a temporary reference to the allocation +/// managed by [`Arc`] without preventing its inner value from being dropped. It is also used to +/// prevent circular references between [`Arc`] pointers, since mutual owning references +/// would never allow either [`Arc`] to be dropped. For example, a tree could +/// have strong [`Arc`] pointers from parent nodes to children, and `Weak` +/// pointers from children back to their parents. +/// +/// The typical way to obtain a `Weak` pointer is to call [`Arc::downgrade`]. +/// +/// [`upgrade`]: Weak::upgrade +#[stable(feature = "arc_weak", since = "1.4.0")] +pub struct Weak< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + // This is a `NonNull` to allow optimizing the size of this type in enums, + // but it is not necessarily a valid pointer. + // `Weak::new` sets this to `usize::MAX` so that it doesn’t need + // to allocate space on the heap. That's not a value a real pointer + // will ever have because ArcInner has alignment at least 2. + ptr: NonNull>, + alloc: A, +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl Send for Weak {} +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl Sync for Weak {} + +#[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> for Weak {} +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for Weak {} + +// SAFETY: `Weak::clone` doesn't access any `Cell`s which could contain the `Weak` being cloned. +#[unstable(feature = "cell_get_cloned", issue = "145329")] +unsafe impl CloneFromCell for Weak {} + +#[stable(feature = "arc_weak", since = "1.4.0")] +impl fmt::Debug for Weak { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "(Weak)") + } +} + +// This is repr(C) to future-proof against possible field-reordering, which +// would interfere with otherwise safe [into|from]_raw() of transmutable +// inner types. +// Unlike RcInner, repr(align(2)) is not strictly required because atomic types +// have the alignment same as its size, but we use it for consistency and clarity. +#[repr(C, align(2))] +struct ArcInner { + strong: Atomic, + + // the value usize::MAX acts as a sentinel for temporarily "locking" the + // weak count, preventing `Arc::downgrade` from racing to create new + // `Weak` references. `Arc::is_unique` (which backs `Arc::get_mut`) + // needs to observe both the strong and weak counts as indicating + // uniqueness in one logical atomic step; since they live in separate + // atomic words, it locks the weak count while reading the strong + // count to keep the two reads consistent. + weak: Atomic, + + data: T, +} + +/// Calculate layout for `ArcInner` using the inner value's layout +fn arcinner_layout_for_value_layout(layout: Layout) -> Layout { + // Calculate layout using the given value layout. + // Previously, layout was calculated on the expression + // `&*(ptr as *const ArcInner)`, but this created a misaligned + // reference (see #54908). + Layout::new::>() + .extend(layout) + .unwrap_or_else(|_| panic!("capacity overflow")) + .0 + .pad_to_align() +} + +unsafe impl Send for ArcInner {} +unsafe impl Sync for ArcInner {} + +impl Arc { + /// Constructs a new `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "rust1", since = "1.0.0")] + pub fn new(data: T) -> Arc { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x: Box<_> = Box::new(ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }); + // SAFETY: Pointer is valid. + unsafe { Self::from_inner(Box::into_non_null(x)) } + } + + /// Constructs a new `Arc` while giving you a `Weak` to the allocation, + /// to allow you to construct a `T` which holds a weak pointer to itself. + /// + /// Generally, a structure circularly referencing itself, either directly or + /// indirectly, should not hold a strong reference to itself to prevent a memory leak. + /// Using this function, you get access to the weak pointer during the + /// initialization of `T`, before the `Arc` is created, such that you can + /// clone and store it inside the `T`. + /// + /// `new_cyclic` first allocates the managed allocation for the `Arc`, + /// then calls your closure, giving it a `Weak` to this allocation, + /// and only afterwards completes the construction of the `Arc` by placing + /// the `T` returned from your closure into the allocation. + /// + /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic` + /// returns, calling [`upgrade`] on the weak reference inside your closure will + /// fail and result in a `None` value. + /// + /// # Panics + /// + /// If `data_fn` panics, the panic is propagated to the caller, and the + /// temporary [`Weak`] is dropped normally. + /// + /// # Example + /// + /// ``` + /// # #![allow(dead_code)] + /// use std::sync::{Arc, Weak}; + /// + /// struct Gadget { + /// me: Weak, + /// } + /// + /// impl Gadget { + /// /// Constructs a reference counted Gadget. + /// fn new() -> Arc { + /// // `me` is a `Weak` pointing at the new allocation of the + /// // `Arc` we're constructing. + /// Arc::new_cyclic(|me| { + /// // Create the actual struct here. + /// Gadget { me: me.clone() } + /// }) + /// } + /// + /// /// Returns a reference counted pointer to Self. + /// fn me(&self) -> Arc { + /// self.me.upgrade().unwrap() + /// } + /// } + /// ``` + /// [`upgrade`]: Weak::upgrade + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "arc_new_cyclic", since = "1.60.0")] + pub fn new_cyclic(data_fn: F) -> Arc + where + F: FnOnce(&Weak) -> T, + { + Self::new_cyclic_in(data_fn, Global) + } + + /// Constructs a new `Arc` with uninitialized contents. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut five = Arc::::new_uninit(); + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use] + pub fn new_uninit() -> Arc> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr(Arc::allocate_for_layout( + Layout::new::(), + |layout| Global.allocate(layout), + <*mut u8>::cast, + )) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let zero = Arc::::new_zeroed(); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_zeroed_alloc", since = "1.92.0")] + #[must_use] + pub fn new_zeroed() -> Arc> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr(Arc::allocate_for_layout( + Layout::new::(), + |layout| Global.allocate_zeroed(layout), + <*mut u8>::cast, + )) + } + } + + /// Constructs a new `Pin>`. If `T` does not implement `Unpin`, then + /// `data` will be pinned in memory and unable to be moved. + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "pin", since = "1.33.0")] + #[must_use] + pub fn pin(data: T) -> Pin> { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::new(data)) } + } + + /// Constructs a new `Pin>`, return an error if allocation fails. + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_pin(data: T) -> Result>, AllocError> { + // SAFETY: We own and create the pinned pointer. + unsafe { Ok(Pin::new_unchecked(Arc::try_new(data)?)) } + } + + /// Constructs a new `Arc`, returning an error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// + /// let five = Arc::try_new(5)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new(data: T) -> Result, AllocError> { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x: Box<_> = Box::try_new(ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + })?; + // SAFETY: Pointer is valid. + unsafe { Ok(Self::from_inner(Box::into_non_null(x))) } + } + + /// Constructs a new `Arc` with uninitialized contents, returning an error + /// if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// + /// let mut five = Arc::::try_new_uninit()?; + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_new_uninit() -> Result>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr(Arc::try_allocate_for_layout( + Layout::new::(), + |layout| Global.allocate(layout), + <*mut u8>::cast, + )?)) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, returning an error if allocation fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature( allocator_ext)] + /// + /// use std::sync::Arc; + /// + /// let zero = Arc::::try_new_zeroed()?; + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_new_zeroed() -> Result>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr(Arc::try_allocate_for_layout( + Layout::new::(), + |layout| Global.allocate_zeroed(layout), + <*mut u8>::cast, + )?)) + } + } +} + +impl Arc { + /// Constructs a new `Arc` in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// ``` + #[inline] + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_in(data: T, alloc: A) -> Arc { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x = Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + ); + let (ptr, alloc) = Box::into_non_null_with_allocator(x); + // SAFETY: Pointer is valid. + unsafe { Self::from_inner_in(ptr, alloc) } + } + + /// Constructs a new `Arc` with uninitialized contents in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut five = Arc::::new_uninit_in(System); + /// + /// let five = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); + /// + /// five.assume_init() + /// }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_uninit_in(alloc: A) -> Arc, A> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr_in( + Arc::allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate(layout), + <*mut u8>::cast, + ), + alloc, + ) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, in the provided allocator. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let zero = Arc::::new_zeroed_in(System); + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_zeroed_in(alloc: A) -> Arc, A> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr_in( + Arc::allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate_zeroed(layout), + <*mut u8>::cast, + ), + alloc, + ) + } + } + + /// Constructs a new `Arc` in the given allocator while giving you a `Weak` to the allocation, + /// to allow you to construct a `T` which holds a weak pointer to itself. + /// + /// Generally, a structure circularly referencing itself, either directly or + /// indirectly, should not hold a strong reference to itself to prevent a memory leak. + /// Using this function, you get access to the weak pointer during the + /// initialization of `T`, before the `Arc` is created, such that you can + /// clone and store it inside the `T`. + /// + /// `new_cyclic_in` first allocates the managed allocation for the `Arc`, + /// then calls your closure, giving it a `Weak` to this allocation, + /// and only afterwards completes the construction of the `Arc` by placing + /// the `T` returned from your closure into the allocation. + /// + /// Since the new `Arc` is not fully-constructed until `Arc::new_cyclic_in` + /// returns, calling [`upgrade`] on the weak reference inside your closure will + /// fail and result in a `None` value. + /// + /// # Panics + /// + /// If `data_fn` panics, the panic is propagated to the caller, and the + /// temporary [`Weak`] is dropped normally. + /// + /// # Example + /// + /// See [`new_cyclic`] + /// + /// [`new_cyclic`]: Arc::new_cyclic + /// [`upgrade`]: Weak::upgrade + #[cfg(not(no_global_oom_handling))] + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_cyclic_in(data_fn: F, alloc: A) -> Arc + where + F: FnOnce(&Weak) -> T, + { + // Construct the inner in the "uninitialized" state with a single + // weak reference. + let (uninit_ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + weak: atomic::AtomicUsize::new(1), + data: mem::MaybeUninit::::uninit(), + }, + alloc, + )); + let init_ptr: NonNull> = uninit_ptr.cast(); + + let weak = Weak { ptr: init_ptr, alloc }; + + // It's important we don't give up ownership of the weak pointer, or + // else the memory might be freed by the time `data_fn` returns. If + // we really wanted to pass ownership, we could create an additional + // weak pointer for ourselves, but this would result in additional + // updates to the weak reference count which might not be necessary + // otherwise. + let data = data_fn(&weak); + + // Now we can properly initialize the inner value and turn our weak + // reference into a strong reference. + let inner = init_ptr.as_ptr(); + // ignore-tidy-undocumented-unsafe + unsafe { + ptr::write(&raw mut (*inner).data, data); + + // The above write to the data field must be visible to any threads which + // observe a non-zero strong count. Therefore we need at least "Release" ordering + // in order to synchronize with the `compare_exchange_weak` in `Weak::upgrade`. + // + // "Acquire" ordering is not required. When considering the possible behaviors + // of `data_fn` we only need to look at what it could do with a reference to a + // non-upgradeable `Weak`: + // - It can *clone* the `Weak`, increasing the weak reference count. + // - It can drop those clones, decreasing the weak reference count (but never to zero). + // + // These side effects do not impact us in any way, and no other side effects are + // possible with safe code alone. + let prev_value = (*inner).strong.fetch_add(1, Release); + debug_assert_eq!(prev_value, 0, "No prior strong references should exist"); + + // Strong references should collectively own a shared weak reference, + // so don't run the destructor for our old weak reference. + // Calling into_raw_with_allocator has the double effect of giving us back the allocator, + // and forgetting the weak reference. + let alloc = weak.into_raw_with_allocator().1; + + Arc::from_inner_in(init_ptr, alloc) + } + } + + /// Constructs a new `Pin>` in the provided allocator. If `T` does not implement `Unpin`, + /// then `data` will be pinned in memory and unable to be moved. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn pin_in(data: T, alloc: A) -> Pin> + where + A: StaticAllocator, + { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::new_in(data, alloc)) } + } + + /// Constructs a new `Pin>` in the provided allocator, return an error if allocation + /// fails. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_pin_in(data: T, alloc: A) -> Result>, AllocError> + where + A: StaticAllocator, + { + // SAFETY: We own and create the pinned pointer. + unsafe { Ok(Pin::new_unchecked(Arc::try_new_in(data, alloc)?)) } + } + + /// Constructs a new `Arc` in the provided allocator, returning an error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::try_new_in(5, System)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_in(data: T, alloc: A) -> Result, AllocError> { + // Start the weak pointer count as 1 which is the weak pointer that's + // held by all the strong pointers (kinda), see std/rc.rs for more info + let x = Box::try_new_in( + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + )?; + let (ptr, alloc) = Box::into_non_null_with_allocator(x); + // SAFETY: Pointer is valid since we created it. + Ok(unsafe { Self::from_inner_in(ptr, alloc) }) + } + + /// Constructs a new `Arc` with uninitialized contents, in the provided allocator, returning an + /// error if allocation fails. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut five = Arc::::try_new_uninit_in(System)?; + /// + /// let five = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut five).as_mut_ptr().write(5); + /// + /// five.assume_init() + /// }; + /// + /// assert_eq!(*five, 5); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_uninit_in(alloc: A) -> Result, A>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr_in( + Arc::try_allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate(layout), + <*mut u8>::cast, + )?, + alloc, + )) + } + } + + /// Constructs a new `Arc` with uninitialized contents, with the memory + /// being filled with `0` bytes, in the provided allocator, returning an error if allocation + /// fails. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and incorrect usage + /// of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let zero = Arc::::try_new_zeroed_in(System)?; + /// let zero = unsafe { zero.assume_init() }; + /// + /// assert_eq!(*zero, 0); + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn try_new_zeroed_in(alloc: A) -> Result, A>, AllocError> { + // ignore-tidy-undocumented-unsafe + unsafe { + Ok(Arc::from_ptr_in( + Arc::try_allocate_for_layout( + Layout::new::(), + |layout| alloc.allocate_zeroed(layout), + <*mut u8>::cast, + )?, + alloc, + )) + } + } + /// Returns the inner value, if the `Arc` has exactly one strong reference. + /// + /// Otherwise, an [`Err`] is returned with the same `Arc` that was + /// passed in. + /// + /// This will succeed even if there are outstanding weak references. + /// + /// It is strongly recommended to use [`Arc::into_inner`] instead if you don't + /// keep the `Arc` in the [`Err`] case. + /// Immediately dropping the [`Err`]-value, as the expression + /// `Arc::try_unwrap(this).ok()` does, can cause the strong count to + /// drop to zero and the inner value of the `Arc` to be dropped. + /// For instance, if two threads execute such an expression in parallel, + /// there is a race condition without the possibility of unsafety: + /// The threads could first both check whether they own the last instance + /// in `Arc::try_unwrap`, determine that they both do not, and then both + /// discard and drop their instance in the call to [`ok`][`Result::ok`]. + /// In this scenario, the value inside the `Arc` is safely destroyed + /// by exactly one of the threads, but neither thread will ever be able + /// to use the value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// assert_eq!(Arc::try_unwrap(x), Ok(3)); + /// + /// let x = Arc::new(4); + /// let _y = Arc::clone(&x); + /// assert_eq!(*Arc::try_unwrap(x).unwrap_err(), 4); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn try_unwrap(/*@~mut@*/ this: Self) -> Result { + if this.inner().strong.compare_exchange(1, 0, Relaxed, Relaxed).is_err() { + return Err(this); + } + + acquire!(this.inner().strong); + + let this = ManuallyDrop::new(this); + // SAFETY: Pointer is valid for reads, contains initialised memory, + // and not dropped multiple times (we return it). + let elem: T = unsafe { ptr::read(&this.ptr.as_ref().data) }; + // SAFETY: As above, but we explicitly drop the allocator only once + // upon creating and dropping a weak pointer. + let alloc: A = unsafe { ptr::read(&this.alloc) }; // copy the allocator + + // Make a weak pointer to clean up the implicit strong-weak reference + let _weak = Weak { ptr: this.ptr, alloc }; + + Ok(elem) + } + + /// Returns the inner value, if the `Arc` has exactly one strong reference. + /// + /// Otherwise, [`None`] is returned and the `Arc` is dropped. + /// + /// This will succeed even if there are outstanding weak references. + /// + /// If `Arc::into_inner` is called on every clone of this `Arc`, + /// it is guaranteed that exactly one of the calls returns the inner value. + /// This means in particular that the inner value is not dropped. + /// + /// [`Arc::try_unwrap`] is conceptually similar to `Arc::into_inner`, but it + /// is meant for different use-cases. If used as a direct replacement + /// for `Arc::into_inner` anyway, such as with the expression + /// [Arc::try_unwrap]\(this).[ok][Result::ok](), then it does + /// **not** give the same guarantee as described in the previous paragraph. + /// For more information, see the examples below and read the documentation + /// of [`Arc::try_unwrap`]. + /// + /// # Examples + /// + /// Minimal example demonstrating the guarantee that `Arc::into_inner` gives. + /// ```ignore-wasm + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// let y = Arc::clone(&x); + /// + /// // Two threads calling `Arc::into_inner` on both clones of an `Arc`: + /// let x_thread = std::thread::spawn(|| Arc::into_inner(x)); + /// let y_thread = std::thread::spawn(|| Arc::into_inner(y)); + /// + /// let x_inner_value = x_thread.join().unwrap(); + /// let y_inner_value = y_thread.join().unwrap(); + /// + /// // One of the threads is guaranteed to receive the inner value: + /// assert!(matches!( + /// (x_inner_value, y_inner_value), + /// (None, Some(3)) | (Some(3), None) + /// )); + /// // The result could also be `(None, None)` if the threads called + /// // `Arc::try_unwrap(x).ok()` and `Arc::try_unwrap(y).ok()` instead. + /// ``` + /// + /// A more practical example demonstrating the need for `Arc::into_inner`: + /// ```ignore-wasm + /// use std::sync::Arc; + /// + /// // Definition of a simple singly linked list using `Arc`: + /// #[derive(Clone)] + /// struct LinkedList(Option>>); + /// struct Node(T, Option>>); + /// + /// // Dropping a long `LinkedList` relying on the destructor of `Arc` + /// // can cause a stack overflow. To prevent this, we can provide a + /// // manual `Drop` implementation that does the destruction in a loop: + /// impl Drop for LinkedList { + /// fn drop(&mut self) { + /// let mut link = self.0.take(); + /// while let Some(arc_node) = link.take() { + /// if let Some(Node(_value, next)) = Arc::into_inner(arc_node) { + /// link = next; + /// } + /// } + /// } + /// } + /// + /// // Implementation of `new` and `push` omitted + /// impl LinkedList { + /// /* ... */ + /// # fn new() -> Self { + /// # LinkedList(None) + /// # } + /// # fn push(&mut self, x: T) { + /// # self.0 = Some(Arc::new(Node(x, self.0.take()))); + /// # } + /// } + /// + /// // The following code could have still caused a stack overflow + /// // despite the manual `Drop` impl if that `Drop` impl had used + /// // `Arc::try_unwrap(arc).ok()` instead of `Arc::into_inner(arc)`. + /// + /// // Create a long list and clone it + /// let mut x = LinkedList::new(); + /// let size = 100000; + /// # let size = if cfg!(miri) { 100 } else { size }; + /// for i in 0..size { + /// x.push(i); // Adds i to the front of x + /// } + /// let y = x.clone(); + /// + /// // Drop the clones in parallel + /// let x_thread = std::thread::spawn(|| drop(x)); + /// let y_thread = std::thread::spawn(|| drop(y)); + /// x_thread.join().unwrap(); + /// y_thread.join().unwrap(); + /// ``` + #[inline] + #[stable(feature = "arc_into_inner", since = "1.70.0")] + pub fn into_inner(this: Self) -> Option { + // Make sure that the ordinary `Drop` implementation isn’t called as well + let mut this = mem::ManuallyDrop::new(this); + + // Following the implementation of `drop` and `drop_slow` + if this.inner().strong.fetch_sub(1, Release) != 1 { + return None; + } + + acquire!(this.inner().strong); + + // SAFETY: This mirrors the line + // + // unsafe { ptr::drop_in_place(Self::get_mut_unchecked(self)) }; + // + // in `drop_slow`. Instead of dropping the value behind the pointer, + // it is read and eventually returned; `ptr::read` has the same + // safety conditions as `ptr::drop_in_place`. + let inner = unsafe { ptr::read(Self::get_mut_unchecked(&mut this)) }; + // SAFETY: Pointer is valid for reads. + let alloc = unsafe { ptr::read(&this.alloc) }; + + drop(Weak { ptr: this.ptr, alloc }); + + Some(inner) + } + + /// Maps the value in an `Arc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `Arc`, and the result is returned, also in + /// an `Arc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::map(a, f)` instead of `r.map(a)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let r = Arc::new(7); + /// let new = Arc::map(r, |i| i + 7); + /// assert_eq!(*new, 14); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[stable(feature = "smart_pointer_map", since = "1.100.0")] + pub fn map(this: Self, f: impl FnOnce(&T) -> U) -> Arc { + if size_of::() == size_of::() + && align_of::() == align_of::() + && Arc::is_unique(&this) + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + let value = ptr.read(); + let mut allocation = Arc::from_raw_in(ptr.cast::>(), alloc); + + Arc::get_mut_unchecked(&mut allocation).write(f(&value)); + allocation.assume_init() + } + } else { + let output = f(&*this); + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::decrement_strong_count_in(ptr, &alloc) } + + Arc::new_in(output, alloc) + } + } + + /// Attempts to map the value in an `Arc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `Arc`, and if the operation succeeds, the + /// result is returned, also in an `Arc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::try_map(a, f)` instead of `a.try_map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(smart_pointer_try_map)] + /// + /// use std::sync::Arc; + /// + /// let b = Arc::new(7); + /// let new = Arc::try_map(b, |&i| u32::try_from(i)).unwrap(); + /// assert_eq!(*new, 7); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "smart_pointer_try_map", issue = "144419")] + pub fn try_map( + this: Self, + f: impl FnOnce(&T) -> R, + ) -> >>::TryType + where + R: Try, + R::Residual: Residual>, + { + if size_of::() == size_of::() + && align_of::() == align_of::() + && Arc::is_unique(&this) + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + let value = ptr.read(); + let mut allocation = + Arc::from_raw_in(ptr.cast::>(), alloc); + + Arc::get_mut_unchecked(&mut allocation).write(f(&value)?); + try { allocation.assume_init() } + } + } else { + let output = f(&*this)?; + let (ptr, alloc) = Arc::into_raw_with_allocator(this); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::decrement_strong_count_in(ptr, &alloc) } + + try { Arc::new_in(output, alloc) } + } + } +} + +impl Arc<[T]> { + /// Constructs a new atomically reference-counted slice with uninitialized contents. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut values = Arc::<[u32]>::new_uninit_slice(3); + /// + /// // Deferred initialization: + /// let data = Arc::get_mut(&mut values).unwrap(); + /// data[0].write(1); + /// data[1].write(2); + /// data[2].write(3); + /// + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use] + pub fn new_uninit_slice(len: usize) -> Arc<[mem::MaybeUninit]> { + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr(Arc::allocate_for_slice(len)) } + } + + /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being + /// filled with `0` bytes. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and + /// incorrect usage of this method. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let values = Arc::<[u32]>::new_zeroed_slice(3); + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[inline] + #[stable(feature = "new_zeroed_alloc", since = "1.92.0")] + #[must_use] + pub fn new_zeroed_slice(len: usize) -> Arc<[mem::MaybeUninit]> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr(Arc::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| Global.allocate_zeroed(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[mem::MaybeUninit]>, + )) + } + } +} + +impl Arc<[T], A> { + /// Constructs a new atomically reference-counted slice with uninitialized contents in the + /// provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let mut values = Arc::<[u32], _>::new_uninit_slice_in(3, System); + /// + /// let values = unsafe { + /// // Deferred initialization: + /// Arc::get_mut_unchecked(&mut values)[0].as_mut_ptr().write(1); + /// Arc::get_mut_unchecked(&mut values)[1].as_mut_ptr().write(2); + /// Arc::get_mut_unchecked(&mut values)[2].as_mut_ptr().write(3); + /// + /// values.assume_init() + /// }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_uninit_slice_in(len: usize, /*@~mut@*/ alloc: A) -> Arc<[mem::MaybeUninit], A> { + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr_in(Arc::allocate_for_slice_in(len, &alloc), alloc) } + } + + /// Constructs a new atomically reference-counted slice with uninitialized contents, with the memory being + /// filled with `0` bytes, in the provided allocator. + /// + /// See [`MaybeUninit::zeroed`][zeroed] for examples of correct and + /// incorrect usage of this method. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let values = Arc::<[u32], _>::new_zeroed_slice_in(3, System); + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [0, 0, 0]) + /// ``` + /// + /// [zeroed]: mem::MaybeUninit::zeroed + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + #[inline] + pub fn new_zeroed_slice_in(len: usize, alloc: A) -> Arc<[mem::MaybeUninit], A> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::from_ptr_in( + Arc::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| alloc.allocate_zeroed(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[mem::MaybeUninit]>, + ), + alloc, + ) + } + } + + /// Converts the reference-counted slice into a reference-counted array. + /// + /// This operation does not reallocate; the underlying array of the slice is simply reinterpreted as an array type. + /// + /// # Errors + /// + /// Returns the original `Arc<[T]>` in the `Err` variant if `self.len()` does not equal `N`. + /// + /// # Examples + /// + /// ``` + /// #![feature(alloc_slice_into_array)] + /// use std::sync::Arc; + /// + /// let arc_slice: Arc<[i32]> = Arc::new([1, 2, 3]); + /// + /// let arc_array: Arc<[i32; 3]> = arc_slice.into_array().unwrap(); + /// ``` + #[unstable(feature = "alloc_slice_into_array", issue = "148082")] + #[inline] + pub fn into_array(self) -> Result, Self> { + if self.len() == N { + let (ptr, alloc) = Self::into_raw_with_allocator(self); + let ptr = ptr as *const [T; N]; + + // SAFETY: The underlying array of a slice has the exact same layout as an actual array `[T; N]` if `N` is equal to the slice's length. + let me = unsafe { Arc::from_raw_in(ptr, alloc) }; + Ok(me) + } else { + Err(self) + } + } +} + +impl Arc, A> { + /// Converts to `Arc`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the inner value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut five = Arc::::new_uninit(); + /// + /// // Deferred initialization: + /// Arc::get_mut(&mut five).unwrap().write(5); + /// + /// let five = unsafe { five.assume_init() }; + /// + /// assert_eq!(*five, 5) + /// ``` + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub unsafe fn assume_init(self) -> Arc { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_inner_in(ptr.cast(), alloc) } + } +} + +impl Arc { + /// Constructs a new `Arc` with a clone of `value`. + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// use std::sync::Arc; + /// + /// let hello: Arc = Arc::clone_from_ref("hello"); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "clone_from_ref", issue = "149075")] + pub fn clone_from_ref(value: &T) -> Arc { + Arc::clone_from_ref_in(value, Global) + } + + /// Constructs a new `Arc` with a clone of `value`, returning an error if allocation fails + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// use std::sync::Arc; + /// + /// let hello: Arc = Arc::try_clone_from_ref("hello")?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_clone_from_ref(value: &T) -> Result, AllocError> { + Arc::try_clone_from_ref_in(value, Global) + } +} + +impl Arc { + /// Constructs a new `Arc` with a clone of `value` in the provided allocator. + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let hello: Arc = Arc::clone_from_ref_in("hello", System); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn clone_from_ref_in(value: &T, alloc: A) -> Arc { + // `in_progress` drops the allocation if we panic before finishing initializing it. + let mut in_progress: UniqueArcUninit = UniqueArcUninit::new(value, alloc); + + // Initialize with clone of value. + // ignore-tidy-undocumented-unsafe + unsafe { + // Clone. If the clone panics, `in_progress` will be dropped and clean up. + value.clone_to_uninit(in_progress.data_ptr().cast()); + // Cast type of pointer, now that it is initialized. + in_progress.into_arc() + } + } + + /// Constructs a new `Arc` with a clone of `value` in the provided allocator, returning an error if allocation fails + /// + /// # Examples + /// + /// ``` + /// #![feature(clone_from_ref)] + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let hello: Arc = Arc::try_clone_from_ref_in("hello", System)?; + /// # Ok::<(), std::alloc::AllocError>(()) + /// ``` + #[unstable(feature = "clone_from_ref", issue = "149075")] + //#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn try_clone_from_ref_in(value: &T, alloc: A) -> Result, AllocError> { + // `in_progress` drops the allocation if we panic before finishing initializing it. + let mut in_progress: UniqueArcUninit = UniqueArcUninit::try_new(value, alloc)?; + + // Initialize with clone of value. + // ignore-tidy-undocumented-unsafe + let initialized_clone = unsafe { + // Clone. If the clone panics, `in_progress` will be dropped and clean up. + value.clone_to_uninit(in_progress.data_ptr().cast()); + // Cast type of pointer, now that it is initialized. + in_progress.into_arc() + }; + + Ok(initialized_clone) + } +} + +impl Arc<[mem::MaybeUninit], A> { + /// Converts to `Arc<[T]>`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the inner value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut values = Arc::<[u32]>::new_uninit_slice(3); + /// + /// // Deferred initialization: + /// let data = Arc::get_mut(&mut values).unwrap(); + /// data[0].write(1); + /// data[1].write(2); + /// data[2].write(3); + /// + /// let values = unsafe { values.assume_init() }; + /// + /// assert_eq!(*values, [1, 2, 3]) + /// ``` + #[stable(feature = "new_uninit", since = "1.82.0")] + #[must_use = "`self` will be dropped if the result is not used"] + #[inline] + pub unsafe fn assume_init(self) -> Arc<[T], A> { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + // SAFETY: Upheld by caller. + unsafe { Arc::from_ptr_in(ptr.as_ptr() as _, alloc) } + } +} + +impl Arc { + /// Constructs an `Arc` from a raw pointer. + /// + /// The raw pointer must have been previously returned by a call to + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator]. + /// + /// # Safety + /// + /// * Creating a `Arc` from a pointer other than one returned from + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator] + /// is undefined behavior. + /// * If `U` is sized, it must have the same size and alignment as `T`. This + /// is trivially true if `U` is `T`. + /// * If `U` is unsized, its data pointer must have the same size and + /// alignment as `T`. This is trivially true if `Arc` was constructed + /// through `Arc` and then converted to `Arc` through an [unsized + /// coercion]. + /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size + /// and alignment, this is basically like transmuting references of + /// different types. See [`mem::transmute`][transmute] for more information + /// on what restrictions apply in this case. + /// * The raw pointer must point to a block of memory allocated by the global allocator. + /// * The user of `from_raw` has to make sure a specific value of `T` is only + /// dropped once. + /// + /// This function is unsafe because improper use may lead to memory unsafety, + /// even if the returned `Arc` is never accessed. + /// + /// [into_raw]: Arc::into_raw + /// [into_raw_with_allocator]: Arc::into_raw_with_allocator + /// [transmute]: core::mem::transmute + /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let x_ptr = Arc::into_raw(x); + /// + /// unsafe { + /// // Convert back to an `Arc` to prevent leak. + /// let x = Arc::from_raw(x_ptr); + /// assert_eq!(&*x, "hello"); + /// + /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. + /// } + /// + /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! + /// ``` + /// + /// Convert a slice back into its original array: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x: Arc<[u32]> = Arc::new([1, 2, 3]); + /// let x_ptr: *const [u32] = Arc::into_raw(x); + /// + /// unsafe { + /// let x: Arc<[u32; 3]> = Arc::from_raw(x_ptr.cast::<[u32; 3]>()); + /// assert_eq!(&*x, &[1, 2, 3]); + /// } + /// ``` + #[inline] + #[stable(feature = "rc_raw", since = "1.17.0")] + pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: Upheld by caller. + unsafe { Arc::from_raw_in(ptr, Global) } + } + + /// Consumes the `Arc`, returning the wrapped pointer. + /// + /// To avoid a memory leak the pointer must be converted back to an `Arc` using + /// [`Arc::from_raw`]. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let x_ptr = Arc::into_raw(x); + /// assert_eq!(unsafe { &*x_ptr }, "hello"); + /// # // Prevent leaks for Miri. + /// # drop(unsafe { Arc::from_raw(x_ptr) }); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "rc_raw", since = "1.17.0")] + #[lint::never_returns_null_ptr] + pub fn into_raw(this: Self) -> *const T { + let /*@~mut@*/ this = ManuallyDrop::new(this); + Self::as_ptr(&*this) + } + + /// Increments the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory + /// allocated by the global allocator. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// unsafe { + /// let ptr = Arc::into_raw(five); + /// Arc::increment_strong_count(ptr); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// # // Prevent leaks for Miri. + /// # Arc::decrement_strong_count(ptr); + /// } + /// ``` + #[inline] + #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] + pub unsafe fn increment_strong_count(ptr: *const T) { + // SAFETY: Upheld by caller. + unsafe { Arc::increment_strong_count_in(ptr, Global) } + } + + /// Decrements the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) when invoking this method, and `ptr` must point to a block of memory + /// allocated by the global allocator. This method can be used to release the final + /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been + /// released. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// unsafe { + /// let ptr = Arc::into_raw(five); + /// Arc::increment_strong_count(ptr); + /// + /// // Those assertions are deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// Arc::decrement_strong_count(ptr); + /// assert_eq!(1, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[stable(feature = "arc_mutate_strong_count", since = "1.51.0")] + pub unsafe fn decrement_strong_count(ptr: *const T) { + // SAFETY: Upheld by caller. + unsafe { Arc::decrement_strong_count_in(ptr, Global) } + } + + /// Gets the number of strong (`Arc`) pointers to the allocation behind the given raw + /// pointer. + /// + /// This method does not consume or drop the `Arc` behind this pointer. + /// + /// # Safety + /// + /// The pointer must point to (and have valid metadata for) the value inside a live `Arc` + /// allocation, such as a pointer returned by [`Arc::into_raw`], + /// [`Arc::into_raw_with_allocator`], or [`Arc::as_ptr`]. + /// `T` must have the same alignment as that value. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method. + /// + /// Using this method correctly also requires extra care: another thread can change the + /// strong count at any time, including between calling this method and acting on the + /// result. + /// + /// # Examples + /// + /// ``` + /// #![feature(arc_raw_get_strong)] + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _also_five = Arc::clone(&five); + /// let ptr = Arc::into_raw(five); + /// + /// unsafe { + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// assert_eq!(2, Arc::strong_count_from_raw(ptr)); + /// + /// // Convert back to an `Arc` to avoid leaking memory. + /// let five = Arc::from_raw(ptr); + /// assert_eq!(2, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[must_use] + #[unstable(feature = "arc_raw_get_strong", issue = "157021")] + pub unsafe fn strong_count_from_raw(ptr: *const T) -> usize { + // SAFETY: Upheld by caller. + let offset = unsafe { data_offset(ptr) }; + // Reverse the offset to find the original ArcInner. + // SAFETY: Caller ensures this pointer was to an `Arc` allocation, + // so offsetting must be inbounds. + let arc_ptr = unsafe { ptr.byte_sub(offset) as *mut ArcInner }; + // SAFETY: Per the above, an `ArcInner` is stored here. + unsafe { (*arc_ptr).strong.load(Relaxed) } + } +} + +impl Arc { + /// Returns a reference to the underlying allocator. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `Arc::allocator(&a)` instead of `a.allocator()`. This + /// is so that there is no conflict with a method on the inner type. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn allocator(this: &Self) -> &A { + &this.alloc + } + + /// Consumes the `Arc`, returning the wrapped pointer and allocator. + /// + /// To avoid a memory leak the pointer must be converted back to an `Arc` using + /// [`Arc::from_raw_in`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x = Arc::new_in("hello".to_owned(), System); + /// let (ptr, alloc) = Arc::into_raw_with_allocator(x); + /// assert_eq!(unsafe { &*ptr }, "hello"); + /// let x = unsafe { Arc::from_raw_in(ptr, alloc) }; + /// assert_eq!(&*x, "hello"); + /// ``` + #[must_use = "losing the pointer will leak memory"] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn into_raw_with_allocator(this: Self) -> (*const T, A) { + let /*@~mut@*/ this = mem::ManuallyDrop::new(this); + let ptr = Self::as_ptr(&this); + // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped + let alloc = unsafe { ptr::read(&this.alloc) }; + (ptr, alloc) + } + + /// Provides a raw pointer to the data. + /// + /// The counts are not affected in any way and the `Arc` is not consumed. The pointer is valid for + /// as long as there are strong counts in the `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new("hello".to_owned()); + /// let y = Arc::clone(&x); + /// let x_ptr = Arc::as_ptr(&x); + /// assert_eq!(x_ptr, Arc::as_ptr(&y)); + /// assert_eq!(unsafe { &*x_ptr }, "hello"); + /// ``` + #[must_use] + #[stable(feature = "rc_as_ptr", since = "1.45.0")] + #[lint::never_returns_null_ptr] + pub fn as_ptr(this: &Self) -> *const T { + let ptr: *mut ArcInner = NonNull::as_ptr(this.ptr); + + // SAFETY: This cannot go through Deref::deref or ArcInnerPtr::inner because + // this is required to retain raw/mut provenance such that e.g. `get_mut` can + // write through the pointer after the Arc is recovered through `from_raw`. + unsafe { &raw mut (*ptr).data } + } + + /// Constructs an `Arc` from a raw pointer. + /// + /// The raw pointer must have been previously returned by a call to [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator]. + /// + /// # Safety + /// + /// * Creating a `Arc` from a pointer other than one returned from + /// [`Arc::into_raw`][into_raw] or [`Arc::into_raw_with_allocator`][into_raw_with_allocator] + /// is undefined behavior. + /// * If `U` is sized, it must have the same size and alignment as `T`. This + /// is trivially true if `U` is `T`. + /// * If `U` is unsized, its data pointer must have the same size and + /// alignment as `T`. This is trivially true if `Arc` was constructed + /// through `Arc` and then converted to `Arc` through an [unsized + /// coercion]. + /// * Note that if `U` or `U`'s data pointer is not `T` but has the same size + /// and alignment, this is basically like transmuting references of + /// different types. See [`mem::transmute`][transmute] for more information + /// on what restrictions apply in this case. + /// * The raw pointer must point to a block of memory allocated by `alloc` + /// * The user of `from_raw` has to make sure a specific value of `T` is only + /// dropped once. + /// + /// This function is unsafe because improper use may lead to memory unsafety, + /// even if the returned `Arc` is never accessed. + /// + /// [into_raw]: Arc::into_raw + /// [into_raw_with_allocator]: Arc::into_raw_with_allocator + /// [transmute]: core::mem::transmute + /// [unsized coercion]: https://doc.rust-lang.org/reference/type-coercions.html#unsized-coercions + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x = Arc::new_in("hello".to_owned(), System); + /// let (x_ptr, alloc) = Arc::into_raw_with_allocator(x); + /// + /// unsafe { + /// // Convert back to an `Arc` to prevent leak. + /// let x = Arc::from_raw_in(x_ptr, System); + /// assert_eq!(&*x, "hello"); + /// + /// // Further calls to `Arc::from_raw(x_ptr)` would be memory-unsafe. + /// } + /// + /// // The memory was freed when `x` went out of scope above, so `x_ptr` is now dangling! + /// ``` + /// + /// Convert a slice back into its original array: + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let x: Arc<[u32], _> = Arc::new_in([1, 2, 3], System); + /// let x_ptr: *const [u32] = Arc::into_raw_with_allocator(x).0; + /// + /// unsafe { + /// let x: Arc<[u32; 3], _> = Arc::from_raw_in(x_ptr.cast::<[u32; 3]>(), System); + /// assert_eq!(&*x, &[1, 2, 3]); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self { + // SAFETY: Upheld by caller. + unsafe { + let offset = data_offset(ptr); + + // Reverse the offset to find the original ArcInner. + let arc_ptr = ptr.byte_sub(offset) as *mut ArcInner; + + Self::from_ptr_in(arc_ptr, alloc) + } + } + + /// Creates a new [`Weak`] pointer to this allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let weak_five = Arc::downgrade(&five); + /// ``` + #[must_use = "this returns a new `Weak` pointer, \ + without modifying the original `Arc`"] + #[stable(feature = "arc_weak", since = "1.4.0")] + pub fn downgrade(this: &Self) -> Weak + where + A: AllocatorClone, + { + // This Relaxed is OK because we're checking the value in the CAS + // below. + let mut cur = this.inner().weak.load(Relaxed); + + loop { + // check if the weak counter is currently "locked"; if so, spin. + if cur == usize::MAX { + hint::spin_loop(); + cur = this.inner().weak.load(Relaxed); + continue; + } + + // We can't allow the refcount to increase much past `MAX_REFCOUNT`. + if cur > MAX_REFCOUNT { + panic_arc_overflow(); + } + // NOTE: this code currently ignores the possibility of overflow + // into usize::MAX; in general both Rc and Arc need to be adjusted + // to deal with overflow. + + // Unlike with Clone(), we need this to be an Acquire read to + // synchronize with the write coming from `is_unique`, so that the + // events prior to that write happen before this read. + match this.inner().weak.compare_exchange_weak(cur, cur + 1, Acquire, Relaxed) { + Ok(_) => { + // Make sure we do not create a dangling Weak + debug_assert!(!is_dangling(this.ptr.as_ptr())); + return Weak { ptr: this.ptr, alloc: this.alloc.clone() }; + } + Err(old) => cur = old, + } + } + } + + /// Gets the number of [`Weak`] pointers to this allocation. + /// + /// # Safety + /// + /// This method by itself is safe, but using it correctly requires extra care. + /// Another thread can change the weak count at any time, + /// including potentially between calling this method and acting on the result. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _weak_five = Arc::downgrade(&five); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` or `Weak` between threads. + /// assert_eq!(1, Arc::weak_count(&five)); + /// ``` + #[inline] + #[must_use] + #[stable(feature = "arc_counts", since = "1.15.0")] + pub fn weak_count(this: &Self) -> usize { + let cnt = this.inner().weak.load(Relaxed); + // If the weak count is currently locked, the value of the + // count was 0 just before taking the lock. + if cnt == usize::MAX { 0 } else { cnt - 1 } + } + + /// Gets the number of strong (`Arc`) pointers to this allocation. + /// + /// # Safety + /// + /// This method by itself is safe, but using it correctly requires extra care. + /// Another thread can change the strong count at any time, + /// including potentially between calling this method and acting on the result. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let _also_five = Arc::clone(&five); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// assert_eq!(2, Arc::strong_count(&five)); + /// ``` + #[inline] + #[must_use] + #[stable(feature = "arc_counts", since = "1.15.0")] + pub fn strong_count(this: &Self) -> usize { + this.inner().strong.load(Relaxed) + } + + /// Increments the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) for the duration of this method, and `ptr` must point to a block of memory + /// allocated by `alloc`. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// + /// unsafe { + /// let (ptr, _alloc) = Arc::into_raw_with_allocator(five); + /// Arc::increment_strong_count_in(ptr, System); + /// + /// // This assertion is deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw_in(ptr, System); + /// assert_eq!(2, Arc::strong_count(&five)); + /// # // Prevent leaks for Miri. + /// # Arc::decrement_strong_count_in(ptr, System); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn increment_strong_count_in(ptr: *const T, alloc: A) + where + A: AllocatorClone, + { + // Retain Arc, but don't touch refcount by wrapping in ManuallyDrop + // SAFETY: Upheld by caller. + let /*@~mut@*/ arc = unsafe { mem::ManuallyDrop::new(Arc::from_raw_in(ptr, alloc)) }; + // Now increase refcount, but don't drop new refcount either + let _arc_clone: mem::ManuallyDrop<_> = arc.clone(); + } + + /// Decrements the strong reference count on the `Arc` associated with the + /// provided pointer by one. + /// + /// # Safety + /// + /// The pointer must have been obtained through `Arc::into_raw` and must satisfy the + /// same layout requirements specified in [`Arc::from_raw_in`][from_raw_in]. + /// The associated `Arc` instance must be valid (i.e. the strong count must be at + /// least 1) when invoking this method, and `ptr` must point to a block of memory + /// allocated by `alloc`. This method can be used to release the final + /// `Arc` and backing storage, but **should not** be called after the final `Arc` has been + /// released. + /// + /// [from_raw_in]: Arc::from_raw_in + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Arc; + /// use std::alloc::System; + /// + /// let five = Arc::new_in(5, System); + /// + /// unsafe { + /// let (ptr, _alloc) = Arc::into_raw_with_allocator(five); + /// Arc::increment_strong_count_in(ptr, System); + /// + /// // Those assertions are deterministic because we haven't shared + /// // the `Arc` between threads. + /// let five = Arc::from_raw_in(ptr, System); + /// assert_eq!(2, Arc::strong_count(&five)); + /// Arc::decrement_strong_count_in(ptr, System); + /// assert_eq!(1, Arc::strong_count(&five)); + /// } + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn decrement_strong_count_in(ptr: *const T, alloc: A) { + // SAFETY: Upheld by caller. + unsafe { drop(Arc::from_raw_in(ptr, alloc)) }; + } + + #[inline] + fn inner(&self) -> &ArcInner { + // SAFETY: While this arc is alive we're guaranteed + // that the inner pointer is valid. Furthermore, we know that the + // `ArcInner` structure itself is `Sync` if the inner data is + // `Sync` as well, so we're ok loaning out an immutable pointer to these + // contents. + unsafe { self.ptr.as_ref() } + } + + // Non-inlined part of `drop`. + #[inline(never)] + unsafe fn drop_slow(&mut self) { + // Drop the weak ref collectively held by all strong references when this + // variable goes out of scope. This ensures that the memory is deallocated + // even if the destructor of `T` panics. + // Take a reference to `self.alloc` instead of cloning because 1. it'll last long + // enough, and 2. you should be able to drop `Arc`s with unclonable allocators + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + + // Destroy the data at this time, even though we must not free the box + // allocation itself (there might still be weak pointers lying around). + // We cannot use `get_mut_unchecked` here, because `self.alloc` is borrowed. + // ignore-tidy-undocumented-unsafe + unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) }; + } + + /// Returns `true` if the two `Arc`s point to the same allocation in a vein similar to + /// [`ptr::eq`]. This function ignores the metadata of `dyn Trait` pointers. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// let same_five = Arc::clone(&five); + /// let other_five = Arc::new(5); + /// + /// assert!(Arc::ptr_eq(&five, &same_five)); + /// assert!(!Arc::ptr_eq(&five, &other_five)); + /// ``` + /// + /// [`ptr::eq`]: core::ptr::eq "ptr::eq" + #[inline] + #[must_use] + #[stable(feature = "ptr_eq", since = "1.17.0")] + pub fn ptr_eq(this: &Self, other: &Self) -> bool { + ptr::addr_eq(this.ptr.as_ptr(), other.ptr.as_ptr()) + } +} + +impl Arc { + /// Allocates an `ArcInner` with sufficient space for + /// a possibly-unsized inner value where the value has the layout provided. + /// + /// The function `mem_to_arcinner` is called with the data pointer + /// and must return back a (potentially fat)-pointer for the `ArcInner`. + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_layout( + value_layout: Layout, + allocate: impl FnOnce(Layout) -> Result, AllocError>, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> *mut ArcInner { + let layout = arcinner_layout_for_value_layout(value_layout); + + let ptr = allocate(layout).unwrap_or_else(|_| handle_alloc_error(layout)); + + // ignore-tidy-undocumented-unsafe + unsafe { Self::initialize_arcinner(ptr, layout, mem_to_arcinner) } + } + + /// Allocates an `ArcInner` with sufficient space for + /// a possibly-unsized inner value where the value has the layout provided, + /// returning an error if allocation fails. + /// + /// The function `mem_to_arcinner` is called with the data pointer + /// and must return back a (potentially fat)-pointer for the `ArcInner`. + unsafe fn try_allocate_for_layout( + value_layout: Layout, + allocate: impl FnOnce(Layout) -> Result, AllocError>, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> Result<*mut ArcInner, AllocError> { + let layout = arcinner_layout_for_value_layout(value_layout); + + let ptr = allocate(layout)?; + + // ignore-tidy-undocumented-unsafe + let inner = unsafe { Self::initialize_arcinner(ptr, layout, mem_to_arcinner) }; + + Ok(inner) + } + + unsafe fn initialize_arcinner( + ptr: NonNull<[u8]>, + layout: Layout, + mem_to_arcinner: impl FnOnce(*mut u8) -> *mut ArcInner, + ) -> *mut ArcInner { + let inner = mem_to_arcinner(ptr.as_non_null_ptr().as_ptr()); + // SAFETY: Upheld by caller. + debug_assert_eq!(unsafe { Layout::for_value_raw(inner) }, layout); + + // ignore-tidy-undocumented-unsafe + unsafe { + (&raw mut (*inner).strong).write(atomic::AtomicUsize::new(1)); + (&raw mut (*inner).weak).write(atomic::AtomicUsize::new(1)); + } + + inner + } +} + +impl Arc { + /// Allocates an `ArcInner` with sufficient space for an unsized inner value. + #[inline] + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_ptr_in(ptr: *const T, alloc: &A) -> *mut ArcInner { + // Allocate for the `ArcInner` using the given value. + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::allocate_for_layout( + Layout::for_value_raw(ptr), + |layout| alloc.allocate(layout), + |mem| mem.with_metadata_of(ptr as *const ArcInner), + ) + } + } + + #[cfg(not(no_global_oom_handling))] + fn from_box_in(/*@~mut@*/ src: Box) -> Arc { + // ignore-tidy-undocumented-unsafe + unsafe { + let value_size = size_of_val(&*src); + let ptr = Self::allocate_for_ptr_in(&*src, Box::allocator(&src)); + + // Copy value as bytes + ptr::copy_nonoverlapping( + (&raw const *src) as *const u8, + (&raw mut (*ptr).data) as *mut u8, + value_size, + ); + + // Free the allocation without dropping its contents + let (bptr, alloc) = Box::into_raw_with_allocator(src); + let src = Box::from_raw_in(bptr as *mut mem::ManuallyDrop, &alloc); + drop(src); + + Self::from_ptr_in(ptr, alloc) + } + } +} + +impl Arc<[T]> { + /// Allocates an `ArcInner<[T]>` with the given length. + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_slice(len: usize) -> *mut ArcInner<[T]> { + // ignore-tidy-undocumented-unsafe + unsafe { + Self::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| Global.allocate(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[T]>, + ) + } + } + + /// Copy elements from slice into newly allocated `Arc<[T]>` + /// + /// Unsafe because the caller must either take ownership, bind `T: Copy` or + /// bind `T: TrivialClone`. + #[cfg(not(no_global_oom_handling))] + unsafe fn copy_from_slice(v: &[T]) -> Arc<[T]> { + // ignore-tidy-undocumented-unsafe + unsafe { + let ptr = Self::allocate_for_slice(v.len()); + + ptr::copy_nonoverlapping(v.as_ptr(), (&raw mut (*ptr).data) as *mut T, v.len()); + + Self::from_ptr(ptr) + } + } + + /// Constructs an `Arc<[T]>` from an iterator known to be of a certain size. + /// + /// Behavior is undefined should the size be wrong. + #[cfg(not(no_global_oom_handling))] + unsafe fn from_iter_exact(iter: impl Iterator, len: usize) -> Arc<[T]> { + // Panic guard while cloning T elements. + // In the event of a panic, elements that have been written + // into the new ArcInner will be dropped, then the memory freed. + struct Guard { + mem: NonNull, + elems: *mut T, + layout: Layout, + n_elems: usize, + } + + impl Drop for Guard { + fn drop(&mut self) { + // ignore-tidy-undocumented-unsafe + unsafe { + let slice = from_raw_parts_mut(self.elems, self.n_elems); + ptr::drop_in_place(slice); + + Global.deallocate(self.mem, self.layout); + } + } + } + + // ignore-tidy-undocumented-unsafe + unsafe { + let ptr = Self::allocate_for_slice(len); + + let mem = ptr as *mut _ as *mut u8; + let layout = Layout::for_value_raw(ptr); + + // Pointer to first element + let elems = (&raw mut (*ptr).data) as *mut T; + + let mut guard = Guard { mem: NonNull::new_unchecked(mem), elems, layout, n_elems: 0 }; + + for (i, item) in iter.enumerate() { + ptr::write(elems.add(i), item); + guard.n_elems += 1; + } + + // All clear. Forget the guard so it doesn't free the new ArcInner. + mem::forget(guard); + + Self::from_ptr(ptr) + } + } +} + +impl Arc<[T], A> { + /// Allocates an `ArcInner<[T]>` with the given length. + #[inline] + #[cfg(not(no_global_oom_handling))] + unsafe fn allocate_for_slice_in(len: usize, alloc: &A) -> *mut ArcInner<[T]> { + // ignore-tidy-undocumented-unsafe + unsafe { + Arc::allocate_for_layout( + Layout::array::(len).unwrap(), + |layout| alloc.allocate(layout), + |mem| mem.cast::().cast_slice(len) as *mut ArcInner<[T]>, + ) + } + } +} + +/// Specialization trait used for `From<&[T]>`. +#[cfg(not(no_global_oom_handling))] +trait ArcFromSlice { + fn from_slice(slice: &[T]) -> Self; +} + +#[cfg(not(no_global_oom_handling))] +impl ArcFromSlice for Arc<[T]> { + #[inline] + default fn from_slice(v: &[T]) -> Self { + // ignore-tidy-undocumented-unsafe + unsafe { Self::from_iter_exact(v.iter().cloned(), v.len()) } + } +} + +#[cfg(not(no_global_oom_handling))] +impl ArcFromSlice for Arc<[T]> { + #[inline] + fn from_slice(v: &[T]) -> Self { + // SAFETY: `T` implements `TrivialClone`, so this is sound and equivalent + // to the above. + unsafe { Arc::copy_from_slice(v) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Clone for Arc { + /// Makes a clone of the `Arc` pointer. + /// + /// This creates another pointer to the same allocation, increasing the + /// strong reference count. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let _ = Arc::clone(&five); + /// ``` + #[inline] + fn clone(&self) -> Arc { + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object. + // + // As explained in the [Boost documentation][1], Increasing the + // reference counter can always be done with memory_order_relaxed: New + // references to an object can only be formed from an existing + // reference, and passing an existing reference from one thread to + // another must already provide any required synchronization. + // + // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) + let old_size = self.inner().strong.fetch_add(1, Relaxed); + + // However we need to guard against massive refcounts in case someone is `mem::forget`ing + // Arcs. If we don't do this the count can overflow and users will use-after free. This + // branch will never be taken in any realistic program. We abort because such a program is + // incredibly degenerate, and we don't care to support it. + // + // This check is not 100% water-proof: we error when the refcount grows beyond `isize::MAX`. + // But we do that check *after* having done the increment, so there is a chance here that + // the worst already happened and we actually do overflow the `usize` counter. However, that + // requires the counter to grow from `isize::MAX` to `usize::MAX` between the increment + // above and the `abort` below, which seems exceedingly unlikely. + // + // This is a global invariant, and also applies when using a compare-exchange loop to increment + // counters in other methods. + // Otherwise, the counter could be brought to an almost-overflow using a compare-exchange loop, + // and then overflow using a few `fetch_add`s. + if old_size > MAX_REFCOUNT { + intrinsics::abort(); + } + + // SAFETY: Pointer is valid & allocator corresponds to the one used to allocate it. + unsafe { Self::from_inner_in(self.ptr, self.alloc.clone()) } + } +} + +#[unstable(feature = "ergonomic_clones", issue = "132290")] +impl UseCloned for Arc {} + +#[unstable(feature = "share_trait", issue = "156756")] +impl Share for Arc {} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Deref for Arc { + type Target = T; + + #[inline] + fn deref(&self) -> &T { + &self.inner().data + } +} + +// The API of this pointer type enforces that if the `T` is pinned, then *all* +// clones of this `Arc` are wrapped as `Pin>`. Since an `&Arc` +// could be used to obtain an `Arc` that is not wrapped in `Pin` (and later +// used with `Arc::get_mut`), this means that this type treats `&Arc` as +// evidence that the `T` is not pinned. The implementations of various traits +// are written accordingly. Since this type is not fundamental, downstream +// crates cannot provide malicious implementations of any of the traits relevant +// for `Pin`. +#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")] +unsafe impl PinSafePointer for Arc {} + +#[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for Arc {} + +#[unstable(feature = "legacy_receiver_trait", issue = "none")] +impl LegacyReceiver for Arc {} + +#[cfg(not(no_global_oom_handling))] +impl Arc { + /// Makes a mutable reference into the given `Arc`. + /// + /// If there are other `Arc` pointers to the same allocation, then `make_mut` will + /// [`clone`] the inner value to a new allocation to ensure unique ownership. This is also + /// referred to as clone-on-write. + /// + /// However, if there are no other `Arc` pointers to this allocation, but some [`Weak`] + /// pointers, then the [`Weak`] pointers will be dissociated and the inner value will not + /// be cloned. + /// + /// See also [`get_mut`], which will fail rather than cloning the inner value + /// or dissociating [`Weak`] pointers. + /// + /// [`clone`]: Clone::clone + /// [`get_mut`]: Arc::get_mut + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut data = Arc::new(5); + /// + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// let mut other_data = Arc::clone(&data); // Won't clone inner data + /// *Arc::make_mut(&mut data) += 1; // Clones inner data + /// *Arc::make_mut(&mut data) += 1; // Won't clone anything + /// *Arc::make_mut(&mut other_data) *= 2; // Won't clone anything + /// + /// // Now `data` and `other_data` point to different allocations. + /// assert_eq!(*data, 8); + /// assert_eq!(*other_data, 12); + /// ``` + /// + /// [`Weak`] pointers will be dissociated: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut data = Arc::new(75); + /// let weak = Arc::downgrade(&data); + /// + /// assert!(75 == *data); + /// assert!(75 == *weak.upgrade().unwrap()); + /// + /// *Arc::make_mut(&mut data) += 1; + /// + /// assert!(76 == *data); + /// assert!(weak.upgrade().is_none()); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn make_mut(this: &mut Self) -> &mut T { + let size_of_val = size_of_val::(&**this); + + // Note that we hold both a strong reference and a weak reference. + // Thus, releasing our strong reference only will not, by itself, cause + // the memory to be deallocated. + // + // Use Acquire to ensure that we see any writes to `weak` that happen + // before release writes (i.e., decrements) to `strong`. Since we hold a + // weak count, there's no chance the ArcInner itself could be + // deallocated. + if this.inner().strong.compare_exchange(1, 0, Acquire, Relaxed).is_err() { + // Another strong pointer exists, so we must clone. + *this = Arc::clone_from_ref_in(&**this, this.alloc.clone()); + } else if this.inner().weak.load(Relaxed) != 1 { + // Relaxed suffices in the above because this is fundamentally an + // optimization: we are always racing with weak pointers being + // dropped. Worst case, we end up allocated a new Arc unnecessarily. + + // We removed the last strong ref, but there are additional weak + // refs remaining. We'll move the contents to a new Arc, and + // invalidate the other weak refs. + + // Note that it is not possible for the read of `weak` to yield + // usize::MAX (i.e., locked), since the weak count can only be + // locked by a thread with a strong reference. + + // Guard against panics while using the allocator. + // If we unwind before the Arc is overwritten, we expose a strong + // count of 0, resulting in a UAF (#155746, #157203). + // Until the new Arc is written, the old Arc must remain valid + struct Guard<'a, T: ?Sized> { + inner: &'a ArcInner, + } + impl<'a, T: ?Sized> Drop for Guard<'a, T> { + fn drop(&mut self) { + self.inner.strong.store(1, Release); + } + } + let guard = Guard { inner: this.inner() }; + + // Can just steal the data, all that's left is Weaks + // Note that this can panic in two ways: + // - The allocation can fail + // - The allocator clone can fail + let mut in_progress: UniqueArcUninit = + UniqueArcUninit::new(&**this, this.alloc.clone()); + + // ignore-tidy-undocumented-unsafe + unsafe { + // Initialize `in_progress` with move of **this. + // We have to express this in terms of bytes because `T: ?Sized`; there is no + // operation that just copies a value based on its `size_of_val()`. + ptr::copy_nonoverlapping( + ptr::from_ref(&**this).cast::(), + in_progress.data_ptr().cast::(), + size_of_val, + ); + + // We are now safe from panics. + mem::forget(guard); + + // Materialize our own implicit weak pointer, so that it can clean + // up the ArcInner as needed. + // Make sure the allocator is not leaked when the Arc is overwritten. + // Only drop at the end of the scope to avoid panics. + let _weak = Weak { ptr: this.ptr, alloc: ptr::read(&this.alloc) }; + + ptr::write(this, in_progress.into_arc()); + } + } else { + // We were the sole reference of either kind; bump back up the + // strong ref count. + this.inner().strong.store(1, Release); + } + + // SAFETY: As with `get_mut()`, our reference was + // either unique to begin with, or became one upon cloning the contents. + unsafe { Self::get_mut_unchecked(this) } + } +} + +impl Arc { + /// If we have the only reference to `T` then unwrap it. Otherwise, clone `T` and return the + /// clone. + /// + /// Assuming `arc_t` is of type `Arc`, this function is functionally equivalent to + /// `(*arc_t).clone()`, but will avoid cloning the inner value where possible. + /// + /// # Examples + /// + /// ``` + /// # use std::{ptr, sync::Arc}; + /// let inner = String::from("test"); + /// let ptr = inner.as_ptr(); + /// + /// let arc = Arc::new(inner); + /// let inner = Arc::unwrap_or_clone(arc); + /// // The inner value was not cloned + /// assert!(ptr::eq(ptr, inner.as_ptr())); + /// + /// let arc = Arc::new(inner); + /// let arc2 = arc.clone(); + /// let inner = Arc::unwrap_or_clone(arc); + /// // Because there were 2 references, we had to clone the inner value. + /// assert!(!ptr::eq(ptr, inner.as_ptr())); + /// // `arc2` is the last reference, so when we unwrap it we get back + /// // the original `String`. + /// let inner = Arc::unwrap_or_clone(arc2); + /// assert!(ptr::eq(ptr, inner.as_ptr())); + /// ``` + #[inline] + #[stable(feature = "arc_unwrap_or_clone", since = "1.76.0")] + pub fn unwrap_or_clone(this: Self) -> T { + Arc::try_unwrap(this).unwrap_or_else(|arc| (*arc).clone()) + } +} + +impl Arc { + /// Returns a mutable reference into the given `Arc`, if there are + /// no other `Arc` or [`Weak`] pointers to the same allocation. + /// + /// Returns [`None`] otherwise, because it is not safe to + /// mutate a shared value. + /// + /// See also [`make_mut`][make_mut], which will [`clone`][clone] + /// the inner value when there are other `Arc` pointers. + /// + /// [make_mut]: Arc::make_mut + /// [clone]: Clone::clone + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let mut x = Arc::new(3); + /// *Arc::get_mut(&mut x).unwrap() = 4; + /// assert_eq!(*x, 4); + /// + /// let _y = Arc::clone(&x); + /// assert!(Arc::get_mut(&mut x).is_none()); + /// ``` + #[inline] + #[stable(feature = "arc_unique", since = "1.4.0")] + pub fn get_mut(this: &mut Self) -> Option<&mut T> { + if Self::is_unique(this) { + // SAFETY: We're guaranteed that the pointer + // returned is the *only* pointer that will ever be returned to T. Our + // reference count is guaranteed to be 1 at this point, and we required + // the Arc itself to be `mut`, so we're returning the only possible + // reference to the inner data. + unsafe { Some(Arc::get_mut_unchecked(this)) } + } else { + None + } + } + + /// Returns a mutable reference into the given `Arc`, + /// without any check. + /// + /// See also [`get_mut`], which is safe and does appropriate checks. + /// + /// [`get_mut`]: Arc::get_mut + /// + /// # Safety + /// + /// If any other `Arc` or [`Weak`] pointers to the same allocation exist, then + /// they must not be dereferenced or have active borrows for the duration + /// of the returned borrow, and their inner type must be exactly the same as the + /// inner type of this Arc (including lifetimes). This is trivially the case if no + /// such pointers exist, for example immediately after `Arc::new`. + /// + /// # Examples + /// + /// ``` + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let mut x = Arc::new(String::new()); + /// unsafe { + /// Arc::get_mut_unchecked(&mut x).push_str("foo") + /// } + /// assert_eq!(*x, "foo"); + /// ``` + /// Other `Arc` pointers to the same allocation must be to the same type. + /// ```no_run + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let x: Arc = Arc::from("Hello, world!"); + /// let mut y: Arc<[u8]> = x.clone().into(); + /// unsafe { + /// // this is Undefined Behavior, because x's inner type is str, not [u8] + /// Arc::get_mut_unchecked(&mut y).fill(0xff); // 0xff is invalid in UTF-8 + /// } + /// println!("{}", &*x); // Invalid UTF-8 in a str + /// ``` + /// Other `Arc` pointers to the same allocation must be to the exact same type, including lifetimes. + /// ```no_run + /// #![feature(get_mut_unchecked)] + /// + /// use std::sync::Arc; + /// + /// let x: Arc<&str> = Arc::new("Hello, world!"); + /// { + /// let s = String::from("Oh, no!"); + /// let mut y: Arc<&str> = x.clone(); + /// unsafe { + /// // this is Undefined Behavior, because x's inner type + /// // is &'long str, not &'short str + /// *Arc::get_mut_unchecked(&mut y) = &s; + /// } + /// } + /// println!("{}", &*x); // Use-after-free + /// ``` + #[inline] + #[unstable(feature = "get_mut_unchecked", issue = "63292")] + pub unsafe fn get_mut_unchecked(this: &mut Self) -> &mut T { + // We are careful to *not* create a reference covering the "count" fields, as + // this would alias with concurrent access to the reference counts (e.g. by `Weak`). + // ignore-tidy-undocumented-unsafe + unsafe { &mut (*this.ptr.as_ptr()).data } + } + + /// Determine whether this is the unique reference to the underlying data. + /// + /// Returns `true` if there are no other `Arc` or [`Weak`] pointers to the same allocation; + /// returns `false` otherwise. + /// + /// If this function returns `true`, then it is guaranteed to be safe to call [`get_mut_unchecked`] + /// on this `Arc`, as long as no clones occur in between. + /// + /// The result can become stale if another thread can call `clone` or + /// `downgrade` through a shared reference. Make sure you have exclusive + /// access to the `Arc`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x = Arc::new(3); + /// assert!(Arc::is_unique(&x)); + /// + /// let y = Arc::clone(&x); + /// assert!(!Arc::is_unique(&x)); + /// drop(y); + /// + /// // Weak references also count, because they could be upgraded at any time. + /// let z = Arc::downgrade(&x); + /// assert!(!Arc::is_unique(&x)); + /// ``` + /// + /// # Pointer invalidation + /// + /// This function will always return the same value as `Arc::get_mut(arc).is_some()`. However, + /// unlike that operation it does not produce any mutable references to the underlying data, + /// meaning no pointers to the data inside the `Arc` are invalidated by the call. Thus, the + /// following code is valid: + /// + /// ``` + /// use std::sync::Arc; + /// + /// let arc = Arc::new(5); + /// let pointer: *const i32 = &*arc; + /// assert!(Arc::is_unique(&arc)); + /// assert_eq!(unsafe { *pointer }, 5); + /// ``` + /// + /// The following changes would make the example unsound: + /// + /// - Using `Arc::get_mut` to create a mutable reference while also accessing the value + /// through `pointer`. + /// - Dropping `arc` before dereferencing `pointer`, leaving it dangling. + /// + /// # Atomic orderings + /// + /// Concurrent drops to other `Arc` pointers to the same allocation will synchronize with this + /// call - that is, this call performs an `Acquire` operation on the underlying strong and weak + /// ref counts. This ensures that calling `get_mut_unchecked` is safe. + /// + /// Note that this operation requires locking the weak ref count, so concurrent calls to + /// `downgrade` may spin-loop for a short period of time. + /// + /// [`get_mut_unchecked`]: Self::get_mut_unchecked + #[inline] + #[stable(feature = "arc_is_unique", since = "1.101.0")] + pub fn is_unique(this: &Self) -> bool { + // lock the weak pointer count if we appear to be the sole weak pointer + // holder. + // + // The acquire label here ensures a happens-before relationship with any + // writes to `strong` (in particular in `Weak::upgrade`) prior to decrements + // of the `weak` count (via `Weak::drop`, which uses release). If the upgraded + // weak ref was never dropped, the CAS here will fail so we do not care to synchronize. + if this.inner().weak.compare_exchange(1, usize::MAX, Acquire, Relaxed).is_ok() { + // This needs to be an `Acquire` to synchronize with the decrement of the `strong` + // counter in `drop` -- the only access that happens when any but the last reference + // is being dropped. + let unique = this.inner().strong.load(Acquire) == 1; + + // The release write here synchronizes with a read in `downgrade`, + // effectively preventing the above read of `strong` from happening + // after the write. + this.inner().weak.store(1, Release); // release the lock + unique + } else { + false + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Arc { + /// Drops the `Arc`. + /// + /// This will decrement the strong reference count. If the strong reference + /// count reaches zero then the only other references (if any) are + /// [`Weak`], so we `drop` the inner value. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// struct Foo; + /// + /// impl Drop for Foo { + /// fn drop(&mut self) { + /// println!("dropped!"); + /// } + /// } + /// + /// let foo = Arc::new(Foo); + /// let foo2 = Arc::clone(&foo); + /// + /// drop(foo); // Doesn't print anything + /// drop(foo2); // Prints "dropped!" + /// ``` + #[inline] + fn drop(&mut self) { + // Because `fetch_sub` is already atomic, we do not need to synchronize + // with other threads unless we are going to delete the object. This + // same logic applies to the below `fetch_sub` to the `weak` count. + if self.inner().strong.fetch_sub(1, Release) != 1 { + return; + } + + // This fence is needed to prevent reordering of use of the data and + // deletion of the data. Because it is marked `Release`, the decreasing + // of the reference count synchronizes with this `Acquire` fence. This + // means that use of the data happens before decreasing the reference + // count, which happens before this fence, which happens before the + // deletion of the data. + // + // As explained in the [Boost documentation][1], + // + // > It is important to enforce any possible access to the object in one + // > thread (through an existing reference) to *happen before* deleting + // > the object in a different thread. This is achieved by a "release" + // > operation after dropping a reference (any access to the object + // > through this reference must obviously happened before), and an + // > "acquire" operation before deleting the object. + // + // In particular, while the contents of an Arc are usually immutable, it's + // possible to have interior writes to something like a Mutex. Since a + // Mutex is not acquired when it is deleted, we can't rely on its + // synchronization logic to make writes in thread A visible to a destructor + // running in thread B. + // + // Also note that the Acquire fence here could probably be replaced with an + // Acquire load, which could improve performance in highly-contended + // situations. See [2]. + // + // [1]: (www.boost.org/doc/libs/1_55_0/doc/html/atomic/usage_examples.html) + // [2]: (https://github.com/rust-lang/rust/pull/41714) + acquire!(self.inner().strong); + + // Make sure we aren't trying to "drop" the shared static for empty slices + // used by Default::default. + debug_assert!( + !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner), + "Arcs backed by a static should never reach a strong count of 0. \ + Likely decrement_strong_count or from_raw were called too many times.", + ); + + // ignore-tidy-undocumented-unsafe + unsafe { + self.drop_slow(); + } + } +} + +impl Arc { + /// Attempts to downcast the `Arc` to a concrete type. + /// + /// # Examples + /// + /// ``` + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// fn print_if_string(value: Arc) { + /// if let Ok(string) = value.downcast::() { + /// println!("String ({}): {}", string.len(), string); + /// } + /// } + /// + /// let my_string = "Hello World".to_string(); + /// print_if_string(Arc::new(my_string)); + /// print_if_string(Arc::new(0i8)); + /// ``` + #[inline] + #[stable(feature = "rc_downcast", since = "1.29.0")] + pub fn downcast(self) -> Result, Self> + where + T: Any + Send + Sync, + { + if (*self).is::() { + // SAFETY: Check ensures the typecast is okay. + unsafe { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + Ok(Arc::from_inner_in(ptr.cast(), alloc)) + } + } else { + Err(self) + } + } + + /// Downcasts the `Arc` to a concrete type. + /// + /// For a safe alternative see [`downcast`]. + /// + /// # Examples + /// + /// ``` + /// #![feature(downcast_unchecked)] + /// + /// use std::any::Any; + /// use std::sync::Arc; + /// + /// let x: Arc = Arc::new(1_usize); + /// + /// unsafe { + /// assert_eq!(*x.downcast_unchecked::(), 1); + /// } + /// ``` + /// + /// # Safety + /// + /// The contained value must be of type `T`. Calling this method + /// with the incorrect type is *undefined behavior*. + /// + /// + /// [`downcast`]: Self::downcast + #[inline] + #[unstable(feature = "downcast_unchecked", issue = "90850")] + #[cfg_attr(kani, requires((*self).is::()))] + #[cfg_attr(kani, ensures(|result| ub_checks::can_dereference(&**result as *const T)))] + pub unsafe fn downcast_unchecked(self) -> Arc + where + T: Any + Send + Sync, + { + // SAFETY: Upheld by caller. + unsafe { + let (ptr, alloc) = Arc::into_inner_with_allocator(self); + Arc::from_inner_in(ptr.cast(), alloc) + } + } +} + +impl Weak { + /// Constructs a new `Weak`, without allocating any memory. + /// Calling [`upgrade`] on the return value always gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// use std::sync::Weak; + /// + /// let empty: Weak = Weak::new(); + /// assert!(empty.upgrade().is_none()); + /// ``` + #[inline] + #[stable(feature = "downgraded_weak", since = "1.10.0")] + #[rustc_const_stable(feature = "const_weak_new", since = "1.73.0")] + #[must_use] + pub const fn new() -> Weak { + Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc: Global } + } +} + +impl Weak { + /// Constructs a new `Weak`, without allocating any memory, technically in the provided + /// allocator. + /// Calling [`upgrade`] on the return value always gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// + /// use std::sync::Weak; + /// use std::alloc::System; + /// + /// let empty: Weak = Weak::new_in(System); + /// assert!(empty.upgrade().is_none()); + /// ``` + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn new_in(alloc: A) -> Weak { + Weak { ptr: NonNull::without_provenance(NonZeroUsize::MAX), alloc } + } +} + +/// Helper type to allow accessing the reference counts without +/// making any assertions about the data field. +struct WeakInner<'a> { + weak: &'a Atomic, + strong: &'a Atomic, +} + +impl Weak { + /// Converts a raw pointer previously created by [`into_raw`] back into `Weak`. + /// + /// This can be used to safely get a strong reference (by calling [`upgrade`] + /// later) or to deallocate the weak count by dropping the `Weak`. + /// + /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], + /// as these don't own anything; the method still works on them). + /// + /// # Safety + /// + /// The pointer must have originated from the [`into_raw`] and must still own its potential + /// weak reference, and must point to a block of memory allocated by global allocator. + /// + /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this + /// takes ownership of one weak reference currently represented as a raw pointer (the weak + /// count is not modified by this operation) and therefore it must be paired with a previous + /// call to [`into_raw`]. + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// + /// let raw_1 = Arc::downgrade(&strong).into_raw(); + /// let raw_2 = Arc::downgrade(&strong).into_raw(); + /// + /// assert_eq!(2, Arc::weak_count(&strong)); + /// + /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); + /// assert_eq!(1, Arc::weak_count(&strong)); + /// + /// drop(strong); + /// + /// // Decrement the last weak count. + /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); + /// ``` + /// + /// [`new`]: Weak::new + /// [`into_raw`]: Weak::into_raw + /// [`upgrade`]: Weak::upgrade + #[inline] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub unsafe fn from_raw(ptr: *const T) -> Self { + // SAFETY: Upheld by caller. + unsafe { Weak::from_raw_in(ptr, Global) } + } + + /// Consumes the `Weak` and turns it into a raw pointer. + /// + /// This converts the weak pointer into a raw pointer, while still preserving the ownership of + /// one weak reference (the weak count is not modified by this operation). It can be turned + /// back into the `Weak` with [`from_raw`]. + /// + /// The same restrictions of accessing the target of the pointer as with + /// [`as_ptr`] apply. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// let weak = Arc::downgrade(&strong); + /// let raw = weak.into_raw(); + /// + /// assert_eq!(1, Arc::weak_count(&strong)); + /// assert_eq!("hello", unsafe { &*raw }); + /// + /// drop(unsafe { Weak::from_raw(raw) }); + /// assert_eq!(0, Arc::weak_count(&strong)); + /// ``` + /// + /// [`from_raw`]: Weak::from_raw + /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub fn into_raw(self) -> *const T { + ManuallyDrop::new(self).as_ptr() + } +} + +impl Weak { + /// Returns a reference to the underlying allocator. + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn allocator(&self) -> &A { + &self.alloc + } + + /// Returns a raw pointer to the object `T` pointed to by this `Weak`. + /// + /// The pointer is valid only if there are some strong references. The pointer may be dangling, + /// unaligned or even [`null`] otherwise. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::ptr; + /// + /// let strong = Arc::new("hello".to_owned()); + /// let weak = Arc::downgrade(&strong); + /// // Both point to the same object + /// assert!(ptr::eq(&*strong, weak.as_ptr())); + /// // The strong here keeps it alive, so we can still access the object. + /// assert_eq!("hello", unsafe { &*weak.as_ptr() }); + /// + /// drop(strong); + /// // But not any more. We can do weak.as_ptr(), but accessing the pointer would lead to + /// // undefined behavior. + /// // assert_eq!("hello", unsafe { &*weak.as_ptr() }); + /// ``` + /// + /// [`null`]: core::ptr::null "ptr::null" + #[must_use] + #[stable(feature = "weak_into_raw", since = "1.45.0")] + pub fn as_ptr(&self) -> *const T { + let ptr: *mut ArcInner = NonNull::as_ptr(self.ptr); + + if is_dangling(ptr) { + // If the pointer is dangling, we return the sentinel directly. This cannot be + // a valid payload address, as the payload is at least as aligned as ArcInner (usize). + ptr as *const T + } else { + // SAFETY: if is_dangling returns false, then the pointer is dereferenceable. + // The payload may be dropped at this point, and we have to maintain provenance, + // so use raw pointer manipulation. + unsafe { &raw mut (*ptr).data } + } + } + + /// Consumes the `Weak`, returning the wrapped pointer and allocator. + /// + /// This converts the weak pointer into a raw pointer, while still preserving the ownership of + /// one weak reference (the weak count is not modified by this operation). It can be turned + /// back into the `Weak` with [`from_raw_in`]. + /// + /// The same restrictions of accessing the target of the pointer as with + /// [`as_ptr`] apply. + /// + /// # Examples + /// + /// ``` + /// #![feature(allocator_ext)] + /// use std::sync::{Arc, Weak}; + /// use std::alloc::System; + /// + /// let strong = Arc::new_in("hello".to_owned(), System); + /// let weak = Arc::downgrade(&strong); + /// let (raw, alloc) = weak.into_raw_with_allocator(); + /// + /// assert_eq!(1, Arc::weak_count(&strong)); + /// assert_eq!("hello", unsafe { &*raw }); + /// + /// drop(unsafe { Weak::from_raw_in(raw, alloc) }); + /// assert_eq!(0, Arc::weak_count(&strong)); + /// ``` + /// + /// [`from_raw_in`]: Weak::from_raw_in + /// [`as_ptr`]: Weak::as_ptr + #[must_use = "losing the pointer will leak memory"] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub fn into_raw_with_allocator(self) -> (*const T, A) { + let /*@~mut@*/ this = mem::ManuallyDrop::new(self); + let result = this.as_ptr(); + // SAFETY: `this` is ManuallyDrop so the allocator will not be double-dropped + let alloc = unsafe { ptr::read(&this.alloc) }; + (result, alloc) + } + + /// Converts a raw pointer previously created by [`into_raw`] back into `Weak` in the provided + /// allocator. + /// + /// This can be used to safely get a strong reference (by calling [`upgrade`] + /// later) or to deallocate the weak count by dropping the `Weak`. + /// + /// It takes ownership of one weak reference (with the exception of pointers created by [`new`], + /// as these don't own anything; the method still works on them). + /// + /// # Safety + /// + /// The pointer must have originated from the [`into_raw`] and must still own its potential + /// weak reference, and must point to a block of memory allocated by `alloc`. + /// + /// It is allowed for the strong count to be 0 at the time of calling this. Nevertheless, this + /// takes ownership of one weak reference currently represented as a raw pointer (the weak + /// count is not modified by this operation) and therefore it must be paired with a previous + /// call to [`into_raw`]. + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let strong = Arc::new("hello".to_owned()); + /// + /// let raw_1 = Arc::downgrade(&strong).into_raw(); + /// let raw_2 = Arc::downgrade(&strong).into_raw(); + /// + /// assert_eq!(2, Arc::weak_count(&strong)); + /// + /// assert_eq!("hello", &*unsafe { Weak::from_raw(raw_1) }.upgrade().unwrap()); + /// assert_eq!(1, Arc::weak_count(&strong)); + /// + /// drop(strong); + /// + /// // Decrement the last weak count. + /// assert!(unsafe { Weak::from_raw(raw_2) }.upgrade().is_none()); + /// ``` + /// + /// [`new`]: Weak::new + /// [`into_raw`]: Weak::into_raw + /// [`upgrade`]: Weak::upgrade + #[inline] + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] + pub unsafe fn from_raw_in(ptr: *const T, alloc: A) -> Self { + // See Weak::as_ptr for context on how the input pointer is derived. + + let ptr = if is_dangling(ptr) { + // This is a dangling Weak. + ptr as *mut ArcInner + } else { + // Otherwise, we're guaranteed the pointer came from a nondangling Weak. + // SAFETY: data_offset is safe to call, as ptr references a real (potentially dropped) T. + let offset = unsafe { data_offset(ptr) }; + // Thus, we reverse the offset to get the whole ArcInner. + // SAFETY: the pointer originated from a Weak, so this offset is safe. + unsafe { ptr.byte_sub(offset) as *mut ArcInner } + }; + + // SAFETY: we now have recovered the original Weak pointer, so can create the Weak. + Weak { ptr: unsafe { NonNull::new_unchecked(ptr) }, alloc } + } +} + +impl Weak { + /// Attempts to upgrade the `Weak` pointer to an [`Arc`], delaying + /// dropping of the inner value if successful. + /// + /// Returns [`None`] in the following cases: + /// + /// 1. The inner value has since been dropped or moved out. + /// + /// 2. This `Weak` does not point to an allocation. + /// + /// 3. The owning reference this `Weak` is associated with is either not fully-constructed or does not allow an upgrade. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// let weak_five = Arc::downgrade(&five); + /// + /// let strong_five: Option> = weak_five.upgrade(); + /// assert!(strong_five.is_some()); + /// + /// // Destroy all strong pointers. + /// drop(strong_five); + /// drop(five); + /// + /// assert!(weak_five.upgrade().is_none()); + /// ``` + #[must_use = "this returns a new `Arc`, \ + without modifying the original weak pointer"] + #[stable(feature = "arc_weak", since = "1.4.0")] + pub fn upgrade(&self) -> Option> + where + A: AllocatorClone, + { + #[inline] + fn checked_increment(n: usize) -> Option { + // Any write of 0 we can observe leaves the field in permanently zero state. + if n == 0 { + return None; + } + // See comments in `Arc::clone` for why we do this (for `mem::forget`). + if n > MAX_REFCOUNT { + panic_arc_overflow(); + } + Some(n + 1) + } + + // We use a CAS loop to increment the strong count instead of a + // fetch_add as this function should never take the reference count + // from zero to one. + // + // Relaxed is fine for the failure case because we don't have any expectations about the new state. + // Acquire is necessary for the success case to synchronise with `Arc::new_cyclic`, when the inner + // value can be initialized after `Weak` references have already been created. In that case, we + // expect to observe the fully initialized value. + if self.inner()?.strong.try_update(Acquire, Relaxed, checked_increment).is_ok() { + // SAFETY: pointer is not null, verified in checked_increment + unsafe { Some(Arc::from_inner_in(self.ptr, self.alloc.clone())) } + } else { + None + } + } + + /// Gets the number of strong (`Arc`) pointers pointing to this allocation. + /// + /// If `self` was created using [`Weak::new`], this will return 0. + #[must_use] + #[stable(feature = "weak_counts", since = "1.41.0")] + pub fn strong_count(&self) -> usize { + if let Some(inner) = self.inner() { inner.strong.load(Relaxed) } else { 0 } + } + + /// Gets an approximation of the number of `Weak` pointers pointing to this + /// allocation. + /// + /// If `self` was created using [`Weak::new`], or if there are no remaining + /// strong pointers, this will return 0. + /// + /// # Accuracy + /// + /// Due to implementation details, the returned value can be off by 1 in + /// either direction when other threads are manipulating any `Arc`s or + /// `Weak`s pointing to the same allocation. + #[must_use] + #[stable(feature = "weak_counts", since = "1.41.0")] + pub fn weak_count(&self) -> usize { + if let Some(inner) = self.inner() { + let weak = inner.weak.load(Acquire); + let strong = inner.strong.load(Relaxed); + if strong == 0 { + 0 + } else { + // Since we observed that there was at least one strong pointer + // after reading the weak count, we know that the implicit weak + // reference (present whenever any strong references are alive) + // was still around when we observed the weak count, and can + // therefore safely subtract it. + weak - 1 + } + } else { + 0 + } + } + + /// Returns `None` when the pointer is dangling and there is no allocated `ArcInner`, + /// (i.e., when this `Weak` was created by `Weak::new`). + #[inline] + fn inner(&self) -> Option> { + let ptr = self.ptr.as_ptr(); + if is_dangling(ptr) { + None + } else { + // We are careful to *not* create a reference covering the "data" field, as + // the field may be mutated concurrently (for example, if the last `Arc` + // is dropped, the data field will be dropped in-place). + // ignore-tidy-undocumented-unsafe + Some(unsafe { WeakInner { strong: &(*ptr).strong, weak: &(*ptr).weak } }) + } + } + + /// Returns `true` if the two `Weak`s point to the same allocation similar to [`ptr::eq`], or if + /// both don't point to any allocation (because they were created with `Weak::new()`). However, + /// this function ignores the metadata of `dyn Trait` pointers. + /// + /// # Notes + /// + /// Since this compares pointers it means that `Weak::new()` will equal each + /// other, even though they don't point to any allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let first_rc = Arc::new(5); + /// let first = Arc::downgrade(&first_rc); + /// let second = Arc::downgrade(&first_rc); + /// + /// assert!(first.ptr_eq(&second)); + /// + /// let third_rc = Arc::new(5); + /// let third = Arc::downgrade(&third_rc); + /// + /// assert!(!first.ptr_eq(&third)); + /// ``` + /// + /// Comparing `Weak::new`. + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let first = Weak::new(); + /// let second = Weak::new(); + /// assert!(first.ptr_eq(&second)); + /// + /// let third_rc = Arc::new(()); + /// let third = Arc::downgrade(&third_rc); + /// assert!(!first.ptr_eq(&third)); + /// ``` + /// + /// [`ptr::eq`]: core::ptr::eq "ptr::eq" + #[inline] + #[must_use] + #[stable(feature = "weak_ptr_eq", since = "1.39.0")] + pub fn ptr_eq(&self, other: &Self) -> bool { + ptr::addr_eq(self.ptr.as_ptr(), other.ptr.as_ptr()) + } +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +impl Clone for Weak { + /// Makes a clone of the `Weak` pointer that points to the same allocation. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// let weak_five = Arc::downgrade(&Arc::new(5)); + /// + /// let _ = Weak::clone(&weak_five); + /// ``` + #[inline] + fn clone(&self) -> Weak { + if let Some(inner) = self.inner() { + // See comments in Arc::clone() for why this is relaxed. This can use a + // fetch_add (ignoring the lock) because the weak count is only locked + // where are *no other* weak pointers in existence. (So we can't be + // running this code in that case). + let old_size = inner.weak.fetch_add(1, Relaxed); + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { + intrinsics::abort(); + } + } + + Weak { ptr: self.ptr, alloc: self.alloc.clone() } + } +} + +#[unstable(feature = "ergonomic_clones", issue = "132290")] +impl UseCloned for Weak {} + +#[stable(feature = "downgraded_weak", since = "1.10.0")] +impl Default for Weak { + /// Constructs a new `Weak`, without allocating memory. + /// Calling [`upgrade`] on the return value always + /// gives [`None`]. + /// + /// [`upgrade`]: Weak::upgrade + /// + /// # Examples + /// + /// ``` + /// use std::sync::Weak; + /// + /// let empty: Weak = Default::default(); + /// assert!(empty.upgrade().is_none()); + /// ``` + fn default() -> Weak { + Weak::new() + } +} + +#[stable(feature = "arc_weak", since = "1.4.0")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for Weak { + /// Drops the `Weak` pointer. + /// + /// # Examples + /// + /// ``` + /// use std::sync::{Arc, Weak}; + /// + /// struct Foo; + /// + /// impl Drop for Foo { + /// fn drop(&mut self) { + /// println!("dropped!"); + /// } + /// } + /// + /// let foo = Arc::new(Foo); + /// let weak_foo = Arc::downgrade(&foo); + /// let other_weak_foo = Weak::clone(&weak_foo); + /// + /// drop(weak_foo); // Doesn't print anything + /// drop(foo); // Prints "dropped!" + /// + /// assert!(other_weak_foo.upgrade().is_none()); + /// ``` + fn drop(&mut self) { + // If we find out that we were the last weak pointer, then its time to + // deallocate the data entirely. See the discussion in Arc::drop() about + // the memory orderings + // + // It's not necessary to check for the locked state here, because the + // weak count can only be locked if there was precisely one weak ref, + // meaning that drop could only subsequently run ON that remaining weak + // ref, which can only happen after the lock is released. + let inner = if let Some(inner) = self.inner() { inner } else { return }; + + if inner.weak.fetch_sub(1, Release) == 1 { + acquire!(inner.weak); + + // Make sure we aren't trying to "deallocate" the shared static for empty slices + // used by Default::default. + debug_assert!( + !ptr::addr_eq(self.ptr.as_ptr(), &STATIC_INNER_SLICE.inner), + "Arc/Weaks backed by a static should never be deallocated. \ + Likely decrement_strong_count or from_raw were called too many times.", + ); + + // ignore-tidy-undocumented-unsafe + unsafe { + self.alloc.deallocate(self.ptr.cast(), Layout::for_value_raw(self.ptr.as_ptr())) + } + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +trait ArcEqIdent { + fn eq(&self, other: &Arc) -> bool; + fn ne(&self, other: &Arc) -> bool; +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + default fn eq(&self, other: &Arc) -> bool { + **self == **other + } + #[inline] + default fn ne(&self, other: &Arc) -> bool { + **self != **other + } +} + +/// We're doing this specialization here, and not as a more general optimization on `&T`, because it +/// would otherwise add a cost to all equality checks on refs. We assume that `Arc`s are used to +/// store large values, that are slow to clone, but also heavy to check for equality, causing this +/// cost to pay off more easily. It's also more likely to have two `Arc` clones, that point to +/// the same value, than two `&T`s. +/// +/// We can only do this when `T: Eq` as a `PartialEq` might be deliberately irreflexive. +#[stable(feature = "rust1", since = "1.0.0")] +impl ArcEqIdent for Arc { + #[inline] + fn eq(&self, other: &Arc) -> bool { + ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) || **self == **other + } + + #[inline] + fn ne(&self, other: &Arc) -> bool { + !ptr::eq(self.ptr.as_ptr(), other.ptr.as_ptr()) && **self != **other + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialEq for Arc { + /// Equality for two `Arc`s. + /// + /// Two `Arc`s are equal if their inner values are equal, even if they are + /// stored in different allocation. + /// + /// If `T` also implements `Eq` (implying reflexivity of equality), + /// two `Arc`s that point to the same allocation are always equal. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five == Arc::new(5)); + /// ``` + #[inline] + fn eq(&self, other: &Arc) -> bool { + ArcEqIdent::eq(self, other) + } + + /// Inequality for two `Arc`s. + /// + /// Two `Arc`s are not equal if their inner values are not equal. + /// + /// If `T` also implements `Eq` (implying reflexivity of equality), + /// two `Arc`s that point to the same value are always equal. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five != Arc::new(6)); + /// ``` + #[inline] + fn ne(&self, other: &Arc) -> bool { + ArcEqIdent::ne(self, other) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl PartialOrd for Arc { + /// Partial comparison for two `Arc`s. + /// + /// The two are compared by calling `partial_cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::cmp::Ordering; + /// + /// let five = Arc::new(5); + /// + /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&Arc::new(6))); + /// ``` + fn partial_cmp(&self, other: &Arc) -> Option { + (**self).partial_cmp(&**other) + } + + /// Less-than comparison for two `Arc`s. + /// + /// The two are compared by calling `<` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five < Arc::new(6)); + /// ``` + fn lt(&self, other: &Arc) -> bool { + *(*self) < *(*other) + } + + /// 'Less than or equal to' comparison for two `Arc`s. + /// + /// The two are compared by calling `<=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five <= Arc::new(5)); + /// ``` + fn le(&self, other: &Arc) -> bool { + *(*self) <= *(*other) + } + + /// Greater-than comparison for two `Arc`s. + /// + /// The two are compared by calling `>` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five > Arc::new(4)); + /// ``` + fn gt(&self, other: &Arc) -> bool { + *(*self) > *(*other) + } + + /// 'Greater than or equal to' comparison for two `Arc`s. + /// + /// The two are compared by calling `>=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let five = Arc::new(5); + /// + /// assert!(five >= Arc::new(5)); + /// ``` + fn ge(&self, other: &Arc) -> bool { + *(*self) >= *(*other) + } +} +#[stable(feature = "rust1", since = "1.0.0")] +impl Ord for Arc { + /// Comparison for two `Arc`s. + /// + /// The two are compared by calling `cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// use std::cmp::Ordering; + /// + /// let five = Arc::new(5); + /// + /// assert_eq!(Ordering::Less, five.cmp(&Arc::new(6))); + /// ``` + fn cmp(&self, other: &Arc) -> Ordering { + (**self).cmp(&**other) + } +} +#[stable(feature = "rust1", since = "1.0.0")] +impl Eq for Arc {} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Display for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Debug for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl fmt::Pointer for Arc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&(&raw const **self), f) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "rust1", since = "1.0.0")] +impl Default for Arc { + /// Creates a new `Arc`, with the `Default` value for `T`. + /// + /// # Examples + /// + /// ``` + /// use std::sync::Arc; + /// + /// let x: Arc = Default::default(); + /// assert_eq!(*x, 0); + /// ``` + fn default() -> Arc { + // ignore-tidy-undocumented-unsafe + unsafe { + Self::from_inner(Box::into_non_null(Box::write( + Box::new_uninit(), + ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: T::default(), + }, + ))) + } + } +} + +/// Struct to hold the static `ArcInner` used for empty `Arc` as +/// returned by `Default::default`. +/// +/// Layout notes: +/// * `repr(align(16))` so we can use it for `[T]` with `align_of::() <= 16`. +/// * `repr(C)` so `inner` is at offset 0 (and thus guaranteed to actually be aligned to 16). +/// * `[u8; 1]` (to be initialized with 0) so it can be used for `Arc`. +#[repr(C, align(16))] +struct SliceArcInnerForStatic { + inner: ArcInner<[u8; 1]>, +} +#[cfg(not(no_global_oom_handling))] +const MAX_STATIC_INNER_SLICE_ALIGNMENT: usize = 16; + +static STATIC_INNER_SLICE: SliceArcInnerForStatic = SliceArcInnerForStatic { + inner: ArcInner { + strong: atomic::AtomicUsize::new(1), + weak: atomic::AtomicUsize::new(1), + data: [0], + }, +}; + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc { + /// Creates an empty str inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + let arc: Arc<[u8]> = Default::default(); + debug_assert!(core::str::from_utf8(&arc).is_ok()); + let (ptr, alloc) = Arc::into_inner_with_allocator(arc); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_ptr_in(ptr.as_ptr() as *mut ArcInner, alloc) } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc { + /// Creates an empty CStr inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + use core::ffi::CStr; + let inner: NonNull> = NonNull::from(&STATIC_INNER_SLICE.inner); + let inner: NonNull> = + NonNull::new(inner.as_ptr() as *mut ArcInner).unwrap(); + // `this` semantically is the Arc "owned" by the static, so make sure not to drop it. + let this: mem::ManuallyDrop> = + // ignore-tidy-undocumented-unsafe + unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) }; + (*this).clone() + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "more_rc_default_impls", since = "1.80.0")] +impl Default for Arc<[T]> { + /// Creates an empty `[T]` inside an Arc + /// + /// This may or may not share an allocation with other Arcs. + #[inline] + fn default() -> Self { + if align_of::() <= MAX_STATIC_INNER_SLICE_ALIGNMENT { + // We take a reference to the whole struct instead of the ArcInner<[u8; 1]> inside it so + // we don't shrink the range of bytes the ptr is allowed to access under Stacked Borrows. + // (Miri complains on 32-bit targets with Arc<[Align16]> otherwise.) + // (Note that NonNull::from(&STATIC_INNER_SLICE.inner) is fine under Tree Borrows.) + let inner: NonNull = NonNull::from(&STATIC_INNER_SLICE); + let inner: NonNull> = inner.cast(); + // `this` semantically is the Arc "owned" by the static, so make sure not to drop it. + let this: mem::ManuallyDrop> = + // ignore-tidy-undocumented-unsafe + unsafe { mem::ManuallyDrop::new(Arc::from_inner(inner)) }; + return (*this).clone(); + } + + // If T's alignment is too large for the static, make a new unique allocation. + let arr: [T; 0] = []; + Arc::from(arr) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "pin_default_impls", since = "1.91.0")] +impl Default for Pin> +where + T: ?Sized, + Arc: Default, +{ + #[inline] + fn default() -> Self { + // SAFETY: We own and create the pinned pointer. + unsafe { Pin::new_unchecked(Arc::::default()) } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl Hash for Arc { + fn hash(&self, state: &mut H) { + (**self).hash(state) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "from_for_ptrs", since = "1.6.0")] +impl From for Arc { + /// Converts a `T` into an `Arc` + /// + /// The conversion moves the value into a + /// newly allocated `Arc`. It is equivalent to + /// calling `Arc::new(t)`. + /// + /// # Example + /// ```rust + /// # use std::sync::Arc; + /// let x = 5; + /// let arc = Arc::new(5); + /// + /// assert_eq!(Arc::from(x), arc); + /// ``` + fn from(t: T) -> Self { + Arc::new(t) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_array", since = "1.74.0")] +impl From<[T; N]> for Arc<[T]> { + /// Converts a [`[T; N]`](prim@array) into an `Arc<[T]>`. + /// + /// The conversion moves the array into a newly allocated `Arc`. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let original: [i32; 3] = [1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: [T; N]) -> Arc<[T]> { + Arc::<[T; N]>::from(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From<&[T]> for Arc<[T]> { + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let original: &[i32] = &[1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: &[T]) -> Arc<[T]> { + >::from_slice(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_mut_slice", since = "1.84.0")] +impl From<&mut [T]> for Arc<[T]> { + /// Allocates a reference-counted slice and fills it by cloning `v`'s items. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let mut original = [1, 2, 3]; + /// let original: &mut [i32] = &mut original; + /// let shared: Arc<[i32]> = Arc::from(original); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: &mut [T]) -> Arc<[T]> { + Arc::from(&*v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From<&str> for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let shared: Arc = Arc::from("eggplant"); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: &str) -> Arc { + let arc = Arc::<[u8]>::from(v.as_bytes()); + // ignore-tidy-undocumented-unsafe + unsafe { Arc::from_raw(Arc::into_raw(arc) as *const str) } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_mut_slice", since = "1.84.0")] +impl From<&mut str> for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let mut original = String::from("eggplant"); + /// let original: &mut str = &mut original; + /// let shared: Arc = Arc::from(original); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: &mut str) -> Arc { + Arc::from(&*v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From for Arc { + /// Allocates a reference-counted `str` and copies `v` into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: String = "eggplant".to_owned(); + /// let shared: Arc = Arc::from(unique); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: String) -> Arc { + Arc::from(&v[..]) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From> for Arc { + /// Move a boxed object to a new, reference-counted allocation. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: Box = Box::from("eggplant"); + /// let shared: Arc = Arc::from(unique); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(v: Box) -> Arc { + Arc::from_box_in(v) + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_slice", since = "1.21.0")] +impl From> for Arc<[T], A> { + /// Allocates a reference-counted slice and moves `v`'s items into it. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let unique: Vec = vec![1, 2, 3]; + /// let shared: Arc<[i32]> = Arc::from(unique); + /// assert_eq!(&[1, 2, 3], &shared[..]); + /// ``` + #[inline] + fn from(v: Vec) -> Arc<[T], A> { + // ignore-tidy-undocumented-unsafe + unsafe { + let (vec_ptr, len, cap, /*@~mut@*/ alloc) = v.into_raw_parts_with_allocator(); + + let rc_ptr = Self::allocate_for_slice_in(len, &alloc); + ptr::copy_nonoverlapping(vec_ptr, (&raw mut (*rc_ptr).data) as *mut T, len); + + // Create a `Vec` with length 0, to deallocate the buffer + // without dropping its contents or the allocator + let _ = Vec::from_raw_parts_in(vec_ptr, 0, cap, &alloc); + + Self::from_ptr_in(rc_ptr, alloc) + } + } +} + +#[stable(feature = "shared_from_cow", since = "1.45.0")] +impl<'a, B> From> for Arc +where + B: ToOwned + ?Sized, + Arc: From<&'a B> + From, +{ + /// Creates an atomically reference-counted pointer from a clone-on-write + /// pointer by copying its content. + /// + /// # Example + /// + /// ```rust + /// # use std::sync::Arc; + /// # use std::borrow::Cow; + /// let cow: Cow<'_, str> = Cow::Borrowed("eggplant"); + /// let shared: Arc = Arc::from(cow); + /// assert_eq!("eggplant", &shared[..]); + /// ``` + #[inline] + fn from(cow: Cow<'a, B>) -> Arc { + match cow { + Cow::Borrowed(s) => Arc::from(s), + Cow::Owned(s) => Arc::from(s), + } + } +} + +#[stable(feature = "shared_from_str", since = "1.62.0")] +impl From> for Arc<[u8]> { + /// Converts an atomically reference-counted string slice into a byte slice. + /// + /// # Example + /// + /// ``` + /// # use std::sync::Arc; + /// let string: Arc = Arc::from("eggplant"); + /// let bytes: Arc<[u8]> = Arc::from(string); + /// assert_eq!("eggplant".as_bytes(), bytes.as_ref()); + /// ``` + #[inline] + fn from(rc: Arc) -> Self { + // SAFETY: `str` has the same layout as `[u8]`. + unsafe { Arc::from_raw(Arc::into_raw(rc) as *const [u8]) } + } +} + +#[stable(feature = "boxed_slice_try_from", since = "1.43.0")] +impl TryFrom> for Arc<[T; N], A> { + type Error = Arc<[T], A>; + + fn try_from(boxed_slice: Arc<[T], A>) -> Result { + if boxed_slice.len() == N { + let (ptr, alloc) = Arc::into_inner_with_allocator(boxed_slice); + // ignore-tidy-undocumented-unsafe + Ok(unsafe { Arc::from_inner_in(ptr.cast(), alloc) }) + } else { + Err(boxed_slice) + } + } +} + +#[cfg(not(no_global_oom_handling))] +#[stable(feature = "shared_from_iter", since = "1.37.0")] +impl FromIterator for Arc<[T]> { + /// Takes each element in the `Iterator` and collects it into an `Arc<[T]>`. + /// + /// # Performance characteristics + /// + /// ## The general case + /// + /// In the general case, collecting into `Arc<[T]>` is done by first + /// collecting into a `Vec`. That is, when writing the following: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0).collect(); + /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); + /// ``` + /// + /// this behaves as if we wrote: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).filter(|&x| x % 2 == 0) + /// .collect::>() // The first set of allocations happens here. + /// .into(); // A second allocation for `Arc<[T]>` happens here. + /// # assert_eq!(&*evens, &[0, 2, 4, 6, 8]); + /// ``` + /// + /// This will allocate as many times as needed for constructing the `Vec` + /// and then it will allocate once for turning the `Vec` into the `Arc<[T]>`. + /// + /// ## Iterators of known length + /// + /// When your `Iterator` implements `TrustedLen` and is of an exact size, + /// a single allocation will be made for the `Arc<[T]>`. For example: + /// + /// ```rust + /// # use std::sync::Arc; + /// let evens: Arc<[u8]> = (0..10).collect(); // Just a single allocation happens here. + /// # assert_eq!(&*evens, &*(0..10).collect::>()); + /// ``` + fn from_iter>(iter: I) -> Self { + ToArcSlice::to_arc_slice(iter.into_iter()) + } +} + +#[cfg(not(no_global_oom_handling))] +/// Specialization trait used for collecting into `Arc<[T]>`. +trait ToArcSlice: Iterator + Sized { + fn to_arc_slice(self) -> Arc<[T]>; +} + +#[cfg(not(no_global_oom_handling))] +impl> ToArcSlice for I { + default fn to_arc_slice(self) -> Arc<[T]> { + self.collect::>().into() + } +} + +#[cfg(not(no_global_oom_handling))] +impl> ToArcSlice for I { + fn to_arc_slice(self) -> Arc<[T]> { + // This is the case for a `TrustedLen` iterator. + let (low, high) = self.size_hint(); + if let Some(high) = high { + debug_assert_eq!( + low, + high, + "TrustedLen iterator's size hint is not exact: {:?}", + (low, high) + ); + + // SAFETY: We need to ensure that the iterator has an exact length and we have. + unsafe { Arc::from_iter_exact(self, low) } + } else { + // TrustedLen contract guarantees that `upper_bound == None` implies an iterator + // length exceeding `usize::MAX`. + // The default implementation would collect into a vec which would panic. + // Thus we panic here immediately without invoking `Vec` code. + panic!("capacity overflow"); + } + } +} + +#[stable(feature = "rust1", since = "1.0.0")] +impl borrow::Borrow for Arc { + fn borrow(&self) -> &T { + self + } +} + +#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")] +impl AsRef for Arc { + fn as_ref(&self) -> &T { + self + } +} + +#[stable(feature = "pin", since = "1.33.0")] +impl Unpin for Arc {} + +/// Gets the offset within an `ArcInner` for the payload behind a pointer. +/// +/// # Safety +/// +/// The pointer must point to (and have valid metadata for) a previously +/// valid instance of T, but the T is allowed to be dropped. +unsafe fn data_offset(ptr: *const T) -> usize { + // Align the unsized value to the end of the ArcInner. + // Because ArcInner is repr(C), it will always be the last field in memory. + // SAFETY: since the only unsized types possible are slices, trait objects, + // and extern types, the input safety requirement is currently enough to + // satisfy the requirements of Alignment::of_val_raw; this is an implementation + // detail of the language that must not be relied upon outside of std. + unsafe { data_offset_alignment(Alignment::of_val_raw(ptr)) } +} + +#[inline] +fn data_offset_alignment(alignment: Alignment) -> usize { + let /*@~mut@*/ layout = Layout::new::>(); + layout.size() + layout.padding_needed_for(alignment) +} + +/// A unique owning pointer to an [`ArcInner`] **that does not imply the contents are initialized,** +/// but will deallocate it (without dropping the value) when dropped. +/// +/// This is a helper for [`Arc::make_mut()`] to ensure correct cleanup on panic. +struct UniqueArcUninit { + ptr: NonNull>, + layout_for_value: Layout, + alloc: Option, +} + +impl UniqueArcUninit { + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it. + #[cfg(not(no_global_oom_handling))] + fn new(for_value: &T, alloc: A) -> UniqueArcUninit { + let layout = Layout::for_value(for_value); + // ignore-tidy-undocumented-unsafe + let ptr = unsafe { + Arc::allocate_for_layout( + layout, + |layout_for_arcinner| alloc.allocate(layout_for_arcinner), + |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner), + ) + }; + Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) } + } + + /// Allocates an ArcInner with layout suitable to contain `for_value` or a clone of it, + /// returning an error if allocation fails. + fn try_new(for_value: &T, alloc: A) -> Result, AllocError> { + let layout = Layout::for_value(for_value); + // ignore-tidy-undocumented-unsafe + let ptr = unsafe { + Arc::try_allocate_for_layout( + layout, + |layout_for_arcinner| alloc.allocate(layout_for_arcinner), + |mem| mem.with_metadata_of(ptr::from_ref(for_value) as *const ArcInner), + )? + }; + Ok(Self { ptr: NonNull::new(ptr).unwrap(), layout_for_value: layout, alloc: Some(alloc) }) + } + + /// Returns the pointer to be written into to initialize the [`Arc`]. + fn data_ptr(&mut self) -> *mut T { + let offset = data_offset_alignment(self.layout_for_value.alignment()); + // ignore-tidy-undocumented-unsafe + unsafe { self.ptr.as_ptr().byte_add(offset) as *mut T } + } + + /// Upgrade this into a normal [`Arc`]. + /// + /// # Safety + /// + /// The data must have been initialized (by writing to [`Self::data_ptr()`]). + unsafe fn into_arc(self) -> Arc { + let mut this = ManuallyDrop::new(self); + let ptr = this.ptr.as_ptr(); + let alloc = this.alloc.take().unwrap(); + + // SAFETY: The pointer is valid as per `UniqueArcUninit::new`, and the caller is responsible + // for having initialized the data. + unsafe { Arc::from_ptr_in(ptr, alloc) } + } +} + +impl Drop for UniqueArcUninit { + fn drop(&mut self) { + // SAFETY: + // * new() produced a pointer safe to deallocate. + // * We own the pointer unless into_arc() was called, which forgets us. + unsafe { + self.alloc.take().unwrap().deallocate( + self.ptr.cast(), + arcinner_layout_for_value_layout(self.layout_for_value), + ); + } + } +} + +#[stable(feature = "arc_error", since = "1.52.0")] +impl core::error::Error for Arc { + #[allow(deprecated)] + fn cause(&self) -> Option<&dyn core::error::Error> { + core::error::Error::cause(&**self) + } + + fn source(&self) -> Option<&(dyn core::error::Error + 'static)> { + core::error::Error::source(&**self) + } + + fn provide<'a>(&'a self, req: &mut core::error::Request<'a>) { + core::error::Error::provide(&**self, req); + } +} + +/// A uniquely owned [`Arc`]. +/// +/// This represents an `Arc` that is known to be uniquely owned -- that is, have exactly one strong +/// reference. Multiple weak pointers can be created, but attempts to upgrade those to strong +/// references will fail unless the `UniqueArc` they point to has been converted into a regular `Arc`. +/// +/// Because it is uniquely owned, the contents of a `UniqueArc` can be freely mutated. A common +/// use case is to have an object be mutable during its initialization phase but then have it become +/// immutable and converted to a normal `Arc`. +/// +/// This can be used as a flexible way to create cyclic data structures, as in the example below. +/// +/// ``` +/// #![feature(unique_rc_arc)] +/// use std::sync::{Arc, Weak, UniqueArc}; +/// +/// struct Gadget { +/// me: Weak, +/// } +/// +/// fn create_gadget() -> Option> { +/// let mut rc = UniqueArc::new(Gadget { +/// me: Weak::new(), +/// }); +/// rc.me = UniqueArc::downgrade(&rc); +/// Some(UniqueArc::into_arc(rc)) +/// } +/// +/// create_gadget().unwrap(); +/// ``` +/// +/// An advantage of using `UniqueArc` over [`Arc::new_cyclic`] to build cyclic data structures is that +/// [`Arc::new_cyclic`]'s `data_fn` parameter cannot be async or return a [`Result`]. As shown in the +/// previous example, `UniqueArc` allows for more flexibility in the construction of cyclic data, +/// including fallible or async constructors. +#[unstable(feature = "unique_rc_arc", issue = "112566")] +pub struct UniqueArc< + T: ?Sized, + #[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] A: Allocator = Global, +> { + ptr: NonNull>, + // Define the ownership of `ArcInner` for drop-check + _marker: PhantomData>, + // Invariance is necessary for soundness: once other `Weak` + // references exist, we already have a form of shared mutability! + _marker2: PhantomData<*mut T>, + alloc: A, +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl Send for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl Sync for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +// #[unstable(feature = "coerce_unsized", issue = "18598")] +impl, U: ?Sized, A: Allocator> CoerceUnsized> + for UniqueArc +{ +} + +//#[unstable(feature = "unique_rc_arc", issue = "112566")] +#[unstable(feature = "dispatch_from_dyn", issue = "none")] +impl, U: ?Sized> DispatchFromDyn> for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Display for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Display::fmt(&**self, f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Debug for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&**self, f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl fmt::Pointer for UniqueArc { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Pointer::fmt(&(&raw const **self), f) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl borrow::Borrow for UniqueArc { + fn borrow(&self) -> &T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl borrow::BorrowMut for UniqueArc { + fn borrow_mut(&mut self) -> &mut T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl AsRef for UniqueArc { + fn as_ref(&self) -> &T { + self + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl AsMut for UniqueArc { + fn as_mut(&mut self) -> &mut T { + self + } +} + +#[cfg(not(no_global_oom_handling))] +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl From for UniqueArc { + #[inline(always)] + fn from(value: T) -> Self { + Self::new(value) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Unpin for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl PartialEq for UniqueArc { + /// Equality for two `UniqueArc`s. + /// + /// Two `UniqueArc`s are equal if their inner values are equal. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five == UniqueArc::new(5)); + /// ``` + #[inline] + fn eq(&self, other: &Self) -> bool { + PartialEq::eq(&**self, &**other) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl PartialOrd for UniqueArc { + /// Partial comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `partial_cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// use std::cmp::Ordering; + /// + /// let five = UniqueArc::new(5); + /// + /// assert_eq!(Some(Ordering::Less), five.partial_cmp(&UniqueArc::new(6))); + /// ``` + #[inline(always)] + fn partial_cmp(&self, other: &UniqueArc) -> Option { + (**self).partial_cmp(&**other) + } + + /// Less-than comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `<` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five < UniqueArc::new(6)); + /// ``` + #[inline(always)] + fn lt(&self, other: &UniqueArc) -> bool { + **self < **other + } + + /// 'Less than or equal to' comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `<=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five <= UniqueArc::new(5)); + /// ``` + #[inline(always)] + fn le(&self, other: &UniqueArc) -> bool { + **self <= **other + } + + /// Greater-than comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `>` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five > UniqueArc::new(4)); + /// ``` + #[inline(always)] + fn gt(&self, other: &UniqueArc) -> bool { + **self > **other + } + + /// 'Greater than or equal to' comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `>=` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// + /// let five = UniqueArc::new(5); + /// + /// assert!(five >= UniqueArc::new(5)); + /// ``` + #[inline(always)] + fn ge(&self, other: &UniqueArc) -> bool { + **self >= **other + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Ord for UniqueArc { + /// Comparison for two `UniqueArc`s. + /// + /// The two are compared by calling `cmp()` on their inner values. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// use std::sync::UniqueArc; + /// use std::cmp::Ordering; + /// + /// let five = UniqueArc::new(5); + /// + /// assert_eq!(Ordering::Less, five.cmp(&UniqueArc::new(6))); + /// ``` + #[inline] + fn cmp(&self, other: &UniqueArc) -> Ordering { + (**self).cmp(&**other) + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Eq for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Hash for UniqueArc { + fn hash(&self, state: &mut H) { + (**self).hash(state); + } +} + +impl UniqueArc { + /// Creates a new `UniqueArc`. + /// + /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading + /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`]. + /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will + /// point to the new [`Arc`]. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn new(value: T) -> Self { + Self::new_in(value, Global) + } + + /// Like [`new`](Self::new), but returns an error if the allocation + /// fails, instead of calling [`handle_alloc_error`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + pub fn try_new(value: T) -> Result { + Self::try_new_in(value, Global) + } +} + +impl UniqueArc { + /// Creates a new `UniqueArc` in the provided allocator. + /// + /// Weak references to this `UniqueArc` can be created with [`UniqueArc::downgrade`]. Upgrading + /// these weak references will fail before the `UniqueArc` has been converted into an [`Arc`]. + /// After converting the `UniqueArc` into an [`Arc`], any weak references created beforehand will + /// point to the new [`Arc`]. + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + #[must_use] + pub fn new_in(data: T, alloc: A) -> Self { + let (ptr, alloc) = Box::into_non_null_with_allocator(Box::new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + // keep one weak reference so if all the weak pointers that are created are dropped + // the UniqueArc still stays valid. + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + )); + Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc } + } + + /// Like [`new_in`](Self::new_in), but returns an error if the allocation + /// fails, instead of calling [`handle_alloc_error`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + pub fn try_new_in(data: T, alloc: A) -> Result { + let (ptr, alloc) = Box::into_non_null_with_allocator(Box::try_new_in( + ArcInner { + strong: atomic::AtomicUsize::new(0), + // keep one weak reference so if all the weak pointers that are created are dropped + // the UniqueArc still stays valid. + weak: atomic::AtomicUsize::new(1), + data, + }, + alloc, + )?); + Ok(Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc }) + } + + /// Consumes the `UniqueArc`, returning its wrapped value and allocator. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + // #[unstable(feature = "allocator_api", issue = "163177")] + #[must_use] + pub fn unwrap_with_allocator(this: Self) -> (T, A) { + let inner_ptr = this.ptr; + let (data_ptr, alloc) = Self::into_raw_with_allocator(this); + + // SAFETY: Conceptually moves out of the `UniqueRc`. + // We do not use the data inside ever again. + let val = unsafe { data_ptr.read() }; + + // Drop the strong-weak ref + drop(Weak { ptr: inner_ptr, alloc: &alloc }); + + (val, alloc) + } + + /// Consumes the `UniqueArc`, returning its wrapped value. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn unwrap(this: Self) -> T { + Self::unwrap_with_allocator(this).0 + } + + /// Maps the value in a `UniqueArc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `UniqueArc`, and the result is returned, + /// also in a `UniqueArc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `UniqueArc::map(u, f)` instead of `u.map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(unique_rc_arc)] + /// + /// use std::sync::UniqueArc; + /// + /// let r = UniqueArc::new(7); + /// let new = UniqueArc::map(r, |i| i + 7); + /// assert_eq!(*new, 14); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "unique_rc_arc", issue = "112566")] + pub fn map(this: Self, f: impl FnOnce(T) -> U) -> UniqueArc { + if size_of::() == size_of::() + && align_of::() == align_of::() + && UniqueArc::weak_count(&this) == 0 + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this); + let value = ptr.read(); + let allocation = + UniqueArc::from_raw_with_allocator(ptr.cast::>(), alloc); + + UniqueArc::write(allocation, f(value)) + } + } else { + let (val, alloc) = UniqueArc::unwrap_with_allocator(this); + UniqueArc::new_in(f(val), alloc) + } + } + + /// Attempts to map the value in a `UniqueArc`, reusing the allocation if possible. + /// + /// `f` is called on a reference to the value in the `UniqueArc`, and if the operation succeeds, + /// the result is returned, also in a `UniqueArc`. + /// + /// Note: this is an associated function, which means that you have + /// to call it as `UniqueArc::try_map(u, f)` instead of `u.try_map(f)`. This + /// is so that there is no conflict with a method on the inner type. + /// + /// # Examples + /// + /// ``` + /// #![feature(smart_pointer_try_map)] + /// #![feature(unique_rc_arc)] + /// + /// use std::sync::UniqueArc; + /// + /// let b = UniqueArc::new(7); + /// let new = UniqueArc::try_map(b, u32::try_from).unwrap(); + /// assert_eq!(*new, 7); + /// ``` + #[cfg(not(no_global_oom_handling))] + #[unstable(feature = "smart_pointer_try_map", issue = "144419")] + pub fn try_map( + this: Self, + f: impl FnOnce(T) -> R, + ) -> >>::TryType + where + R: Try, + R::Residual: Residual>, + { + if size_of::() == size_of::() + && align_of::() == align_of::() + && UniqueArc::weak_count(&this) == 0 + { + // ignore-tidy-undocumented-unsafe + unsafe { + let (ptr, alloc) = UniqueArc::into_raw_with_allocator(this); + let value = ptr.read(); + let allocation = UniqueArc::from_raw_with_allocator( + ptr.cast::>(), + alloc, + ); + + try { UniqueArc::write(allocation, f(value)?) } + } + } else { + let (val, alloc) = UniqueArc::unwrap_with_allocator(this); + try { UniqueArc::new_in(f(val)?, alloc) } + } + } +} + +impl UniqueArc { + #[cfg(not(no_global_oom_handling))] + unsafe fn from_raw_with_allocator(ptr: *const T, alloc: A) -> Self { + // SAFETY: Upheld by caller. + let offset = unsafe { data_offset(ptr) }; + + // Reverse the offset to find the original ArcInner. + // SAFETY: Upheld by caller. + let rc_ptr = unsafe { ptr.byte_sub(offset) as *mut ArcInner }; + + Self { + // SAFETY: Upheld by caller. + ptr: unsafe { NonNull::new_unchecked(rc_ptr) }, + _marker: PhantomData, + _marker2: PhantomData, + alloc, + } + } + + fn into_raw_with_allocator(this: Self) -> (*const T, A) { + let /*@~mut@*/ this = ManuallyDrop::new(this); + // SAFETY: The copy of the allocator stored in `this` is forgotten + (Self::as_ptr(&*this), unsafe { ptr::read(&this.alloc) }) + } + + /// Converts the `UniqueArc` into a regular [`Arc`]. + /// + /// This consumes the `UniqueArc` and returns a regular [`Arc`] that contains the `value` that + /// is passed to `into_arc`. + /// + /// Any weak references created before this method is called can now be upgraded to strong + /// references. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn into_arc(this: Self) -> Arc { + let this = ManuallyDrop::new(this); + + // Move the allocator out. + // SAFETY: `this.alloc` will not be accessed again, nor dropped because it is in + // a `ManuallyDrop`. + let alloc: A = unsafe { ptr::read(&this.alloc) }; + + // SAFETY: This pointer was allocated at creation time so we know it is valid. + unsafe { + // Convert our weak reference into a strong reference + (*this.ptr.as_ptr()).strong.store(1, Release); + Arc::from_inner_in(this.ptr, alloc) + } + } + + #[cfg(not(no_global_oom_handling))] + fn weak_count(this: &Self) -> usize { + this.inner().weak.load(Acquire) - 1 + } + + #[cfg(not(no_global_oom_handling))] + fn inner(&self) -> &ArcInner { + // SAFETY: while this UniqueArc is alive we're guaranteed that the inner pointer is valid. + unsafe { self.ptr.as_ref() } + } + + fn as_ptr(this: &Self) -> *const T { + let ptr: *mut ArcInner = NonNull::as_ptr(this.ptr); + + // SAFETY: This cannot go through Deref::deref or UniqueArc::inner because + // this is required to retain raw/mut provenance such that e.g. `get_mut` can + // write through the pointer after the Rc is recovered through `from_raw`. + unsafe { &raw mut (*ptr).data } + } + + #[inline] + fn into_inner_with_allocator(this: Self) -> (NonNull>, A) { + let this = mem::ManuallyDrop::new(this); + // SAFETY: Pointer is valid for reads and only read once. + (this.ptr, unsafe { ptr::read(&this.alloc) }) + } + + #[inline] + unsafe fn from_inner_in(ptr: NonNull>, alloc: A) -> Self { + Self { ptr, _marker: PhantomData, _marker2: PhantomData, alloc } + } +} + +impl UniqueArc { + /// Creates a new weak reference to the `UniqueArc`. + /// + /// Attempting to upgrade this weak reference will fail before the `UniqueArc` has been converted + /// to a [`Arc`] using [`UniqueArc::into_arc`]. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn downgrade(this: &Self) -> Weak { + // Using a relaxed ordering is alright here, as knowledge of the + // original reference prevents other threads from erroneously deleting + // the object or converting the object to a normal `Arc`. + // + // Note that we don't need to test if the weak counter is locked because there + // are no such operations like `Arc::get_mut` or `Arc::make_mut` that will lock + // the weak counter. + // + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let old_size = unsafe { (*this.ptr.as_ptr()).weak.fetch_add(1, Relaxed) }; + + // See comments in Arc::clone() for why we do this (for mem::forget). + if old_size > MAX_REFCOUNT { + intrinsics::abort(); + } + + Weak { ptr: this.ptr, alloc: this.alloc.clone() } + } +} + +impl UniqueArc, A> { + /// Writes the value and converts to `UniqueArc`. + /// + /// This method converts similarly to [`assume_init`](Self::assume_init) but + /// writes `value` into it before conversion, thus guaranteeing safety. + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub fn write(mut this: Self, value: T) -> UniqueArc { + // SAFETY: Writing initialises the wrapped value. + unsafe { + this.write(value); + this.assume_init() + } + } + + /// Converts to `UniqueArc`. + /// + /// # Safety + /// + /// As with [`MaybeUninit::assume_init`], + /// it is up to the caller to guarantee that the value + /// really is in an initialized state. + /// Calling this when the content is not yet fully initialized + /// causes immediate undefined behavior. + /// + /// [`MaybeUninit::assume_init`]: mem::MaybeUninit::assume_init + #[unstable(feature = "unique_rc_arc", issue = "112566")] + #[must_use] + pub unsafe fn assume_init(self) -> UniqueArc { + let (ptr, alloc) = UniqueArc::into_inner_with_allocator(self); + // SAFETY: Upheld by caller. + unsafe { UniqueArc::from_inner_in(ptr.cast(), alloc) } + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl Deref for UniqueArc { + type Target = T; + + fn deref(&self) -> &T { + // SAFETY: This pointer was allocated at creation time so we know it is valid. + unsafe { &self.ptr.as_ref().data } + } +} + +// #[unstable(feature = "unique_rc_arc", issue = "112566")] +#[unstable(feature = "pin_coerce_unsized_trait", issue = "150112")] +unsafe impl PinSafePointer for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +impl DerefMut for UniqueArc { + fn deref_mut(&mut self) -> &mut T { + // SAFETY: This pointer was allocated at creation time so we know it is valid. We know we + // have unique ownership and therefore it's safe to make a mutable reference because + // `UniqueArc` owns the only strong reference to itself. + // We also need to be careful to only create a mutable reference to the `data` field, + // as a mutable reference to the entire `ArcInner` would assert uniqueness over the + // ref count fields too, invalidating any attempt by `Weak`s to access the ref count. + unsafe { &mut (*self.ptr.as_ptr()).data } + } +} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +// #[unstable(feature = "deref_pure_trait", issue = "87121")] +unsafe impl DerefPure for UniqueArc {} + +#[unstable(feature = "unique_rc_arc", issue = "112566")] +unsafe impl<#[may_dangle] T: ?Sized, A: Allocator> Drop for UniqueArc { + fn drop(&mut self) { + // See `Arc::drop_slow` which drops an `Arc` with a strong count of 0. + // SAFETY: This pointer was allocated at creation time so we know it is valid. + let _weak = Weak { ptr: self.ptr, alloc: &self.alloc }; + + // ignore-tidy-undocumented-unsafe + unsafe { ptr::drop_in_place(&mut (*self.ptr.as_ptr()).data) }; + } +} + +#[stable(feature = "allocator_api", since = "1.100.0")] +unsafe impl Allocator for Arc { + #[inline] + fn allocate(&self, layout: Layout) -> Result, AllocError> { + (**self).allocate(layout) + } + + #[inline] + fn allocate_zeroed(&self, layout: Layout) -> Result, AllocError> { + (**self).allocate_zeroed(layout) + } + + #[inline] + unsafe fn deallocate(&self, ptr: NonNull, layout: Layout) { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).deallocate(ptr, layout) } + } + + #[inline] + unsafe fn grow( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn grow_zeroed( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).grow_zeroed(ptr, old_layout, new_layout) } + } + + #[inline] + unsafe fn shrink( + &self, + ptr: NonNull, + old_layout: Layout, + new_layout: Layout, + ) -> Result, AllocError> { + // SAFETY: the safety contract must be upheld by the caller + unsafe { (**self).shrink(ptr, old_layout, new_layout) } + } +} + +/// This trait impl is unstable and only usable on nightly with `feature(allocator_ext)`. +#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] +#[unstable_feature_bound(allocator_ext)] +impl AllocatorNightly for Arc {} + +#[unstable(feature = "allocator_ext", issue = "163177", implied_by = "allocator_api")] +unsafe impl AllocatorClone for Arc {} + +#[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::::downcast_unchecked::)] + pub fn check_downcast_unchecked_i32() { + let value: i32 = kani::any(); + let shared: bool = kani::any(); + let erased: Arc = + 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::() }; + assert!(*arc == value); + assert!(Arc::strong_count(&arc) == expected_strong); + drop(extra); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::)] + pub fn check_downcast_unchecked_bool() { + let value: bool = kani::any(); + let erased: Arc = + if kani::any() { Arc::new(value) } else { Arc::new(0u16) }; + let arc = unsafe { erased.downcast_unchecked::() }; + assert!(*arc == value); + cover_reached(); + } + + #[kani::proof_for_contract(Arc::::downcast_unchecked::<()>)] + pub fn check_downcast_unchecked_zst() { + let erased: Arc = + 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 = Arc::new(value); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + 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 = Arc::new(other); + let extra = if shared { Some(Arc::clone(&erased)) } else { None }; + let expected_strong = if shared { 2 } else { 1 }; + match erased.downcast::() { + Ok(_) => unreachable!("mismatched concrete type must downcast to Err"), + Err(orig) => { + assert!((*orig).is::()); + assert!(Arc::strong_count(&orig) == expected_strong); + kani::cover(true, "downcast Err branch reached"); + } + } + drop(extra); + } + } +} diff --git a/verifast-proofs/alloc/rcs/arc.rs/with-directives/lib.rs b/verifast-proofs/alloc/rcs/arc.rs/with-directives/lib.rs new file mode 100644 index 0000000000000..08331cfa27538 --- /dev/null +++ b/verifast-proofs/alloc/rcs/arc.rs/with-directives/lib.rs @@ -0,0 +1,104 @@ +// verifast_options{skip_specless_fns ignore_unwind_paths} + +#![allow(dead_code)] +#![allow(unused_features)] +#![allow(internal_features)] +#![allow(incomplete_features)] +#![no_std] +#![stable(feature = "rust1", since = "1.0.0")] + +#![feature(allocator_api)] +#![feature(allocator_ext)] +#![feature(allow_internal_unstable)] +#![feature(box_into_inner)] +#![feature(cast_maybe_uninit)] +#![feature(cell_get_cloned)] +#![feature(cfg_sanitize)] +#![feature(clone_to_uninit)] +#![feature(coerce_unsized)] +#![feature(const_clone)] +#![feature(const_cmp)] +#![feature(const_convert)] +#![feature(const_default)] +#![feature(const_destruct)] +#![feature(const_drop_in_place)] +#![feature(const_eval_select)] +#![feature(const_heap)] +#![feature(const_option_ops)] +#![feature(const_trait_impl)] +#![feature(const_try)] +#![feature(core_intrinsics)] +#![feature(deref_pure_trait)] +#![feature(diagnostic_on_move)] +#![feature(dispatch_from_dyn)] +#![feature(dropck_eyepatch)] +#![feature(ergonomic_clones)] +#![feature(error_generic_member_access)] +#![feature(exact_size_is_empty)] +#![feature(extend_one)] +#![feature(generic_atomic)] +#![feature(hasher_prefixfree_extras)] +#![feature(intrinsics)] +#![feature(legacy_receiver_trait)] +#![feature(likely_unlikely)] +#![feature(maybe_uninit_array_assume_init)] +#![feature(maybe_uninit_fill)] +#![feature(min_specialization)] +#![feature(panic_internals)] +#![feature(pin_coerce_unsized_trait)] +#![feature(ptr_alignment_type)] +#![feature(ptr_cast_array)] +#![feature(ptr_cast_slice)] +#![feature(ptr_internals)] +#![feature(ptr_metadata)] +#![feature(register_tool)] +#![feature(rustc_attrs)] +#![feature(rustdoc_internals)] +#![feature(set_ptr_value)] +#![feature(share_trait)] +#![feature(sized_type_properties)] +#![feature(slice_from_ptr_range)] +#![feature(slice_internals)] +#![feature(slice_ptr_get)] +#![feature(specialization)] +#![feature(staged_api)] +#![feature(std_internals)] +#![feature(temporary_niche_types)] +#![feature(trivial_clone)] +#![feature(trusted_len)] +#![feature(try_blocks)] +#![feature(try_trait_v2)] +#![feature(try_trait_v2_residual)] +#![feature(ub_checks)] +#![feature(unsize)] +#![feature(unsized_fn_params)] +#![register_tool(lint)] + +extern crate alloc as std; + +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::alloc as alloc; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::borrow as borrow; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::boxed as boxed; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::collections as collections; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::string as string; +#[stable(feature = "rust1", since = "1.0.0")] +pub use std::vec as vec; + +mod rc { + pub(crate) fn is_dangling(ptr: *const T) -> bool { + (ptr.cast::<()>()).addr() == usize::MAX + } + #[rustc_specialization_trait] + pub(crate) trait MarkerEq: Eq {} +} + +#[stable(feature = "rust1", since = "1.0.0")] +pub mod arc; + +extern crate arc_atomic_cas; +extern crate arc_pin; diff --git a/verifast-proofs/check-verifast-proofs.sh b/verifast-proofs/check-verifast-proofs.sh index 23bd82948efbd..8cb0963d88bfd 100755 --- a/verifast-proofs/check-verifast-proofs.sh +++ b/verifast-proofs/check-verifast-proofs.sh @@ -17,4 +17,10 @@ cd alloc bash verify.sh cd .. cd .. + cd rcs + cd arc.rs + bash atomic_model/verify.sh + bash verify.sh + cd .. + cd .. cd .. diff --git a/verifast-proofs/patch-verifast-proofs.sh b/verifast-proofs/patch-verifast-proofs.sh index 802b68ba7b68a..810a518729869 100755 --- a/verifast-proofs/patch-verifast-proofs.sh +++ b/verifast-proofs/patch-verifast-proofs.sh @@ -22,3 +22,6 @@ popd pushd alloc/raw_vec/mod.rs patch_proof popd +pushd alloc/rcs/arc.rs + patch_proof +popd