[<prev] [next>] [<thread-prev] [thread-next>] [day] [month] [year] [list]
Message-ID: <Z0SjvVIALIkOE3nj@boqun-archlinux>
Date: Mon, 25 Nov 2024 08:20:13 -0800
From: Boqun Feng <boqun.feng@...il.com>
To: Miguel Ojeda <miguel.ojeda.sandonis@...il.com>
Cc: Asahi Lina <lina@...hilina.net>, Danilo Krummrich <dakr@...nel.org>,
Miguel Ojeda <ojeda@...nel.org>,
Alex Gaynor <alex.gaynor@...il.com>, Gary Guo <gary@...yguo.net>,
Björn Roy Baron <bjorn3_gh@...tonmail.com>,
Benno Lossin <benno.lossin@...ton.me>,
Andreas Hindborg <a.hindborg@...nel.org>,
Alice Ryhl <aliceryhl@...gle.com>, Trevor Gross <tmgross@...ch.edu>,
Janne Grunau <j@...nau.net>, rust-for-linux@...r.kernel.org,
linux-kernel@...r.kernel.org, asahi@...ts.linux.dev
Subject: Re: [PATCH] rust: alloc: Fix `ArrayLayout` allocations
On Sat, Nov 23, 2024 at 06:39:23PM +0100, Miguel Ojeda wrote:
> On Sat, Nov 23, 2024 at 11:30 AM Asahi Lina <lina@...hilina.net> wrote:
> >
> > We were accidentally allocating a layout for the *square* of the object
> > size due to a variable shadowing mishap.
>
> Good catch, thanks! (Square?)
>
While we are at it, I think it'll be good to add some example/tests for
those functions of ArrayLayout, for example, the below will catch this:
I will open a good-first-issue.
Regards,
Boqun
------------------------>8
diff --git a/rust/kernel/alloc/layout.rs b/rust/kernel/alloc/layout.rs
index 7e0c2f46157b..bb3ce3b2218b 100644
--- a/rust/kernel/alloc/layout.rs
+++ b/rust/kernel/alloc/layout.rs
@@ -7,6 +7,7 @@
use core::{alloc::Layout, marker::PhantomData};
/// Error when constructing an [`ArrayLayout`].
+#[derive(Debug)]
pub struct LayoutError;
/// A layout for an array `[T; n]`.
@@ -43,6 +44,20 @@ pub const fn empty() -> Self {
/// # Errors
///
/// When `len * size_of::<T>()` overflows or when `len * size_of::<T>() > isize::MAX`.
+ ///
+ /// # Examples
+ ///
+ /// ```rust
+ /// use kernel::alloc::layout::ArrayLayout;
+ ///
+ /// // No overflow.
+ /// let layout = ArrayLayout::<i32>::new(12);
+ /// assert_eq!(layout.expect("sizeof(i32) * 12 is 48, not overflow").len(), 12);
+ ///
+ /// // Overflow, should return `Err`.
+ /// let layout = ArrayLayout::<i32>::new(isize::MAX as usize);
+ /// assert!(layout.is_err());
+ /// ```
pub const fn new(len: usize) -> Result<Self, LayoutError> {
match len.checked_mul(core::mem::size_of::<T>()) {
Some(len) if len <= ISIZE_MAX => {
Powered by blists - more mailing lists