Skip to contentSkip to conversation

rust: harden index manipulation using ownership

PATCH In review Alice Ryhl 3 participants 5 messages Sep 13, 2024 – Oct 1, 2024

Subsystems (2)
lore
Share & tools
lore

Alice Ryhl

author maintainer
#0 lore raw

PATCH 1/2 rust: harden index manipulation using ownership

Rust is very effective at preventing memory safety bugs such as use-after-free bugs. Can we also make it effective at preventing bugs that arise from using indices incorrectly? As it stands today, accessing an array out of bounds is caught and results in a kernel panic, but Rust will not stop you from doing it. Accessing an array at the wrong index is not caught at all. This patch explores ways to catch these kinds of indexing bugs.

The Android Binder driver has a component where it "translates" the contents of transactions sent using the driver, which involves complex and error-prone index manipulation. The C driver has had several bugs in this area. A few examples:

4df153652cc4 ("binder: fix UAF caused by offsets overwrite") bdc1c5fac982 ("binder: fix UAF caused by faulty buffer cleanup") 16981742717b ("binder: fix incorrect calculation for num_valid") a56587065094 ("binder: Set end of SG buffer area properly.")

Rust is not immune to these issues either. In fact, I've already encountered and fixed two bugs like this in Rust Binder. In both cases, the bugs could result in Allocation::cleanup_object calls on invalid data. Rust's safety guarantees prevented these bugs from affecting the integrity of kernel itself, but an attacker could use them to e.g. manipulate handles that are present in other processes and for example obtaining IApplicationThread handle belonging to another app from system_server, which in turn allows loading code into that app.

Ultimately, the root cause of all of these bugs is that there is some index in the destination buffer that gets written to twice.

The primary idea of this new Range API is to utilize Rust's ownership semantics to prevent reuse of indices. The idea is that you create one big Range for the entire range of indices, and then there are various methods to split it into smaller ranges. An example from Rust Binder, where several kinds of data are stored next to each other:

// Split the buffer size into sub-ranges.
let full_range = Range::new_area(len);
let (data_range, after_data) = full_range.split_within(aligned_data_size)?; let (offsets_range, after_offsets) = after_data.split_within(aligned_offsets_size)?; let (buffers_range, after_buffers) = after_offsets.split_within(aligned_buffers_size)?; let (secctx_range, after_secctx) = after_buffers.split_within(aligned_secctx_size)?; after_secctx.assert_empty()?;

The Range type is set up so that it cannot be copied or cloned, which means that any attempts to use a Range more than once will fail to compile. For example, if the line creating buffers_range accidentally tried to split after_data instead of after_offsets, then that would lead to this compilation error:

error[E0382]: use of moved value: after_data

    --> /usr/local/google/home/aliceryhl/rust-android-mainline/common/drivers/android/binder/thread.rs:1101:50
     |
1099 | let (data_range, after_data) = full_range.split_within(aligned_data_size)?;
     |                  ---------- move occurs because `after_data` has type `kernel::range::Range`, which does not implement the `Copy` trait
1100 | let (offsets_range, after_offsets) = after_data.split_within(aligned_offsets_size)?;
     |                                                 ---------------------------------- `after_data` moved due to this method call
1101 | let (buffers_range, after_buffers) = after_data.split_within(aligned_buffers_size)?;
     |                                      ^^^^^^^^^^ value used here after move
     |
note: `kernel::range::Range::split_within` takes ownership of the receiver `self`, which moves `after_data`
    --> /usr/local/google/home/aliceryhl/rust-android-mainline/common/rust/kernel/range.rs:108:29
     |

108 | pub fn split_within(mut self, length: usize) -> Result<(Range, Range), RangeError> {
| ^^^^

Basically, the error says that you tried to use the after_data range twice, which is not allowed because split_within destroys the object you call it on.

In Rust Binder, I am using the ranges to prevent reuse of indices in the *destination* buffer. To enforce that, all methods for writing to the destination buffer are modified to take a Range as an argument, consuming the range being written to. As ranges can only be split into smaller pieces, this enforces that you will never write to the same index twice.

Of course, the API is not completely bullet-proof. If you call Range::new_area twice, you'll get two overlapping ranges. But we don't need it to be completely impossible to misuse. It just needs to be really difficult to do so accidentally.

Binder has one case where it intentionally writes to the same location
twice: when sending file descriptors over Binder, the driver does not know what value the fd will have when transferring the data, so it will first write u32::MAX. Much later, it will overwrite it with the real fd. There is a duplicate_range_careful method for this case.

It is interesting to compare with the uaccess patchset [1]. The uaccess API takes a userspace pointer and length representing a range of bytes in userspace, and lets you read the range incrementally. The API design prevents reading the same address twice. This helps prevent time-of-check-to-time-of-use bugs where userspace modifies the data in between two reads, which can cause bugs if the driver assumes that the memory is unchanged.

In fact, both Rust Binder bugs mentioned earlier are caught by this part of the uaccess API, as both bugs eventually attempt to read past the end of the userspace region, triggering an error. Unfortunately, this happens too late, as the previously translated data has already been overwritten by the time the error is triggered.

This patchset is also simliar to Benno's untrusted data patchset [2], which explores a different way to write misuse-resistant APIs.

---
 rust/kernel/lib.rs   |   1 +
 rust/kernel/range.rs | 236 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 237 insertions(+)
 create mode 100644 rust/kernel/range.rs
rust/kernel/lib.rs +1 -0
index a7fefc4ae725..72a998cd02e0 100644
@@ -48,6 +48,7 @@
 pub mod page;
 pub mod prelude;
 pub mod print;
+pub mod range;
 pub mod rbtree;
 pub mod security;
 pub mod seq_file;
rust/kernel/range.rs new file +236 -0

236 lines not on this page · raw message

Signature · 1 line
2.46.0.662.g92d0881bb0-goog
author maintainer
#1 lore raw

RFC PATCH 2/2 rust_binder: use `Range` API when translating transactions

This RFC illustrates how my Range API can be used in Rust Binder. Please see the other patch in this series for more information.

View this change on the web: https://r.android.com/3267276

Change-Id I77b7ee3e734dc54975331620c49afe7713efc8a1
---
 drivers/android/binder/allocation.rs |  73 +++++----
 drivers/android/binder/error.rs      |   8 +
 drivers/android/binder/thread.rs     | 237 ++++++++++++++-------------
 3 files changed, 178 insertions(+), 140 deletions(-)
drivers/android/binder/allocation.rs +44 -29
index e552f3350f18..b8d6b27169e0 100644
@@ -3,12 +3,12 @@
 // Copyright (C) 2024 Google LLC.
 
 use core::mem::{size_of, size_of_val, MaybeUninit};
-use core::ops::Range;
 
 use kernel::{
     bindings,
     fs::file::{File, FileDescriptorReservation},
     prelude::*,
+    range::{Range, RangeFixedSize, UsedRange},
     sync::Arc,
     types::{ARef, AsBytes, FromBytes},
     uaccess::UserSliceReader,
@@ -25,7 +25,7 @@
 #[derive(Default)]
 pub(crate) struct AllocationInfo {
     /// Range within the allocation where we can find the offsets to the object descriptors.
-    pub(crate) offsets: Option<Range<usize>>,
+    pub(crate) offsets: Option<core::ops::Range<usize>>,
     /// The target node of the transaction this allocation is associated to.
     /// Not set for replies.
     pub(crate) target_node: Option<NodeRef>,
@@ -81,7 +81,17 @@ pub(crate) fn new(
         }
     }
 
-    fn size_check(&self, offset: usize, size: usize) -> Result {
+    fn size_check(&self, range: Range) -> Result<UsedRange> {
+        let range = range.use_range();
+        let overflow_fail = range.offset.checked_add(range.length).is_none();
+        let cmp_size_fail = range.offset.wrapping_add(range.length) > self.size;
+        if overflow_fail || cmp_size_fail {
+            return Err(EFAULT);
+        }
+        Ok(range)
+    }
+
+    fn size_check2(&self, offset: usize, size: usize) -> Result<()> {
         let overflow_fail = offset.checked_add(size).is_none();
         let cmp_size_fail = offset.wrapping_add(size) > self.size;
         if overflow_fail || cmp_size_fail {
@@ -90,37 +100,35 @@ fn size_check(&self, offset: usize, size: usize) -> Result {
         Ok(())
     }
 
-    pub(crate) fn copy_into(
-        &self,
-        reader: &mut UserSliceReader,
-        offset: usize,
-        size: usize,
-    ) -> Result {
-        self.size_check(offset, size)?;
+    pub(crate) fn copy_into(&self, reader: &mut UserSliceReader, range: Range) -> Result {
+        let range = self.size_check(range)?;
 
         // SAFETY: While this object exists, the range allocator will keep the range allocated, and
         // in turn, the pages will be marked as in use.
         unsafe {
-            self.process
-                .pages
-                .copy_from_user_slice(reader, self.offset + offset, size)
+            self.process.pages.copy_from_user_slice(
+                reader,
+                self.offset + range.offset,
+                range.length,
+            )
         }
     }
 
     pub(crate) fn read<T: FromBytes>(&self, offset: usize) -> Result<T> {
-        self.size_check(offset, size_of::<T>())?;
+        self.size_check2(offset, size_of::<T>())?;
 
         // SAFETY: While this object exists, the range allocator will keep the range allocated, and
         // in turn, the pages will be marked as in use.
         unsafe { self.process.pages.read(self.offset + offset) }
     }
 
-    pub(crate) fn write<T: ?Sized>(&self, offset: usize, obj: &T) -> Result {
-        self.size_check(offset, size_of_val::<T>(obj))?;
+    pub(crate) fn write<T: ?Sized>(&self, range: Range, obj: &T) -> Result {
+        range.assert_length_eq(size_of_val::<T>(obj))?;
+        let range = self.size_check(range)?;
 
         // SAFETY: While this object exists, the range allocator will keep the range allocated, and
         // in turn, the pages will be marked as in use.
-        unsafe { self.process.pages.write(self.offset + offset, obj) }
+        unsafe { self.process.pages.write(self.offset + range.offset, obj) }
     }
 
     pub(crate) fn fill_zero(&self) -> Result {
@@ -143,7 +151,7 @@ pub(crate) fn get_or_init_info(&mut self) -> &mut AllocationInfo {
         self.allocation_info.get_or_insert_with(Default::default)
     }
 
-    pub(crate) fn set_info_offsets(&mut self, offsets: Range<usize>) {
+    pub(crate) fn set_info_offsets(&mut self, offsets: core::ops::Range<usize>) {
         self.get_or_init_info().offsets = Some(offsets);
     }
 
@@ -172,13 +180,13 @@ pub(crate) fn info_add_fd_reserve(&mut self, num_fds: usize) -> Result {
     pub(crate) fn info_add_fd(
         &mut self,
         file: ARef<File>,
-        buffer_offset: usize,
+        range: Range,
         close_on_free: bool,
     ) -> Result {
         self.get_or_init_info().file_list.files_to_translate.push(
             FileEntry {
                 file,
-                buffer_offset,
+                range: RangeFixedSize::from_range(range)?,
                 close_on_free,
             },
             GFP_KERNEL,
@@ -206,8 +214,9 @@ pub(crate) fn translate_fds(&mut self) -> Result<TranslatedFds> {
         for file_info in files {
             let res = FileDescriptorReservation::get_unused_fd_flags(bindings::O_CLOEXEC)?;
             let fd = res.reserved_fd();
-            self.write::<u32>(file_info.buffer_offset, &fd)?;
-            crate::trace::trace_transaction_fd_recv(self.debug_id, fd, file_info.buffer_offset);
+            let range = file_info.range.into_range();
+            crate::trace::trace_transaction_fd_recv(self.debug_id, fd, range.peek_offset());
+            self.write::<u32>(range, &fd)?;
 
             reservations.push(
                 Reservation {
@@ -343,20 +352,26 @@ pub(crate) fn read<T: FromBytes>(&self, offset: usize) -> Result<T> {
         self.alloc.read(offset)
     }
 
-    pub(crate) fn write<T: AsBytes>(&self, offset: usize, obj: &T) -> Result {
-        if offset.checked_add(size_of::<T>()).ok_or(EINVAL)? > self.limit {
+    pub(crate) fn write<T: AsBytes>(&self, range: Range, obj: &T) -> Result {
+        range.assert_length_eq(size_of::<T>())?;
+        let end = range
+            .peek_offset()
+            .checked_add(size_of::<T>())
+            .ok_or(EINVAL)?;
+        if end > self.limit {
             return Err(EINVAL);
         }
-        self.alloc.write(offset, obj)
+        self.alloc.write(range, obj)
     }
 
     pub(crate) fn transfer_binder_object(
         &self,
-        offset: usize,
+        range: Range,
         obj: &bindings::flat_binder_object,
         strong: bool,
         node_ref: NodeRef,
     ) -> Result {
+        range.assert_length_eq(size_of::<FlatBinderObject>())?;
         let mut newobj = FlatBinderObject::default();
         let node = node_ref.node.clone();
         if Arc::ptr_eq(&node_ref.node.owner, &self.alloc.process) {
@@ -371,7 +386,7 @@ pub(crate) fn transfer_binder_object(
             newobj.flags = obj.flags;
             newobj.__bindgen_anon_1.binder = ptr as _;
             newobj.cookie = cookie as _;
-            self.write(offset, &newobj)?;
+            self.write(range, &newobj)?;
             // Increment the user ref count on the node. It will be decremented as part of the
             // destruction of the buffer, when we see a binder or weak-binder object.
             node.update_refcount(true, 1, strong);
@@ -390,7 +405,7 @@ pub(crate) fn transfer_binder_object(
             };
             newobj.flags = obj.flags;
             newobj.__bindgen_anon_1.handle = handle;
-            if self.write(offset, &newobj).is_err() {
+            if self.write(range, &newobj).is_err() {
                 // Decrement ref count on the handle we just created.
                 let _ = self
                     .alloc
@@ -561,7 +576,7 @@ struct FileEntry {
     /// The file for which a descriptor will be created in the recipient process.
     file: ARef<File>,
     /// The offset in the buffer where the file descriptor is stored.
-    buffer_offset: usize,
+    range: RangeFixedSize<4>,
     /// Whether this fd should be closed when the allocation is freed.
     close_on_free: bool,
 }
drivers/android/binder/error.rs +8 -0
index dfce0c6270ca..8267134ff74b 100644
@@ -67,6 +67,14 @@ fn from(source: kernel::fs::file::BadFdError) -> Self {
     }
 }
 
+impl From<kernel::range::RangeError> for BinderError {
+    #[track_caller]
+    fn from(source: kernel::range::RangeError) -> Self {
+        unsafe { kernel::bindings::dump_stack() };
+        BinderError::from(Error::from(source))
+    }
+}
+
 impl From<kernel::alloc::AllocError> for BinderError {
     fn from(_: kernel::alloc::AllocError) -> Self {
         Self {
drivers/android/binder/thread.rs +126 -111

454 lines not on this page · raw message

Signature · 1 line
2.46.0.662.g92d0881bb0-goog
#2 lore raw
In reply to Alice Ryhl
Quoted 88 lines · Alice Ryhl

Rust is very effective at preventing memory safety bugs such as use-after-free bugs. Can we also make it effective at preventing bugs that arise from using indices incorrectly? As it stands today, accessing an array out of bounds is caught and results in a kernel panic, but Rust will not stop you from doing it. Accessing an array at the wrong index is not caught at all. This patch explores ways to catch these kinds of indexing bugs.

The Android Binder driver has a component where it "translates" the contents of transactions sent using the driver, which involves complex and error-prone index manipulation. The C driver has had several bugs in this area. A few examples:

4df153652cc4 ("binder: fix UAF caused by offsets overwrite") bdc1c5fac982 ("binder: fix UAF caused by faulty buffer cleanup") 16981742717b ("binder: fix incorrect calculation for num_valid") a56587065094 ("binder: Set end of SG buffer area properly.")

Rust is not immune to these issues either. In fact, I've already encountered and fixed two bugs like this in Rust Binder. In both cases, the bugs could result in Allocation::cleanup_object calls on invalid data. Rust's safety guarantees prevented these bugs from affecting the integrity of kernel itself, but an attacker could use them to e.g. manipulate handles that are present in other processes and for example obtaining IApplicationThread handle belonging to another app from system_server, which in turn allows loading code into that app.

Ultimately, the root cause of all of these bugs is that there is some index in the destination buffer that gets written to twice.

The primary idea of this new Range API is to utilize Rust's ownership semantics to prevent reuse of indices. The idea is that you create one big Range for the entire range of indices, and then there are various methods to split it into smaller ranges. An example from Rust Binder, where several kinds of data are stored next to each other:

// Split the buffer size into sub-ranges.
let full_range = Range::new_area(len);
let (data_range, after_data) = full_range.split_within(aligned_data_size)?; let (offsets_range, after_offsets) = after_data.split_within(aligned_offsets_size)?; let (buffers_range, after_buffers) = after_offsets.split_within(aligned_buffers_size)?; let (secctx_range, after_secctx) = after_buffers.split_within(aligned_secctx_size)?; after_secctx.assert_empty()?;

The Range type is set up so that it cannot be copied or cloned, which means that any attempts to use a Range more than once will fail to compile. For example, if the line creating buffers_range accidentally tried to split after_data instead of after_offsets, then that would lead to this compilation error:

error[E0382]: use of moved value: after_data

    --> /usr/local/google/home/aliceryhl/rust-android-mainline/common/drivers/android/binder/thread.rs:1101:50
     |
1099 | let (data_range, after_data) = full_range.split_within(aligned_data_size)?;
     |                  ---------- move occurs because `after_data` has type `kernel::range::Range`, which does not implement the `Copy` trait
1100 | let (offsets_range, after_offsets) = after_data.split_within(aligned_offsets_size)?;
     |                                                 ---------------------------------- `after_data` moved due to this method call
1101 | let (buffers_range, after_buffers) = after_data.split_within(aligned_buffers_size)?;
     |                                      ^^^^^^^^^^ value used here after move
     |
note: `kernel::range::Range::split_within` takes ownership of the receiver `self`, which moves `after_data`
    --> /usr/local/google/home/aliceryhl/rust-android-mainline/common/rust/kernel/range.rs:108:29
     |

108 | pub fn split_within(mut self, length: usize) -> Result<(Range, Range), RangeError> {
| ^^^^

Basically, the error says that you tried to use the after_data range twice, which is not allowed because split_within destroys the object you call it on.

In Rust Binder, I am using the ranges to prevent reuse of indices in the *destination* buffer. To enforce that, all methods for writing to the destination buffer are modified to take a Range as an argument, consuming the range being written to. As ranges can only be split into smaller pieces, this enforces that you will never write to the same index twice.

Of course, the API is not completely bullet-proof. If you call Range::new_area twice, you'll get two overlapping ranges. But we don't need it to be completely impossible to misuse. It just needs to be really difficult to do so accidentally.

Binder has one case where it intentionally writes to the same location
twice: when sending file descriptors over Binder, the driver does not know what value the fd will have when transferring the data, so it will first write u32::MAX. Much later, it will overwrite it with the real fd. There is a duplicate_range_careful method for this case.

Quoted 7 lines

It is interesting to compare with the uaccess patchset [1]. The uaccess API takes a userspace pointer and length representing a range of bytes in userspace, and lets you read the range incrementally. The API design prevents reading the same address twice. This helps prevent time-of-check-to-time-of-use bugs where userspace modifies the data in between two reads, which can cause bugs if the driver assumes that the memory is unchanged.

I don't really see an overlap between Range and UserSlice. The former is about managing a range of indexes, the other about incremental reading/writing to userspace without screwing up. I think we want both, since often you get the things you need to carefuly slice/dice with Range from somewhere else, e.g. from pagecache or the fw loader.

Also where performance doesn't matter so much often the copy_from_user is one step and then we parse some complex data structure in there where Range should be useful.

Quoted 8 lines

In fact, both Rust Binder bugs mentioned earlier are caught by this part of the uaccess API, as both bugs eventually attempt to read past the end of the userspace region, triggering an error. Unfortunately, this happens too late, as the previously translated data has already been overwritten by the time the error is triggered.

This patchset is also simliar to Benno's untrusted data patchset [2], which explores a different way to write misuse-resistant APIs.

I think you want both: Range to slice up a block of memory into variable length structure, Untrusted to safely parse each part.

Quoted 4 lines

I didn't take a close look at the api since real feedback would mean I need to type up a user, but this looks great and I want :-) -Sima

Quoted 263 lines
---
 rust/kernel/lib.rs   |   1 +
 rust/kernel/range.rs | 236 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 237 insertions(+)
 create mode 100644 rust/kernel/range.rs
rust/kernel/lib.rs +1 -0
index a7fefc4ae725..72a998cd02e0 100644
@@ -48,6 +48,7 @@
 pub mod page;
 pub mod prelude;
 pub mod print;
+pub mod range;
 pub mod rbtree;
 pub mod security;
 pub mod seq_file;
rust/kernel/range.rs new file +236 -0
new file mode 100644
index 000000000000..8fb9d96ac724
@@ -0,0 +1,236 @@
+// SPDX-License-Identifier: GPL-2.0
+
+// Copyright (C) 2024 Google LLC.
+
+//! Utilities for working with ranges of indices.
+
+/// A range of indices.
+///
+/// This utility is useful for ensuring that no index in the range is used more than once.
+#[derive(Debug)]
+pub struct Range {
+    offset: usize,
+    length: usize,
+}
+
+impl Range {
+    /// Creates a new `Range` for an area of the given size.
+    pub fn new_area(size: usize) -> Self {
+        Self {
+            offset: 0,
+            length: size,
+        }
+    }
+
+    /// Use this range of indices.
+    ///
+    /// This destroys the `Range` object, so these indices cannot be used again after this call.
+    pub fn use_range(self) -> UsedRange {
+        UsedRange {
+            offset: self.offset,
+            length: self.length,
+        }
+    }
+
+    /// Duplicate this range.
+    ///
+    /// Be careful when using this method, as it allows you to use a range twice.
+    pub fn duplicate_range_careful(&self) -> Range {
+        Range {
+            offset: self.offset,
+            length: self.length,
+        }
+    }
+
+    /// Peek at the offset without using the range.
+    ///
+    /// This doesn't destroy the `Range` object, so be careful that the range is not used twice.
+    pub fn peek_offset(&self) -> usize {
+        self.offset
+    }
+
+    /// Peek at the length without using the range.
+    ///
+    /// This doesn't destroy the `Range` object, so be careful that the range is not used twice.
+    pub fn peek_length(&self) -> usize {
+        self.length
+    }
+
+    /// Peek at the end without using the range.
+    ///
+    /// This doesn't destroy the `Range` object, so be careful that the range is not used twice.
+    pub fn peek_end(&self) -> Result<usize, RangeError> {
+        self.offset.checked_add(self.length).ok_or(RangeError)
+    }
+
+    /// Truncates this range to the given length.
+    pub fn truncate(&mut self, length: usize) -> Result<(), RangeError> {
+        if length > self.length {
+            return Err(RangeError);
+        }
+        self.length = length;
+        Ok(())
+    }
+
+    /// Assert that this range is aligned properly.
+    pub fn assert_aligned(&self, alignment: usize) -> Result<(), RangeError> {
+        if self.offset % alignment == 0 {
+            Ok(())
+        } else {
+            Err(RangeError)
+        }
+    }
+
+    /// Assert that this range has the expected length.
+    pub fn assert_length_eq(&self, length: usize) -> Result<(), RangeError> {
+        if self.length == length {
+            Ok(())
+        } else {
+            Err(RangeError)
+        }
+    }
+
+    /// Assert that this range is empty.
+    pub fn assert_empty(self) -> Result<(), RangeError> {
+        self.assert_length_eq(0)
+    }
+
+    /// Splits the range into two sub-ranges.
+    ///
+    /// Fails if the `length` is greater than the range being split.
+    pub fn split_within(mut self, length: usize) -> Result<(Range, Range), RangeError> {
+        let left = self.take_from_start(length)?;
+        Ok((left, self))
+    }
+
+    /// Splits the range into two sub-ranges.
+    ///
+    /// Fails if the `position` is not within the current range.
+    pub fn split_at(mut self, position: usize) -> Result<(Range, Range), RangeError> {
+        let left = self.take_until(position)?;
+        Ok((left, self))
+    }
+
+    /// Modify this range by taking the first `length` bytes.
+    pub fn take_until(&mut self, position: usize) -> Result<Range, RangeError> {
+        let from_start = Range {
+            offset: self.offset,
+            length: position.checked_sub(self.offset).ok_or(RangeError)?,
+        };
+
+        let new_self = Range {
+            offset: position,
+            length: self
+                .length
+                .checked_sub(from_start.length)
+                .ok_or(RangeError)?,
+        };
+
+        *self = new_self;
+
+        Ok(from_start)
+    }
+
+    /// Modify this range by taking the first `length` bytes.
+    pub fn take_from_start(&mut self, length: usize) -> Result<Range, RangeError> {
+        let from_start = Range {
+            offset: self.offset,
+            length: length,
+        };
+
+        let new_self = Range {
+            offset: self.offset.checked_add(length).ok_or(RangeError)?,
+            length: self.length.checked_sub(length).ok_or(RangeError)?,
+        };
+
+        *self = new_self;
+
+        Ok(from_start)
+    }
+
+    /// Split this range into sub-ranges of the given size.
+    pub fn iter_chunks(self, chunk_size: usize) -> Result<ChunkIter, RangeError> {
+        if self.length % chunk_size != 0 {
+            return Err(RangeError);
+        }
+
+        Ok(ChunkIter {
+            pos: self.offset,
+            end: self.offset.checked_add(self.length).ok_or(RangeError)?,
+            chunk_size,
+        })
+    }
+}
+
+/// An iterator over ranges of the same size.
+pub struct ChunkIter {
+    pos: usize,
+    end: usize,
+    chunk_size: usize,
+}
+
+impl Iterator for ChunkIter {
+    type Item = Range;
+    fn next(&mut self) -> Option<Range> {
+        if self.pos >= self.end {
+            return None;
+        }
+
+        let range = Range {
+            offset: self.pos,
+            length: self.chunk_size,
+        };
+        self.pos = self.pos + self.chunk_size;
+
+        Some(range)
+    }
+}
+
+/// A version of [`Range`] where the length is a compile-time constant.
+///
+/// This can be used to store a `Range` without using up space to store the length.
+pub struct RangeFixedSize<const LENGTH: usize> {
+    offset: usize,
+}
+
+impl<const LENGTH: usize> RangeFixedSize<LENGTH> {
+    /// Create a `RangeFixedSize` from a `Range`.
+    pub fn from_range(range: Range) -> Result<Self, RangeError> {
+        if range.length == LENGTH {
+            Ok(Self {
+                offset: range.offset,
+            })
+        } else {
+            Err(RangeError)
+        }
+    }
+
+    /// Convert this back into a `Range`.
+    pub fn into_range(self) -> Range {
+        Range {
+            offset: self.offset,
+            length: LENGTH,
+        }
+    }
+}
+
+/// The return value of [`Range::use_range`].
+///
+/// The only way to access the indices in a range is to mark it "used", which converts it into this
+/// type, destroying the original [`Range`] object.
+#[derive(Copy, Clone)]
+pub struct UsedRange {
+    /// The offset of this range.
+    pub offset: usize,
+    /// The length of this range.
+    pub length: usize,
+}
+
+/// The error type returned when ranges are used incorrectly.
+pub struct RangeError;
+
+impl From<RangeError> for crate::error::Error {
+    fn from(_range: RangeError) -> crate::error::Error {
+        crate::error::code::EINVAL
+    }
+}
Signature · 1 line
2.46.0.662.g92d0881bb0-goog
Signature · 3 lines
Simona Vetter
Software Engineer, Intel Corporation
http://blog.ffwll.ch
reviewer
#3 lore raw
In reply to Alice Ryhl

rust/kernel/range.rs line 14

Quoted 10 lines · Alice Ryhl
rust/kernel/range.rs new file +10 -0
+//! Utilities for working with ranges of indices.
+
+/// A range of indices.
+///
+/// This utility is useful for ensuring that no index in the range is used more than once.
+#[derive(Debug)]
+pub struct Range {
+    offset: usize,
+    length: usize,
+}

Would a name like "DataRange" or "CheckedRange" be better here, to avoid confusion with core::ops::Range?

rust/kernel/range.rs line 28

Quoted 4 lines
rust/kernel/range.rs new file +4 -0
+    /// Use this range of indices.
+    ///
+    /// This destroys the `Range` object, so these indices cannot be used again after this call.
+    pub fn use_range(self) -> UsedRange {

Maybe just .use()?

rust/kernel/range.rs line 76

Quoted 2 lines
rust/kernel/range.rs new file +2 -0
+    /// Assert that this range is aligned properly.
+    pub fn assert_aligned(&self, alignment: usize) -> Result<(), RangeError> {

It would probably be good to warn that this alignment is relative to the offset, i.e. if you split a range at an unaligned point then this may not be useful.

This is a pretty cool API idea.

- Trevor

author maintainer
#4 lore raw
Quoted 16 lines · Trevor Gross

rust/kernel/range.rs line 14

Quoted 10 lines · Alice Ryhl
rust/kernel/range.rs new file +10 -0
+//! Utilities for working with ranges of indices.
+
+/// A range of indices.
+///
+/// This utility is useful for ensuring that no index in the range is used more than once.
+#[derive(Debug)]
+pub struct Range {
+    offset: usize,
+    length: usize,
+}

Would a name like "DataRange" or "CheckedRange" be better here, to avoid confusion with core::ops::Range?

Probably a good idea. I've had collisions on those types.

Quoted 6 lines

rust/kernel/range.rs line 28

Quoted 4 lines
rust/kernel/range.rs new file +4 -0
+    /// Use this range of indices.
+    ///
+    /// This destroys the `Range` object, so these indices cannot be used again after this call.
+    pub fn use_range(self) -> UsedRange {

Maybe just .use()?

Makes sense to me.

Quoted 8 lines

rust/kernel/range.rs line 76

Quoted 2 lines
rust/kernel/range.rs new file +2 -0
+    /// Assert that this range is aligned properly.
+    pub fn assert_aligned(&self, alignment: usize) -> Result<(), RangeError> {

It would probably be good to warn that this alignment is relative to the offset, i.e. if you split a range at an unaligned point then this may not be useful.

This is a pretty cool API idea.

Thanks!

Alice