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