rust-for-linux.vger.kernel.org archive mirror
 help / color / mirror / Atom feed
* [PATCH] rust: Return Option from page_align and ensure no usize overflow
@ 2025-11-27 13:07 Brendan Shephard
  2025-11-27 13:42 ` Alexandre Courbot
                   ` (2 more replies)
  0 siblings, 3 replies; 14+ messages in thread
From: Brendan Shephard @ 2025-11-27 13:07 UTC (permalink / raw)
  To: dakr, acourbot, airlied, aliceryhl; +Cc: rust-for-linux

Changed page_align() to return Option<usize> which allows for validation
of the provided addr value. This ensures that any value that is provided
within one PAGE_SIZE of usize::MAX will not panic and instead page_align
will return None.

Callers of page_align() should raise a EINVAL when they receive None
from page_align().

Signed-off-by: Brendan Shephard <bshephar@bne-home.net>
---
 rust/kernel/page.rs | 13 ++++++-------
 1 file changed, 6 insertions(+), 7 deletions(-)

diff --git a/rust/kernel/page.rs b/rust/kernel/page.rs
index 432fc0297d4a..b78473b67003 100644
--- a/rust/kernel/page.rs
+++ b/rust/kernel/page.rs
@@ -26,13 +26,12 @@
 pub const PAGE_MASK: usize = !(PAGE_SIZE - 1);

 /// Round up the given number to the next multiple of [`PAGE_SIZE`].
-///
-/// It is incorrect to pass an address where the next multiple of [`PAGE_SIZE`] doesn't fit in a
-/// [`usize`].
-pub const fn page_align(addr: usize) -> usize {
-    // Parentheses around `PAGE_SIZE - 1` to avoid triggering overflow sanitizers in the wrong
-    // cases.
-    (addr + (PAGE_SIZE - 1)) & PAGE_MASK
+/// Return None in cases where the next multiple of [`PAGE_SIZE`] would overflow a [`usize`]
+pub const fn page_align(addr: usize) -> Option<usize> {
+    if let Some(sum) = addr.checked_add(PAGE_SIZE - 1) {
+        return Some(sum & PAGE_MASK);
+    }
+    None
 }

 /// Representation of a non-owning reference to a [`Page`].
--
2.51.1

^ permalink raw reply related	[flat|nested] 14+ messages in thread

end of thread, other threads:[~2025-11-28 13:35 UTC | newest]

Thread overview: 14+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-11-27 13:07 [PATCH] rust: Return Option from page_align and ensure no usize overflow Brendan Shephard
2025-11-27 13:42 ` Alexandre Courbot
2025-11-27 14:18   ` Brendan Shephard
2025-11-28  0:28     ` Alexandre Courbot
2025-11-28  2:12       ` Miguel Ojeda
2025-11-28  5:29         ` Brendan Shephard
2025-11-28  6:51           ` Alexandre Courbot
2025-11-28  9:09             ` Alice Ryhl
2025-11-28 13:34               ` Alexandre Courbot
2025-11-27 13:44 ` Daniel Almeida
2025-11-27 14:21   ` Brendan Shephard
2025-11-27 14:40 ` [PATCH v2] " Brendan Shephard
2025-11-27 16:24   ` Miguel Ojeda
2025-11-28  3:35     ` Brendan Shephard

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox;
as well as URLs for NNTP newsgroup(s).