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