Skip to content

Commit e63c184

Browse files
BennoLossinjannau
authored andcommitted
rust: derive Zeroable for all structs & unions generated by bindgen where possible
Using the `--with-derive-custom-{struct,union}` option of bindgen, add `#[derive(MaybeZeroable)]` to every struct & union. This makes those types implement `Zeroable` if all their fields implement it. Sadly bindgen doesn't add custom derives to the `__BindgenBitfieldUnit` struct. So manually implement `Zeroable` for that. Signed-off-by: Benno Lossin <lossin@kernel.org>
1 parent 2008b8e commit e63c184

3 files changed

Lines changed: 14 additions & 0 deletions

File tree

rust/bindgen_parameters

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,7 @@
3434
# We use const helpers to aid bindgen, to avoid conflicts when constants are
3535
# recognized, block generation of the non-helper constants.
3636
--blocklist-item ARCH_SLAB_MINALIGN
37+
38+
# Structs should implement Zeroable when all of their fields do.
39+
--with-derive-custom-struct .*=MaybeZeroable
40+
--with-derive-custom-union .*=MaybeZeroable

rust/bindings/lib.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,11 +31,19 @@
3131
#[allow(clippy::undocumented_unsafe_blocks)]
3232
#[cfg_attr(CONFIG_RUSTC_HAS_UNNECESSARY_TRANSMUTES, allow(unnecessary_transmutes))]
3333
mod bindings_raw {
34+
use pin_init::{MaybeZeroable, Zeroable};
35+
3436
// Manual definition for blocklisted types.
3537
type __kernel_size_t = usize;
3638
type __kernel_ssize_t = isize;
3739
type __kernel_ptrdiff_t = isize;
3840

41+
// `bindgen` doesn't automatically do this, see
42+
// <https://github.com/rust-lang/rust-bindgen/issues/3196>
43+
//
44+
// SAFETY: `__BindgenBitfieldUnit<Storage>` is a newtype around `Storage`.
45+
unsafe impl<Storage> Zeroable for __BindgenBitfieldUnit<Storage> where Storage: Zeroable {}
46+
3947
// Use glob import here to expose all helpers.
4048
// Symbols defined within the module will take precedence to the glob import.
4149
pub use super::bindings_helper::*;

rust/uapi/lib.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,4 +34,6 @@ type __kernel_size_t = usize;
3434
type __kernel_ssize_t = isize;
3535
type __kernel_ptrdiff_t = isize;
3636

37+
use pin_init::MaybeZeroable;
38+
3739
include!(concat!(env!("OBJTREE"), "/rust/uapi/uapi_generated.rs"));

0 commit comments

Comments
 (0)