Skip to main content

ostd/sync/rcu/non_null/
mod.rs

1// SPDX-License-Identifier: MPL-2.0
2//! This module provides a trait and some auxiliary types to help abstract and
3//! work with non-null pointers.
4use vstd::prelude::*;
5use vstd::raw_ptr::*;
6#[cfg(feature = "irc11")]
7use vstd::thread_view::Objective;
8use vstd_extra::prelude::*;
9
10use alloc::{boxed::Box, sync::Arc};
11
12mod either;
13
14use core::{marker::PhantomData, mem::ManuallyDrop, ops::Deref, ptr::NonNull};
15
16verus! {
17
18broadcast use {group_nonull_axioms, group_raw_ptr_axioms};
19// [FIXED] BUG FOUND BY FV: UB for Weak. https://github.com/asterinas/asterinas/issues/2801
20
21/// A trait that abstracts non-null pointers.
22///
23/// All common smart pointer types such as `Box<T>`,  `Arc<T>`, and `Weak<T>`
24/// implement this trait as they can be converted to and from the raw pointer
25/// type of `*const T`.
26///
27/// # Safety
28///
29/// This trait must be implemented correctly (according to the doc comments for
30/// each method). Types like [`Rcu`] rely on this assumption to safely use the
31/// raw pointers.
32///
33/// [`Rcu`]: super::Rcu
34#[verus_verify]
35pub unsafe trait NonNullPtr: Inv + Sized + 'static {
36    /// The target type that this pointer refers to.
37    // TODO: Support `Target: ?Sized`.
38    type Target;
39
40    /// A type that behaves just like a shared reference to the owning pointer.
41    /// `Self: 'a` is implied by `Self: 'static`; omit that redundant GAT where-clause
42    /// because the current Verus translator rejects it in associated-type impls.
43    type Ref<'a>: Inv + 'a;
44
45    /// A verification-only permission type that represents the ownership of the memory managed by the pointer.
46    #[cfg(not(feature = "irc11"))]
47    type Permission: Inv;
48
49    #[cfg(feature = "irc11")]
50    type Permission: Inv + Objective;
51
52    /// A verification-only permission type that represents the reading permission of the memory managed by the pointer.
53    type RefPermission<'a>: Inv;
54
55    /// The power of two of the pointer alignment.
56    const ALIGN_BITS: u32;
57
58    /// Optional implementation-specific alignment facts.
59    open spec fn align_bits_inv() -> bool {
60        true
61    }
62
63    /// Converts to a raw pointer.
64    ///
65    /// Each call to `into_raw` must be paired with a call to `from_raw`
66    /// in order to avoid memory leakage.
67    ///
68    /// The lower [`Self::ALIGN_BITS`] of the raw pointer is guaranteed to
69    /// be zero. In other words, the pointer is guaranteed to be aligned to
70    /// `1 << Self::ALIGN_BITS`.
71    /// VERUS LIMITATION: the #[verus_spec] attribute does not support `with` in trait yet.
72    fn into_raw(self) -> ((res_ptr, perm): (NonNull<Self::Target>, Tracked<Self::Permission>))
73        requires
74            self.inv(),
75        ensures
76            Self::ptr_perm_match(res_ptr.as_ptr(), perm@),
77            self.rel_perm(perm@),
78            perm@.inv(),
79            res_ptr.as_ptr().addr() % (1usize << Self::ALIGN_BITS) == 0,
80    ;
81
82    /// Converts back from a raw pointer.
83    ///
84    /// # Safety
85    ///
86    /// 1. The raw pointer must have been previously returned by a call to
87    ///    `into_raw`.
88    /// 2. The raw pointer must not be used after calling `from_raw`.
89    ///
90    /// Note that the second point is a hard requirement: Even if the
91    /// resulting value has not (yet) been dropped, the pointer cannot be
92    /// used because it may break Rust aliasing rules (e.g., `Box<T>`
93    /// requires the pointer to be unique and thus _never_ aliased).
94    /// VERIFICATION DESIGN: It's easy to verify the second point by consuming the permission produced by `into_raw`,
95    /// so we can do nothing with the raw pointer because of the absence of permission.
96    /// VERUS LIMITATION: the #[verus_spec] attribute does not support `with` in trait yet.
97    unsafe fn from_raw(ptr: NonNull<Self::Target>, perm: Tracked<Self::Permission>) -> (ret: Self)
98        requires
99            Self::ptr_perm_match(ptr.as_ptr(), perm@),
100            perm@.inv(),
101        ensures
102            ret.rel_perm(perm@),
103            ret.inv(),
104    ;
105
106    /// A specification function that constraints the nonnull pointer and the permission returned by `into_raw`.
107    /// This design is to support the tagged pointer trick used in `Either`.
108    spec fn ptr_perm_match(ptr: *mut Self::Target, perm: Self::Permission) -> bool;
109
110    /// A specification function that relates the original smart pointer and the permission.
111    spec fn rel_perm(self, perm: Self::Permission) -> bool;
112
113    /// Establishes ALIGN_BITS bounds and implementation-specific facts.
114    proof fn lemma_align_bits_properties()
115        ensures
116            Self::ALIGN_BITS < usize::BITS,
117            Self::align_bits_inv(),
118    ;
119
120    /// The RefPermission must be able to be viewed as the owned Permission.
121    spec fn ref_perm_view_permission<'a>(perm: Self::RefPermission<'a>) -> Self::Permission;
122
123    /// A specification function that relates the `Ref` type and the `RefPermission`.
124    spec fn ref_rel_perm<'a>(r: Self::Ref<'a>, perm: Self::RefPermission<'a>) -> bool;
125
126    /// Borrows a reusable reading permission from the owned permission.
127    proof fn tracked_borrow_perm_as_ref_perm<'a>(
128        tracked perm: &'a Self::Permission,
129    ) -> (tracked ret: Self::RefPermission<'a>)
130        requires
131            perm.inv(),
132        ensures
133            Self::ref_perm_view_permission(ret) == *perm,
134            ret.inv(),
135    ;
136
137    /// Obtains a shared reference to the original pointer.
138    ///
139    /// # Safety
140    ///
141    /// The original pointer must outlive the lifetime parameter `'a`, and during `'a`
142    /// no mutable references to the pointer will exist.
143    unsafe fn raw_as_ref<'a>(
144        raw: NonNull<Self::Target>,
145        perm: Tracked<Self::RefPermission<'a>>,
146    ) -> (ret: Self::Ref<'a>)
147        requires
148            Self::ptr_perm_match(raw.as_ptr(), Self::ref_perm_view_permission(perm@)),
149            perm@.inv(),
150        ensures
151            Self::ref_rel_perm(ret, perm@),
152            ret.inv(),
153    ;
154
155    /// Converts a shared reference to a raw pointer.
156    fn ref_as_raw<'a>(ptr_ref: Self::Ref<'a>) -> ((res_ptr, perm): (
157        NonNull<Self::Target>,
158        Tracked<Self::RefPermission<'a>>,
159    ))
160        requires
161            ptr_ref.inv(),
162        ensures
163            Self::ref_rel_perm(ptr_ref, perm@),
164            perm@.inv(),
165            Self::ptr_perm_match(res_ptr.as_ptr(), Self::ref_perm_view_permission(perm@)),
166            res_ptr.as_ptr().addr() % (1usize << Self::ALIGN_BITS) == 0,
167    ;
168}
169
170} // verus!
171/// A type that represents `&'a Box<T>`.
172#[verus_verify]
173#[derive(Debug)]
174pub struct BoxRef<'a, T> {
175    inner: *mut T,
176    _marker: PhantomData<&'a T>,
177    tracked_perm: Tracked<BoxPointsToRef<'a, T>>,
178}
179
180/*
181impl<T> Deref for BoxRef<'_, T> {
182    type Target = Box<T>;
183
184    fn deref(&self) -> &Self::Target {
185        // SAFETY: A `Box<T>` is guaranteed to be represented by a single pointer [1] and a shared
186        // reference to the `Box<T>` during the lifetime `'a` can be created according to the
187        // safety requirements of `NonNullPtr::raw_as_ref`.
188        //
189        // [1]: https://doc.rust-lang.org/std/boxed/#memory-layout
190        unsafe { core::mem::transmute(&self.inner) }
191    }
192}
193*/
194
195verus! {
196
197#[verus_verify]
198impl<'a, T> BoxRef<'a, T> {
199    /// Dereferences `self` to get a reference to `T` with the lifetime `'a`.
200    #[verus_spec(ret => ensures *ret == self.value())]
201    pub fn deref_target(&self) -> &'a T {
202        proof!{
203            use_type_invariant(self);
204        }
205        // [VERIFIED] SAFETY: The reference is created through `NonNullPtr::raw_as_ref`, hence
206        // the original owned pointer and target must outlive the lifetime parameter `'a`,
207        // and during `'a` no mutable references to the pointer will exist.
208
209        // The function body of ptr_ref is exactly the same as `unsafe { &*(self.inner) }`
210        //unsafe { &*(self.inner) }
211        // FIXME: Fix when verus supports attribute syntax for raw pointers.
212        vstd::raw_ptr::ptr_ref(
213            self.inner,
214            Tracked(self.tracked_perm.borrow().tracked_borrow_points_to()),
215        )
216    }
217}
218
219unsafe impl<T: 'static> NonNullPtr for Box<T> {
220    type Target = T;
221
222    type Permission = BoxPointsTo<T>;
223
224    type Ref<'a> = BoxRef<'a, T>;
225
226    type RefPermission<'a> = BoxPointsToRef<'a, T>;
227
228    #[verifier::external_body]
229    const ALIGN_BITS: u32 = core::mem::align_of::<T>().trailing_zeros();
230
231    open spec fn align_bits_inv() -> bool {
232        1usize << Self::ALIGN_BITS == vstd::layout::align_of::<T>()
233    }
234
235    #[verus_spec]
236    fn into_raw(self) -> (NonNull<Self::Target>, Tracked<Self::Permission>) {
237        proof_decl! {
238            let tracked perm: (PointsTo<T>, Option<Dealloc>);
239        }
240
241        //let ptr = Box::into_raw(self);
242        proof_with!(=> Tracked(perm));
243        let ptr = box_into_raw(self);
244
245        proof_decl!{
246            let tracked box_points_to = BoxPointsTo {
247                perm: PointsTowithDealloc::new(perm.0, perm.1),
248            };
249        }
250        proof! { Self::lemma_align_bits_properties(); }
251
252        // [VERIFIED] SAFETY: The pointer representing a `Box` can never be NULL.
253        (unsafe { NonNull::new_unchecked(ptr) }, Tracked(box_points_to))
254    }
255
256    #[verus_spec]
257    unsafe fn from_raw(
258        ptr: NonNull<Self::Target>,
259        Tracked(perm): Tracked<Self::Permission>,
260    ) -> Self {
261        proof_decl!{
262            let tracked perm = perm.tracked_get_points_to_with_dealloc();
263        }
264
265        let ptr = ptr.as_ptr();
266
267        // [VERIFIED] SAFETY: The safety is upheld by the caller.
268        // unsafe { Box::from_raw(ptr) }
269        unsafe {
270            proof_with!(Tracked(perm.points_to), Tracked(perm.dealloc));
271            box_from_raw(ptr)
272        }
273    }
274
275    open spec fn ptr_perm_match(ptr: *mut Self::Target, perm: Self::Permission) -> bool {
276        ptr == perm.ptr()
277    }
278
279    open spec fn rel_perm(self, perm: Self::Permission) -> bool {
280        perm.view_target() == *self
281    }
282
283    // Trusted relation between external ALIGN_BITS and Rust type alignment.
284    axiom fn lemma_align_bits_properties();
285
286    open spec fn ref_perm_view_permission<'a>(perm: Self::RefPermission<'a>) -> Self::Permission {
287        perm@
288    }
289
290    open spec fn ref_rel_perm<'a>(r: Self::Ref<'a>, perm: Self::RefPermission<'a>) -> bool {
291        &&& r.value() == perm@.value()
292        &&& r.ptr() == perm@.ptr()
293    }
294
295    proof fn tracked_borrow_perm_as_ref_perm<'a>(
296        tracked perm: &'a Self::Permission,
297    ) -> tracked Self::RefPermission<'a> {
298        BoxPointsToRef(perm)
299    }
300
301    unsafe fn raw_as_ref<'a>(
302        raw: NonNull<Self::Target>,
303        perm: Tracked<Self::RefPermission<'a>>,
304    ) -> Self::Ref<'a> {
305        BoxRef { inner: raw.as_ptr(), _marker: PhantomData, tracked_perm: perm }
306    }
307
308    fn ref_as_raw<'a>(ptr_ref: Self::Ref<'a>) -> (
309        NonNull<Self::Target>,
310        Tracked<Self::RefPermission<'a>>,
311    ) {
312        proof!{
313            use_type_invariant(&ptr_ref);
314            Self::lemma_align_bits_properties();
315        }
316        // [VERIFIED] SAFETY: The pointer representing a `Box` can never be NULL.
317        (unsafe { NonNull::new_unchecked(ptr_ref.inner) }, ptr_ref.tracked_perm)
318    }
319}
320
321// BoxRef's memory validity is enforced by its type invariant.
322impl<T> Inv for BoxRef<'_, T> {
323    open spec fn inv(self) -> bool {
324        true
325    }
326}
327
328impl<'a, T> BoxRef<'a, T> {
329    #[verifier::type_invariant]
330    spec fn type_inv(self) -> bool {
331        &&& self.inner@.addr != 0
332        &&& self.inner@.addr as int % vstd::layout::align_of::<T>() as int == 0
333        &&& self.tracked_perm@@.ptr() == self.inner
334        &&& self.tracked_perm@.inv()
335    }
336
337    pub closed spec fn ptr(self) -> *mut T {
338        self.inner
339    }
340
341    pub closed spec fn value(self) -> T {
342        self.tracked_perm@@.value()
343    }
344}
345
346} // verus!
347/// A type that represents `&'a Arc<T>`.
348#[verus_verify]
349#[derive(Debug)]
350pub struct ArcRef<'a, T: 'static> {
351    inner: ManuallyDrop<Arc<T>>,
352    _marker: PhantomData<&'a Arc<T>>,
353}
354
355#[verus_verify]
356impl<T> Deref for ArcRef<'_, T> {
357    type Target = Arc<T>;
358
359    #[verus_spec(ret =>
360        ensures *ret == self@
361    )]
362    fn deref(&self) -> &Self::Target {
363        &self.inner
364    }
365}
366
367#[verus_verify]
368impl<'a, T> ArcRef<'a, T> {
369    /// Dereferences `self` to get a reference to `T` with the lifetime `'a`.
370    /// VERUS LIMITATION: The code includes a cast from `&T` to `*const T`, which is not specified yet in Verus.
371    /// This is also a nontrivial use case that extends the lifetime of the reference.
372    #[verus_verify(external_body)]
373    #[verus_spec(ret => ensures *ret == *self@)]
374    pub fn deref_target(&self) -> &'a T {
375        // SAFETY: The reference is created through `NonNullPtr::raw_as_ref`, hence
376        // the original owned pointer and target must outlive the lifetime parameter `'a`,
377        // and during `'a` no mutable references to the pointer will exist.
378        unsafe { &*(self.deref().deref() as *const T) }
379    }
380}
381
382verus! {
383
384unsafe impl<T: 'static> NonNullPtr for Arc<T> {
385    type Target = T;
386
387    type Permission = ArcPointsTo<T>;
388
389    type Ref<'a> = ArcRef<'a, T>;
390
391    type RefPermission<'a> = ArcPointsTo<T>;
392
393    #[verifier::external_body]
394    const ALIGN_BITS: u32 = core::mem::align_of::<T>().trailing_zeros();
395
396    open spec fn align_bits_inv() -> bool {
397        1usize << Self::ALIGN_BITS == vstd::layout::align_of::<T>()
398    }
399
400    #[verus_spec]
401    fn into_raw(self) -> (NonNull<Self::Target>, Tracked<Self::Permission>) {
402        proof_decl! { let tracked perm: ArcPointsTo<T>; }
403        let ptr = (#[verus_spec(with => Tracked(perm))]
404        arc_into_raw(self)).cast_mut();
405        proof! { Self::lemma_align_bits_properties(); }
406
407        // [VERIFIED] SAFETY: The pointer representing an `Arc` can never be NULL.
408        (unsafe { NonNull::new_unchecked(ptr) }, Tracked(perm))
409    }
410
411    unsafe fn from_raw(
412        ptr: NonNull<Self::Target>,
413        Tracked(perm): Tracked<Self::Permission>,
414    ) -> Self {
415        let ptr = ptr.as_ptr().cast_const();
416
417        // [VERIFIED] SAFETY: The safety is upheld by the caller.
418        // unsafe { Arc::from_raw(ptr) }
419        unsafe {
420            #[verus_spec(with Tracked(perm))]
421            arc_from_raw(ptr)
422        }
423    }
424
425    open spec fn ptr_perm_match(ptr: *mut Self::Target, perm: Self::Permission) -> bool {
426        ptr == perm.ptr()
427    }
428
429    open spec fn rel_perm(self, perm: Self::Permission) -> bool {
430        perm.view_target() == *self
431    }
432
433    // Same trusted alignment relation as Box.
434    axiom fn lemma_align_bits_properties();
435
436    open spec fn ref_perm_view_permission<'a>(perm: Self::RefPermission<'a>) -> Self::Permission {
437        perm
438    }
439
440    open spec fn ref_rel_perm<'a>(r: Self::Ref<'a>, perm: Self::RefPermission<'a>) -> bool {
441        // Allocation identity is not represented by Arc's value model.
442        perm.view_target() == *r@
443    }
444
445    proof fn tracked_borrow_perm_as_ref_perm<'a>(
446        tracked perm: &'a Self::Permission,
447    ) -> tracked Self::RefPermission<'a> {
448        ArcPointsTo { perm: perm.perm }
449    }
450
451    unsafe fn raw_as_ref<'a>(
452        raw: NonNull<Self::Target>,
453        perm: Tracked<Self::RefPermission<'a>>,
454    ) -> Self::Ref<'a> {
455        unsafe {
456            ArcRef {
457                inner: ManuallyDrop::new(
458                    #[verus_spec(with perm)]
459                    arc_from_raw(raw.as_ptr()),
460                ),
461                _marker: PhantomData,
462            }
463        }
464    }
465
466    fn ref_as_raw<'a>(ptr_ref: Self::Ref<'a>) -> (
467        NonNull<Self::Target>,
468        Tracked<Self::RefPermission<'a>>,
469    ) {
470        NonNullPtr::into_raw(ManuallyDrop::into_inner(ptr_ref.inner))
471    }
472}
473
474impl<T> Inv for ArcRef<'_, T> {
475    open spec fn inv(self) -> bool {
476        true
477    }
478}
479
480impl<T> View for ArcRef<'_, T> {
481    type V = Arc<T>;
482
483    closed spec fn view(&self) -> Arc<T> {
484        self.inner@
485    }
486}
487
488} // verus!