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::__init_internal!( 680 @this($($this)?), 681 @typ($t $(::<$($generics),*>)?), 682 @fields($($fields)*), 683 @error(::core::convert::Infallible), 684 @data(PinData, use_data), 685 @has_data(HasPinData, __pin_data), 686 @construct_closure(pin_init_from_closure), 687 @munch_fields($($fields)*), 688 ) 689 }; 690 } 691 692 /// Construct an in-place, fallible pinned initializer for `struct`s. 693 /// 694 /// If the initialization can complete without error (or [`Infallible`]), then use [`pin_init!`]. 695 /// 696 /// You can use the `?` operator or use `return Err(err)` inside the initializer to stop 697 /// initialization and return the error. 698 /// 699 /// IMPORTANT: if you have `unsafe` code inside of the initializer you have to ensure that when 700 /// initialization fails, the memory can be safely deallocated without any further modifications. 701 /// 702 /// This macro defaults the error to [`Error`]. 703 /// 704 /// The syntax is identical to [`pin_init!`] with the following exception: you can append `? $type` 705 /// after the `struct` initializer to specify the error type you want to use. 706 /// 707 /// # Examples 708 /// 709 /// ```rust,ignore 710 /// # #![feature(allocator_api)] 711 /// # #[path = "../examples/error.rs"] mod error; use error::Error; 712 /// use pin_init::*; 713 /// #[pin_data] 714 /// struct BigBuf { 715 /// big: Box<[u8; 1024 * 1024 * 1024]>, 716 /// small: [u8; 1024 * 1024], 717 /// ptr: *mut u8, 718 /// } 719 /// 720 /// impl BigBuf { 721 /// fn new() -> impl PinInit<Self, Error> { 722 /// try_pin_init!(Self { 723 /// big: Box::init(init::zeroed())?, 724 /// small: [0; 1024 * 1024], 725 /// ptr: core::ptr::null_mut(), 726 /// }? Error) 727 /// } 728 /// } 729 /// # let _ = Box::pin_init(BigBuf::new()); 730 /// ``` 731 // For a detailed example of how this macro works, see the module documentation of the hidden 732 // module `__internal` inside of `init/__internal.rs`. 733 #[macro_export] 734 macro_rules! try_pin_init { 735 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 736 $($fields:tt)* 737 }) => { 738 $crate::__init_internal!( 739 @this($($this)?), 740 @typ($t $(::<$($generics),*>)? ), 741 @fields($($fields)*), 742 @error($crate::error::Error), 743 @data(PinData, use_data), 744 @has_data(HasPinData, __pin_data), 745 @construct_closure(pin_init_from_closure), 746 @munch_fields($($fields)*), 747 ) 748 }; 749 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 750 $($fields:tt)* 751 }? $err:ty) => { 752 $crate::__init_internal!( 753 @this($($this)?), 754 @typ($t $(::<$($generics),*>)? ), 755 @fields($($fields)*), 756 @error($err), 757 @data(PinData, use_data), 758 @has_data(HasPinData, __pin_data), 759 @construct_closure(pin_init_from_closure), 760 @munch_fields($($fields)*), 761 ) 762 }; 763 } 764 765 /// Construct an in-place initializer for `struct`s. 766 /// 767 /// This macro defaults the error to [`Infallible`]. If you need [`Error`], then use 768 /// [`try_init!`]. 769 /// 770 /// The syntax is identical to [`pin_init!`] and its safety caveats also apply: 771 /// - `unsafe` code must guarantee either full initialization or return an error and allow 772 /// deallocation of the memory. 773 /// - the fields are initialized in the order given in the initializer. 774 /// - no references to fields are allowed to be created inside of the initializer. 775 /// 776 /// This initializer is for initializing data in-place that might later be moved. If you want to 777 /// pin-initialize, use [`pin_init!`]. 778 /// 779 /// [`try_init!`]: crate::try_init! 780 // For a detailed example of how this macro works, see the module documentation of the hidden 781 // module `__internal` inside of `init/__internal.rs`. 782 #[macro_export] 783 macro_rules! init { 784 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 785 $($fields:tt)* 786 }) => { 787 $crate::__init_internal!( 788 @this($($this)?), 789 @typ($t $(::<$($generics),*>)?), 790 @fields($($fields)*), 791 @error(::core::convert::Infallible), 792 @data(InitData, /*no use_data*/), 793 @has_data(HasInitData, __init_data), 794 @construct_closure(init_from_closure), 795 @munch_fields($($fields)*), 796 ) 797 } 798 } 799 800 /// Construct an in-place fallible initializer for `struct`s. 801 /// 802 /// This macro defaults the error to [`Error`]. If you need [`Infallible`], then use 803 /// [`init!`]. 804 /// 805 /// The syntax is identical to [`try_pin_init!`]. If you want to specify a custom error, 806 /// append `? $type` after the `struct` initializer. 807 /// The safety caveats from [`try_pin_init!`] also apply: 808 /// - `unsafe` code must guarantee either full initialization or return an error and allow 809 /// deallocation of the memory. 810 /// - the fields are initialized in the order given in the initializer. 811 /// - no references to fields are allowed to be created inside of the initializer. 812 /// 813 /// # Examples 814 /// 815 /// ```rust,ignore 816 /// # #![feature(allocator_api)] 817 /// # use core::alloc::AllocError; 818 /// use pin_init::*; 819 /// struct BigBuf { 820 /// big: Box<[u8; 1024 * 1024 * 1024]>, 821 /// small: [u8; 1024 * 1024], 822 /// } 823 /// 824 /// impl BigBuf { 825 /// fn new() -> impl Init<Self, AllocError> { 826 /// try_init!(Self { 827 /// big: Box::init(zeroed())?, 828 /// small: [0; 1024 * 1024], 829 /// }? AllocError) 830 /// } 831 /// } 832 /// ``` 833 // For a detailed example of how this macro works, see the module documentation of the hidden 834 // module `__internal` inside of `init/__internal.rs`. 835 #[macro_export] 836 macro_rules! try_init { 837 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 838 $($fields:tt)* 839 }) => { 840 $crate::__init_internal!( 841 @this($($this)?), 842 @typ($t $(::<$($generics),*>)?), 843 @fields($($fields)*), 844 @error($crate::error::Error), 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 ($(&$this:ident in)? $t:ident $(::<$($generics:ty),* $(,)?>)? { 852 $($fields:tt)* 853 }? $err:ty) => { 854 $crate::__init_internal!( 855 @this($($this)?), 856 @typ($t $(::<$($generics),*>)?), 857 @fields($($fields)*), 858 @error($err), 859 @data(InitData, /*no use_data*/), 860 @has_data(HasInitData, __init_data), 861 @construct_closure(init_from_closure), 862 @munch_fields($($fields)*), 863 ) 864 }; 865 } 866 867 /// Asserts that a field on a struct using `#[pin_data]` is marked with `#[pin]` ie. that it is 868 /// structurally pinned. 869 /// 870 /// # Example 871 /// 872 /// This will succeed: 873 /// ```ignore 874 /// use pin_init::assert_pinned; 875 /// #[pin_data] 876 /// struct MyStruct { 877 /// #[pin] 878 /// some_field: u64, 879 /// } 880 /// 881 /// assert_pinned!(MyStruct, some_field, u64); 882 /// ``` 883 /// 884 /// This will fail: 885 /// ```compile_fail,ignore 886 /// use pin_init::assert_pinned; 887 /// #[pin_data] 888 /// struct MyStruct { 889 /// some_field: u64, 890 /// } 891 /// 892 /// assert_pinned!(MyStruct, some_field, u64); 893 /// ``` 894 /// 895 /// Some uses of the macro may trigger the `can't use generic parameters from outer item` error. To 896 /// work around this, you may pass the `inline` parameter to the macro. The `inline` parameter can 897 /// only be used when the macro is invoked from a function body. 898 /// ```ignore 899 /// use pin_init::assert_pinned; 900 /// #[pin_data] 901 /// struct Foo<T> { 902 /// #[pin] 903 /// elem: T, 904 /// } 905 /// 906 /// impl<T> Foo<T> { 907 /// fn project(self: Pin<&mut Self>) -> Pin<&mut T> { 908 /// assert_pinned!(Foo<T>, elem, T, inline); 909 /// 910 /// // SAFETY: The field is structurally pinned. 911 /// unsafe { self.map_unchecked_mut(|me| &mut me.elem) } 912 /// } 913 /// } 914 /// ``` 915 #[macro_export] 916 macro_rules! assert_pinned { 917 ($ty:ty, $field:ident, $field_ty:ty, inline) => { 918 let _ = move |ptr: *mut $field_ty| { 919 // SAFETY: This code is unreachable. 920 let data = unsafe { <$ty as $crate::init::__internal::HasPinData>::__pin_data() }; 921 let init = $crate::init::__internal::AlwaysFail::<$field_ty>::new(); 922 // SAFETY: This code is unreachable. 923 unsafe { data.$field(ptr, init) }.ok(); 924 }; 925 }; 926 927 ($ty:ty, $field:ident, $field_ty:ty) => { 928 const _: () = { 929 $crate::assert_pinned!($ty, $field, $field_ty, inline); 930 }; 931 }; 932 } 933 934 /// A pin-initializer for the type `T`. 935 /// 936 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can 937 /// be [`KBox<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use 938 /// the [`InPlaceInit::pin_init`] function of a smart pointer like [`Arc<T>`] on this. 939 /// 940 /// Also see the [module description](self). 941 /// 942 /// # Safety 943 /// 944 /// When implementing this trait you will need to take great care. Also there are probably very few 945 /// cases where a manual implementation is necessary. Use [`pin_init_from_closure`] where possible. 946 /// 947 /// The [`PinInit::__pinned_init`] function: 948 /// - returns `Ok(())` if it initialized every field of `slot`, 949 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 950 /// - `slot` can be deallocated without UB occurring, 951 /// - `slot` does not need to be dropped, 952 /// - `slot` is not partially initialized. 953 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 954 /// 955 /// [`Arc<T>`]: crate::sync::Arc 956 /// [`Arc::pin_init`]: crate::sync::Arc::pin_init 957 #[must_use = "An initializer must be used in order to create its value."] 958 pub unsafe trait PinInit<T: ?Sized, E = Infallible>: Sized { 959 /// Initializes `slot`. 960 /// 961 /// # Safety 962 /// 963 /// - `slot` is a valid pointer to uninitialized memory. 964 /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to 965 /// deallocate. 966 /// - `slot` will not move until it is dropped, i.e. it will be pinned. 967 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E>; 968 969 /// First initializes the value using `self` then calls the function `f` with the initialized 970 /// value. 971 /// 972 /// If `f` returns an error the value is dropped and the initializer will forward the error. 973 /// 974 /// # Examples 975 /// 976 /// ```rust,ignore 977 /// # #![feature(allocator_api)] 978 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 979 /// # use pin_init::*; 980 /// let mtx_init = CMutex::new(42); 981 /// // Make the initializer print the value. 982 /// let mtx_init = mtx_init.pin_chain(|mtx| { 983 /// println!("{:?}", mtx.get_data_mut()); 984 /// Ok(()) 985 /// }); 986 /// ``` 987 fn pin_chain<F>(self, f: F) -> ChainPinInit<Self, F, T, E> 988 where 989 F: FnOnce(Pin<&mut T>) -> Result<(), E>, 990 { 991 ChainPinInit(self, f, PhantomData) 992 } 993 } 994 995 /// An initializer returned by [`PinInit::pin_chain`]. 996 pub struct ChainPinInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, KBox<T>)>); 997 998 // SAFETY: The `__pinned_init` function is implemented such that it 999 // - returns `Ok(())` on successful initialization, 1000 // - returns `Err(err)` on error and in this case `slot` will be dropped. 1001 // - considers `slot` pinned. 1002 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainPinInit<I, F, T, E> 1003 where 1004 I: PinInit<T, E>, 1005 F: FnOnce(Pin<&mut T>) -> Result<(), E>, 1006 { 1007 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 1008 // SAFETY: All requirements fulfilled since this function is `__pinned_init`. 1009 unsafe { self.0.__pinned_init(slot)? }; 1010 // SAFETY: The above call initialized `slot` and we still have unique access. 1011 let val = unsafe { &mut *slot }; 1012 // SAFETY: `slot` is considered pinned. 1013 let val = unsafe { Pin::new_unchecked(val) }; 1014 // SAFETY: `slot` was initialized above. 1015 (self.1)(val).inspect_err(|_| unsafe { core::ptr::drop_in_place(slot) }) 1016 } 1017 } 1018 1019 /// An initializer for `T`. 1020 /// 1021 /// To use this initializer, you will need a suitable memory location that can hold a `T`. This can 1022 /// be [`KBox<T>`], [`Arc<T>`], [`UniqueArc<T>`] or even the stack (see [`stack_pin_init!`]). Use 1023 /// the [`InPlaceInit::init`] function of a smart pointer like [`Arc<T>`] on this. Because 1024 /// [`PinInit<T, E>`] is a super trait, you can use every function that takes it as well. 1025 /// 1026 /// Also see the [module description](self). 1027 /// 1028 /// # Safety 1029 /// 1030 /// When implementing this trait you will need to take great care. Also there are probably very few 1031 /// cases where a manual implementation is necessary. Use [`init_from_closure`] where possible. 1032 /// 1033 /// The [`Init::__init`] function: 1034 /// - returns `Ok(())` if it initialized every field of `slot`, 1035 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 1036 /// - `slot` can be deallocated without UB occurring, 1037 /// - `slot` does not need to be dropped, 1038 /// - `slot` is not partially initialized. 1039 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 1040 /// 1041 /// The `__pinned_init` function from the supertrait [`PinInit`] needs to execute the exact same 1042 /// code as `__init`. 1043 /// 1044 /// Contrary to its supertype [`PinInit<T, E>`] the caller is allowed to 1045 /// move the pointee after initialization. 1046 /// 1047 /// [`Arc<T>`]: crate::sync::Arc 1048 #[must_use = "An initializer must be used in order to create its value."] 1049 pub unsafe trait Init<T: ?Sized, E = Infallible>: PinInit<T, E> { 1050 /// Initializes `slot`. 1051 /// 1052 /// # Safety 1053 /// 1054 /// - `slot` is a valid pointer to uninitialized memory. 1055 /// - the caller does not touch `slot` when `Err` is returned, they are only permitted to 1056 /// deallocate. 1057 unsafe fn __init(self, slot: *mut T) -> Result<(), E>; 1058 1059 /// First initializes the value using `self` then calls the function `f` with the initialized 1060 /// value. 1061 /// 1062 /// If `f` returns an error the value is dropped and the initializer will forward the error. 1063 /// 1064 /// # Examples 1065 /// 1066 /// ```rust,ignore 1067 /// # #![expect(clippy::disallowed_names)] 1068 /// use pin_init::{init_from_closure, zeroed}; 1069 /// struct Foo { 1070 /// buf: [u8; 1_000_000], 1071 /// } 1072 /// 1073 /// impl Foo { 1074 /// fn setup(&mut self) { 1075 /// pr_info!("Setting up foo"); 1076 /// } 1077 /// } 1078 /// 1079 /// let foo = init!(Foo { 1080 /// buf <- zeroed() 1081 /// }).chain(|foo| { 1082 /// foo.setup(); 1083 /// Ok(()) 1084 /// }); 1085 /// ``` 1086 fn chain<F>(self, f: F) -> ChainInit<Self, F, T, E> 1087 where 1088 F: FnOnce(&mut T) -> Result<(), E>, 1089 { 1090 ChainInit(self, f, PhantomData) 1091 } 1092 } 1093 1094 /// An initializer returned by [`Init::chain`]. 1095 pub struct ChainInit<I, F, T: ?Sized, E>(I, F, __internal::Invariant<(E, KBox<T>)>); 1096 1097 // SAFETY: The `__init` function is implemented such that it 1098 // - returns `Ok(())` on successful initialization, 1099 // - returns `Err(err)` on error and in this case `slot` will be dropped. 1100 unsafe impl<T: ?Sized, E, I, F> Init<T, E> for ChainInit<I, F, T, E> 1101 where 1102 I: Init<T, E>, 1103 F: FnOnce(&mut T) -> Result<(), E>, 1104 { 1105 unsafe fn __init(self, slot: *mut T) -> Result<(), E> { 1106 // SAFETY: All requirements fulfilled since this function is `__init`. 1107 unsafe { self.0.__pinned_init(slot)? }; 1108 // SAFETY: The above call initialized `slot` and we still have unique access. 1109 (self.1)(unsafe { &mut *slot }).inspect_err(|_| 1110 // SAFETY: `slot` was initialized above. 1111 unsafe { core::ptr::drop_in_place(slot) }) 1112 } 1113 } 1114 1115 // SAFETY: `__pinned_init` behaves exactly the same as `__init`. 1116 unsafe impl<T: ?Sized, E, I, F> PinInit<T, E> for ChainInit<I, F, T, E> 1117 where 1118 I: Init<T, E>, 1119 F: FnOnce(&mut T) -> Result<(), E>, 1120 { 1121 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 1122 // SAFETY: `__init` has less strict requirements compared to `__pinned_init`. 1123 unsafe { self.__init(slot) } 1124 } 1125 } 1126 1127 /// Creates a new [`PinInit<T, E>`] from the given closure. 1128 /// 1129 /// # Safety 1130 /// 1131 /// The closure: 1132 /// - returns `Ok(())` if it initialized every field of `slot`, 1133 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 1134 /// - `slot` can be deallocated without UB occurring, 1135 /// - `slot` does not need to be dropped, 1136 /// - `slot` is not partially initialized. 1137 /// - may assume that the `slot` does not move if `T: !Unpin`, 1138 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 1139 #[inline] 1140 pub const unsafe fn pin_init_from_closure<T: ?Sized, E>( 1141 f: impl FnOnce(*mut T) -> Result<(), E>, 1142 ) -> impl PinInit<T, E> { 1143 __internal::InitClosure(f, PhantomData) 1144 } 1145 1146 /// Creates a new [`Init<T, E>`] from the given closure. 1147 /// 1148 /// # Safety 1149 /// 1150 /// The closure: 1151 /// - returns `Ok(())` if it initialized every field of `slot`, 1152 /// - returns `Err(err)` if it encountered an error and then cleaned `slot`, this means: 1153 /// - `slot` can be deallocated without UB occurring, 1154 /// - `slot` does not need to be dropped, 1155 /// - `slot` is not partially initialized. 1156 /// - the `slot` may move after initialization. 1157 /// - while constructing the `T` at `slot` it upholds the pinning invariants of `T`. 1158 #[inline] 1159 pub const unsafe fn init_from_closure<T: ?Sized, E>( 1160 f: impl FnOnce(*mut T) -> Result<(), E>, 1161 ) -> impl Init<T, E> { 1162 __internal::InitClosure(f, PhantomData) 1163 } 1164 1165 /// An initializer that leaves the memory uninitialized. 1166 /// 1167 /// The initializer is a no-op. The `slot` memory is not changed. 1168 #[inline] 1169 pub fn uninit<T, E>() -> impl Init<MaybeUninit<T>, E> { 1170 // SAFETY: The memory is allowed to be uninitialized. 1171 unsafe { init_from_closure(|_| Ok(())) } 1172 } 1173 1174 /// Initializes an array by initializing each element via the provided initializer. 1175 /// 1176 /// # Examples 1177 /// 1178 /// ```rust,ignore 1179 /// # use pin_init::*; 1180 /// use pin_init::init_array_from_fn; 1181 /// let array: Box<[usize; 1_000]> = Box::init(init_array_from_fn(|i| i)).unwrap(); 1182 /// assert_eq!(array.len(), 1_000); 1183 /// ``` 1184 pub fn init_array_from_fn<I, const N: usize, T, E>( 1185 mut make_init: impl FnMut(usize) -> I, 1186 ) -> impl Init<[T; N], E> 1187 where 1188 I: Init<T, E>, 1189 { 1190 let init = move |slot: *mut [T; N]| { 1191 let slot = slot.cast::<T>(); 1192 // Counts the number of initialized elements and when dropped drops that many elements from 1193 // `slot`. 1194 let mut init_count = ScopeGuard::new_with_data(0, |i| { 1195 // We now free every element that has been initialized before. 1196 // SAFETY: The loop initialized exactly the values from 0..i and since we 1197 // return `Err` below, the caller will consider the memory at `slot` as 1198 // uninitialized. 1199 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; 1200 }); 1201 for i in 0..N { 1202 let init = make_init(i); 1203 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`. 1204 let ptr = unsafe { slot.add(i) }; 1205 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` 1206 // requirements. 1207 unsafe { init.__init(ptr) }?; 1208 *init_count += 1; 1209 } 1210 init_count.dismiss(); 1211 Ok(()) 1212 }; 1213 // SAFETY: The initializer above initializes every element of the array. On failure it drops 1214 // any initialized elements and returns `Err`. 1215 unsafe { init_from_closure(init) } 1216 } 1217 1218 /// Initializes an array by initializing each element via the provided initializer. 1219 /// 1220 /// # Examples 1221 /// 1222 /// ```rust,ignore 1223 /// # #![feature(allocator_api)] 1224 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 1225 /// # use pin_init::*; 1226 /// # use core::pin::Pin; 1227 /// use pin_init::pin_init_array_from_fn; 1228 /// use std::sync::Arc; 1229 /// let array: Pin<Arc<[CMutex<usize>; 1_000]>> = 1230 /// Arc::pin_init(pin_init_array_from_fn(|i| CMutex::new(i))).unwrap(); 1231 /// assert_eq!(array.len(), 1_000); 1232 /// ``` 1233 pub fn pin_init_array_from_fn<I, const N: usize, T, E>( 1234 mut make_init: impl FnMut(usize) -> I, 1235 ) -> impl PinInit<[T; N], E> 1236 where 1237 I: PinInit<T, E>, 1238 { 1239 let init = move |slot: *mut [T; N]| { 1240 let slot = slot.cast::<T>(); 1241 // Counts the number of initialized elements and when dropped drops that many elements from 1242 // `slot`. 1243 let mut init_count = ScopeGuard::new_with_data(0, |i| { 1244 // We now free every element that has been initialized before. 1245 // SAFETY: The loop initialized exactly the values from 0..i and since we 1246 // return `Err` below, the caller will consider the memory at `slot` as 1247 // uninitialized. 1248 unsafe { ptr::drop_in_place(ptr::slice_from_raw_parts_mut(slot, i)) }; 1249 }); 1250 for i in 0..N { 1251 let init = make_init(i); 1252 // SAFETY: Since 0 <= `i` < N, it is still in bounds of `[T; N]`. 1253 let ptr = unsafe { slot.add(i) }; 1254 // SAFETY: The pointer is derived from `slot` and thus satisfies the `__init` 1255 // requirements. 1256 unsafe { init.__pinned_init(ptr) }?; 1257 *init_count += 1; 1258 } 1259 init_count.dismiss(); 1260 Ok(()) 1261 }; 1262 // SAFETY: The initializer above initializes every element of the array. On failure it drops 1263 // any initialized elements and returns `Err`. 1264 unsafe { pin_init_from_closure(init) } 1265 } 1266 1267 // SAFETY: Every type can be initialized by-value. 1268 unsafe impl<T, E> Init<T, E> for T { 1269 unsafe fn __init(self, slot: *mut T) -> Result<(), E> { 1270 // SAFETY: TODO. 1271 unsafe { slot.write(self) }; 1272 Ok(()) 1273 } 1274 } 1275 1276 // SAFETY: Every type can be initialized by-value. `__pinned_init` calls `__init`. 1277 unsafe impl<T, E> PinInit<T, E> for T { 1278 unsafe fn __pinned_init(self, slot: *mut T) -> Result<(), E> { 1279 // SAFETY: TODO. 1280 unsafe { self.__init(slot) } 1281 } 1282 } 1283 1284 /// Smart pointer that can initialize memory in-place. 1285 pub trait InPlaceInit<T>: Sized { 1286 /// Pinned version of `Self`. 1287 /// 1288 /// If a type already implicitly pins its pointee, `Pin<Self>` is unnecessary. In this case use 1289 /// `Self`, otherwise just use `Pin<Self>`. 1290 type PinnedSelf; 1291 1292 /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this 1293 /// type. 1294 /// 1295 /// If `T: !Unpin` it will not be able to move afterwards. 1296 fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E> 1297 where 1298 E: From<AllocError>; 1299 1300 /// Use the given pin-initializer to pin-initialize a `T` inside of a new smart pointer of this 1301 /// type. 1302 /// 1303 /// If `T: !Unpin` it will not be able to move afterwards. 1304 fn pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> error::Result<Self::PinnedSelf> 1305 where 1306 Error: From<E>, 1307 { 1308 // SAFETY: We delegate to `init` and only change the error type. 1309 let init = unsafe { 1310 pin_init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e))) 1311 }; 1312 Self::try_pin_init(init, flags) 1313 } 1314 1315 /// Use the given initializer to in-place initialize a `T`. 1316 fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> 1317 where 1318 E: From<AllocError>; 1319 1320 /// Use the given initializer to in-place initialize a `T`. 1321 fn init<E>(init: impl Init<T, E>, flags: Flags) -> error::Result<Self> 1322 where 1323 Error: From<E>, 1324 { 1325 // SAFETY: We delegate to `init` and only change the error type. 1326 let init = unsafe { 1327 init_from_closure(|slot| init.__pinned_init(slot).map_err(|e| Error::from(e))) 1328 }; 1329 Self::try_init(init, flags) 1330 } 1331 } 1332 1333 impl<T> InPlaceInit<T> for Arc<T> { 1334 type PinnedSelf = Self; 1335 1336 #[inline] 1337 fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E> 1338 where 1339 E: From<AllocError>, 1340 { 1341 UniqueArc::try_pin_init(init, flags).map(|u| u.into()) 1342 } 1343 1344 #[inline] 1345 fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> 1346 where 1347 E: From<AllocError>, 1348 { 1349 UniqueArc::try_init(init, flags).map(|u| u.into()) 1350 } 1351 } 1352 1353 impl<T> InPlaceInit<T> for UniqueArc<T> { 1354 type PinnedSelf = Pin<Self>; 1355 1356 #[inline] 1357 fn try_pin_init<E>(init: impl PinInit<T, E>, flags: Flags) -> Result<Self::PinnedSelf, E> 1358 where 1359 E: From<AllocError>, 1360 { 1361 UniqueArc::new_uninit(flags)?.write_pin_init(init) 1362 } 1363 1364 #[inline] 1365 fn try_init<E>(init: impl Init<T, E>, flags: Flags) -> Result<Self, E> 1366 where 1367 E: From<AllocError>, 1368 { 1369 UniqueArc::new_uninit(flags)?.write_init(init) 1370 } 1371 } 1372 1373 /// Smart pointer containing uninitialized memory and that can write a value. 1374 pub trait InPlaceWrite<T> { 1375 /// The type `Self` turns into when the contents are initialized. 1376 type Initialized; 1377 1378 /// Use the given initializer to write a value into `self`. 1379 /// 1380 /// Does not drop the current value and considers it as uninitialized memory. 1381 fn write_init<E>(self, init: impl Init<T, E>) -> Result<Self::Initialized, E>; 1382 1383 /// Use the given pin-initializer to write a value into `self`. 1384 /// 1385 /// Does not drop the current value and considers it as uninitialized memory. 1386 fn write_pin_init<E>(self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E>; 1387 } 1388 1389 impl<T> InPlaceWrite<T> for UniqueArc<MaybeUninit<T>> { 1390 type Initialized = UniqueArc<T>; 1391 1392 fn write_init<E>(mut self, init: impl Init<T, E>) -> Result<Self::Initialized, E> { 1393 let slot = self.as_mut_ptr(); 1394 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 1395 // slot is valid. 1396 unsafe { init.__init(slot)? }; 1397 // SAFETY: All fields have been initialized. 1398 Ok(unsafe { self.assume_init() }) 1399 } 1400 1401 fn write_pin_init<E>(mut self, init: impl PinInit<T, E>) -> Result<Pin<Self::Initialized>, E> { 1402 let slot = self.as_mut_ptr(); 1403 // SAFETY: When init errors/panics, slot will get deallocated but not dropped, 1404 // slot is valid and will not be moved, because we pin it later. 1405 unsafe { init.__pinned_init(slot)? }; 1406 // SAFETY: All fields have been initialized. 1407 Ok(unsafe { self.assume_init() }.into()) 1408 } 1409 } 1410 1411 /// Trait facilitating pinned destruction. 1412 /// 1413 /// Use [`pinned_drop`] to implement this trait safely: 1414 /// 1415 /// ```rust,ignore 1416 /// # #![feature(allocator_api)] 1417 /// # #[path = "../examples/mutex.rs"] mod mutex; use mutex::*; 1418 /// # use pin_init::*; 1419 /// use core::pin::Pin; 1420 /// #[pin_data(PinnedDrop)] 1421 /// struct Foo { 1422 /// #[pin] 1423 /// mtx: CMutex<usize>, 1424 /// } 1425 /// 1426 /// #[pinned_drop] 1427 /// impl PinnedDrop for Foo { 1428 /// fn drop(self: Pin<&mut Self>) { 1429 /// println!("Foo is being dropped!"); 1430 /// } 1431 /// } 1432 /// ``` 1433 /// 1434 /// # Safety 1435 /// 1436 /// This trait must be implemented via the [`pinned_drop`] proc-macro attribute on the impl. 1437 /// 1438 /// [`pinned_drop`]: kernel::macros::pinned_drop 1439 pub unsafe trait PinnedDrop: __internal::HasPinData { 1440 /// Executes the pinned destructor of this type. 1441 /// 1442 /// While this function is marked safe, it is actually unsafe to call it manually. For this 1443 /// reason it takes an additional parameter. This type can only be constructed by `unsafe` code 1444 /// and thus prevents this function from being called where it should not. 1445 /// 1446 /// This extra parameter will be generated by the `#[pinned_drop]` proc-macro attribute 1447 /// automatically. 1448 fn drop(self: Pin<&mut Self>, only_call_from_drop: __internal::OnlyCallFromDrop); 1449 } 1450 1451 /// Marker trait for types that can be initialized by writing just zeroes. 1452 /// 1453 /// # Safety 1454 /// 1455 /// The bit pattern consisting of only zeroes is a valid bit pattern for this type. In other words, 1456 /// this is not UB: 1457 /// 1458 /// ```rust,ignore 1459 /// let val: Self = unsafe { core::mem::zeroed() }; 1460 /// ``` 1461 pub unsafe trait Zeroable {} 1462 1463 /// Create a new zeroed T. 1464 /// 1465 /// The returned initializer will write `0x00` to every byte of the given `slot`. 1466 #[inline] 1467 pub fn zeroed<T: Zeroable>() -> impl Init<T> { 1468 // SAFETY: Because `T: Zeroable`, all bytes zero is a valid bit pattern for `T` 1469 // and because we write all zeroes, the memory is initialized. 1470 unsafe { 1471 init_from_closure(|slot: *mut T| { 1472 slot.write_bytes(0, 1); 1473 Ok(()) 1474 }) 1475 } 1476 } 1477 1478 macro_rules! impl_zeroable { 1479 ($($({$($generics:tt)*})? $t:ty, )*) => { 1480 // SAFETY: Safety comments written in the macro invocation. 1481 $(unsafe impl$($($generics)*)? Zeroable for $t {})* 1482 }; 1483 } 1484 1485 impl_zeroable! { 1486 // SAFETY: All primitives that are allowed to be zero. 1487 bool, 1488 char, 1489 u8, u16, u32, u64, u128, usize, 1490 i8, i16, i32, i64, i128, isize, 1491 f32, f64, 1492 1493 // Note: do not add uninhabited types (such as `!` or `core::convert::Infallible`) to this list; 1494 // creating an instance of an uninhabited type is immediate undefined behavior. For more on 1495 // uninhabited/empty types, consult The Rustonomicon: 1496 // <https://doc.rust-lang.org/stable/nomicon/exotic-sizes.html#empty-types>. The Rust Reference 1497 // also has information on undefined behavior: 1498 // <https://doc.rust-lang.org/stable/reference/behavior-considered-undefined.html>. 1499 // 1500 // SAFETY: These are inhabited ZSTs; there is nothing to zero and a valid value exists. 1501 {<T: ?Sized>} PhantomData<T>, core::marker::PhantomPinned, (), 1502 1503 // SAFETY: Type is allowed to take any value, including all zeros. 1504 {<T>} MaybeUninit<T>, 1505 // SAFETY: Type is allowed to take any value, including all zeros. 1506 {<T>} Opaque<T>, 1507 1508 // SAFETY: `T: Zeroable` and `UnsafeCell` is `repr(transparent)`. 1509 {<T: ?Sized + Zeroable>} UnsafeCell<T>, 1510 1511 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee). 1512 Option<NonZeroU8>, Option<NonZeroU16>, Option<NonZeroU32>, Option<NonZeroU64>, 1513 Option<NonZeroU128>, Option<NonZeroUsize>, 1514 Option<NonZeroI8>, Option<NonZeroI16>, Option<NonZeroI32>, Option<NonZeroI64>, 1515 Option<NonZeroI128>, Option<NonZeroIsize>, 1516 1517 // SAFETY: All zeros is equivalent to `None` (option layout optimization guarantee). 1518 // 1519 // In this case we are allowed to use `T: ?Sized`, since all zeros is the `None` variant. 1520 {<T: ?Sized>} Option<NonNull<T>>, 1521 {<T: ?Sized>} Option<KBox<T>>, 1522 1523 // SAFETY: `null` pointer is valid. 1524 // 1525 // We cannot use `T: ?Sized`, since the VTABLE pointer part of fat pointers is not allowed to be 1526 // null. 1527 // 1528 // When `Pointee` gets stabilized, we could use 1529 // `T: ?Sized where <T as Pointee>::Metadata: Zeroable` 1530 {<T>} *mut T, {<T>} *const T, 1531 1532 // SAFETY: `null` pointer is valid and the metadata part of these fat pointers is allowed to be 1533 // zero. 1534 {<T>} *mut [T], {<T>} *const [T], *mut str, *const str, 1535 1536 // SAFETY: `T` is `Zeroable`. 1537 {<const N: usize, T: Zeroable>} [T; N], {<T: Zeroable>} Wrapping<T>, 1538 } 1539 1540 macro_rules! impl_tuple_zeroable { 1541 ($(,)?) => {}; 1542 ($first:ident, $($t:ident),* $(,)?) => { 1543 // SAFETY: All elements are zeroable and padding can be zero. 1544 unsafe impl<$first: Zeroable, $($t: Zeroable),*> Zeroable for ($first, $($t),*) {} 1545 impl_tuple_zeroable!($($t),* ,); 1546 } 1547 } 1548 1549 impl_tuple_zeroable!(A, B, C, D, E, F, G, H, I, J); 1550