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