Rust fixes for v7.1

Toolchain and infrastructure:
 
  - Add 'bindgen' target to make UML 32-bit builds work with GCC.
 
  - Disable two Clippy warnings ('collapsible_{if,match}').
 
 'pin-init' crate:
 
  - Fix unsoundness issue that created &'static references.
 -----BEGIN PGP SIGNATURE-----
 
 iQIzBAABCgAdFiEEPjU5OPd5QIZ9jqqOGXyLc2htIW0FAmn/aDwACgkQGXyLc2ht
 IW3geQ//egJL7Gt0ndl2gj95O0Zolmxc13LyauIYdl/QapZWHNaAAEHpgvs1aa7R
 TwSLGHA0fpZKYunjtOvo0/WFbAZXXcUXKM5PMbvEx6NK1/EdVK7i3pnVdlbLdELY
 NhJIwSTs1GL2j0KQgDl40miAnhUOJ42mbQ9qfSBU9B5Ypi3WxTceVHSPVvtw0Hlo
 mBPM6TZPJTI974HZt6yzyvKayIc+L+rFbqiphSd0NSXth3LNBK7SvDDSh8cm1LBy
 Av/0kWXpb7fV/TyZMOp+Wjo+CSjOnjAcDtwHGkMytHFlzyXjNdv/DTNryUQJ397h
 o+WVit639ESrJw2U0qKnpxmlJc8vgHxxsd2TWyHR7CCZaI1V5AD4Qxrx4SBdcsyf
 zvYQXuZ/zKqjLu2IJpp7heDb37k6CdHKWKJjbkxDImBay/KF0LMoObdS2G+IQ8oH
 mpxuMSDVpQzAhxhyIBJvle85KkogfHvjRWxvp9ZkNolSQAlrWnK40J/+DD/pJuQa
 WNYG+HzmLUKn/nxKydNZ9ExnB1+xSFIeXA7kdnEflUi8AO5QsvntsQdHAFyWCYD2
 NzBEsIapXPAg1+4bkrOe4Glo5HX+41z/Nks9xjrkjGmXeaHDIMkuZr2+E5mfZ8oS
 1RWpUt+T/zM4c5/tihQoXavillJ5JMuC3OWWd/k85x+phPrjHUc=
 =knuc
 -----END PGP SIGNATURE-----

Merge tag 'rust-fixes-7.1' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux

Pull Rust fixes from Miguel Ojeda:
 "Toolchain and infrastructure:

    - Add 'bindgen' target to make UML 32-bit builds work with GCC

    - Disable two Clippy warnings ('collapsible_{if,match}')

  'pin-init' crate:

    - Fix unsoundness issue that created &'static references"

* tag 'rust-fixes-7.1' of git://git.kernel.org/pub/scm/linux/kernel/git/ojeda/linux:
  rust: allow `clippy::collapsible_if` globally
  rust: allow `clippy::collapsible_match` globally
  rust: pin-init: fix incorrect accessor reference lifetime
  rust: pin-init: internal: move alignment check to `make_field_check`
  rust: arch: um: Fix building 32-bit UML with GCC
This commit is contained in:
Linus Torvalds 2026-05-09 11:24:02 -07:00
commit e92b2872d0
5 changed files with 107 additions and 110 deletions

View File

@ -486,6 +486,8 @@ export rust_common_flags := --edition=2021 \
-Wclippy::as_ptr_cast_mut \ -Wclippy::as_ptr_cast_mut \
-Wclippy::as_underscore \ -Wclippy::as_underscore \
-Wclippy::cast_lossless \ -Wclippy::cast_lossless \
-Aclippy::collapsible_if \
-Aclippy::collapsible_match \
-Wclippy::ignored_unit_patterns \ -Wclippy::ignored_unit_patterns \
-Aclippy::incompatible_msrv \ -Aclippy::incompatible_msrv \
-Wclippy::mut_mut \ -Wclippy::mut_mut \

View File

@ -204,7 +204,6 @@ pub(crate) fn reservation_abort(&mut self, offset: usize) -> Result<FreedRange>
// caller will mark them as unused, which means that they can be freed if the system comes // caller will mark them as unused, which means that they can be freed if the system comes
// under memory pressure. // under memory pressure.
let mut freed_range = FreedRange::interior_pages(offset, size); let mut freed_range = FreedRange::interior_pages(offset, size);
#[expect(clippy::collapsible_if)] // reads better like this
if offset % PAGE_SIZE != 0 { if offset % PAGE_SIZE != 0 {
if i == 0 || self.ranges[i - 1].endpoint() <= (offset & PAGE_MASK) { if i == 0 || self.ranges[i - 1].endpoint() <= (offset & PAGE_MASK) {
freed_range.start_page_idx -= 1; freed_range.start_page_idx -= 1;

View File

@ -403,6 +403,8 @@ BINDGEN_TARGET_x86 := x86_64-linux-gnu
BINDGEN_TARGET_arm64 := aarch64-linux-gnu BINDGEN_TARGET_arm64 := aarch64-linux-gnu
BINDGEN_TARGET_arm := arm-linux-gnueabi BINDGEN_TARGET_arm := arm-linux-gnueabi
BINDGEN_TARGET_loongarch := loongarch64-linux-gnusf BINDGEN_TARGET_loongarch := loongarch64-linux-gnusf
# This is only for i386 UM builds, which need the 32-bit target not -m32
BINDGEN_TARGET_i386 := i386-linux-gnu
BINDGEN_TARGET_um := $(BINDGEN_TARGET_$(SUBARCH)) BINDGEN_TARGET_um := $(BINDGEN_TARGET_$(SUBARCH))
BINDGEN_TARGET := $(BINDGEN_TARGET_$(SRCARCH)) BINDGEN_TARGET := $(BINDGEN_TARGET_$(SRCARCH))

View File

@ -249,22 +249,6 @@ fn init_fields(
}); });
// Again span for better diagnostics // Again span for better diagnostics
let write = quote_spanned!(ident.span()=> ::core::ptr::write); let write = quote_spanned!(ident.span()=> ::core::ptr::write);
// NOTE: the field accessor ensures that the initialized field is properly aligned.
// Unaligned fields will cause the compiler to emit E0793. We do not support
// unaligned fields since `Init::__init` requires an aligned pointer; the call to
// `ptr::write` below has the same requirement.
let accessor = if pinned {
let project_ident = format_ident!("__project_{ident}");
quote! {
// SAFETY: TODO
unsafe { #data.#project_ident(&mut (*#slot).#ident) }
}
} else {
quote! {
// SAFETY: TODO
unsafe { &mut (*#slot).#ident }
}
};
quote! { quote! {
#(#attrs)* #(#attrs)*
{ {
@ -272,21 +256,12 @@ fn init_fields(
// SAFETY: TODO // SAFETY: TODO
unsafe { #write(&raw mut (*#slot).#ident, #value_ident) }; unsafe { #write(&raw mut (*#slot).#ident, #value_ident) };
} }
#(#cfgs)*
#[allow(unused_variables)]
let #ident = #accessor;
} }
} }
InitializerKind::Init { ident, value, .. } => { InitializerKind::Init { ident, value, .. } => {
// Again span for better diagnostics // Again span for better diagnostics
let init = format_ident!("init", span = value.span()); let init = format_ident!("init", span = value.span());
// NOTE: the field accessor ensures that the initialized field is properly aligned. let value_init = if pinned {
// Unaligned fields will cause the compiler to emit E0793. We do not support
// unaligned fields since `Init::__init` requires an aligned pointer; the call to
// `ptr::write` below has the same requirement.
let (value_init, accessor) = if pinned {
let project_ident = format_ident!("__project_{ident}");
(
quote! { quote! {
// SAFETY: // SAFETY:
// - `slot` is valid, because we are inside of an initializer closure, we // - `slot` is valid, because we are inside of an initializer closure, we
@ -294,14 +269,8 @@ fn init_fields(
// - We also use `#data` to require the correct trait (`Init` or `PinInit`) // - We also use `#data` to require the correct trait (`Init` or `PinInit`)
// for `#ident`. // for `#ident`.
unsafe { #data.#ident(&raw mut (*#slot).#ident, #init)? }; unsafe { #data.#ident(&raw mut (*#slot).#ident, #init)? };
}, }
quote! {
// SAFETY: TODO
unsafe { #data.#project_ident(&mut (*#slot).#ident) }
},
)
} else { } else {
(
quote! { quote! {
// SAFETY: `slot` is valid, because we are inside of an initializer // SAFETY: `slot` is valid, because we are inside of an initializer
// closure, we return when an error/panic occurs. // closure, we return when an error/panic occurs.
@ -311,12 +280,7 @@ fn init_fields(
&raw mut (*#slot).#ident, &raw mut (*#slot).#ident,
)? )?
}; };
}, }
quote! {
// SAFETY: TODO
unsafe { &mut (*#slot).#ident }
},
)
}; };
quote! { quote! {
#(#attrs)* #(#attrs)*
@ -324,9 +288,6 @@ fn init_fields(
let #init = #value; let #init = #value;
#value_init #value_init
} }
#(#cfgs)*
#[allow(unused_variables)]
let #ident = #accessor;
} }
} }
InitializerKind::Code { block: value, .. } => quote! { InitializerKind::Code { block: value, .. } => quote! {
@ -339,18 +300,41 @@ fn init_fields(
if let Some(ident) = kind.ident() { if let Some(ident) = kind.ident() {
// `mixed_site` ensures that the guard is not accessible to the user-controlled code. // `mixed_site` ensures that the guard is not accessible to the user-controlled code.
let guard = format_ident!("__{ident}_guard", span = Span::mixed_site()); let guard = format_ident!("__{ident}_guard", span = Span::mixed_site());
// NOTE: The reference is derived from the guard so that it only lives as long as the
// guard does and cannot escape the scope. If it's created via `&mut (*#slot).#ident`
// like the unaligned field guard, it will become effectively `'static`.
let accessor = if pinned {
let project_ident = format_ident!("__project_{ident}");
quote! {
// SAFETY: the initialization is pinned.
unsafe { #data.#project_ident(#guard.let_binding()) }
}
} else {
quote! {
#guard.let_binding()
}
};
res.extend(quote! { res.extend(quote! {
#(#cfgs)* #(#cfgs)*
// Create the drop guard: // Create the drop guard.
// //
// We rely on macro hygiene to make it impossible for users to access this local // SAFETY:
// variable. // - `&raw mut (*slot).#ident` is valid.
// SAFETY: We forget the guard later when initialization has succeeded. // - `make_field_check` checks that `&raw mut (*slot).#ident` is properly aligned.
let #guard = unsafe { // - `(*slot).#ident` has been initialized above.
// - We only need the ownership to the pointee back when initialization has
// succeeded, where we `forget` the guard.
let mut #guard = unsafe {
::pin_init::__internal::DropGuard::new( ::pin_init::__internal::DropGuard::new(
&raw mut (*slot).#ident &raw mut (*slot).#ident
) )
}; };
#(#cfgs)*
#[allow(unused_variables)]
let #ident = #accessor;
}); });
guards.push(guard); guards.push(guard);
guard_attrs.push(cfgs); guard_attrs.push(cfgs);
@ -367,49 +351,49 @@ fn init_fields(
} }
} }
/// Generate the check for ensuring that every field has been initialized. /// Generate the check for ensuring that every field has been initialized and aligned.
fn make_field_check( fn make_field_check(
fields: &Punctuated<InitializerField, Token![,]>, fields: &Punctuated<InitializerField, Token![,]>,
init_kind: InitKind, init_kind: InitKind,
path: &Path, path: &Path,
) -> TokenStream { ) -> TokenStream {
let field_attrs = fields let field_attrs: Vec<_> = fields
.iter() .iter()
.filter_map(|f| f.kind.ident().map(|_| &f.attrs)); .filter_map(|f| f.kind.ident().map(|_| &f.attrs))
let field_name = fields.iter().filter_map(|f| f.kind.ident()); .collect();
match init_kind { let field_name: Vec<_> = fields.iter().filter_map(|f| f.kind.ident()).collect();
InitKind::Normal => quote! { let zeroing_trailer = match init_kind {
// We use unreachable code to ensure that all fields have been mentioned exactly once, InitKind::Normal => None,
// this struct initializer will still be type-checked and complain with a very natural InitKind::Zeroing => Some(quote! {
// error message if a field is forgotten/mentioned more than once.
#[allow(unreachable_code, clippy::diverging_sub_expression)]
// SAFETY: this code is never executed.
let _ = || unsafe {
::core::ptr::write(slot, #path {
#(
#(#field_attrs)*
#field_name: ::core::panic!(),
)*
})
};
},
InitKind::Zeroing => quote! {
// We use unreachable code to ensure that all fields have been mentioned at most once.
// Since the user specified `..Zeroable::zeroed()` at the end, all missing fields will
// be zeroed. This struct initializer will still be type-checked and complain with a
// very natural error message if a field is mentioned more than once, or doesn't exist.
#[allow(unreachable_code, clippy::diverging_sub_expression, unused_assignments)]
// SAFETY: this code is never executed.
let _ = || unsafe {
::core::ptr::write(slot, #path {
#(
#(#field_attrs)*
#field_name: ::core::panic!(),
)*
..::core::mem::zeroed() ..::core::mem::zeroed()
}),
};
quote! {
#[allow(unreachable_code, clippy::diverging_sub_expression)]
// We use unreachable code to perform field checks. They're still checked by the compiler.
// SAFETY: this code is never executed.
let _ = || unsafe {
// Create references to ensure that the initialized field is properly aligned.
// Unaligned fields will cause the compiler to emit E0793. We do not support
// unaligned fields since `Init::__init` requires an aligned pointer; the call to
// `ptr::write` for value-initialization case has the same requirement.
#(
#(#field_attrs)*
let _ = &(*slot).#field_name;
)*
// If the zeroing trailer is not present, this checks that all fields have been
// mentioned exactly once. If the zeroing trailer is present, all missing fields will be
// zeroed, so this checks that all fields have been mentioned at most once. The use of
// struct initializer will still generate very natural error messages for any misuse.
::core::ptr::write(slot, #path {
#(
#(#field_attrs)*
#field_name: ::core::panic!(),
)*
#zeroing_trailer
}) })
}; };
},
} }
} }

View File

@ -238,32 +238,42 @@ struct Foo {
/// When a value of this type is dropped, it drops a `T`. /// When a value of this type is dropped, it drops a `T`.
/// ///
/// Can be forgotten to prevent the drop. /// Can be forgotten to prevent the drop.
///
/// # Invariants
///
/// - `ptr` is valid and properly aligned.
/// - `*ptr` is initialized and owned by this guard.
pub struct DropGuard<T: ?Sized> { pub struct DropGuard<T: ?Sized> {
ptr: *mut T, ptr: *mut T,
} }
impl<T: ?Sized> DropGuard<T> { impl<T: ?Sized> DropGuard<T> {
/// Creates a new [`DropGuard<T>`]. It will [`ptr::drop_in_place`] `ptr` when it gets dropped. /// Creates a drop guard and transfer the ownership of the pointer content.
///
/// The ownership is only relinguished if the guard is forgotten via [`core::mem::forget`].
/// ///
/// # Safety /// # Safety
/// ///
/// `ptr` must be a valid pointer. /// - `ptr` is valid and properly aligned.
/// /// - `*ptr` is initialized, and the ownership is transferred to this guard.
/// It is the callers responsibility that `self` will only get dropped if the pointee of `ptr`:
/// - has not been dropped,
/// - is not accessible by any other means,
/// - will not be dropped by any other means.
#[inline] #[inline]
pub unsafe fn new(ptr: *mut T) -> Self { pub unsafe fn new(ptr: *mut T) -> Self {
// INVARIANT: By safety requirement.
Self { ptr } Self { ptr }
} }
/// Create a let binding for accessor use.
#[inline]
pub fn let_binding(&mut self) -> &mut T {
// SAFETY: Per type invariant.
unsafe { &mut *self.ptr }
}
} }
impl<T: ?Sized> Drop for DropGuard<T> { impl<T: ?Sized> Drop for DropGuard<T> {
#[inline] #[inline]
fn drop(&mut self) { fn drop(&mut self) {
// SAFETY: A `DropGuard` can only be constructed using the unsafe `new` function // SAFETY: `self.ptr` is valid, properly aligned and `*self.ptr` is owned by this guard.
// ensuring that this operation is safe.
unsafe { ptr::drop_in_place(self.ptr) } unsafe { ptr::drop_in_place(self.ptr) }
} }
} }