1 // SPDX-License-Identifier: Apache-2.0 OR MIT 2 3 //! API to safely and fallibly initialize pinned `struct`s using in-place constructors. 4 //! 5 //! It also allows in-place initialization of big `struct`s that would otherwise produce a stack 6 //! overflow. 7 //! 8 //! Most `struct`s from the [`sync`] module need to be pinned, because they contain self-referential 9 //! `struct`s from C. [Pinning][pinning] is Rust's way of ensuring data does not move. 10 //! 11 //! # Overview 12 //! 13 //! To initialize a `struct` with an in-place constructor you will need two things: 14 //! - an in-place constructor, 15 //! - a memory location that can hold your `struct` (this can be the [stack], an [`Arc<T>`], 16 //! [`UniqueArc<T>`], [`Box<T>`] or any other smart pointer that implements [`InPlaceInit`]). 17 //! 18 //! To get an in-place constructor there are generally three options: 19 //! - directly creating an in-place constructor using the [`pin_init!`] macro, 20 //! - a custom function/macro returning an in-place constructor provided by someone else, 21 //! - using the unsafe function [`pin_init_from_closure()`] to manually create an initializer. 22 //! 23 //! Aside from pinned initialization, this API also supports in-place construction without pinning, 24 //! the macros/types/functions are generally named like the pinned variants without the `pin` 25 //! prefix. 26 //! 27 //! # Examples 28 //! 29 //! ## Using the [`pin_init!`] macro 30 //! 31 //! If you want to use [`PinInit`], then you will have to annotate your `struct` with 32 //! `#[`[`pin_data`]`]`. It is a macro that uses `#[pin]` as a marker for 33 //! [structurally pinned fields]. After doing this, you can then create an in-place constructor via 34 //! [`pin_init!`]. The syntax is almost the same as normal `struct` initializers. The difference is 35 //! that you need to write `<-` instead of `:` for fields that you want to initialize in-place. 36 //! 37 //! ```rust 38 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 39 //! use kernel::{prelude::*, sync::Mutex, new_mutex}; 40 //! # use core::pin::Pin; 41 //! #[pin_data] 42 //! struct Foo { 43 //! #[pin] 44 //! a: Mutex<usize>, 45 //! b: u32, 46 //! } 47 //! 48 //! let foo = pin_init!(Foo { 49 //! a <- new_mutex!(42, "Foo::a"), 50 //! b: 24, 51 //! }); 52 //! ``` 53 //! 54 //! `foo` now is of the type [`impl PinInit<Foo>`]. We can now use any smart pointer that we like 55 //! (or just the stack) to actually initialize a `Foo`: 56 //! 57 //! ```rust 58 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 59 //! # use kernel::{prelude::*, sync::Mutex, new_mutex}; 60 //! # use core::pin::Pin; 61 //! # #[pin_data] 62 //! # struct Foo { 63 //! # #[pin] 64 //! # a: Mutex<usize>, 65 //! # b: u32, 66 //! # } 67 //! # let foo = pin_init!(Foo { 68 //! # a <- new_mutex!(42, "Foo::a"), 69 //! # b: 24, 70 //! # }); 71 //! let foo: Result<Pin<Box<Foo>>> = Box::pin_init(foo); 72 //! ``` 73 //! 74 //! For more information see the [`pin_init!`] macro. 75 //! 76 //! ## Using a custom function/macro that returns an initializer 77 //! 78 //! Many types from the kernel supply a function/macro that returns an initializer, because the 79 //! above method only works for types where you can access the fields. 80 //! 81 //! ```rust 82 //! # use kernel::{new_mutex, sync::{Arc, Mutex}}; 83 //! let mtx: Result<Arc<Mutex<usize>>> = Arc::pin_init(new_mutex!(42, "example::mtx")); 84 //! ``` 85 //! 86 //! To declare an init macro/function you just return an [`impl PinInit<T, E>`]: 87 //! 88 //! ```rust 89 //! # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 90 //! # use kernel::{sync::Mutex, prelude::*, new_mutex, init::PinInit, try_pin_init}; 91 //! #[pin_data] 92 //! struct DriverData { 93 //! #[pin] 94 //! status: Mutex<i32>, 95 //! buffer: Box<[u8; 1_000_000]>, 96 //! } 97 //! 98 //! impl DriverData { 99 //! fn new() -> impl PinInit<Self, Error> { 100 //! try_pin_init!(Self { 101 //! status <- new_mutex!(0, "DriverData::status"), 102 //! buffer: Box::init(kernel::init::zeroed())?, 103 //! }) 104 //! } 105 //! } 106 //! ``` 107 //! 108 //! ## Manual creation of an initializer 109 //! 110 //! Often when working with primitives the previous approaches are not sufficient. That is where 111 //! [`pin_init_from_closure()`] comes in. This `unsafe` function allows you to create a 112 //! [`impl PinInit<T, E>`] directly from a closure. Of course you have to ensure that the closure 113 //! actually does the initialization in the correct way. Here are the things to look out for 114 //! (we are calling the parameter to the closure `slot`): 115 //! - when the closure returns `Ok(())`, then it has completed the initialization successfully, so 116 //! `slot` now contains a valid bit pattern for the type `T`, 117 //! - when the closure returns `Err(e)`, then the caller may deallocate the memory at `slot`, so 118 //! you need to take care to clean up anything if your initialization fails mid-way, 119 //! - you may assume that `slot` will stay pinned even after the closure returns until `drop` of 120 //! `slot` gets called. 121 //! 122 //! ```rust 123 //! use kernel::{prelude::*, init}; 124 //! use core::{ptr::addr_of_mut, marker::PhantomPinned, pin::Pin}; 125 //! # mod bindings { 126 //! # pub struct foo; 127 //! # pub unsafe fn init_foo(_ptr: *mut foo) {} 128 //! # pub unsafe fn destroy_foo(_ptr: *mut foo) {} 129 //! # pub unsafe fn enable_foo(_ptr: *mut foo, _flags: u32) -> i32 { 0 } 130 //! # } 131 //! /// # Invariants 132 //! /// 133 //! /// `foo` is always initialized 134 //! #[pin_data(PinnedDrop)] 135 //! pub struct RawFoo { 136 //! #[pin] 137 //! foo: Opaque<bindings::foo>, 138 //! #[pin] 139 //! _p: PhantomPinned, 140 //! } 141 //! 142 //! impl RawFoo { 143 //! pub fn new(flags: u32) -> impl PinInit<Self, Error> { 144 //! // SAFETY: 145 //! // - when the closure returns `Ok(())`, then it has successfully initialized and 146 //! // enabled `foo`, 147 //! // - when it returns `Err(e)`, then it has cleaned up before 148 //! unsafe { 149 //! init::pin_init_from_closure(move |slot: *mut Self| { 150 //! // `slot` contains uninit memory, avoid creating a reference. 151 //! let foo = addr_of_mut!((*slot).foo); 152 //! 153 //! // Initialize the `foo` 154 //! bindings::init_foo(Opaque::raw_get(foo)); 155 //! 156 //! // Try to enable it. 157 //! let err = bindings::enable_foo(Opaque::raw_get(foo), flags); 158 //! if err != 0 { 159 //! // Enabling has failed, first clean up the foo and then return the error. 160 //! bindings::destroy_foo(Opaque::raw_get(foo)); 161 //! return Err(Error::from_kernel_errno(err)); 162 //! } 163 //! 164 //! // All fields of `RawFoo` have been initialized, since `_p` is a ZST. 165 //! Ok(()) 166 //! }) 167 //! } 168 //! } 169 //! } 170 //! 171 //! #[pinned_drop] 172 //! impl PinnedDrop for RawFoo { 173 //! fn drop(self: Pin<&mut Self>) { 174 //! // SAFETY: Since `foo` is initialized, destroying is safe. 175 //! unsafe { bindings::destroy_foo(self.foo.get()) }; 176 //! } 177 //! } 178 //! ``` 179 //! 180 //! For the special case where initializing a field is a single FFI-function call that cannot fail, 181 //! there exist the helper function [`Opaque::ffi_init`]. This function initialize a single 182 //! [`Opaque`] field by just delegating to the supplied closure. You can use these in combination 183 //! with [`pin_init!`]. 184 //! 185 //! For more information on how to use [`pin_init_from_closure()`], take a look at the uses inside 186 //! the `kernel` crate. The [`sync`] module is a good starting point. 187 //! 188 //! [`sync`]: kernel::sync 189 //! [pinning]: https://doc.rust-lang.org/std/pin/index.html 190 //! [structurally pinned fields]: 191 //! https://doc.rust-lang.org/std/pin/index.html#pinning-is-structural-for-field 192 //! [stack]: crate::stack_pin_init 193 //! [`Arc<T>`]: crate::sync::Arc 194 //! [`impl PinInit<Foo>`]: PinInit 195 //! [`impl PinInit<T, E>`]: PinInit 196 //! [`impl Init<T, E>`]: Init 197 //! [`Opaque`]: kernel::types::Opaque 198 //! [`Opaque::ffi_init`]: kernel::types::Opaque::ffi_init 199 //! [`pin_data`]: ::macros::pin_data 200 //! [`pin_init!`]: crate::pin_init! 201 202 use crate::{ 203 error::{self, Error}, 204 sync::UniqueArc, 205 types::{Opaque, ScopeGuard}, 206 }; 207 use alloc::boxed::Box; 208 use core::{ 209 alloc::AllocError, 210 cell::UnsafeCell, 211 convert::Infallible, 212 marker::PhantomData, 213 mem::MaybeUninit, 214 num::*, 215 pin::Pin, 216 ptr::{self, NonNull}, 217 }; 218 219 #[doc(hidden)] 220 pub mod __internal; 221 #[doc(hidden)] 222 pub mod macros; 223 224 /// Initialize and pin a type directly on the stack. 225 /// 226 /// # Examples 227 /// 228 /// ```rust 229 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 230 /// # use kernel::{init, pin_init, stack_pin_init, init::*, sync::Mutex, new_mutex}; 231 /// # use macros::pin_data; 232 /// # use core::pin::Pin; 233 /// #[pin_data] 234 /// struct Foo { 235 /// #[pin] 236 /// a: Mutex<usize>, 237 /// b: Bar, 238 /// } 239 /// 240 /// #[pin_data] 241 /// struct Bar { 242 /// x: u32, 243 /// } 244 /// 245 /// stack_pin_init!(let foo = pin_init!(Foo { 246 /// a <- new_mutex!(42), 247 /// b: Bar { 248 /// x: 64, 249 /// }, 250 /// })); 251 /// let foo: Pin<&mut Foo> = foo; 252 /// pr_info!("a: {}", &*foo.a.lock()); 253 /// ``` 254 /// 255 /// # Syntax 256 /// 257 /// A normal `let` binding with optional type annotation. The expression is expected to implement 258 /// [`PinInit`]/[`Init`] with the error type [`Infallible`]. If you want to use a different error 259 /// type, then use [`stack_try_pin_init!`]. 260 /// 261 /// [`stack_try_pin_init!`]: crate::stack_try_pin_init! 262 #[macro_export] 263 macro_rules! stack_pin_init { 264 (let $var:ident $(: $t:ty)? = $val:expr) => { 265 let val = $val; 266 let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit()); 267 let mut $var = match $crate::init::__internal::StackInit::init($var, val) { 268 Ok(res) => res, 269 Err(x) => { 270 let x: ::core::convert::Infallible = x; 271 match x {} 272 } 273 }; 274 }; 275 } 276 277 /// Initialize and pin a type directly on the stack. 278 /// 279 /// # Examples 280 /// 281 /// ```rust 282 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 283 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex}; 284 /// # use macros::pin_data; 285 /// # use core::{alloc::AllocError, pin::Pin}; 286 /// #[pin_data] 287 /// struct Foo { 288 /// #[pin] 289 /// a: Mutex<usize>, 290 /// b: Box<Bar>, 291 /// } 292 /// 293 /// struct Bar { 294 /// x: u32, 295 /// } 296 /// 297 /// stack_try_pin_init!(let foo: Result<Pin<&mut Foo>, AllocError> = pin_init!(Foo { 298 /// a <- new_mutex!(42), 299 /// b: Box::try_new(Bar { 300 /// x: 64, 301 /// })?, 302 /// })); 303 /// let foo = foo.unwrap(); 304 /// pr_info!("a: {}", &*foo.a.lock()); 305 /// ``` 306 /// 307 /// ```rust 308 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 309 /// # use kernel::{init, pin_init, stack_try_pin_init, init::*, sync::Mutex, new_mutex}; 310 /// # use macros::pin_data; 311 /// # use core::{alloc::AllocError, pin::Pin}; 312 /// #[pin_data] 313 /// struct Foo { 314 /// #[pin] 315 /// a: Mutex<usize>, 316 /// b: Box<Bar>, 317 /// } 318 /// 319 /// struct Bar { 320 /// x: u32, 321 /// } 322 /// 323 /// stack_try_pin_init!(let foo: Pin<&mut Foo> =? pin_init!(Foo { 324 /// a <- new_mutex!(42), 325 /// b: Box::try_new(Bar { 326 /// x: 64, 327 /// })?, 328 /// })); 329 /// pr_info!("a: {}", &*foo.a.lock()); 330 /// # Ok::<_, AllocError>(()) 331 /// ``` 332 /// 333 /// # Syntax 334 /// 335 /// A normal `let` binding with optional type annotation. The expression is expected to implement 336 /// [`PinInit`]/[`Init`]. This macro assigns a result to the given variable, adding a `?` after the 337 /// `=` will propagate this error. 338 #[macro_export] 339 macro_rules! stack_try_pin_init { 340 (let $var:ident $(: $t:ty)? = $val:expr) => { 341 let val = $val; 342 let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit()); 343 let mut $var = $crate::init::__internal::StackInit::init($var, val); 344 }; 345 (let $var:ident $(: $t:ty)? =? $val:expr) => { 346 let val = $val; 347 let mut $var = ::core::pin::pin!($crate::init::__internal::StackInit$(::<$t>)?::uninit()); 348 let mut $var = $crate::init::__internal::StackInit::init($var, val)?; 349 }; 350 } 351 352 /// Construct an in-place, pinned initializer for `struct`s. 353 /// 354 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use 355 /// [`try_pin_init!`]. 356 /// 357 /// The syntax is almost identical to that of a normal `struct` initializer: 358 /// 359 /// ```rust 360 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 361 /// # use kernel::{init, pin_init, macros::pin_data, init::*}; 362 /// # use core::pin::Pin; 363 /// #[pin_data] 364 /// struct Foo { 365 /// a: usize, 366 /// b: Bar, 367 /// } 368 /// 369 /// #[pin_data] 370 /// struct Bar { 371 /// x: u32, 372 /// } 373 /// 374 /// # fn demo() -> impl PinInit<Foo> { 375 /// let a = 42; 376 /// 377 /// let initializer = pin_init!(Foo { 378 /// a, 379 /// b: Bar { 380 /// x: 64, 381 /// }, 382 /// }); 383 /// # initializer } 384 /// # Box::pin_init(demo()).unwrap(); 385 /// ``` 386 /// 387 /// Arbitrary Rust expressions can be used to set the value of a variable. 388 /// 389 /// The fields are initialized in the order that they appear in the initializer. So it is possible 390 /// to read already initialized fields using raw pointers. 391 /// 392 /// IMPORTANT: You are not allowed to create references to fields of the struct inside of the 393 /// initializer. 394 /// 395 /// # Init-functions 396 /// 397 /// When working with this API it is often desired to let others construct your types without 398 /// giving access to all fields. This is where you would normally write a plain function `new` 399 /// that would return a new instance of your type. With this API that is also possible. 400 /// However, there are a few extra things to keep in mind. 401 /// 402 /// To create an initializer function, simply declare it like this: 403 /// 404 /// ```rust 405 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 406 /// # use kernel::{init, pin_init, prelude::*, init::*}; 407 /// # use core::pin::Pin; 408 /// # #[pin_data] 409 /// # struct Foo { 410 /// # a: usize, 411 /// # b: Bar, 412 /// # } 413 /// # #[pin_data] 414 /// # struct Bar { 415 /// # x: u32, 416 /// # } 417 /// impl Foo { 418 /// fn new() -> impl PinInit<Self> { 419 /// pin_init!(Self { 420 /// a: 42, 421 /// b: Bar { 422 /// x: 64, 423 /// }, 424 /// }) 425 /// } 426 /// } 427 /// ``` 428 /// 429 /// Users of `Foo` can now create it like this: 430 /// 431 /// ```rust 432 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 433 /// # use kernel::{init, pin_init, macros::pin_data, init::*}; 434 /// # use core::pin::Pin; 435 /// # #[pin_data] 436 /// # struct Foo { 437 /// # a: usize, 438 /// # b: Bar, 439 /// # } 440 /// # #[pin_data] 441 /// # struct Bar { 442 /// # x: u32, 443 /// # } 444 /// # impl Foo { 445 /// # fn new() -> impl PinInit<Self> { 446 /// # pin_init!(Self { 447 /// # a: 42, 448 /// # b: Bar { 449 /// # x: 64, 450 /// # }, 451 /// # }) 452 /// # } 453 /// # } 454 /// let foo = Box::pin_init(Foo::new()); 455 /// ``` 456 /// 457 /// They can also easily embed it into their own `struct`s: 458 /// 459 /// ```rust 460 /// # #![allow(clippy::disallowed_names, clippy::new_ret_no_self)] 461 /// # use kernel::{init, pin_init, macros::pin_data, init::*}; 462 /// # use core::pin::Pin; 463 /// # #[pin_data] 464 /// # struct Foo { 465 /// # a: usize, 466 /// # b: Bar, 467 /// # } 468 /// # #[pin_data] 469 /// # struct Bar { 470 /// # x: u32, 471 /// # } 472 /// # impl Foo { 473 /// # fn new() -> impl PinInit<Self> { 474 /// # pin_init!(Self { 475 /// # a: 42, 476 /// # b: Bar { 477 /// # x: 64, 478 /// # }, 479 /// # }) 480 /// # } 481 /// # } 482 /// #[pin_data] 483 /// struct FooContainer { 484 /// #[pin] 485 /// foo1: Foo, 486 /// #[pin] 487 /// foo2: Foo, 488 /// other: u32, 489 /// } 490 /// 491 /// impl FooContainer { 492 /// fn new(other: u32) -> impl PinInit<Self> { 493 /// pin_init!(Self { 494 /// foo1 <- Foo::new(), 495 /// foo2 <- Foo::new(), 496 /// other, 497 /// }) 498 /// } 499 /// } 500 /// ``` 501 /// 502 /// Here we see that when using `pin_init!` with `PinInit`, one needs to write `<-` instead of `:`. 503 /// This signifies that the given field is initialized in-place. As with `struct` initializers, just 504 /// writing the field (in this case `other`) without `:` or `<-` means `other: other,`. 505 /// 506 /// # Syntax 507 /// 508 /// As already mentioned in the examples above, inside of `pin_init!` a `struct` initializer with 509 /// the following modifications is expected: 510 /// - Fields that you want to initialize in-place have to use `<-` instead of `:`. 511 /// - In front of the initializer you can write `&this in` to have access to a [`NonNull<Self>`] 512 /// pointer named `this` inside of the initializer. 513 /// - Using struct update syntax one can place `..Zeroable::zeroed()` at the very end of the 514 /// struct, this initializes every field with 0 and then runs all initializers specified in the 515 /// body. This can only be done if [`Zeroable`] is implemented for the struct. 516 /// 517 /// For instance: 518 /// 519 /// ```rust 520 /// # use kernel::pin_init; 521 /// # use macros::{Zeroable, pin_data}; 522 /// # use core::{ptr::addr_of_mut, marker::PhantomPinned}; 523 /// #[pin_data] 524 /// #[derive(Zeroable)] 525 /// struct Buf { 526 /// // `ptr` points into `buf`. 527 /// ptr: *mut u8, 528 /// buf: [u8; 64], 529 /// #[pin] 530 /// pin: PhantomPinned, 531 /// } 532 /// pin_init!(&this in Buf { 533 /// buf: [0; 64], 534 /// ptr: unsafe { addr_of_mut!((*this.as_ptr()).buf).cast() }, 535 /// pin: PhantomPinned, 536 /// }); 537 /// pin_init!(Buf { 538 /// buf: [1; 64], 539 /// ..Zeroable::zeroed() 540 /// }); 541 /// ``` 542 /// 543 /// [`try_pin_init!`]: kernel::try_pin_init 544 /// [`NonNull<Self>`]: core::ptr::NonNull 545 // For a detailed example of how this macro works, see the module documentation of the hidden 546 // module `__internal` inside of `init/__internal.rs`. 547 #[macro_export] 548 macro_rules! pin_init { 549 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 550 $($fields:tt)* 551 }) => { 552 $crate::__init_internal!( 553 @this($($this)?), 554 @typ($t $(::<$($generics),*>)?), 555 @fields($($fields)*), 556 @error(::core::convert::Infallible), 557 @data(PinData, use_data), 558 @has_data(HasPinData, __pin_data), 559 @construct_closure(pin_init_from_closure), 560 @munch_fields($($fields)*), 561 ) 562 }; 563 } 564 565 /// Construct an in-place, fallible pinned initializer for `struct`s. 566 /// 567 /// If the initialization can complete without error (or [`Infallible`]), then use [`pin_init!`]. 568 /// 569 /// You can use the `?` operator or use `return Err(err)` inside the initializer to stop 570 /// initialization and return the error. 571 /// 572 /// IMPORTANT: if you have `unsafe` code inside of the initializer you have to ensure that when 573 /// initialization fails, the memory can be safely deallocated without any further modifications. 574 /// 575 /// This macro defaults the error to [`Error`]. 576 /// 577 /// The syntax is identical to [`pin_init!`] with the following exception: you can append `? $type` 578 /// after the `struct` initializer to specify the error type you want to use. 579 /// 580 /// # Examples 581 /// 582 /// ```rust 583 /// # #![feature(new_uninit)] 584 /// use kernel::{init::{self, PinInit}, error::Error}; 585 /// #[pin_data] 586 /// struct BigBuf { 587 /// big: Box<[u8; 1024 * 1024 * 1024]>, 588 /// small: [u8; 1024 * 1024], 589 /// ptr: *mut u8, 590 /// } 591 /// 592 /// impl BigBuf { 593 /// fn new() -> impl PinInit<Self, Error> { 594 /// try_pin_init!(Self { 595 /// big: Box::init(init::zeroed())?, 596 /// small: [0; 1024 * 1024], 597 /// ptr: core::ptr::null_mut(), 598 /// }? Error) 599 /// } 600 /// } 601 /// ``` 602 // For a detailed example of how this macro works, see the module documentation of the hidden 603 // module `__internal` inside of `init/__internal.rs`. 604 #[macro_export] 605 macro_rules! try_pin_init { 606 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 607 $($fields:tt)* 608 }) => { 609 $crate::__init_internal!( 610 @this($($this)?), 611 @typ($t $(::<$($generics),*>)? ), 612 @fields($($fields)*), 613 @error($crate::error::Error), 614 @data(PinData, use_data), 615 @has_data(HasPinData, __pin_data), 616 @construct_closure(pin_init_from_closure), 617 @munch_fields($($fields)*), 618 ) 619 }; 620 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 621 $($fields:tt)* 622 }? $err:ty) => { 623 $crate::__init_internal!( 624 @this($($this)?), 625 @typ($t $(::<$($generics),*>)? ), 626 @fields($($fields)*), 627 @error($err), 628 @data(PinData, use_data), 629 @has_data(HasPinData, __pin_data), 630 @construct_closure(pin_init_from_closure), 631 @munch_fields($($fields)*), 632 ) 633 }; 634 } 635 636 /// Construct an in-place initializer for `struct`s. 637 /// 638 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use 639 /// [`try_init!`]. 640 /// 641 /// The syntax is identical to [`pin_init!`] and its safety caveats also apply: 642 /// - `unsafe` code must guarantee either full initialization or return an error and allow 643 /// deallocation of the memory. 644 /// - the fields are initialized in the order given in the initializer. 645 /// - no references to fields are allowed to be created inside of the initializer. 646 /// 647 /// This initializer is for initializing data in-place that might later be moved. If you want to 648 /// pin-initialize, use [`pin_init!`]. 649 /// 650 /// [`try_init!`]: crate::try_init! 651 // For a detailed example of how this macro works, see the module documentation of the hidden 652 // module `__internal` inside of `init/__internal.rs`. 653 #[macro_export] 654 macro_rules! init { 655 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 656 $($fields:tt)* 657 }) => { 658 $crate::__init_internal!( 659 @this($($this)?), 660 @typ($t $(::<$($generics),*>)?), 661 @fields($($fields)*), 662 @error(::core::convert::Infallible), 663 @data(InitData, /*no use_data*/), 664 @has_data(HasInitData, __init_data), 665 @construct_closure(init_from_closure), 666 @munch_fields($($fields)*), 667 ) 668 } 669 } 670 671 /// Construct an in-place fallible initializer for `struct`s. 672 /// 673 /// This macro defaults the error to [`Error`]. If you need [`Infallible`], then use 674 /// [`init!`]. 675 /// 676 /// The syntax is identical to [`try_pin_init!`]. If you want to specify a custom error, 677 /// append `? $type` after the `struct` initializer. 678 /// The safety caveats from [`try_pin_init!`] also apply: 679 /// - `unsafe` code must guarantee either full initialization or return an error and allow 680 /// deallocation of the memory. 681 /// - the fields are initialized in the order given in the initializer. 682 /// - no references to fields are allowed to be created inside of the initializer. 683 /// 684 /// # Examples 685 /// 686 /// ```rust 687 /// use kernel::{init::PinInit, error::Error, InPlaceInit}; 688 /// struct BigBuf { 689 /// big: Box<[u8; 1024 * 1024 * 1024]>, 690 /// small: [u8; 1024 * 1024], 691 /// } 692 /// 693 /// impl BigBuf { 694 /// fn new() -> impl Init<Self, Error> { 695 /// try_init!(Self { 696 /// big: Box::init(zeroed())?, 697 /// small: [0; 1024 * 1024], 698 /// }? Error) 699 /// } 700 /// } 701 /// ``` 702 // For a detailed example of how this macro works, see the module documentation of the hidden 703 // module `__internal` inside of `init/__internal.rs`. 704 #[macro_export] 705 macro_rules! try_init { 706 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 707 $($fields:tt)* 708 }) => { 709 $crate::__init_internal!( 710 @this($($this)?), 711 @typ($t $(::<$($generics),*>)?), 712 @fields($($fields)*), 713 @error($crate::error::Error), 714 @data(InitData, /*no use_data*/), 715 @has_data(HasInitData, __init_data), 716 @construct_closure(init_from_closure), 717 @munch_fields($($fields)*), 718 ) 719 }; 720 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 721 $($fields:tt)* 722 }? $err:ty) => { 723 $crate::__init_internal!( 724 @this($($this)?), 725 @typ($t $(::<$($generics),*>)?), 726 @fields($($fields)*), 727 @error($err), 728 @data(InitData, /*no use_data*/), 729 @has_data(HasInitData, __init_data), 730 @construct_closure(init_from_closure), 731 @munch_fields($($fields)*), 732 ) 733 }; 734 } 735 736 /// A pin-initializer for the type `T`. 737 /// 738 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can 739 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the 740 /// [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this. 741 /// 742 /// Also see the [module description](self). 743 /// 744 /// # Safety 745 /// 746 /// When implementing this type you will need to take great care. Also there are probably very few 747 /// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible. 748 /// 749 /// The [`PinInit::__pinned_init`] function 750 /// - returns `Ok(())` if it initialized every field of `slot`, 751 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 752 /// - `slot` can be deallocated without UB occurring, 753 /// - `slot` does not need to be dropped, 754 /// - `slot` is not partially initialized. 755 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 756 /// 757 /// [`Arc<T>`]: crate::sync::Arc 758 /// [`Arc::pin_init`]: crate::sync::Arc::pin_init 759 #[must_use = "An initializer must be used in order to create its value."] 760 pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized { 761 /// Initializes `slot`. 762 /// 763 /// # Safety 764 /// 765 /// - `slot` is a valid pointer to uninitialized memory. 766 /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to 767 /// deallocate. 768 /// - `slot` will not move until it is dropped, i.e. it will be pinned. 769 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>; 770 771 /// First initializes the value using `self` then calls the function `f` with the initialized 772 /// value. 773 /// 774 /// If `f` returns an error the value is dropped and the initializer will forward the error. 775 /// 776 /// # Examples 777 /// 778 /// ```rust 779 /// # #![allow(clippy::disallowed_names)] 780 /// use kernel::{types::Opaque, init::pin_init_from_closure}; 781 /// #[repr(C)] 782 /// struct RawFoo([u8; 16]); 783 /// extern { 784 /// fn init_foo(_: *mut RawFoo); 785 /// } 786 /// 787 /// #[pin_data] 788 /// struct Foo { 789 /// #[pin] 790 /// raw: Opaque<RawFoo>, 791 /// } 792 /// 793 /// impl Foo { 794 /// fn setup(self: Pin<&mut Self>) { 795 /// pr_info!("Setting up foo"); 796 /// } 797 /// } 798 /// 799 /// let foo = pin_init!(Foo { 800 /// raw <- unsafe { 801 /// Opaque::ffi_init(|s| { 802 /// init_foo(s); 803 /// }) 804 /// }, 805 /// }).pin_chain(|foo| { 806 /// foo.setup(); 807 /// Ok(()) 808 /// }); 809 /// ``` 810 fn pin_chain<F>(self, f: F) -> ChainPinInit<Self, F, T, E> 811 where 812 F: FnOnce(Pin<&mut T>) -> Result<(), E>, 813 { 814 ChainPinInit(self, f, PhantomData) 815 } 816 } 817 818 /// An initializer returned by [`PinInit::pin_chain`]. 819 pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, Box<T>)>); 820 821 // SAFETY: The `__pinned_init` function is implemented such that it 822 // - returns `Ok(())` on successful initialization, 823 // - returns `Err(err)` on error and in this case `slot` will be dropped. 824 // - considers `slot` pinned. 825 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainPinInit<I, F, T, E> 826 where 827 I: PinInit<T, E>, 828 F: FnOnce(Pin<&mut T>) -> Result<(), E>, 829 { 830 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 831 // SAFETY: All requirements fulfilled since this function is `__pinned_init`. 832 unsafe { self.0.__pinned_init(slot)? }; 833 // SAFETY: The above call initialized `slot` and we still have unique access. 834 let val = unsafe { &mut *slot }; 835 // SAFETY: `slot` is considered pinned. 836 let val = unsafe { Pin::new_unchecked(val) }; 837 (self.1)(val).map_err(|e| { 838 // SAFETY: `slot` was initialized above. 839 unsafe { core::ptr::drop_in_place(slot) }; 840 e 841 }) 842 } 843 } 844 845 /// An initializer for `T`. 846 /// 847 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can 848 /// be [`Box<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use the 849 /// [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because 850 /// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well. 851 /// 852 /// Also see the [module description](self). 853 /// 854 /// # Safety 855 /// 856 /// When implementing this type you will need to take great care. Also there are probably very few 857 /// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible. 858 /// 859 /// The [`Init::__init`] function 860 /// - returns `Ok(())` if it initialized every field of `slot`, 861 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 862 /// - `slot` can be deallocated without UB occurring, 863 /// - `slot` does not need to be dropped, 864 /// - `slot` is not partially initialized. 865 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 866 /// 867 /// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same 868 /// code as `__init`. 869 /// 870 /// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to 871 /// move the pointee after initialization. 872 /// 873 /// [`Arc<T>`]: crate::sync::Arc 874 #[must_use = "An initializer must be used in order to create its value."] 875 pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> { 876 /// Initializes `slot`. 877 /// 878 /// # Safety 879 /// 880 /// - `slot` is a valid pointer to uninitialized memory. 881 /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to 882 /// deallocate. 883 unsafe fn __init(self, slot: *mut T) -> Result<(), E>; 884 885 /// First initializes the value using `self` then calls the function `f` with the initialized 886 /// value. 887 /// 888 /// If `f` returns an error the value is dropped and the initializer will forward the error. 889 /// 890 /// # Examples 891 /// 892 /// ```rust 893 /// # #![allow(clippy::disallowed_names)] 894 /// use kernel::{types::Opaque, init::{self, init_from_closure}}; 895 /// struct Foo { 896 /// buf: [u8; 1_000_000], 897 /// } 898 /// 899 /// impl Foo { 900 /// fn setup(&mut self) { 901 /// pr_info!("Setting up foo"); 902 /// } 903 /// } 904 /// 905 /// let foo = init!(Foo { 906 /// buf <- init::zeroed() 907 /// }).chain(|foo| { 908 /// foo.setup(); 909 /// Ok(()) 910 /// }); 911 /// ``` 912 fn chain<F>(self, f: F) -> ChainInit<Self, F, T, E> 913 where 914 F: FnOnce(&mut T) -> Result<(), E>, 915 { 916 ChainInit(self, f, PhantomData) 917 } 918 } 919 920 /// An initializer returned by [`Init::chain`]. 921 pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, Box<T>)>); 922 923 // SAFETY: The `__init` function is implemented such that it 924 // - returns `Ok(())` on successful initialization, 925 // - returns `Err(err)` on error and in this case `slot` will be dropped. 926 unsafe impl<T: ?Sized, E, I, F> Init<T, E> for ChainInit<I, F, T, E> 927 where 928 I: Init<T, E>, 929 F: FnOnce(&mut T) -> Result<(), E>, 930 { 931 unsafe fn __init(self, slot: *mut T) -> Result<(), E> { 932 // SAFETY: All requirements fulfilled since this function is `__init`. 933 unsafe { self.0.__pinned_init(slot)? }; 934 // SAFETY: The above call initialized `slot` and we still have unique access. 935 (self.1)(unsafe { &mut *slot }).map_err(|e| { 936 // SAFETY: `slot` was initialized above. 937 unsafe { core::ptr::drop_in_place(slot) }; 938 e 939 }) 940 } 941 } 942 943 // SAFETY: `__pinned_init` behaves exactly the same as `__init`. 944 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainInit<I, F, T, E> 945 where 946 I: Init<T, E>, 947 F: FnOnce(&mut T) -> Result<(), E>, 948 { 949 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 950 // SAFETY: `__init` has less strict requirements compared to `__pinned_init`. 951 unsafe { self.__init(slot) } 952 } 953 } 954 955 /// Creates a new [`PinInit<T, E>`] from the given closure. 956 /// 957 /// # Safety 958 /// 959 /// The closure: 960 /// - returns `Ok(())` if it initialized every field of `slot`, 961 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 962 /// - `slot` can be deallocated without UB occurring, 963 /// - `slot` does not need to be dropped, 964 /// - `slot` is not partially initialized. 965 /// - may assume that the `slot` does not move if `T: !Unpin`, 966 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 967 #[inline] 968 pub const unsafe fn pin_init_from_closure<T: ?Sized, E>( 969 f: impl FnOnce(*mut T) -> Result<(), E>, 970 ) -> impl PinInit<T, E> { 971 __internal::InitClosure(f, PhantomData) 972 } 973 974 /// Creates a new [`Init<T, E>`] from the given closure. 975 /// 976 /// # Safety 977 /// 978 /// The closure: 979 /// - returns `Ok(())` if it initialized every field of `slot`, 980 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 981 /// - `slot` can be deallocated without UB occurring, 982 /// - `slot` does not need to be dropped, 983 /// - `slot` is not partially initialized. 984 /// - the `slot` may move after initialization. 985 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 986 #[inline] 987 pub const unsafe fn init_from_closure<T: ?Sized, E>( 988 f: impl FnOnce(*mut T) -> Result<(), E>, 989 ) -> impl Init<T, E> { 990 __internal::InitClosure(f, PhantomData) 991 } 992 993 /// An initializer that leaves the memory uninitialized. 994 /// 995 /// The initializer is a no-op. The `slot` memory is not changed. 996 #[inline] 997 pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> { 998 // SAFETY: The memory is allowed to be uninitialized. 999 unsafe { init_from_closure(|_| Ok(())) } 1000 } 1001 1002 /// Initializes an array by initializing each element via the provided initializer. 1003 /// 1004 /// # Examples 1005 /// 1006 /// ```rust 1007 /// use kernel::{error::Error, init::init_array_from_fn}; 1008 /// let array: Box<[usize; 1_000]>= Box::init::<Error>(init_array_from_fn(|i| i)).unwrap(); 1009 /// assert_eq!(array.len(), 1_000); 1010 /// ``` 1011 pub fn init_array_from_fn<I, const N: usize, T, E>( 1012 mut make_init: impl FnMut(usize) -> I, 1013 ) -> impl Init<[T; N], E> 1014 where 1015 I: Init<T, E>, 1016 { 1017 let init = move |slot: *mut [T; N]| { 1018 let slot = slot.cast::<T>(); 1019 // Counts the number of initialized elements and when dropped drops that many elements from 1020 // `slot`. 1021 let mut init_count = ScopeGuard::new_with_data(0, |i| { 1022 // We now free every element that has been initialized before: 1023 // SAFETY: The loop initialized exactly the values from 0..i and since we 1024 // return `Err` below, the caller will consider the memory at `slot` as 1025 // uninitialized. 1026 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; 1027 }); 1028 for i in 0..N { 1029 let init = make_init(i); 1030 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`. 1031 let ptr = unsafe { slot.add(i) }; 1032 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` 1033 // requirements. 1034 unsafe { init.__init(ptr) }?; 1035 *init_count += 1; 1036 } 1037 init_count.dismiss(); 1038 Ok(()) 1039 }; 1040 // SAFETY: The initializer above initializes every element of the array. On failure it drops 1041 // any initialized elements and returns `Err`. 1042 unsafe { init_from_closure(init) } 1043 } 1044 1045 /// Initializes an array by initializing each element via the provided initializer. 1046 /// 1047 /// # Examples 1048 /// 1049 /// ```rust 1050 /// use kernel::{sync::{Arc, Mutex}, init::pin_init_array_from_fn, new_mutex}; 1051 /// let array: Arc<[Mutex<usize>; 1_000]>= 1052 /// Arc::pin_init(pin_init_array_from_fn(|i| new_mutex!(i))).unwrap(); 1053 /// assert_eq!(array.len(), 1_000); 1054 /// ``` 1055 pub fn pin_init_array_from_fn<I, const N: usize, T, E>( 1056 mut make_init: impl FnMut(usize) -> I, 1057 ) -> impl PinInit<[T; N], E> 1058 where 1059 I: PinInit<T, E>, 1060 { 1061 let init = move |slot: *mut [T; N]| { 1062 let slot = slot.cast::<T>(); 1063 // Counts the number of initialized elements and when dropped drops that many elements from 1064 // `slot`. 1065 let mut init_count = ScopeGuard::new_with_data(0, |i| { 1066 // We now free every element that has been initialized before: 1067 // SAFETY: The loop initialized exactly the values from 0..i and since we 1068 // return `Err` below, the caller will consider the memory at `slot` as 1069 // uninitialized. 1070 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; 1071 }); 1072 for i in 0..N { 1073 let init = make_init(i); 1074 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`. 1075 let ptr = unsafe { slot.add(i) }; 1076 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` 1077 // requirements. 1078 unsafe { init.__pinned_init(ptr) }?; 1079 *init_count += 1; 1080 } 1081 init_count.dismiss(); 1082 Ok(()) 1083 }; 1084 // SAFETY: The initializer above initializes every element of the array. On failure it drops 1085 // any initialized elements and returns `Err`. 1086 unsafe { pin_init_from_closure(init) } 1087 } 1088 1089 // SAFETY: Every type can be initialized by-value. 1090 unsafe impl<T, E> Init<T, E> for T { 1091 unsafe fn __init(self, slot: *mut T) -> Result<(), E> { 1092 unsafe { slot.write(self) }; 1093 Ok(()) 1094 } 1095 } 1096 1097 // SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`. 1098 unsafe impl<T, E> PinInit<T, E> for T { 1099 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 1100 unsafe { self.__init(slot) } 1101 } 1102 } 1103 1104 /// Smart pointer that can initialize memory in-place. 1105 pub trait InPlaceInit<T>: Sized { 1106 /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this 1107 /// type. 1108 /// 1109 /// If `T: !Unpin` it will not be able to move afterwards. 1110 fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E> 1111 where 1112 E: From<AllocError>; 1113 1114 /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this 1115 /// type. 1116 /// 1117 /// If `T: !Unpin` it will not be able to move afterwards. 1118 fn pin_init<E>(init: impl PinInit<T, E>) -> error::Result<Pin<Self>> 1119 where 1120 Error: From<E>, 1121 { 1122 // SAFETY: We delegate to `init` and only change the error type. 1123 let init = unsafe { 1124 pin_init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e))) 1125 }; 1126 Self::try_pin_init(init) 1127 } 1128 1129 /// Use the given initializer to in-place initialize a `T`. 1130 fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E> 1131 where 1132 E: From<AllocError>; 1133 1134 /// Use the given initializer to in-place initialize a `T`. 1135 fn init<E>(init: impl Init<T, E>) -> error::Result<Self> 1136 where 1137 Error: From<E>, 1138 { 1139 // SAFETY: We delegate to `init` and only change the error type. 1140 let init = unsafe { 1141 init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e))) 1142 }; 1143 Self::try_init(init) 1144 } 1145 } 1146 1147 impl<T> InPlaceInit<T> for Box<T> { 1148 #[inline] 1149 fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E> 1150 where 1151 E: From<AllocError>, 1152 { 1153 let mut this = Box::try_new_uninit()?; 1154 let slot = this.as_mut_ptr(); 1155 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 1156 // slot is valid and will not be moved, because we pin it later. 1157 unsafe { init.__pinned_init(slot)? }; 1158 // SAFETY: All fields have been initialized. 1159 Ok(unsafe { this.assume_init() }.into()) 1160 } 1161 1162 #[inline] 1163 fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E> 1164 where 1165 E: From<AllocError>, 1166 { 1167 let mut this = Box::try_new_uninit()?; 1168 let slot = this.as_mut_ptr(); 1169 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 1170 // slot is valid. 1171 unsafe { init.__init(slot)? }; 1172 // SAFETY: All fields have been initialized. 1173 Ok(unsafe { this.assume_init() }) 1174 } 1175 } 1176 1177 impl<T> InPlaceInit<T> for UniqueArc<T> { 1178 #[inline] 1179 fn try_pin_init<E>(init: impl PinInit<T, E>) -> Result<Pin<Self>, E> 1180 where 1181 E: From<AllocError>, 1182 { 1183 let mut this = UniqueArc::try_new_uninit()?; 1184 let slot = this.as_mut_ptr(); 1185 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 1186 // slot is valid and will not be moved, because we pin it later. 1187 unsafe { init.__pinned_init(slot)? }; 1188 // SAFETY: All fields have been initialized. 1189 Ok(unsafe { this.assume_init() }.into()) 1190 } 1191 1192 #[inline] 1193 fn try_init<E>(init: impl Init<T, E>) -> Result<Self, E> 1194 where 1195 E: From<AllocError>, 1196 { 1197 let mut this = UniqueArc::try_new_uninit()?; 1198 let slot = this.as_mut_ptr(); 1199 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 1200 // slot is valid. 1201 unsafe { init.__init(slot)? }; 1202 // SAFETY: All fields have been initialized. 1203 Ok(unsafe { this.assume_init() }) 1204 } 1205 } 1206 1207 /// Trait facilitating pinned destruction. 1208 /// 1209 /// Use [`pinned_drop`] to implement this trait safely: 1210 /// 1211 /// ```rust 1212 /// # use kernel::sync::Mutex; 1213 /// use kernel::macros::pinned_drop; 1214 /// use core::pin::Pin; 1215 /// #[pin_data(PinnedDrop)] 1216 /// struct Foo { 1217 /// #[pin] 1218 /// mtx: Mutex<usize>, 1219 /// } 1220 /// 1221 /// #[pinned_drop] 1222 /// impl PinnedDrop for Foo { 1223 /// fn drop(self: Pin<&mut Self>) { 1224 /// pr_info!("Foo is being dropped!"); 1225 /// } 1226 /// } 1227 /// ``` 1228 /// 1229 /// # Safety 1230 /// 1231 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl. 1232 /// 1233 /// [`pinned_drop`]: kernel::macros::pinned_drop 1234 pub unsafe trait PinnedDrop: __internal::HasPinData { 1235 /// Executes the pinned destructor of this type. 1236 /// 1237 /// While this function is marked safe, it is actually unsafe to call it manually. For this 1238 /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code 1239 /// and thus prevents this function from being called where it should not. 1240 /// 1241 /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute 1242 /// automatically. 1243 fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop); 1244 } 1245 1246 /// Marker trait for types that can be initialized by writing just zeroes. 1247 /// 1248 /// # Safety 1249 /// 1250 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words, 1251 /// this is not UB: 1252 /// 1253 /// ```rust,ignore 1254 /// let val: Self = unsafe { core::mem::zeroed() }; 1255 /// ``` 1256 pub unsafe trait Zeroable {} 1257 1258 /// Create a new zeroed T. 1259 /// 1260 /// The returned initializer will write `0x00` to every byte of the given `slot`. 1261 #[inline] 1262 pub fn zeroed<T: Zeroable>() -> impl Init<T> { 1263 // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T` 1264 // and because we write all zeroes, the memory is initialized. 1265 unsafe { 1266 init_from_closure(|slot: *mut T| { 1267 slot.write_bytes(0, 1); 1268 Ok(()) 1269 }) 1270 } 1271 } 1272 1273 macro_rules! impl_zeroable { 1274 ($($({$($generics:tt)*})? $t:ty, )*) => { 1275 $(unsafe impl$($($generics)*)? Zeroable for $t {})* 1276 }; 1277 } 1278 1279 impl_zeroable! { 1280 // SAFETY: All primitives that are allowed to be zero. 1281 bool, 1282 char, 1283 u8, u16, u32, u64, u128, usize, 1284 i8, i16, i32, i64, i128, isize, 1285 f32, f64, 1286 1287 // SAFETY: These are ZSTs, there is nothing to zero. 1288 {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, Infallible, (), 1289 1290 // SAFETY: Type is allowed to take any value, including all zeros. 1291 {<T>} MaybeUninit<T>, 1292 // SAFETY: Type is allowed to take any value, including all zeros. 1293 {<T>} Opaque<T>, 1294 1295 // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`. 1296 {<T: ?Sized + Zeroable>} UnsafeCell<T>, 1297 1298 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee). 1299 Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>, 1300 Option<NonZeroU128>, Option<NonZeroUsize>, 1301 Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>, 1302 Option<NonZeroI128>, Option<NonZeroIsize>, 1303 1304 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee). 1305 // 1306 // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant. 1307 {<T: ?Sized>} Option<NonNull<T>>, 1308 {<T: ?Sized>} Option<Box<T>>, 1309 1310 // SAFETY: `null` pointer is valid. 1311 // 1312 // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be 1313 // null. 1314 // 1315 // When `Pointee` gets stabilized, we could use 1316 // `T: ?Sized where <T as Pointee>::Metadata: Zeroable` 1317 {<T>} *mut T, {<T>} *const T, 1318 1319 // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be 1320 // zero. 1321 {<T>} *mut [T], {<T>} *const [T], *mut str, *const str, 1322 1323 // SAFETY: `T` is `Zeroable`. 1324 {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>, 1325 } 1326 1327 macro_rules! impl_tuple_zeroable { 1328 ($(,)?) => {}; 1329 ($first:ident, $($t:ident),* $(,)?) => { 1330 // SAFETY: All elements are zeroable and padding can be zero. 1331 unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {} 1332 impl_tuple_zeroable!($($t),* ,); 1333 } 1334 } 1335 1336 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J); 1337