[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-Id: <DFK4173K583S.DFF6M0ZYY6RC@garyguo.net>
Date: Fri, 09 Jan 2026 13:58:23 +0000
From: "Gary Guo" <gary@...yguo.net>
To: "Benno Lossin" <lossin@...nel.org>, "Gary Guo" <gary@...yguo.net>,
"Miguel Ojeda" <ojeda@...nel.org>, "Boqun Feng" <boqun.feng@...il.com>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>, "Andreas
Hindborg" <a.hindborg@...nel.org>, "Alice Ryhl" <aliceryhl@...gle.com>,
"Trevor Gross" <tmgross@...ch.edu>, "Danilo Krummrich" <dakr@...nel.org>
Cc: "Janne Grunau" <j@...nau.net>, <rust-for-linux@...r.kernel.org>,
<linux-kernel@...r.kernel.org>
Subject: Re: [PATCH 12/12] rust: pin-init: internal: init: add escape hatch
for referencing initialized fields
On Thu Jan 8, 2026 at 1:50 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.
An alternative might be checking if the specific field is actually used later
and only generate references if so. Although, that might be "too much magic"?
Best,
Gary
>
> Requested-by: Janne Grunau <j@...nau.net>
> Link: https://lore.kernel.org/all/20251206170214.GE1097212@robin.jannau.net [1]
> Signed-off-by: Benno Lossin <lossin@...nel.org>
Powered by blists - more mailing lists