Skip to main content Skip to main content
Pigweed's logo Pigweed
code_xml
  1. Home
  2. Reference
  3. Rust
  4. pw_kernel
  5. src
  6. foreign_box/foreign_box.rs

foreign_box/
foreign_box.rs

1// Copyright 2025 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#![no_std]
15#![cfg_attr(test, no_main)]
16
17use core::cell::UnsafeCell;
18use core::marker::PhantomData;
19use core::mem::{ManuallyDrop, offset_of};
20use core::ops::{Deref, DerefMut};
21use core::ptr::NonNull;
22use core::sync::atomic::Ordering;
23
24use pw_atomic::AtomicUsize;
25
26pub struct ForeignBox<T: ?Sized> {
27    inner: NonNull<T>,
28
29    // Guards against the type being dropped w/o a consume call.
30    //
31    // TODO: add feature to disable this field on production builds to avoid
32    // the overhead of the extra bool.
33    consumed: bool,
34
35    // NunNull is covariant over `T` which can not be guaranteed of `KernelRef`.
36    // Use `PhantomData` in mark as invariant.
37    _phantom: PhantomData<T>,
38}
39
40// Safety: Same bounds on `T` as [`Box`].
41unsafe impl<T: Send + ?Sized> Send for ForeignBox<T> {}
42unsafe impl<T: Sync + ?Sized> Sync for ForeignBox<T> {}
43
44impl<T: ?Sized> ForeignBox<T> {
45    #[allow(dead_code)]
46    /// Create a new `ForeignBox` from a `NonNull<T>`.
47    ///
48    /// # Safety
49    /// The caller guarantees that `ptr` remains valid throughout the lifetime
50    /// of the `ForeignBox` object.
51    #[must_use]
52    pub const unsafe fn new(ptr: NonNull<T>) -> Self {
53        Self {
54            inner: ptr,
55            consumed: false,
56            _phantom: PhantomData,
57        }
58    }
59
60    /// Create a new `ForeignBox` from a `*mut T`.
61    ///
62    /// # Panics
63    /// panics if `ptr` is null.
64    /// # Safety
65    /// The caller guarantees that `ptr` remains valid throughout the lifetime
66    /// of the `ForeignBox` object.
67    #[must_use]
68    pub unsafe fn new_from_ptr(ptr: *mut T) -> Self {
69        let Some(ptr) = NonNull::new(ptr) else {
70            pw_assert::panic!("Null pointer");
71        };
72        unsafe { Self::new(ptr) }
73    }
74
75    #[allow(clippy::must_use_candidate)]
76    pub fn consume(mut self) -> NonNull<T> {
77        self.consumed = true;
78        self.inner
79    }
80
81    /// Returns a pointer to the contained data.
82    ///
83    /// # Safety
84    /// Creates an "unenforceable borrow" of the contained data.
85    #[must_use]
86    pub unsafe fn as_ptr(&self) -> *const T {
87        self.inner.as_ptr()
88    }
89
90    /// Returns a mutable pointer to the contained data.
91    ///
92    /// # Safety
93    /// Creates an "mutable unenforceable borrow" of the contained data.
94    #[must_use]
95    pub unsafe fn as_mut_ptr(&mut self) -> *mut T {
96        unsafe { self.inner.as_mut() }
97    }
98}
99
100impl<T: ?Sized> Drop for ForeignBox<T> {
101    fn drop(&mut self) {
102        if !self.consumed {
103            pw_assert::panic!(
104                "ForeignBox@{:08x} dropped before being consumed!",
105                self.inner.as_ptr().cast::<()>() as usize
106            );
107        }
108    }
109}
110
111impl<T: ?Sized> From<&'static mut T> for ForeignBox<T> {
112    fn from(t: &'static mut T) -> ForeignBox<T> {
113        // SAFETY: The `'static` lifetime guarantees that `t`'s referent will
114        // remain valid for the lifetime of the returned `ForeignBox`.
115        unsafe { ForeignBox::new(NonNull::from(t)) }
116    }
117}
118
119impl<T: ?Sized> AsRef<T> for ForeignBox<T> {
120    fn as_ref(&self) -> &T {
121        unsafe { self.inner.as_ref() }
122    }
123}
124
125impl<T: ?Sized> AsMut<T> for ForeignBox<T> {
126    fn as_mut(&mut self) -> &mut T {
127        unsafe { self.inner.as_mut() }
128    }
129}
130
131impl<T: ?Sized> Deref for ForeignBox<T> {
132    type Target = T;
133
134    fn deref(&self) -> &Self::Target {
135        self.as_ref()
136    }
137}
138
139impl<T: ?Sized> DerefMut for ForeignBox<T> {
140    fn deref_mut(&mut self) -> &mut Self::Target {
141        self.as_mut()
142    }
143}
144
145#[doc(hidden)]
146pub struct ForeignRcState<A: AtomicUsize, T: ?Sized> {
147    // Disable auto `Send` and `Sync`. We implement them manually to give us an
148    // opportunity to document their safety proofs.
149    _not_send_sync: PhantomData<NonNull<()>>,
150
151    // `ForeignRcState` has the following lifecycle:
152    // - At creation, `ref_count` is equal to 1 and no `ForeignRc` references
153    //   exist.
154    // - `create_first_ref` is called, which creates the first `ForeignRc`
155    //   reference without incrementing the `ref_count`.
156    // - From here on out, `ref_count` counts the number of `ForeignRc`
157    //   references which exist or which have been forgotten. Each time a
158    //   `ForeignRc` is created or dropped, `ref_count` is updated accordingly.
159    // - Once `ref_count` reaches 0, there are no `ForeignRc` references, and so
160    //   `inner` can be dropped. At this point, `inner` is in an invalid state
161    //   and must never be operated on or exposed to safe code outside of this
162    //   module.
163    //
164    // INVARIANTS:
165    // - `ref_count` is only modified consistent with this lifecycle
166    // - `ref_count` is only modified using thread-safe operations
167    ref_count: A,
168    // INVARIANTS: `inner` is in a valid state so long as `ref_count > 0`.
169    inner: UnsafeCell<ManuallyDrop<T>>,
170}
171
172// SAFETY: None of the `ForeignRcState` lifecycle is affected by sending a
173// `ForeignRcState` across threads. TODO: Make this more precise
174unsafe impl<A: Send + AtomicUsize, T: Send + ?Sized> Send for ForeignRcState<A, T> {}
175// SAFETY: By invariant on `ref_count`, it is only modified using thread-safe
176// operations. Thus, permitting references (and, by extension, `ForeignRc`s,
177// which contain a `&ForeignRcState`) to be sent between threads won't violate
178// the `ForeignRcState` lifecycle (so long as `A: Sync` and `T: Sync`).
179unsafe impl<A: Sync + AtomicUsize, T: Sync + ?Sized> Sync for ForeignRcState<A, T> {}
180
181impl<A: AtomicUsize, T> ForeignRcState<A, T> {
182    pub fn new(val: T) -> Self {
183        Self {
184            ref_count: A::new(1),
185            inner: UnsafeCell::new(ManuallyDrop::new(val)),
186            _not_send_sync: PhantomData,
187        }
188    }
189}
190
191impl<A: AtomicUsize, T: ?Sized> ForeignRcState<A, T> {
192    /// # Safety
193    ///
194    /// `create_first_ref` must be the first method called on `self` after
195    /// creation with [`new`]. It must not be called twice.
196    ///
197    /// [`new`]: ForeignRcState::new
198    pub unsafe fn create_first_ref(&'static mut self) -> ForeignRc<A, T> {
199        // SAFETY: The caller promises that this is the first method call. Thus,
200        // this is the first `ForeignRc` reference, consistent with the
201        // lifecycle.
202        ForeignRc { state: self }
203    }
204
205    pub fn ref_count(&self) -> &A {
206        &self.ref_count
207    }
208}
209
210impl<A: AtomicUsize, T: Sized> ForeignRcState<A, T> {
211    /// Return a new [`ForeignRc`] from a reference to a [`ForeignRcState`]'s
212    /// inner storage.
213    ///
214    /// # Safety
215    /// The caller must guarantee that `inner: &T` is a reference storage that
216    /// is contained inside a [`ForeignRcState<A, T>`].
217    pub unsafe fn create_ref_from_inner(inner: &T) -> ForeignRc<A, T> {
218        let inner = NonNull::from_ref(inner);
219        let state: &Self = unsafe { inner.byte_sub(offset_of!(Self, inner)).cast().as_ref() };
220        state.ref_count.fetch_add(1, Ordering::SeqCst);
221        ForeignRc { state }
222    }
223}
224
225pub struct ForeignRc<A: AtomicUsize + 'static, T: ?Sized + 'static> {
226    state: &'static ForeignRcState<A, T>,
227}
228
229impl<A: AtomicUsize, T: ?Sized> ForeignRc<A, T> {
230    #[must_use]
231    pub fn state(&self) -> &ForeignRcState<A, T> {
232        self.state
233    }
234
235    #[doc(hidden)]
236    /// Map a `ForeignRc` into a compatible type.
237    ///
238    /// # Safety
239    /// The caller must guarantee that the `map` closure returns a reference
240    /// pointing to the same address and byte range as was passed in.
241    pub unsafe fn map<U: ?Sized>(
242        self,
243        map: impl Fn(&ForeignRcState<A, T>) -> &ForeignRcState<A, U>,
244    ) -> ForeignRc<A, U> {
245        // Ensure the destructor is not run to avoid decrementing the refcount.
246        let this = core::mem::ManuallyDrop::new(self);
247        ForeignRc {
248            state: map(this.state),
249        }
250    }
251}
252
253impl<A: AtomicUsize, T: ?Sized> Deref for ForeignRc<A, T> {
254    type Target = T;
255
256    fn deref(&self) -> &T {
257        let ptr = self.state.inner.get();
258        // SAFETY: By invariant, `self.state.ref_count` is at least 1 since this
259        // `ForeignRc` exists, and also by invariant, `self.state.inner` is
260        // valid since `ref_count` is at least 1.
261        unsafe { &*ptr }
262    }
263}
264
265impl<A: AtomicUsize, T: ?Sized> Clone for ForeignRc<A, T> {
266    fn clone(&self) -> Self {
267        self.state.ref_count.fetch_add(1, Ordering::SeqCst);
268        // SAFETY: We're creating a new `ForeignRc`, but we've just increased
269        // the `ref_count` by 1. Since, by invariant, `ref_count` previously
270        // accurately counted the number of `ForeignRc`s, and since we just
271        // created a new one and incremented `ref_count`, it is still accurate.
272        Self { state: self.state }
273    }
274}
275
276impl<A: AtomicUsize, T: ?Sized> Drop for ForeignRc<A, T> {
277    fn drop(&mut self) {
278        let old = self.state.ref_count.fetch_sub(1, Ordering::SeqCst);
279        if old == 1 {
280            let ptr = self.state.inner.get();
281            // SAFETY: By invariant, `ref_count` counts the number of
282            // `ForeignRc`s which exist or which have been forgotten. Since it
283            // was 1 before being decremented, this is the last `ForeignRc`. It
284            // is sound to construct a mutable reference to `self.state.inner`
285            // because:
286            // - By virtue of being the last `ForeignRc`, no other code is
287            //   accessing `self.state.inner`
288            // - By invariant, `self.state.inner` is valid so long as `ref_count
289            //   > 0`, which it was at the beginning of this function
290            let md = unsafe { &mut *ptr };
291            // SAFETY: As described above, `md` references a valid value, so it
292            // is sound to drop it. By invariant, since `ref_count` is now 0, no
293            // other code will be permitted to access `self.state.inner`, so it
294            // is acceptable to leave it in an invalid state.
295            unsafe { ManuallyDrop::drop(md) };
296        }
297    }
298}
299
300/// Upcasts a [`ForeignRc`] from a concrete type to a `dyn Trait` that the concrete
301/// type implements
302#[macro_export]
303macro_rules! upcast_foreign_rc {
304    ($rc:expr => dyn $trait:ident $(<$($trait_tyvar:ident),*>)? ) => {{
305        use $crate::ForeignRcState;
306        let rc = $rc;
307        // SAFETY: The closure passed to `.map()` fulfils the precondition that
308        // the returned reference points to the same place as the passed in reference.
309        unsafe {
310            rc.map(|inner: &ForeignRcState<_, _>|
311                -> &ForeignRcState<_, dyn $trait $(<$($trait_tyvar),*>)?> { inner })
312        }
313    }};
314}
315
316/// Helper type to declare a static value with runtime initialization.
317///
318/// # Safety
319/// The user must ensure that [`StaticStorage::init()`] is only called once.
320#[doc(hidden)]
321pub struct StaticStorage<T> {
322    inner: UnsafeCell<core::mem::MaybeUninit<T>>,
323}
324
325impl<T> StaticStorage<T> {
326    /// Initialize a new `StaticStorage`.
327    #[must_use]
328    pub const fn new() -> Self {
329        Self {
330            inner: UnsafeCell::new(core::mem::MaybeUninit::uninit()),
331        }
332    }
333
334    /// Initialize the value in the `StaticStorage` and return a mutable
335    /// reference to it.
336    ///
337    /// # Safety
338    /// The user must ensure that this method is only called once.
339    #[allow(clippy::mut_from_ref)]
340    pub unsafe fn init(&self, val: T) -> &mut T {
341        unsafe { (*self.inner.get()).write(val) }
342    }
343
344    /// Return the address of the underlying storage as an untyped pointer.
345    ///
346    /// There are circumstances where the address of the static storage needs to
347    /// be known at `const` time. One example of this is adding debug annotation
348    /// to an image.
349    ///
350    /// # Safety
351    ///
352    /// It is up to the caller to ensure that all uses of the returned addresses
353    /// are safe and sound with respect to uses of `init()`
354    pub const unsafe fn address(&self) -> *const () {
355        self.inner.get() as *const ()
356    }
357}
358
359// SAFETY: By contract, the user will only call `init()` once therefore only
360// creating a single reference to the inner data.
361unsafe impl<T> Sync for StaticStorage<T> {}
362
363/// Declare a [`ForeignBox`] in static storage that is runtime initialized.
364///
365/// # Safety
366/// Caller must ensure that the macro is executed only once.
367#[macro_export]
368macro_rules! static_foreign_box {
369    ($ty:ty, $init:expr) => {{
370        unsafe fn declare_static(val: $ty) -> &'static mut $ty {
371            use $crate::StaticStorage;
372
373            static STORAGE: StaticStorage<$ty> = StaticStorage::new();
374            unsafe { STORAGE.init(val) }
375        }
376        let r = declare_static($init);
377
378        // ForeignBox created outside of function to allow type coercion.
379        $crate::ForeignBox::new(NonNull::from_ref(r))
380    }};
381}
382
383/// Declare a [`ForeignRc`] in static storage that is runtime initialized.
384///
385/// # Safety
386/// Caller must ensure that the macro is executed only once.
387#[macro_export]
388macro_rules! static_foreign_rc {
389    ($atomic_usize:ty, $ty:ty, $init:expr) => {{
390        unsafe fn declare_static(val: $ty) -> $crate::ForeignRc<$atomic_usize, $ty> {
391            use $crate::{ForeignRcState, StaticStorage};
392
393            static STORAGE: StaticStorage<ForeignRcState<$atomic_usize, $ty>> =
394                StaticStorage::new();
395            unsafe {
396                let r = STORAGE.init(ForeignRcState::new(val));
397                r.create_first_ref()
398            }
399        }
400
401        declare_static($init)
402    }};
403}
404
405#[cfg(test)]
406mod tests {
407    use core::cell::Cell;
408
409    use pw_atomic::AtomicLoad;
410    use unittest::test;
411
412    use super::*;
413
414    #[test]
415    fn consume_returns_the_same_pointer() -> unittest::Result<()> {
416        let mut value = 0xdecafbad_u32;
417        let ptr = &raw mut value;
418        let foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
419        let consumed_ptr = foreign_box.consume();
420
421        unittest::assert_eq!(ptr, consumed_ptr.as_ptr());
422        Ok(())
423    }
424
425    #[test]
426    fn value_can_be_read_through_as_ref() -> unittest::Result<()> {
427        let mut value = 0xdecafbad_u32;
428        let ptr = &raw mut value;
429        let foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
430        unittest::assert_eq!(value, *(foreign_box.as_ref()));
431
432        // Prevent foreign_box from being dropped.
433        let _ = foreign_box.consume();
434        Ok(())
435    }
436
437    #[test]
438    fn value_can_be_modified_through_as_mut() -> unittest::Result<()> {
439        let mut value = 0xdecafbad_u32;
440        let ptr = &raw mut value;
441        let mut foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
442        *(foreign_box.as_mut()) = 0xcafecafe;
443
444        unittest::assert_eq!(unsafe { ptr.read_volatile() }, 0xcafecafe);
445
446        // Prevent foreign_box from being dropped.
447        let _ = foreign_box.consume();
448        Ok(())
449    }
450
451    #[test]
452    fn value_can_be_read_through_deref() -> unittest::Result<()> {
453        let mut value = 0xdecafbad_u32;
454        let ptr = &raw mut value;
455        let foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
456        unittest::assert_eq!(value, *foreign_box);
457
458        // Prevent foreign_box from being dropped.
459        let _ = foreign_box.consume();
460        Ok(())
461    }
462
463    #[test]
464    fn value_can_be_modified_through_deref_mut() -> unittest::Result<()> {
465        let mut value = 0xdecafbad_u32;
466        let ptr = &raw mut value;
467        let mut foreign_box = unsafe { ForeignBox::new(NonNull::new_unchecked(ptr)) };
468        *foreign_box = 0xcafecafe;
469
470        unittest::assert_eq!(unsafe { ptr.read_volatile() }, 0xcafecafe);
471
472        // Prevent foreign_box from being dropped.
473        let _ = foreign_box.consume();
474        Ok(())
475    }
476
477    trait TestDynTrait {
478        fn number(&self) -> u32;
479    }
480
481    struct TimesOne {
482        val: u32,
483    }
484
485    impl TestDynTrait for TimesOne {
486        fn number(&self) -> u32 {
487            self.val
488        }
489    }
490
491    #[allow(dead_code)]
492    struct TimesTwo {
493        val: u32,
494    }
495
496    #[allow(dead_code)]
497    impl TestDynTrait for TimesTwo {
498        fn number(&self) -> u32 {
499            self.val * 2
500        }
501    }
502
503    fn get_number(val: &ForeignBox<dyn TestDynTrait>) -> u32 {
504        val.as_ref().number()
505    }
506
507    #[test]
508    fn supports_dynamic_dispatch() -> unittest::Result<()> {
509        let mut times_one_val = TimesOne { val: 10 };
510        let ptr = &raw mut times_one_val;
511        let times_one_box = unsafe { ForeignBox::<dyn TestDynTrait>::new_from_ptr(ptr) };
512
513        let mut times_two_val = TimesTwo { val: 10 };
514        let ptr = &raw mut times_two_val;
515        let times_two_box = unsafe { ForeignBox::<dyn TestDynTrait>::new_from_ptr(ptr) };
516
517        unittest::assert_eq!(get_number(&times_one_box), 10);
518        unittest::assert_eq!(get_number(&times_two_box), 20);
519
520        times_one_box.consume();
521        times_two_box.consume();
522        Ok(())
523    }
524
525    #[test]
526    fn static_foreign_box_can_be_created_and_consumed() -> unittest::Result<()> {
527        let b = unsafe { static_foreign_box!(u32, 42) };
528        unittest::assert_eq!(*b, 42);
529        let ptr = b.consume();
530        unittest::assert_eq!(unsafe { ptr.read() }, 42);
531        Ok(())
532    }
533
534    /// A `pw_atomic::AtomicUsize` backed by a plain `Cell` for use in these
535    /// single-threaded tests.
536    ///
537    /// Production code reaches `ForeignRc` through the arch-provided
538    /// `Kernel::AtomicUsize`, which exists on every supported target. The
539    /// `core` atomics do not: `pw_atomic` only implements its traits for
540    /// them on targets with native compare-and-swap. Using this type keeps
541    /// the test compiling and running on every target, including riscv32
542    /// cores without the A extension.
543    struct TestAtomicUsize(Cell<usize>);
544
545    // SAFETY: The unit-test runner is single threaded, so no two threads ever
546    // access a `TestAtomicUsize` concurrently.
547    unsafe impl Sync for TestAtomicUsize {}
548
549    impl pw_atomic::AtomicNew<usize> for TestAtomicUsize {
550        fn new(val: usize) -> Self {
551            Self(Cell::new(val))
552        }
553    }
554
555    impl pw_atomic::AtomicLoad<usize> for TestAtomicUsize {
556        fn load(&self, _order: Ordering) -> usize {
557            self.0.get()
558        }
559    }
560
561    impl pw_atomic::AtomicStore<usize> for TestAtomicUsize {
562        fn store(&self, val: usize, _order: Ordering) {
563            self.0.set(val);
564        }
565    }
566
567    impl pw_atomic::AtomicCompareExchange<usize> for TestAtomicUsize {
568        fn compare_exchange(
569            &self,
570            current: usize,
571            new: usize,
572            _success: Ordering,
573            _failure: Ordering,
574        ) -> Result<usize, usize> {
575            let prev = self.0.get();
576            if prev == current {
577                self.0.set(new);
578                Ok(prev)
579            } else {
580                Err(prev)
581            }
582        }
583    }
584
585    impl pw_atomic::AtomicAdd<usize> for TestAtomicUsize {
586        fn fetch_add(&self, val: usize, _order: Ordering) -> usize {
587            self.0.replace(self.0.get().wrapping_add(val))
588        }
589    }
590
591    impl pw_atomic::AtomicSub<usize> for TestAtomicUsize {
592        fn fetch_sub(&self, val: usize, _order: Ordering) -> usize {
593            self.0.replace(self.0.get().wrapping_sub(val))
594        }
595    }
596
597    impl pw_atomic::AtomicZero for TestAtomicUsize {
598        const ZERO: Self = Self(Cell::new(0));
599    }
600
601    impl pw_atomic::AtomicOne for TestAtomicUsize {
602        const ONE: Self = Self(Cell::new(1));
603    }
604
605    impl pw_atomic::Atomic<usize> for TestAtomicUsize {}
606    impl AtomicUsize for TestAtomicUsize {}
607
608    #[test]
609    fn static_foreign_rc_ref_count_is_correct() -> unittest::Result<()> {
610        let rc = unsafe { static_foreign_rc!(TestAtomicUsize, u32, 42) };
611        unittest::assert_eq!(*rc, 42);
612        unittest::assert_eq!(rc.state.ref_count.load(Ordering::SeqCst), 1);
613        let rc2 = rc.clone();
614        unittest::assert_eq!(rc.state.ref_count.load(Ordering::SeqCst), 2);
615        drop(rc2);
616        unittest::assert_eq!(rc.state.ref_count.load(Ordering::SeqCst), 1);
617        Ok(())
618    }
619}