Skip to main content

vstd_extra/external/
smart_ptr.rs

1use crate::ownership::*;
2use crate::raw_ptr_extra::*;
3use alloc::boxed::Box;
4use alloc::sync::Arc;
5use vstd::layout::valid_layout;
6use vstd::prelude::*;
7use vstd::raw_ptr::*;
8#[cfg(feature = "irc11")]
9use vstd::thread_view::Objective;
10
11// A unified interface for the raw ptr permission returned by `into_raw` methods of smart pointers like `Box` and `Arc`.
12verus! {
13
14/// A verification-only trait that abstracts the permission that tracks both the pointer and the value it points to.
15pub trait PtrPointsToTrait {
16    /// The type of the pointer.
17    type Ptr;
18
19    /// The type of the value that the pointer points to.
20    type Target;
21
22    spec fn ptr(self) -> *mut Self::Target;
23
24    spec fn view_target(self) -> Self::Target;
25}
26
27impl<T> PtrPointsToTrait for BoxPointsTo<T> {
28    type Ptr = Box<T>;
29
30    type Target = T;
31
32    open spec fn ptr(self) -> *mut T {
33        self.perm.ptr()
34    }
35
36    open spec fn view_target(self) -> T {
37        self.perm.value()
38    }
39}
40
41impl<T> PtrPointsToTrait for ArcPointsTo<T> {
42    type Ptr = Arc<T>;
43
44    type Target = T;
45
46    open spec fn ptr(self) -> *mut T {
47        self.perm().ptr()
48    }
49
50    open spec fn view_target(self) -> T {
51        self.perm().value()
52    }
53}
54
55// The permission to access memory given by the `into_raw` methods of smart pointers like `Box` and `Arc`.
56/// For `Box<T>`, the `into_raw` method gives you the ownership of the memory
57pub tracked struct BoxPointsTo<T> {
58    pub perm: PointsTowithDealloc<T>,
59}
60
61/// Shared access to an Arc allocation.
62/// TODO: This legacy model does not distinguish read access from ownership;
63/// its tokens can be reconstructed and do not enforce one-time Arc recovery.
64pub tracked struct ArcPointsTo<T: 'static> {
65    pub perm: &'static PointsTo<T>,
66}
67
68// Raw-memory ownership is global state and does not depend on a thread's
69// subjective weak-memory view.
70#[cfg(feature = "irc11")]
71unsafe impl<T> Objective for BoxPointsTo<T> {
72
73}
74
75#[cfg(feature = "irc11")]
76unsafe impl<T> Objective for ArcPointsTo<T> {
77
78}
79
80impl<T> BoxPointsTo<T> {
81    pub open spec fn perm(self) -> PointsTowithDealloc<T> {
82        self.perm
83    }
84
85    pub open spec fn ptr(self) -> *mut T {
86        self.perm.ptr()
87    }
88
89    pub open spec fn addr(self) -> usize {
90        self.ptr().addr()
91    }
92
93    pub open spec fn is_init(self) -> bool {
94        self.perm.is_init()
95    }
96
97    pub open spec fn value(self) -> T {
98        self.perm.value()
99    }
100
101    pub proof fn tracked_get_points_to_with_dealloc(tracked self) -> (tracked ret:
102        PointsTowithDealloc<T>)
103        returns
104            self.perm,
105    {
106        self.perm
107    }
108
109    pub proof fn tracked_borrow_points_to_with_dealloc(tracked &self) -> (tracked ret:
110        &PointsTowithDealloc<T>)
111        returns
112            &self.perm,
113    {
114        &self.perm
115    }
116
117    pub proof fn tracked_get_points_to(tracked self) -> (tracked ret: PointsTo<T>)
118        returns
119            self.perm.points_to,
120    {
121        self.tracked_get_points_to_with_dealloc().tracked_get_points_to()
122    }
123
124    pub proof fn tracked_borrow_points_to(tracked &self) -> (tracked ret: &PointsTo<T>)
125        returns
126            &self.perm.points_to,
127    {
128        &self.tracked_borrow_points_to_with_dealloc().tracked_borrow_points_to()
129    }
130}
131
132impl<T> ArcPointsTo<T> {
133    pub open spec fn perm(self) -> &'static PointsTo<T> {
134        self.perm
135    }
136
137    pub open spec fn ptr(self) -> *mut T {
138        self.perm().ptr()
139    }
140
141    pub open spec fn addr(self) -> usize {
142        self.ptr().addr()
143    }
144
145    pub open spec fn is_init(self) -> bool {
146        self.perm().is_init()
147    }
148
149    pub open spec fn value(self) -> T {
150        self.perm().value()
151    }
152
153    pub proof fn tracked_borrow_points_to(tracked &self) -> (tracked ret: &'static PointsTo<T>)
154        returns
155            self.perm(),
156    {
157        self.perm
158    }
159}
160
161impl<T> Inv for Box<T> {
162    open spec fn inv(self) -> bool {
163        true
164    }
165}
166
167impl<T> Inv for Arc<T> {
168    open spec fn inv(self) -> bool {
169        true
170    }
171}
172
173impl<T> Inv for BoxPointsTo<T> {
174    open spec fn inv(self) -> bool {
175        &&& self.perm.inv()
176        &&& self.perm.dealloc_aligned()
177        &&& self.perm.is_init()
178    }
179}
180
181impl<T> Inv for ArcPointsTo<T> {
182    open spec fn inv(self) -> bool {
183        &&& self.addr() != 0
184        &&& self.addr() as int % vstd::layout::align_of::<T>() as int == 0
185        &&& self.is_init()
186    }
187}
188
189} // verus!
190/// A wrapper around `Box::into_raw` that also returns the permission to access the memory.
191///
192/// Soundness: it is unsound to create a `ptr` method for `Box<T>` that returns the raw pointer without the permission.
193/// As Verus only compares the value of the `Box<T>` for equality, so the following code will be wrongly verified:
194/// ```rust
195/// let b1 = Box::new(1);
196/// let b2 = Box::new(1);
197/// assert(b1.ptr() == b2.ptr()); // this will be verified but is actually not true, as b1 and b2 are different allocations with different pointers.
198/// ```
199// VERUS LIMITATION: can not add ghost parameter in external specification yet, sp we wrap it in an external_body function
200// The memory layout ensures that Box<T> has the following properties:
201//  1. The pointer is aligned.
202//  2. The pointer is non-null even for zero-sized types.
203//  3. The pointer points to a valid value, whose layout is determined by Layout::for_value (exactly size_of::<T>() and align_of::<T>()).
204// See https://doc.rust-lang.org/stable/std/boxed/index.html
205// Its guarantee is actually much stronger than PointsTowithDealloc.inv().
206#[verifier::external_body]
207#[verus_spec(ret =>
208    with
209        -> perm: Tracked<(PointsTo<T>, Option<Dealloc>)>,
210    ensures
211        ret == perm@.0.ptr(),
212        perm@.0.ptr().addr() != 0,
213        perm@.0.is_init(),
214        perm@.0.ptr().addr() as int % vstd::layout::align_of::<T>() as int == 0,
215        perm@.0.value() == *b,
216        match perm@.1 {
217            Some(dealloc) => {
218                &&& vstd::layout::size_of::<T>() > 0
219                &&& dealloc.addr() == perm@.0.ptr().addr()
220                &&& dealloc.size() == vstd::layout::size_of::<T>()
221                &&& dealloc.align() == vstd::layout::align_of::<T>()
222                &&& dealloc.provenance() == perm@.0.ptr()@.provenance
223                &&& valid_layout(size_of::<T>(), align_of::<T>())
224            },
225            None => { &&& vstd::layout::size_of::<T>() == 0 },
226        }
227)]
228pub fn box_into_raw<T>(b: Box<T>) -> *mut T {
229    proof_with!(|= Tracked::assume_new());
230    Box::into_raw(b)
231}
232
233#[verifier::external_body]
234#[verus_spec(ret =>
235    with
236        Tracked(points_to): Tracked<PointsTo<T>>,
237        Tracked(dealloc): Tracked<Option<Dealloc>>,
238    requires
239        ptr@.addr != 0,
240        points_to.ptr() == ptr,
241        points_to.is_init(),
242        points_to.ptr().addr() as int % vstd::layout::align_of::<T>() as int == 0,
243        match dealloc@ {
244            Some(dealloc) => {
245                &&& vstd::layout::size_of::<T>() > 0
246                &&& dealloc.addr() == ptr@.addr
247                &&& dealloc.size() == vstd::layout::size_of::<T>()
248                &&& dealloc.align() == vstd::layout::align_of::<T>()
249                &&& dealloc.provenance() == ptr@.provenance
250                &&& valid_layout(size_of::<T>(), align_of::<T>())
251            },
252            None => { &&& vstd::layout::size_of::<T>() == 0 },
253        },
254    ensures
255        *ret == points_to.value(),
256    )]
257pub unsafe fn box_from_raw<T>(ptr: *mut T) -> Box<T> {
258    unsafe { Box::from_raw(ptr) }
259}
260
261/// A wrapper around `Arc::into_raw` that returns a raw-pointer permission.
262///
263/// Arc's value-only model does not retain allocation identity across raw-pointer
264/// round trips. An uninterpreted Arc::ptr() would identify distinct equal-valued
265/// allocations, so pointer identity is deliberately absent from these contracts.
266#[verifier::external_body]
267#[verus_spec(ret =>
268    with
269        -> perm: Tracked<ArcPointsTo<T>>,
270    ensures
271        ret == perm@.ptr(),
272        perm@.inv(),
273        perm@.value() == *p,
274)]
275pub fn arc_into_raw<T>(p: Arc<T>) -> *const T {
276    proof_with!(|= Tracked::assume_new());
277    Arc::into_raw(p)
278}
279
280/// Reconstructs an Arc using the legacy shared-access permission model.
281#[verifier::external_body]
282#[verus_spec(ret =>
283    with
284        Tracked(permission): Tracked<ArcPointsTo<T>>,
285    requires
286        permission.inv(),
287        permission.ptr() == ptr,
288    ensures
289        *ret == permission.value(),
290)]
291pub unsafe fn arc_from_raw<T>(ptr: *const T) -> Arc<T> {
292    unsafe { Arc::from_raw(ptr) }
293}
294
295verus! {
296
297/// A permission that is equivalent to `&BoxPointsTo<T>`.
298pub tracked struct BoxPointsToRef<'a, T>(pub &'a BoxPointsTo<T>);
299
300impl<'a, T> View for BoxPointsToRef<'a, T> {
301    type V = BoxPointsTo<T>;
302
303    open spec fn view(&self) -> BoxPointsTo<T> {
304        *self.0
305    }
306}
307
308impl<'a, T> Inv for BoxPointsToRef<'a, T> {
309    open spec fn inv(self) -> bool {
310        self@.inv()
311    }
312}
313
314impl<'a, T> BoxPointsToRef<'a, T> {
315    pub proof fn tracked_borrow_points_to(tracked &self) -> (tracked ret: &'a PointsTo<T>)
316        returns
317            self@.perm.points_to,
318    {
319        self.0.tracked_borrow_points_to()
320    }
321}
322
323} // verus!