xref: /linux/rust/kernel/alloc/kbox.rs (revision ec7714e4947909190ffb3041a03311a975350fe0)
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]
from_raw(raw: *mut T) -> Self176     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]
into_raw(b: Self) -> *mut T200     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]
leak<'a>(b: Self) -> &'a mut T208     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.
assume_init(self) -> Box<T, A>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>`.
write(mut self, value: T) -> 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.
new(x: T, flags: Flags) -> Result<Self, AllocError>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     /// ```
new_uninit(flags: Flags) -> Result<Box<MaybeUninit<T>, A>, AllocError>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]
pin(x: T, flags: Flags) -> Result<Pin<Box<T, A>>, AllocError> where A: 'static,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.
into_pin(this: Self) -> Pin<Self>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.
forget_contents(this: Self) -> Box<MaybeUninit<T>, A>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     /// ```
drop_contents(this: Self) -> Box<MaybeUninit<T>, A>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`.
into_inner(b: Self) -> T329     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.
from(b: Box<T, A>) -> Self346     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 
write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E>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 
write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>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]
try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Pin<Self>, E> where E: From<AllocError>,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]
try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> where E: From<AllocError>,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 // SAFETY: The `into_foreign` function returns a pointer that is well-aligned.
402 unsafe impl<T: 'static, A> ForeignOwnable for Box<T, A>
403 where
404     A: Allocator,
405 {
406     type PointedTo = T;
407     type Borrowed<'a> = &'a T;
408     type BorrowedMut<'a> = &'a mut T;
409 
into_foreign(self) -> *mut Self::PointedTo410     fn into_foreign(self) -> *mut Self::PointedTo {
411         Box::into_raw(self)
412     }
413 
from_foreign(ptr: *mut Self::PointedTo) -> Self414     unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self {
415         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
416         // call to `Self::into_foreign`.
417         unsafe { Box::from_raw(ptr) }
418     }
419 
borrow<'a>(ptr: *mut Self::PointedTo) -> &'a T420     unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> &'a T {
421         // SAFETY: The safety requirements of this method ensure that the object remains alive and
422         // immutable for the duration of 'a.
423         unsafe { &*ptr }
424     }
425 
borrow_mut<'a>(ptr: *mut Self::PointedTo) -> &'a mut T426     unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> &'a mut T {
427         // SAFETY: The safety requirements of this method ensure that the pointer is valid and that
428         // nothing else will access the value for the duration of 'a.
429         unsafe { &mut *ptr }
430     }
431 }
432 
433 // SAFETY: The `into_foreign` function returns a pointer that is well-aligned.
434 unsafe impl<T: 'static, A> ForeignOwnable for Pin<Box<T, A>>
435 where
436     A: Allocator,
437 {
438     type PointedTo = T;
439     type Borrowed<'a> = Pin<&'a T>;
440     type BorrowedMut<'a> = Pin<&'a mut T>;
441 
into_foreign(self) -> *mut Self::PointedTo442     fn into_foreign(self) -> *mut Self::PointedTo {
443         // SAFETY: We are still treating the box as pinned.
444         Box::into_raw(unsafe { Pin::into_inner_unchecked(self) })
445     }
446 
from_foreign(ptr: *mut Self::PointedTo) -> Self447     unsafe fn from_foreign(ptr: *mut Self::PointedTo) -> Self {
448         // SAFETY: The safety requirements of this function ensure that `ptr` comes from a previous
449         // call to `Self::into_foreign`.
450         unsafe { Pin::new_unchecked(Box::from_raw(ptr)) }
451     }
452 
borrow<'a>(ptr: *mut Self::PointedTo) -> Pin<&'a T>453     unsafe fn borrow<'a>(ptr: *mut Self::PointedTo) -> Pin<&'a T> {
454         // SAFETY: The safety requirements for this function ensure that the object is still alive,
455         // so it is safe to dereference the raw pointer.
456         // The safety requirements of `from_foreign` also ensure that the object remains alive for
457         // the lifetime of the returned value.
458         let r = unsafe { &*ptr };
459 
460         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
461         unsafe { Pin::new_unchecked(r) }
462     }
463 
borrow_mut<'a>(ptr: *mut Self::PointedTo) -> Pin<&'a mut T>464     unsafe fn borrow_mut<'a>(ptr: *mut Self::PointedTo) -> Pin<&'a mut T> {
465         // SAFETY: The safety requirements for this function ensure that the object is still alive,
466         // so it is safe to dereference the raw pointer.
467         // The safety requirements of `from_foreign` also ensure that the object remains alive for
468         // the lifetime of the returned value.
469         let r = unsafe { &mut *ptr };
470 
471         // SAFETY: This pointer originates from a `Pin<Box<T>>`.
472         unsafe { Pin::new_unchecked(r) }
473     }
474 }
475 
476 impl<T, A> Deref for Box<T, A>
477 where
478     T: ?Sized,
479     A: Allocator,
480 {
481     type Target = T;
482 
deref(&self) -> &T483     fn deref(&self) -> &T {
484         // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
485         // instance of `T`.
486         unsafe { self.0.as_ref() }
487     }
488 }
489 
490 impl<T, A> DerefMut for Box<T, A>
491 where
492     T: ?Sized,
493     A: Allocator,
494 {
deref_mut(&mut self) -> &mut T495     fn deref_mut(&mut self) -> &mut T {
496         // SAFETY: `self.0` is always properly aligned, dereferenceable and points to an initialized
497         // instance of `T`.
498         unsafe { self.0.as_mut() }
499     }
500 }
501 
502 impl<T, A> fmt::Display for Box<T, A>
503 where
504     T: ?Sized + fmt::Display,
505     A: Allocator,
506 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result507     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
508         <T as fmt::Display>::fmt(&**self, f)
509     }
510 }
511 
512 impl<T, A> fmt::Debug for Box<T, A>
513 where
514     T: ?Sized + fmt::Debug,
515     A: Allocator,
516 {
fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result517     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
518         <T as fmt::Debug>::fmt(&**self, f)
519     }
520 }
521 
522 impl<T, A> Drop for Box<T, A>
523 where
524     T: ?Sized,
525     A: Allocator,
526 {
drop(&mut self)527     fn drop(&mut self) {
528         let layout = Layout::for_value::<T>(self);
529 
530         // SAFETY: The pointer in `self.0` is guaranteed to be valid by the type invariant.
531         unsafe { core::ptr::drop_in_place::<T>(self.deref_mut()) };
532 
533         // SAFETY:
534         // - `self.0` was previously allocated with `A`.
535         // - `layout` is equal to the `Layout´ `self.0` was allocated with.
536         unsafe { A::free(self.0.cast(), layout) };
537     }
538 }
539