1 // SPDX-License-Identifier: GPL-2.0 2 3 //! Basic utilities for dealing with memory, values, and types. 4 5 // TODO: `Alignment` should be moved here as well, Rust moved it upstream in 1.96. 6 pub use crate::ptr::Alignment; 7 use crate::prelude::*; 8 9 /// Trait indicating that [`Align<N>`] is a valid alignment. 10 pub trait ValidAlign { 11 #[doc(hidden)] 12 type Repr: Copy; 13 } 14 15 /// Zero-sized type that provides the alignment specified via the generic parameter. 16 /// 17 /// # Examples 18 /// 19 /// ``` 20 /// # use kernel::mem::Align; 21 /// const ALIGN: usize = 128; 22 /// struct MyStruct { 23 /// _align: Align<ALIGN>, 24 /// } 25 /// assert_eq!(align_of::<MyStruct>(), ALIGN); 26 /// ``` 27 #[repr(transparent)] 28 #[derive(Default, Clone, Copy)] 29 pub struct Align<const N: usize>([<Self as ValidAlign>::Repr; 0]) 30 where 31 Self: ValidAlign; 32 33 impl<const N: usize> Align<N> 34 where 35 Self: ValidAlign, 36 { 37 /// Create a new [`Align<N>`]. 38 #[inline] 39 pub const fn new() -> Self { 40 Align([]) 41 } 42 } 43 44 macro_rules! impl_align { 45 () => {}; 46 ($a:literal $($rest:literal)*) => { 47 const _: () = { 48 #[repr(align($a))] 49 #[derive(Clone, Copy)] 50 pub struct Repr; 51 52 impl ValidAlign for Align<$a> { 53 type Repr = Repr; 54 } 55 }; 56 57 impl_align!($($rest)*); 58 } 59 } 60 61 impl_align!(1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768 65536); 62 63 impl<const N: usize> core::fmt::Debug for Align<N> 64 where 65 Self: ValidAlign, 66 { 67 #[inline] 68 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { 69 write!(f, "Align<{N}>") 70 } 71 } 72 73 /// Transmute between two types. 74 /// 75 /// Use this instead of [`core::mem::transmute`] when it is known that sizes are identical but this 76 /// cannot be proven by the compiler. 77 /// 78 /// This is equivalent to Rust's `transmute_unchecked` intrinsics. 79 /// 80 /// # Safety 81 /// 82 /// All safety requirements of [`core::mem::transmute`] apply, plus that the size `Src` and `Dst` 83 /// must match. 84 /// 85 /// # Examples 86 /// 87 /// This can be used when types are known to have the same size, but only at runtime. 88 /// 89 /// ```no_run 90 /// # use core::any::TypeId; 91 /// fn to_u32<T: 'static>(v: T) -> Option<u32> { 92 /// if TypeId::of::<T>() != TypeId::of::<u32>() { 93 /// return None; 94 /// } 95 /// 96 /// // `core::mem::transmute` won't work here. 97 /// // SAFETY: We've checked that `T` is `u32`! 98 /// Some(unsafe { kernel::mem::transmute_unchecked(v) }) 99 /// } 100 /// 101 /// to_u32(1u32); 102 /// ``` 103 #[inline(always)] 104 pub const unsafe fn transmute_unchecked<Src, Dst>(val: Src) -> Dst { 105 // SAFETY: This is identical to `transmute` except that we bypassed the size check; which is 106 // true per safety requirement. 107 unsafe { core::mem::transmute_copy(&core::mem::ManuallyDrop::new(val)) } 108 } 109 110 /// Version of `transmute` that performs size check at monomorphization-time. 111 /// 112 /// Use this instead of [`core::mem::transmute`] when it is known that sizes are identical but this 113 /// cannot be proven by the compiler during type checking and can be proven during monomorphization. 114 /// 115 /// The signature is equivalent to Rust standard library's unstable `transmute_neo` and that of 116 /// [RFC 3844](https://github.com/rust-lang/rfcs/pull/3844). 117 /// 118 /// # Safety 119 /// 120 /// Same as [`core::mem::transmute`]. 121 /// 122 /// # Examples 123 /// 124 /// This is typically used in generic code where it's known that type will have the same size, but 125 /// the compiler cannot prove it generically. 126 /// 127 /// ```no_run 128 /// trait IsU32 {} 129 /// impl IsU32 for u32 {} 130 /// 131 /// fn to_u32<T: IsU32>(v: T) -> u32 { 132 /// // `core::mem::transmute` won't work here. 133 /// // SAFETY: We know that `v` is u32! 134 /// unsafe { kernel::mem::transmute(v) } 135 /// } 136 /// 137 /// to_u32(1u32); 138 /// ``` 139 #[inline(always)] 140 pub const unsafe fn transmute<Src, Dst>(val: Src) -> Dst { 141 const_assert!(size_of::<Src>() == size_of::<Dst>()); 142 143 // SAFETY: Size is checked above. Other safety requirements follow those of the function. 144 unsafe { transmute_unchecked(val) } 145 } 146 147 /// Safely transmutes a value of one type to a value of another type of the same size. 148 /// 149 /// The sizes are checked during monomorphization. 150 /// 151 /// This can be considered as generic version of [`zerocopy::transmute!`] macro that defers the size 152 /// check and thus can be used in more cases. 153 /// 154 /// # Examples 155 /// 156 /// ```no_run 157 /// fn to_u32<T: FromBytes + IntoBytes>(v: T) -> u32 { 158 /// // `zerocopy::transmute!` won't work here. 159 /// kernel::mem::safe_transmute(v) 160 /// } 161 /// 162 /// to_u32(1i32); 163 /// ``` 164 #[inline(always)] 165 pub const fn safe_transmute<Src: IntoBytes, Dst: FromBytes>(val: Src) -> Dst { 166 // SAFETY: `transmute` is safe with `IntoBytes` and `FromBytes` bounds. 167 unsafe { transmute(val) } 168 } 169 170 /// Type that is layout-compatible with a primitive representation. 171 /// 172 /// # Safety 173 /// 174 /// - [`Self`] must have the same size and alignment as [`Self::Repr`]. 175 /// - [`Self`] must be [transmutable] to [`Self::Repr`]. 176 /// - Neither [`Self`] nor [`Self::Repr`] contains interior mutability. 177 /// 178 /// The above basically says that `&Self` can be transmuted to `&Self::Repr`. 179 /// 180 /// [transmutable]: core::mem::transmute 181 pub unsafe trait AsRepr: Sized { 182 /// Primitive representation of this type. 183 type Repr; 184 185 /// Convert from [`&Self`](Self) to [`&Self::Repr`](AsRepr::Repr). 186 #[inline(always)] 187 fn as_repr(this: &Self) -> &Self::Repr { 188 // SAFETY: Per safety requirement of the trait. 189 unsafe { core::mem::transmute(this) } 190 } 191 192 /// Convert from [`Self`] to [`Self::Repr`]. 193 #[inline(always)] 194 fn into_repr(this: Self) -> Self::Repr { 195 // SAFETY: Per safety requirement of the trait. 196 unsafe { transmute(this) } 197 } 198 199 /// Convert from [`Self::Repr`] to [`Self`]. 200 /// 201 /// # Safety 202 /// 203 /// `repr` must be a valid bit pattern of [`Self`] and satisfy type-specific invariants of it. 204 /// 205 /// Alternatively, if `repr` is previously obtained using [`Self::into_repr`], and each 206 /// `from_repr_unchecked` should correspond to a unique `into_repr` call, then it is safe to 207 /// call as well (this means that we're undoing a `into_repr` call getting the exact bytes 208 /// back). 209 /// 210 /// No guarantee is made if the result of a `into_repr` is passed to multiple 211 /// `from_repr_unchecked` (i.e. copies are made), to allow for cases where `Repr` is a pointer 212 /// and the user of the API wants ownership transfer. Users that want the ability to call 213 /// `from_repr_unchecked` after copying can require `Copy` bound explicitly. 214 #[inline(always)] 215 unsafe fn from_repr_unchecked(repr: Self::Repr) -> Self { 216 // SAFETY: Per safety requirement, `repr` is valid repr of `Self`, or it is previously from 217 // `into_repr`, in which case we're undoing the transmute so it is also safe. 218 unsafe { transmute(repr) } 219 } 220 } 221 222 /// Type that is bi-directionally transmutable with a primitive representation. 223 /// 224 /// # Safety 225 /// 226 /// - [`Self`] must be [transmutable] from [`Self::Repr`]. 227 /// 228 /// [transmutable]: core::mem::transmute 229 /// [`Self::Repr`]: AsRepr::Repr 230 pub unsafe trait AsReprMut: AsRepr { 231 /// Convert from `&mut Self` to [`&mut Self::Repr`](AsRepr::Repr). 232 #[inline(always)] 233 fn as_repr_mut(this: &mut Self) -> &mut Self::Repr { 234 // SAFETY: Per safety requirement of the trait. 235 unsafe { core::mem::transmute(this) } 236 } 237 238 /// Convert from [`Self::Repr`](AsRepr::Repr) to `Self`. 239 #[inline(always)] 240 fn from_repr(repr: Self::Repr) -> Self { 241 // SAFETY: Per safety requirement of the trait. 242 unsafe { transmute(repr) } 243 } 244 } 245 246 // SAFETY: `bool` has the same size and alignment as `u8`, and Rust guarantees that `bool` has 247 // only two valid bit patterns: 0 (`false`) and 1 (`true`). Thus `bool` can be transmuted to `u8`. 248 // Neither types contain interior mutability. 249 unsafe impl AsRepr for bool { 250 type Repr = u8; 251 } 252 253 // SAFETY: `*mut T` has the same size and alignment with `*const c_void`, and thus `*mut T` is 254 // transmutable to `*const c_void`. Neither types contain interior mutability. 255 unsafe impl<T> AsRepr for *mut T { 256 type Repr = *const c_void; 257 } 258 259 // SAFETY: `*mut T` is transmutable from `*const c_void`. 260 unsafe impl<T> AsReprMut for *mut T {} 261 262 // SAFETY: `*const T` has the same size and alignment with `*const c_void`, and is transmutable to 263 // `*const c_void`. Neither types contain interior mutability. 264 unsafe impl<T> AsRepr for *const T { 265 type Repr = *const c_void; 266 } 267 268 // SAFETY: `*const T` is transmutable from `*const c_void`. 269 unsafe impl<T> AsReprMut for *const T {} 270 271 macro_rules! int_impl { 272 ($($unsigned:ident $signed:ident ,)*) => {$( 273 // SAFETY: `$unsigned` has the same size and alignment with itself, and is transmutable to 274 // itself. It does not contain interior mutability. 275 unsafe impl AsRepr for $unsigned { 276 type Repr = $unsigned; 277 } 278 279 // SAFETY: `$unsigned` is transmutable from itself. 280 unsafe impl AsReprMut for $unsigned {} 281 282 // SAFETY: `$signed` has the same size and alignment with `$unsigned`, and is transmutable 283 // to it Neither types contain interior mutability. 284 unsafe impl AsRepr for $signed { 285 type Repr = $unsigned; 286 } 287 288 // SAFETY: `$signed` is transmutable from `$unsigned`. 289 unsafe impl AsReprMut for $signed {} 290 )*}; 291 } 292 293 int_impl! { 294 u8 i8, 295 u16 i16, 296 u32 i32, 297 u64 i64, 298 // `usize` is not normalized to particular integer for portability. 299 usize isize, 300 } 301