xref: /linux/rust/kernel/alloc/kbox.rs (revision 9def0d0a2a1c62d7970f4ce5ad5557968c98f637)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! Implementation of [`Box`].
4 
5 #[allow(unused_imports)] // Used in doc comments.
6 use super::allocator::{KVmalloc, Kmalloc, Vmalloc};
7 use super::{AllocError, Allocator, Flags};
8 use core::alloc::Layout;
9 use core::fmt;
10 use core::marker::PhantomData;
11 use core::mem::ManuallyDrop;
12 use core::mem::MaybeUninit;
13 use core::ops::{Deref, DerefMut};
14 use core::pin::Pin;
15 use core::ptr::NonNull;
16 use core::result::Result;
17 
18 use crate::init::InPlaceInit;
19 use crate::types::ForeignOwnable;
20 use pin_init::{InPlaceWrite, Init, PinInit, ZeroableOption};
21 
22 /// The kernel's [`Box`] type -- a heap allocation for a single value of type `T`.
23 ///
24 /// This is the kernel's version of the Rust stdlib's `Box`. There are several differences,
25 /// for example no `noalias` attribute is emitted and partially moving out of a `Box` is not
26 /// supported. There are also several API differences, e.g. `Box` always requires an [`Allocator`]
27 /// implementation to be passed as generic, page [`Flags`] when allocating memory and all functions
28 /// that may allocate memory are fallible.
29 ///
30 /// `Box` works with any of the kernel's allocators, e.g. [`Kmalloc`], [`Vmalloc`] or [`KVmalloc`].
31 /// There are aliases for `Box` with these allocators ([`KBox`], [`VBox`], [`KVBox`]).
32 ///
33 /// When dropping a [`Box`], the value is also dropped and the heap memory is automatically freed.
34 ///
35 /// # Examples
36 ///
37 /// ```
38 /// let b = KBox::<u64>::new(24_u64, GFP_KERNEL)?;
39 ///
40 /// assert_eq!(*b, 24_u64);
41 /// # Ok::<(), Error>(())
42 /// ```
43 ///
44 /// ```
45 /// # use kernel::bindings;
46 /// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1;
47 /// struct Huge([u8; SIZE]);
48 ///
49 /// assert!(KBox::<Huge>::new_uninit(GFP_KERNEL | __GFP_NOWARN).is_err());
50 /// ```
51 ///
52 /// ```
53 /// # use kernel::bindings;
54 /// const SIZE: usize = bindings::KMALLOC_MAX_SIZE as usize + 1;
55 /// struct Huge([u8; SIZE]);
56 ///
57 /// assert!(KVBox::<Huge>::new_uninit(GFP_KERNEL).is_ok());
58 /// ```
59 ///
60 /// [`Box`]es can also be used to store trait objects by coercing their type:
61 ///
62 /// ```
63 /// trait FooTrait {}
64 ///
65 /// struct FooStruct;
66 /// impl FooTrait for FooStruct {}
67 ///
68 /// let _ = KBox::new(FooStruct, GFP_KERNEL)? as KBox<dyn FooTrait>;
69 /// # Ok::<(), Error>(())
70 /// ```
71 ///
72 /// # Invariants
73 ///
74 /// `self.0` is always properly aligned and either points to memory allocated with `A` or, for
75 /// zero-sized types, is a dangling, well aligned pointer.
76 #[repr(transparent)]
77 #[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, derive(core::marker::CoercePointee))]
78 pub struct Box<#[cfg_attr(CONFIG_RUSTC_HAS_COERCE_POINTEE, pointee)] T: ?Sized, A: Allocator>(
79     NonNull<T>,
80     PhantomData<A>,
81 );
82 
83 // This is to allow coercion from `Box<T, A>` to `Box<U, A>` if `T` can be converted to the
84 // dynamically-sized type (DST) `U`.
85 #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]
86 impl<T, U, A> core::ops::CoerceUnsized<Box<U, A>> for Box<T, A>
87 where
88     T: ?Sized + core::marker::Unsize<U>,
89     U: ?Sized,
90     A: Allocator,
91 {
92 }
93 
94 // This is to allow `Box<U, A>` to be dispatched on when `Box<T, A>` can be coerced into `Box<U,
95 // A>`.
96 #[cfg(not(CONFIG_RUSTC_HAS_COERCE_POINTEE))]
97 impl<T, U, A> core::ops::DispatchFromDyn<Box<U, A>> for Box<T, A>
98 where
99     T: ?Sized + core::marker::Unsize<U>,
100     U: ?Sized,
101     A: Allocator,
102 {
103 }
104 
105 /// Type alias for [`Box`] with a [`Kmalloc`] allocator.
106 ///
107 /// # Examples
108 ///
109 /// ```
110 /// let b = KBox::new(24_u64, GFP_KERNEL)?;
111 ///
112 /// assert_eq!(*b, 24_u64);
113 /// # Ok::<(), Error>(())
114 /// ```
115 pub type KBox<T> = Box<T, super::allocator::Kmalloc>;
116 
117 /// Type alias for [`Box`] with a [`Vmalloc`] allocator.
118 ///
119 /// # Examples
120 ///
121 /// ```
122 /// let b = VBox::new(24_u64, GFP_KERNEL)?;
123 ///
124 /// assert_eq!(*b, 24_u64);
125 /// # Ok::<(), Error>(())
126 /// ```
127 pub type VBox<T> = Box<T, super::allocator::Vmalloc>;
128 
129 /// Type alias for [`Box`] with a [`KVmalloc`] allocator.
130 ///
131 /// # Examples
132 ///
133 /// ```
134 /// let b = KVBox::new(24_u64, GFP_KERNEL)?;
135 ///
136 /// assert_eq!(*b, 24_u64);
137 /// # Ok::<(), Error>(())
138 /// ```
139 pub type KVBox<T> = Box<T, super::allocator::KVmalloc>;
140 
141 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee:
142 // https://doc.rust-lang.org/stable/std/option/index.html#representation).
143 unsafe impl<T, A: Allocator> ZeroableOption for Box<T, A> {}
144 
145 // SAFETY: `Box` is `Send` if `T` is `Send` because the `Box` owns a `T`.
146 unsafe impl<T, A> Send for Box<T, A>
147 where
148     T: Send + ?Sized,
149     A: Allocator,
150 {
151 }
152 
153 // SAFETY: `Box` is `Sync` if `T` is `Sync` because the `Box` owns a `T`.
154 unsafe impl<T, A> Sync for Box<T, A>
155 where
156     T: Sync + ?Sized,
157     A: Allocator,
158 {
159 }
160 
161 impl<T, A> Box<T, A>
162 where
163     T: ?Sized,
164     A: Allocator,
165 {
166     /// Creates a new `Box<T, A>` from a raw pointer.
167     ///
168     /// # Safety
169     ///
170     /// For non-ZSTs, `raw` must point at an allocation allocated with `A` that is sufficiently
171     /// aligned for and holds a valid `T`. The caller passes ownership of the allocation to the
172     /// `Box`.
173     ///
174     /// For ZSTs, `raw` must be a dangling, well aligned pointer.
175     #[inline]
176     pub const unsafe fn from_raw(raw: *mut T) -> Self {
177         // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function.
178         // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer.
179         Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData)
180     }
181 
182     /// Consumes the `Box<T, A>` and returns a raw pointer.
183     ///
184     /// This will not run the destructor of `T` and for non-ZSTs the allocation will stay alive
185     /// indefinitely. Use [`Box::from_raw`] to recover the [`Box`], drop the value and free the
186     /// allocation, if any.
187     ///
188     /// # Examples
189     ///
190     /// ```
191     /// let x = KBox::new(24, GFP_KERNEL)?;
192     /// let ptr = KBox::into_raw(x);
193     /// // SAFETY: `ptr` comes from a previous call to `KBox::into_raw`.
194     /// let x = unsafe { KBox::from_raw(ptr) };
195     ///
196     /// assert_eq!(*x, 24);
197     /// # Ok::<(), Error>(())
198     /// ```
199     #[inline]
200     pub fn into_raw(b: Self) -> *mut T {
201         ManuallyDrop::new(b).0.as_ptr()
202     }
203 
204     /// Consumes and leaks the `Box<T, A>` and returns a mutable reference.
205     ///
206     /// See [`Box::into_raw`] for more details.
207     #[inline]
208     pub fn leak<'a>(b: Self) -> &'a mut T {
209         // SAFETY: `Box::into_raw` always returns a properly aligned and dereferenceable pointer
210         // which points to an initialized instance of `T`.
211         unsafe { &mut *Box::into_raw(b) }
212     }
213 }
214 
215 impl<T, A> Box<MaybeUninit<T>, A>
216 where
217     A: Allocator,
218 {
219     /// Converts a `Box<MaybeUninit<T>, A>` to a `Box<T, A>`.
220     ///
221     /// It is undefined behavior to call this function while the value inside of `b` is not yet
222     /// fully initialized.
223     ///
224     /// # Safety
225     ///
226     /// Callers must ensure that the value inside of `b` is in an initialized state.
227     pub unsafe fn assume_init(self) -> Box<T, A> {
228         let raw = Self::into_raw(self);
229 
230         // SAFETY: `raw` comes from a previous call to `Box::into_raw`. By the safety requirements
231         // of this function, the value inside the `Box` is in an initialized state. Hence, it is
232         // safe to reconstruct the `Box` as `Box<T, A>`.
233         unsafe { Box::from_raw(raw.cast()) }
234     }
235 
236     /// Writes the value and converts to `Box<T, A>`.
237     pub fn write(mut self, value: T) -> Box<T, A> {
238         (*self).write(value);
239 
240         // SAFETY: We've just initialized `b`'s value.
241         unsafe { self.assume_init() }
242     }
243 }
244 
245 impl<T, A> Box<T, A>
246 where
247     A: Allocator,
248 {
249     /// Creates a new `Box<T, A>` and initializes its contents with `x`.
250     ///
251     /// New memory is allocated with `A`. The allocation may fail, in which case an error is
252     /// returned. For ZSTs no memory is allocated.
253     pub fn new(x: T, flags: Flags) -> Result<Self, AllocError> {
254         let b = Self::new_uninit(flags)?;
255         Ok(Box::write(b, x))
256     }
257 
258     /// Creates a new `Box<T, A>` with uninitialized contents.
259     ///
260     /// New memory is allocated with `A`. The allocation may fail, in which case an error is
261     /// returned. For ZSTs no memory is allocated.
262     ///
263     /// # Examples
264     ///
265     /// ```
266     /// let b = KBox::<u64>::new_uninit(GFP_KERNEL)?;
267     /// let b = KBox::write(b, 24);
268     ///
269     /// assert_eq!(*b, 24_u64);
270     /// # Ok::<(), Error>(())
271     /// ```
272     pub fn new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError> {
273         let layout = Layout::new::<MaybeUninit<T>>();
274         let ptr = A::alloc(layout, flags)?;
275 
276         // INVARIANT: `ptr` is either a dangling pointer or points to memory allocated with `A`,
277         // which is sufficient in size and alignment for storing a `T`.
278         Ok(Box(ptr.cast(), PhantomData))
279     }
280 
281     /// Constructs a new `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then `x` will be
282     /// pinned in memory and can't be moved.
283     #[inline]
284     pub fn pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError>
285     where
286         A: 'static,
287     {
288         Ok(Self::new(x, flags)?.into())
289     }
290 
291     /// Convert a [`Box<T,A>`] to a [`Pin<Box<T,A>>`]. If `T` does not implement
292     /// [`Unpin`], then `x` will be pinned in memory and can't be moved.
293     pub fn into_pin(this: Self) -> Pin<Self> {
294         this.into()
295     }
296 
297     /// Forgets the contents (does not run the destructor), but keeps the allocation.
298     fn forget_contents(this: Self) -> Box<MaybeUninit<T>, A> {
299         let ptr = Self::into_raw(this);
300 
301         // SAFETY: `ptr` is valid, because it came from `Box::into_raw`.
302         unsafe { Box::from_raw(ptr.cast()) }
303     }
304 
305     /// Drops the contents, but keeps the allocation.
306     ///
307     /// # Examples
308     ///
309     /// ```
310     /// let value = KBox::new([0; 32], GFP_KERNEL)?;
311     /// assert_eq!(*value, [0; 32]);
312     /// let value = KBox::drop_contents(value);
313     /// // Now we can re-use `value`:
314     /// let value = KBox::write(value, [1; 32]);
315     /// assert_eq!(*value, [1; 32]);
316     /// # Ok::<(), Error>(())
317     /// ```
318     pub fn drop_contents(this: Self) -> Box<MaybeUninit<T>, A> {
319         let ptr = this.0.as_ptr();
320 
321         // SAFETY: `ptr` is valid, because it came from `this`. After this call we never access the
322         // value stored in `this` again.
323         unsafe { core::ptr::drop_in_place(ptr) };
324 
325         Self::forget_contents(this)
326     }
327 
328     /// Moves the `Box`'s value out of the `Box` and consumes the `Box`.
329     pub fn into_inner(b: Self) -> T {
330         // SAFETY: By the type invariant `&*b` is valid for `read`.
331         let value = unsafe { core::ptr::read(&*b) };
332         let _ = Self::forget_contents(b);
333         value
334     }
335 }
336 
337 impl<T, A> From<Box<T, A>> for Pin<Box<T, A>>
338 where
339     T: ?Sized,
340     A: Allocator,
341 {
342     /// Converts a `Box<T, A>` into a `Pin<Box<T, A>>`. If `T` does not implement [`Unpin`], then
343     /// `*b` will be pinned in memory and can't be moved.
344     ///
345     /// This moves `b` into `Pin` without moving `*b` or allocating and copying any memory.
346     fn from(b: Box<T, A>) -> Self {
347         // SAFETY: The value wrapped inside a `Pin<Box<T, A>>` cannot be moved or replaced as long
348         // as `T` does not implement `Unpin`.
349         unsafe { Pin::new_unchecked(b) }
350     }
351 }
352 
353 impl<T, A> InPlaceWrite<T> for Box<MaybeUninit<T>, A>
354 where
355     A: Allocator + 'static,
356 {
357     type Initialized = Box<T, A>;
358 
359     fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> {
360         let slot = self.as_mut_ptr();
361         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
362         // slot is valid.
363         unsafe { init.__init(slot)? };
364         // SAFETY: All fields have been initialized.
365         Ok(unsafe { Box::assume_init(self) })
366     }
367 
368     fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> {
369         let slot = self.as_mut_ptr();
370         // SAFETY: When init errors/panics, slot will get deallocated but not dropped,
371         // slot is valid and will not be moved, because we pin it later.
372         unsafe { init.__pinned_init(slot)? };
373         // SAFETY: All fields have been initialized.
374         Ok(unsafe { Box::assume_init(self) }.into())
375     }
376 }
377 
378 impl<T, A> InPlaceInit<T> for Box<T, A>
379 where
380     A: Allocator + 'static,
381 {
382     type PinnedSelf = Pin<Self>;
383 
384     #[inline]
385     fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Pin<Self>, E>
386     where
387         E: From<AllocError>,
388     {
389         Box::<_, A>::new_uninit(flags)?.write_pin_init(init)
390     }
391 
392     #[inline]
393     fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E>
394     where
395         E: From<AllocError>,
396     {
397         Box::<_, A>::new_uninit(flags)?.write_init(init)
398     }
399 }
400 
401 impl<T: 'static, A> ForeignOwnable for Box<T, A>
402 where
403     A: Allocator,
404 {
405     type Borrowed<'a> = &'a T;
406     type BorrowedMut<'a> = &'a mut T;
407 
408     fn into_foreign(self) -> *mut crate::ffi::c_void {
409         Box::into_raw(self).cast()
410     }
411 
412     unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self {
413         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
414         // call to `Self::into_foreign`.
415         unsafe { Box::from_raw(ptr.cast()) }
416     }
417 
418     unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> &'a T {
419         // SAFETY: The safety requirements of this method ensure that the object remains alive and
420         // immutable for the duration of 'a.
421         unsafe { &*ptr.cast() }
422     }
423 
424     unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> &'a mut T {
425         let ptr = ptr.cast();
426         // SAFETY: The safety requirements of this method ensure that the pointer is valid and that
427         // nothing else will access the value for the duration of 'a.
428         unsafe { &mut *ptr }
429     }
430 }
431 
432 impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
433 where
434     A: Allocator,
435 {
436     type Borrowed<'a> = Pin<&'a T>;
437     type BorrowedMut<'a> = Pin<&'a mut T>;
438 
439     fn into_foreign(self) -> *mut crate::ffi::c_void {
440         // SAFETY: We are still treating the box as pinned.
441         Box::into_raw(unsafe { Pin::into_inner_unchecked(self) }).cast()
442     }
443 
444     unsafe fn from_foreign(ptr: *mut crate::ffi::c_void) -> Self {
445         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
446         // call to `Self::into_foreign`.
447         unsafe { Pin::new_unchecked(Box::from_raw(ptr.cast())) }
448     }
449 
450     unsafe fn borrow<'a>(ptr: *mut crate::ffi::c_void) -> Pin<&'a T> {
451         // SAFETY: The safety requirements for this function ensure that the object is still alive,
452         // so it is safe to dereference the raw pointer.
453         // The safety requirements of `from_foreign` also ensure that the object remains alive for
454         // the lifetime of the returned value.
455         let r = unsafe { &*ptr.cast() };
456 
457         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
458         unsafe { Pin::new_unchecked(r) }
459     }
460 
461     unsafe fn borrow_mut<'a>(ptr: *mut crate::ffi::c_void) -> Pin<&'a mut T> {
462         let ptr = ptr.cast();
463         // SAFETY: The safety requirements for this function ensure that the object is still alive,
464         // so it is safe to dereference the raw pointer.
465         // The safety requirements of `from_foreign` also ensure that the object remains alive for
466         // the lifetime of the returned value.
467         let r = unsafe { &mut *ptr };
468 
469         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
470         unsafe { Pin::new_unchecked(r) }
471     }
472 }
473 
474 impl<T, A> Deref for Box<T, A>
475 where
476     T: ?Sized,
477     A: Allocator,
478 {
479     type Target = T;
480 
481     fn deref(&self) -> &T {
482         // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
483         // instance of `T`.
484         unsafe { self.0.as_ref() }
485     }
486 }
487 
488 impl<T, A> DerefMut for Box<T, A>
489 where
490     T: ?Sized,
491     A: Allocator,
492 {
493     fn deref_mut(&mut self) -> &mut T {
494         // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
495         // instance of `T`.
496         unsafe { self.0.as_mut() }
497     }
498 }
499 
500 impl<T, A> fmt::Display for Box<T, A>
501 where
502     T: ?Sized + fmt::Display,
503     A: Allocator,
504 {
505     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
506         <T as fmt::Display>::fmt(&**self, f)
507     }
508 }
509 
510 impl<T, A> fmt::Debug for Box<T, A>
511 where
512     T: ?Sized + fmt::Debug,
513     A: Allocator,
514 {
515     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
516         <T as fmt::Debug>::fmt(&**self, f)
517     }
518 }
519 
520 impl<T, A> Drop for Box<T, A>
521 where
522     T: ?Sized,
523     A: Allocator,
524 {
525     fn drop(&mut self) {
526         let layout = Layout::for_value::<T>(self);
527 
528         // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant.
529         unsafe { core::ptr::drop_in_place::<T>(self.deref_mut()) };
530 
531         // SAFETY:
532         // - `self.0` was previously allocated with `A`.
533         // - `layout` is equal to the `Layout´ `self.0` was allocated with.
534         unsafe { A::free(self.0.cast(), layout) };
535     }
536 }
537