[<prev] [next>] [thread-next>] [day] [month] [year] [list]
Message-ID: <CA+TpbOLLATyTRtNxVEJ9Dz6=YSZHAyYOrt20TR8AAEfP+qm1Qw@mail.gmail.com>
Date: Mon, 4 Aug 2025 01:10:12 +0800
From: Jinheng LI <ahengljh@...il.com>
To: ojeda@...nel.org, rust-for-linux@...r.kernel.org
Cc: linux-kernel@...r.kernel.org, alex.gaynor@...il.com, gary@...yguo.net,
bjorn3_gh@...tonmail.com, lossin@...nel.org, a.hindborg@...nel.org,
aliceryhl@...gle.com, tmgross@...ch.edu
Subject: [PATCH] rust: kernel: add missing safety comments
>From 5cba005b59a032fc80f818b393b7e4c36a460710 Mon Sep 17 00:00:00 2001
From: Jinheng Li <ahengljh@...il.com>
Date: Mon, 4 Aug 2025 00:56:11 +0800
Subject: [PATCH] rust: kernel: add missing safety comments
Add safety documentation for unsafe functions that were missing proper
SAFETY comments. This improves code maintainability and helps
developers understand the safety requirements.
- str.rs: Document safety requirements for as_str_unchecked()
- list.rs: Document safety requirements for remove() method
These functions had TODO markers for safety documentation that are
now properly filled in with clear explanations of the invariants
and caller responsibilities.
Signed-off-by: Jinheng Li <ahengljh@...il.com>
---
rust/kernel/list.rs | 5 ++++-
rust/kernel/str.rs | 5 ++++-
2 files changed, 8 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/list.rs b/rust/kernel/list.rs
index c391c30b80f8..b9dbb73a7ebe 100644
--- a/rust/kernel/list.rs
+++ b/rust/kernel/list.rs
@@ -456,7 +456,10 @@ pub fn pop_front(&mut self) -> Option<ListArc<T, ID>> {
///
/// `item` must not be in a different linked list (with the same id).
pub unsafe fn remove(&mut self, item: &T) -> Option<ListArc<T, ID>> {
- // SAFETY: TODO.
+ // SAFETY: The caller guarantees that `item` is not in a
different linked list with the
+ // same ID. Since we have a mutable reference to the list, we
have exclusive access to all
+ // items in this list. The `view_links` and `fields`
functions are safe to call on any
+ // item reference, and will return the location of the list
links for this item.
let mut item = unsafe { ListLinks::fields(T::view_links(item)) };
// SAFETY: The user provided a reference, and reference are
never dangling.
//
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index a927db8e079c..8fe9a15fc16e 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -349,7 +349,10 @@ pub fn to_str(&self) -> Result<&str,
core::str::Utf8Error> {
/// ```
#[inline]
pub unsafe fn as_str_unchecked(&self) -> &str {
- // SAFETY: TODO.
+ // SAFETY: The caller guarantees that this `CStr` contains
only valid UTF-8 bytes.
+ // Since `CStr` is guaranteed to contain no interior null
bytes (by its invariants),
+ // and we're excluding the trailing null byte via
`as_bytes()`, the resulting slice
+ // is valid for `from_utf8_unchecked`.
unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
}
--
2.39.5 (Apple Git-154)
Powered by blists - more mailing lists