Re: [PATCH v3 13/15] rust: pin-init: internal: init: add escape hatch for referencing initialized fields
From: Gary Guo
Date: Wed Jan 14 2026 - 13:58:44 EST
On Wed Jan 14, 2026 at 6:18 PM GMT, Benno Lossin wrote:
> The initializer macro emits mutable references for already initialized
> fields, which allows modifying or accessing them later in code blocks or
> when initializing other fields. This behavior results in compiler errors
> when combining with packed structs, since those do not permit creating
> references to misaligned fields. For example:
>
> #[repr(C, packed)]
> struct Foo {
> a: i8,
> b: i32,
> }
>
> fn main() {
> let _ = init!(Foo { a: -42, b: 42 });
> }
>
> This will lead to an error like this:
>
> error[E0793]: reference to field of packed struct is unaligned
> --> tests/ui/compile-fail/init/packed_struct.rs:10:13
> |
> 10 | let _ = init!(Foo { a: -42, b: 42 });
> | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> |
> = note: this struct is 1-byte aligned, but the type of this field may require higher alignment
> = note: creating a misaligned reference is undefined behavior (even if that reference is never dereferenced)
> = help: copy the field contents to a local variable, or replace the reference with a raw pointer and use `read_unaligned`/`write_unaligned` (loads and stores via `*p` must be properly aligned even when using raw pointers)
> = note: this error originates in the macro `init` (in Nightly builds, run with -Z macro-backtrace for more info)
>
> This was requested by Janne Grunau [1] and will most certainly be used
> by the kernel when we eventually end up with trying to initialize packed
> structs.
>
> Thus add an initializer attribute `#[disable_initialized_field_access]`
> that does what the name suggests: do not generate references to already
> initialized fields.
>
> There is space for future work: add yet another attribute which can be
> applied on fields of initializers that ask for said field to be made
> accessible. We can add that when the need arises.
>
> Requested-by: Janne Grunau <j@xxxxxxxxxx>
> Link: https://lore.kernel.org/all/20251206170214.GE1097212@xxxxxxxxxxxxxxxx [1]
> Tested-by: Andreas Hindborg <a.hindborg@xxxxxxxxxx>
> Signed-off-by: Benno Lossin <lossin@xxxxxxxxxx>
Reviewed-by: Gary Guo <gary@xxxxxxxxxxx>
> ---
> Changes in v3: none
> Changes in v2:
> * silence clippy warning
> ---
> rust/pin-init/internal/src/init.rs | 76 +++++++++++++++++++++---------
> 1 file changed, 53 insertions(+), 23 deletions(-)