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