[PATCH v2 3/4] rust: alloc: refactor `Vec::truncate` using `dec_len`

Tamir Duberstein posted 4 patches 9 months ago
There is a newer version of this series
[PATCH v2 3/4] rust: alloc: refactor `Vec::truncate` using `dec_len`
Posted by Tamir Duberstein 9 months ago
Use `checked_sub` to satisfy the safety requirements of `dec_len` and
replace nearly the whole body of `truncate` with a call to `dec_len`.

Signed-off-by: Tamir Duberstein <tamird@gmail.com>
---
 rust/kernel/alloc/kvec.rs | 29 +++++++++++------------------
 1 file changed, 11 insertions(+), 18 deletions(-)

diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index 97cc5ab11e2a..6f4dc89ef7f8 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -489,25 +489,18 @@ pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocEr
     /// # Ok::<(), Error>(())
     /// ```
     pub fn truncate(&mut self, len: usize) {
-        if len >= self.len() {
-            return;
+        match self.len().checked_sub(len) {
+            None => {}
+            Some(count) => {
+                // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
+                // equal to `self.len()`.
+                let tail = unsafe { self.dec_len(count) };
+
+                // SAFETY: the contract of `dec_len` guarantees that the elements in `tail` are
+                // valid elements whose ownership has been transferred to the caller.
+                unsafe { ptr::drop_in_place(ptr) };
+            }
         }
-
-        let drop_range = len..self.len();
-
-        // SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
-        let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
-
-        // SAFETY:
-        // - this will always shrink the vector because of the above bounds check
-        // - [`new_len`, `self.len`) will be dropped through the call to `drop_in_place` below
-        unsafe { self.set_len(len) };
-
-        // SAFETY:
-        // - the dropped values are valid `T`s by the type invariant
-        // - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
-        //   len, therefore we have exclusive access to [`new_len`, `old_len`)
-        unsafe { ptr::drop_in_place(ptr) };
     }
 }
 

-- 
2.48.1
Re: [PATCH v2 3/4] rust: alloc: refactor `Vec::truncate` using `dec_len`
Posted by Alice Ryhl 9 months ago
On Tue, Mar 18, 2025 at 04:13:55PM -0400, Tamir Duberstein wrote:
> Use `checked_sub` to satisfy the safety requirements of `dec_len` and
> replace nearly the whole body of `truncate` with a call to `dec_len`.
> 
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> ---
>  rust/kernel/alloc/kvec.rs | 29 +++++++++++------------------
>  1 file changed, 11 insertions(+), 18 deletions(-)
> 
> diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> index 97cc5ab11e2a..6f4dc89ef7f8 100644
> --- a/rust/kernel/alloc/kvec.rs
> +++ b/rust/kernel/alloc/kvec.rs
> @@ -489,25 +489,18 @@ pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocEr
>      /// # Ok::<(), Error>(())
>      /// ```
>      pub fn truncate(&mut self, len: usize) {
> -        if len >= self.len() {
> -            return;
> +        match self.len().checked_sub(len) {
> +            None => {}
> +            Some(count) => {

This could be simplified as:
if let Some(count) = self.len().checked_sub(len) {
    // logic here
}

or
let Some(count) = self.len().checked_sub(len) else {
    return;
}
// logic here

> +                // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
> +                // equal to `self.len()`.
> +                let tail = unsafe { self.dec_len(count) };
> +
> +                // SAFETY: the contract of `dec_len` guarantees that the elements in `tail` are
> +                // valid elements whose ownership has been transferred to the caller.
> +                unsafe { ptr::drop_in_place(ptr) };

We have a mutable reference to these elements until after the
`drop_in_place` call, but the elements are invalidated by that call.
This means that we have a mutable reference to invalid values, which
violates the invariants for mutable references.

Consider converting to a raw pointer when creating `tail` instead to
avoid that:

let tail: *mut [T] = unsafe { self.dec_len(count) };
unsafe { ptr::drop_in_place(ptr) };

Alice
Re: [PATCH v2 3/4] rust: alloc: refactor `Vec::truncate` using `dec_len`
Posted by Tamir Duberstein 9 months ago
On Wed, Mar 19, 2025 at 5:53 AM Alice Ryhl <aliceryhl@google.com> wrote:
>
> On Tue, Mar 18, 2025 at 04:13:55PM -0400, Tamir Duberstein wrote:
> > Use `checked_sub` to satisfy the safety requirements of `dec_len` and
> > replace nearly the whole body of `truncate` with a call to `dec_len`.
> >
> > Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> > ---
> >  rust/kernel/alloc/kvec.rs | 29 +++++++++++------------------
> >  1 file changed, 11 insertions(+), 18 deletions(-)
> >
> > diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> > index 97cc5ab11e2a..6f4dc89ef7f8 100644
> > --- a/rust/kernel/alloc/kvec.rs
> > +++ b/rust/kernel/alloc/kvec.rs
> > @@ -489,25 +489,18 @@ pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocEr
> >      /// # Ok::<(), Error>(())
> >      /// ```
> >      pub fn truncate(&mut self, len: usize) {
> > -        if len >= self.len() {
> > -            return;
> > +        match self.len().checked_sub(len) {
> > +            None => {}
> > +            Some(count) => {
>
> This could be simplified as:
> if let Some(count) = self.len().checked_sub(len) {
>     // logic here
> }
>
> or
> let Some(count) = self.len().checked_sub(len) else {
>     return;
> }
> // logic here

👍

>
> > +                // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
> > +                // equal to `self.len()`.
> > +                let tail = unsafe { self.dec_len(count) };
> > +
> > +                // SAFETY: the contract of `dec_len` guarantees that the elements in `tail` are
> > +                // valid elements whose ownership has been transferred to the caller.
> > +                unsafe { ptr::drop_in_place(ptr) };
>
> We have a mutable reference to these elements until after the
> `drop_in_place` call, but the elements are invalidated by that call.
> This means that we have a mutable reference to invalid values, which
> violates the invariants for mutable references.
>
> Consider converting to a raw pointer when creating `tail` instead to
> avoid that:
>
> let tail: *mut [T] = unsafe { self.dec_len(count) };
> unsafe { ptr::drop_in_place(ptr) };

👍
Re: [PATCH v2 3/4] rust: alloc: refactor `Vec::truncate` using `dec_len`
Posted by Tamir Duberstein 9 months ago
On Tue, Mar 18, 2025 at 4:14 PM Tamir Duberstein <tamird@gmail.com> wrote:
>
> Use `checked_sub` to satisfy the safety requirements of `dec_len` and
> replace nearly the whole body of `truncate` with a call to `dec_len`.
>
> Signed-off-by: Tamir Duberstein <tamird@gmail.com>
> ---
>  rust/kernel/alloc/kvec.rs | 29 +++++++++++------------------
>  1 file changed, 11 insertions(+), 18 deletions(-)
>
> diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
> index 97cc5ab11e2a..6f4dc89ef7f8 100644
> --- a/rust/kernel/alloc/kvec.rs
> +++ b/rust/kernel/alloc/kvec.rs
> @@ -489,25 +489,18 @@ pub fn reserve(&mut self, additional: usize, flags: Flags) -> Result<(), AllocEr
>      /// # Ok::<(), Error>(())
>      /// ```
>      pub fn truncate(&mut self, len: usize) {
> -        if len >= self.len() {
> -            return;
> +        match self.len().checked_sub(len) {
> +            None => {}
> +            Some(count) => {
> +                // SAFETY: `count` is `self.len() - len` so it is guaranteed to be less than or
> +                // equal to `self.len()`.
> +                let tail = unsafe { self.dec_len(count) };
> +
> +                // SAFETY: the contract of `dec_len` guarantees that the elements in `tail` are
> +                // valid elements whose ownership has been transferred to the caller.
> +                unsafe { ptr::drop_in_place(ptr) };

Whoops, this should be s/ptr/tail/. Will fix on respin if necessary.

> +            }
>          }
> -
> -        let drop_range = len..self.len();
> -
> -        // SAFETY: `drop_range` is a subrange of `[0, len)` by the bounds check above.
> -        let ptr: *mut [T] = unsafe { self.get_unchecked_mut(drop_range) };
> -
> -        // SAFETY:
> -        // - this will always shrink the vector because of the above bounds check
> -        // - [`new_len`, `self.len`) will be dropped through the call to `drop_in_place` below
> -        unsafe { self.set_len(len) };
> -
> -        // SAFETY:
> -        // - the dropped values are valid `T`s by the type invariant
> -        // - we are allowed to invalidate [`new_len`, `old_len`) because we just changed the
> -        //   len, therefore we have exclusive access to [`new_len`, `old_len`)
> -        unsafe { ptr::drop_in_place(ptr) };
>      }
>  }
>
>
> --
> 2.48.1
>