__internal.rs 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. // SPDX-License-Identifier: Apache-2.0 OR MIT
  2. //! This module contains API-internal items for pin-init.
  3. //!
  4. //! These items must not be used outside of
  5. //! - `kernel/init.rs`
  6. //! - `macros/pin_data.rs`
  7. //! - `macros/pinned_drop.rs`
  8. use super::*;
  9. /// See the [nomicon] for what subtyping is. See also [this table].
  10. ///
  11. /// [nomicon]: https://doc.rust-lang.org/nomicon/subtyping.html
  12. /// [this table]: https://doc.rust-lang.org/nomicon/phantom-data.html#table-of-phantomdata-patterns
  13. pub(super) type Invariant<T> = PhantomData<fn(*mut T) -> *mut T>;
  14. /// Module-internal type implementing `PinInit` and `Init`.
  15. ///
  16. /// It is unsafe to create this type, since the closure needs to fulfill the same safety
  17. /// requirement as the `__pinned_init`/`__init` functions.
  18. pub(crate) struct InitClosure<F, T: ?Sized, E>(pub(crate) F, pub(crate) Invariant<(E, T)>);
  19. // SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
  20. // `__init` invariants.
  21. unsafe impl<T: ?Sized, F, E> Init<T, E> for InitClosure<F, T, E>
  22. where
  23. F: FnOnce(*mut T) -> Result<(), E>,
  24. {
  25. #[inline]
  26. unsafe fn __init(self, slot: *mut T) -> Result<(), E> {
  27. (self.0)(slot)
  28. }
  29. }
  30. // SAFETY: While constructing the `InitClosure`, the user promised that it upholds the
  31. // `__pinned_init` invariants.
  32. unsafe impl<T: ?Sized, F, E> PinInit<T, E> for InitClosure<F, T, E>
  33. where
  34. F: FnOnce(*mut T) -> Result<(), E>,
  35. {
  36. #[inline]
  37. unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> {
  38. (self.0)(slot)
  39. }
  40. }
  41. /// This trait is only implemented via the `#[pin_data]` proc-macro. It is used to facilitate
  42. /// the pin projections within the initializers.
  43. ///
  44. /// # Safety
  45. ///
  46. /// Only the `init` module is allowed to use this trait.
  47. pub unsafe trait HasPinData {
  48. type PinData: PinData;
  49. #[expect(clippy::missing_safety_doc)]
  50. unsafe fn __pin_data() -> Self::PinData;
  51. }
  52. /// Marker trait for pinning data of structs.
  53. ///
  54. /// # Safety
  55. ///
  56. /// Only the `init` module is allowed to use this trait.
  57. pub unsafe trait PinData: Copy {
  58. type Datee: ?Sized + HasPinData;
  59. /// Type inference helper function.
  60. fn make_closure<F, O, E>(self, f: F) -> F
  61. where
  62. F: FnOnce(*mut Self::Datee) -> Result<O, E>,
  63. {
  64. f
  65. }
  66. }
  67. /// This trait is automatically implemented for every type. It aims to provide the same type
  68. /// inference help as `HasPinData`.
  69. ///
  70. /// # Safety
  71. ///
  72. /// Only the `init` module is allowed to use this trait.
  73. pub unsafe trait HasInitData {
  74. type InitData: InitData;
  75. #[expect(clippy::missing_safety_doc)]
  76. unsafe fn __init_data() -> Self::InitData;
  77. }
  78. /// Same function as `PinData`, but for arbitrary data.
  79. ///
  80. /// # Safety
  81. ///
  82. /// Only the `init` module is allowed to use this trait.
  83. pub unsafe trait InitData: Copy {
  84. type Datee: ?Sized + HasInitData;
  85. /// Type inference helper function.
  86. fn make_closure<F, O, E>(self, f: F) -> F
  87. where
  88. F: FnOnce(*mut Self::Datee) -> Result<O, E>,
  89. {
  90. f
  91. }
  92. }
  93. pub struct AllData<T: ?Sized>(PhantomData<fn(KBox<T>) -> KBox<T>>);
  94. impl<T: ?Sized> Clone for AllData<T> {
  95. fn clone(&self) -> Self {
  96. *self
  97. }
  98. }
  99. impl<T: ?Sized> Copy for AllData<T> {}
  100. // SAFETY: TODO.
  101. unsafe impl<T: ?Sized> InitData for AllData<T> {
  102. type Datee = T;
  103. }
  104. // SAFETY: TODO.
  105. unsafe impl<T: ?Sized> HasInitData for T {
  106. type InitData = AllData<T>;
  107. unsafe fn __init_data() -> Self::InitData {
  108. AllData(PhantomData)
  109. }
  110. }
  111. /// Stack initializer helper type. Use [`stack_pin_init`] instead of this primitive.
  112. ///
  113. /// # Invariants
  114. ///
  115. /// If `self.is_init` is true, then `self.value` is initialized.
  116. ///
  117. /// [`stack_pin_init`]: kernel::stack_pin_init
  118. pub struct StackInit<T> {
  119. value: MaybeUninit<T>,
  120. is_init: bool,
  121. }
  122. impl<T> Drop for StackInit<T> {
  123. #[inline]
  124. fn drop(&mut self) {
  125. if self.is_init {
  126. // SAFETY: As we are being dropped, we only call this once. And since `self.is_init` is
  127. // true, `self.value` is initialized.
  128. unsafe { self.value.assume_init_drop() };
  129. }
  130. }
  131. }
  132. impl<T> StackInit<T> {
  133. /// Creates a new [`StackInit<T>`] that is uninitialized. Use [`stack_pin_init`] instead of this
  134. /// primitive.
  135. ///
  136. /// [`stack_pin_init`]: kernel::stack_pin_init
  137. #[inline]
  138. pub fn uninit() -> Self {
  139. Self {
  140. value: MaybeUninit::uninit(),
  141. is_init: false,
  142. }
  143. }
  144. /// Initializes the contents and returns the result.
  145. #[inline]
  146. pub fn init<E>(self: Pin<&mut Self>, init: impl PinInit<T, E>) -> Result<Pin<&mut T>, E> {
  147. // SAFETY: We never move out of `this`.
  148. let this = unsafe { Pin::into_inner_unchecked(self) };
  149. // The value is currently initialized, so it needs to be dropped before we can reuse
  150. // the memory (this is a safety guarantee of `Pin`).
  151. if this.is_init {
  152. this.is_init = false;
  153. // SAFETY: `this.is_init` was true and therefore `this.value` is initialized.
  154. unsafe { this.value.assume_init_drop() };
  155. }
  156. // SAFETY: The memory slot is valid and this type ensures that it will stay pinned.
  157. unsafe { init.__pinned_init(this.value.as_mut_ptr())? };
  158. // INVARIANT: `this.value` is initialized above.
  159. this.is_init = true;
  160. // SAFETY: The slot is now pinned, since we will never give access to `&mut T`.
  161. Ok(unsafe { Pin::new_unchecked(this.value.assume_init_mut()) })
  162. }
  163. }
  164. /// When a value of this type is dropped, it drops a `T`.
  165. ///
  166. /// Can be forgotten to prevent the drop.
  167. pub struct DropGuard<T: ?Sized> {
  168. ptr: *mut T,
  169. }
  170. impl<T: ?Sized> DropGuard<T> {
  171. /// Creates a new [`DropGuard<T>`]. It will [`ptr::drop_in_place`] `ptr` when it gets dropped.
  172. ///
  173. /// # Safety
  174. ///
  175. /// `ptr` must be a valid pointer.
  176. ///
  177. /// It is the callers responsibility that `self` will only get dropped if the pointee of `ptr`:
  178. /// - has not been dropped,
  179. /// - is not accessible by any other means,
  180. /// - will not be dropped by any other means.
  181. #[inline]
  182. pub unsafe fn new(ptr: *mut T) -> Self {
  183. Self { ptr }
  184. }
  185. }
  186. impl<T: ?Sized> Drop for DropGuard<T> {
  187. #[inline]
  188. fn drop(&mut self) {
  189. // SAFETY: A `DropGuard` can only be constructed using the unsafe `new` function
  190. // ensuring that this operation is safe.
  191. unsafe { ptr::drop_in_place(self.ptr) }
  192. }
  193. }
  194. /// Token used by `PinnedDrop` to prevent calling the function without creating this unsafely
  195. /// created struct. This is needed, because the `drop` function is safe, but should not be called
  196. /// manually.
  197. pub struct OnlyCallFromDrop(());
  198. impl OnlyCallFromDrop {
  199. /// # Safety
  200. ///
  201. /// This function should only be called from the [`Drop::drop`] function and only be used to
  202. /// delegate the destruction to the pinned destructor [`PinnedDrop::drop`] of the same type.
  203. pub unsafe fn new() -> Self {
  204. Self(())
  205. }
  206. }
  207. /// Initializer that always fails.
  208. ///
  209. /// Used by [`assert_pinned!`].
  210. ///
  211. /// [`assert_pinned!`]: crate::assert_pinned
  212. pub struct AlwaysFail<T: ?Sized> {
  213. _t: PhantomData<T>,
  214. }
  215. impl<T: ?Sized> AlwaysFail<T> {
  216. /// Creates a new initializer that always fails.
  217. pub fn new() -> Self {
  218. Self { _t: PhantomData }
  219. }
  220. }
  221. impl<T: ?Sized> Default for AlwaysFail<T> {
  222. fn default() -> Self {
  223. Self::new()
  224. }
  225. }
  226. // SAFETY: `__pinned_init` always fails, which is always okay.
  227. unsafe impl<T: ?Sized> PinInit<T, ()> for AlwaysFail<T> {
  228. unsafe fn __pinned_init(self, _slot: *mut T) -> Result<(), ()> {
  229. Err(())
  230. }
  231. }