Rust for Linux List
 help / color / mirror / Atom feed
* [PATCH v3 0/4] rust: Add safe pointer formatting support
@ 2025-12-24  8:13 Ke Sun
  2025-12-24  8:13 ` [PATCH v3 1/4] lib/vsprintf: Export ptr_to_hashval for Rust use Ke Sun
                   ` (3 more replies)
  0 siblings, 4 replies; 9+ messages in thread
From: Ke Sun @ 2025-12-24  8:13 UTC (permalink / raw)
  To: Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Tamir Duberstein, rust-for-linux,
	Ke Sun

This patch series adds safe pointer formatting support for Rust kernel code,
providing three pointer wrapper types (HashedPtr, RestrictedPtr, RawPtr) that
correspond to C kernel's printk format specifiers %p, %pK, and %px.

The implementation ensures that raw pointers are automatically hashed when
formatted with {:p}, providing safe default behavior that prevents information
leaks about kernel memory layout. Users can also explicitly use wrapper types
when they need specific formatting behavior.

Changes in this series:

1. Export ptr_to_hashval() from lib/vsprintf.c to allow Rust code to hash
   pointers for safe printing.

2. Add three pointer wrapper types in rust/kernel/ptr.rs:
   - HashedPtr: Hashes pointers before printing (corresponds to %p)
   - RestrictedPtr: Respects kptr_restrict sysctl (corresponds to %pK)
   - RawPtr: Prints raw address for debugging (corresponds to %px)

3. Make raw pointers automatically use HashedPtr when formatted with {:p},
   providing safe default behavior while still allowing explicit use of
   wrapper types when needed.

4. Add documentation explaining the pointer wrapper types and their usage.

---
v2: https://lore.kernel.org/rust-for-linux/20251223033018.2814732-1-sunke@kylinos.cn/
- Disabled {:p} raw pointer printing by default to prevent accidental
  information leaks

v1: https://lore.kernel.org/rust-for-linux/20251218032709.2184890-1-sunke@kylinos.cn/
- Initial implementation that directly printed raw pointers
---

Ke Sun (4):
  lib/vsprintf: Export ptr_to_hashval for Rust use
  rust: kernel: Add pointer wrapper types for safe pointer formatting
  rust: fmt: Default raw pointer formatting to HashedPtr
  docs: rust: Add pointer formatting documentation

 Documentation/rust/index.rst              |   1 +
 Documentation/rust/pointer-formatting.rst |  67 ++++++++
 lib/vsprintf.c                            |   1 +
 rust/helpers/fmt.c                        |  61 +++++++
 rust/helpers/helpers.c                    |   3 +-
 rust/kernel/fmt.rs                        |  60 ++++++-
 rust/kernel/ptr.rs                        | 186 ++++++++++++++++++++++
 7 files changed, 377 insertions(+), 2 deletions(-)
 create mode 100644 Documentation/rust/pointer-formatting.rst
 create mode 100644 rust/helpers/fmt.c

base-commit: 9448598b22c50c8a5bb77a9103e2d49f134c9578
-- 
2.43.0

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

* [PATCH v3 1/4] lib/vsprintf: Export ptr_to_hashval for Rust use
  2025-12-24  8:13 [PATCH v3 0/4] rust: Add safe pointer formatting support Ke Sun
@ 2025-12-24  8:13 ` Ke Sun
  2025-12-24  8:13 ` [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting Ke Sun
                   ` (2 subsequent siblings)
  3 siblings, 0 replies; 9+ messages in thread
From: Ke Sun @ 2025-12-24  8:13 UTC (permalink / raw)
  To: Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Tamir Duberstein, rust-for-linux,
	Ke Sun

Export ptr_to_hashval() with EXPORT_SYMBOL_GPL to allow Rust code
to call this function for pointer hashing, which is needed for the
HashedPtr and RestrictedPtr wrapper types in rust/kernel/ptr.rs.

This function is used to hash kernel pointers before printing them,
preventing information leaks about kernel memory layout.

Signed-off-by: Ke Sun <sunke@kylinos.cn>
---
 lib/vsprintf.c | 1 +
 1 file changed, 1 insertion(+)

diff --git a/lib/vsprintf.c b/lib/vsprintf.c
index a3790c43a0aba..d1c682afd792c 100644
--- a/lib/vsprintf.c
+++ b/lib/vsprintf.c
@@ -811,6 +811,7 @@ int ptr_to_hashval(const void *ptr, unsigned long *hashval_out)
 {
 	return __ptr_to_hashval(ptr, hashval_out);
 }
+EXPORT_SYMBOL_GPL(ptr_to_hashval);
 
 static char *ptr_to_id(char *buf, char *end, const void *ptr,
 		       struct printf_spec spec)
-- 
2.43.0


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

* [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting
  2025-12-24  8:13 [PATCH v3 0/4] rust: Add safe pointer formatting support Ke Sun
  2025-12-24  8:13 ` [PATCH v3 1/4] lib/vsprintf: Export ptr_to_hashval for Rust use Ke Sun
@ 2025-12-24  8:13 ` Ke Sun
  2025-12-25  9:19   ` Dirk Behme
  2025-12-25 15:22   ` kernel test robot
  2025-12-24  8:13 ` [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr Ke Sun
  2025-12-24  8:13 ` [PATCH v3 4/4] docs: rust: Add pointer formatting documentation Ke Sun
  3 siblings, 2 replies; 9+ messages in thread
From: Ke Sun @ 2025-12-24  8:13 UTC (permalink / raw)
  To: Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Tamir Duberstein, rust-for-linux,
	Ke Sun

Add three pointer wrapper types (HashedPtr, RestrictedPtr, RawPtr) to
rust/kernel/ptr.rs that correspond to C kernel's printk format specifiers
%p, %pK, and %px. These types provide type-safe pointer formatting that
matches C kernel patterns.

These wrapper types implement core::fmt::Pointer and delegate to the
corresponding kernel formatting functions, enabling safe pointer
formatting in Rust code that prevents information leaks about kernel
memory layout.

Users can explicitly use these types:
    pr_info!("{:p}\n", HashedPtr::from(ptr));
    seq_print!(seq_file, "{:p}\n", RestrictedPtr::from(ptr));
    pr_info!("{:p}\n", RawPtr::from(ptr));

Changes:
- Add HashedPtr for %p (hashed, default behavior)
- Add RestrictedPtr for %pK (restricted, respects kptr_restrict)
- Add RawPtr for %px (raw address, debug only)
- Add helper function kptr_restrict_value() in rust/helpers/fmt.c
- Add impl_ptr_wrapper! macro to reduce code duplication

Signed-off-by: Ke Sun <sunke@kylinos.cn>
---
 rust/helpers/fmt.c     |  61 ++++++++++++++
 rust/helpers/helpers.c |   3 +-
 rust/kernel/ptr.rs     | 186 +++++++++++++++++++++++++++++++++++++++++
 3 files changed, 249 insertions(+), 1 deletion(-)
 create mode 100644 rust/helpers/fmt.c

diff --git a/rust/helpers/fmt.c b/rust/helpers/fmt.c
new file mode 100644
index 0000000000000..9c8991cb8726d
--- /dev/null
+++ b/rust/helpers/fmt.c
@@ -0,0 +1,61 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <linux/kernel.h>
+#include <linux/cred.h>
+#include <linux/capability.h>
+#include <linux/hardirq.h>
+#include <linux/printk.h>
+
+/*
+ * Helper function for Rust to format a restricted pointer (%pK).
+ *
+ * This function determines what pointer value should be printed based on the
+ * kptr_restrict sysctl setting:
+ *
+ * - kptr_restrict == 0: Returns the original pointer (will be hashed by caller)
+ * - kptr_restrict == 1: Returns the original pointer if the current process has
+ *                       CAP_SYSLOG and same euid/egid, NULL otherwise
+ * - kptr_restrict >= 2: Always returns NULL
+ *
+ * Returns:
+ *   - The original pointer if it should be printed (case 0 or case 1 with permission)
+ *   - NULL if it should not be printed (no permission, IRQ context, or restrict >= 2)
+ */
+const void *rust_helper_kptr_restrict_value(const void *ptr)
+{
+	switch (kptr_restrict) {
+	case 0:
+		/* Handle as %p - return original pointer for hashing */
+		return ptr;
+	case 1: {
+		const struct cred *cred;
+
+		/*
+		 * kptr_restrict==1 cannot be used in IRQ context because the
+		 * capability check would be meaningless (no process context).
+		 */
+		if (in_hardirq() || in_serving_softirq() || in_nmi())
+			return NULL;
+
+		/*
+		 * Only return the real pointer value if the current process has
+		 * CAP_SYSLOG and is running with the same credentials it started with.
+		 * This prevents privilege escalation attacks where a process opens a
+		 * file with %pK, then elevates privileges before reading it.
+		 */
+		cred = current_cred();
+		if (!has_capability_noaudit(current, CAP_SYSLOG) ||
+		    !uid_eq(cred->euid, cred->uid) ||
+		    !gid_eq(cred->egid, cred->gid))
+			return NULL;
+		break;
+	}
+	case 2:
+	default:
+		/* Always hide pointer values when kptr_restrict >= 2 */
+		return NULL;
+	}
+
+	return ptr;
+}
+
diff --git a/rust/helpers/helpers.c b/rust/helpers/helpers.c
index 79c72762ad9c4..b6877fe8dafc0 100644
--- a/rust/helpers/helpers.c
+++ b/rust/helpers/helpers.c
@@ -27,8 +27,9 @@
 #include "dma.c"
 #include "drm.c"
 #include "err.c"
-#include "irq.c"
+#include "fmt.c"
 #include "fs.c"
+#include "irq.c"
 #include "io.c"
 #include "jump_label.c"
 #include "kunit.c"
diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs
index e3893ed04049d..deb4d72bcecca 100644
--- a/rust/kernel/ptr.rs
+++ b/rust/kernel/ptr.rs
@@ -1,11 +1,17 @@
 // SPDX-License-Identifier: GPL-2.0
 
 //! Types and functions to work with pointers and addresses.
+//!
+//! This module provides wrapper types for formatting kernel pointers that correspond to the
+//! C kernel's printk format specifiers `%p`, `%pK`, and `%px`.
 
+use core::fmt;
 use core::mem::align_of;
 use core::num::NonZero;
 
+use crate::bindings;
 use crate::build_assert;
+use crate::ffi::c_void;
 
 /// Type representing an alignment, which is always a power of two.
 ///
@@ -225,3 +231,183 @@ fn align_up(self, alignment: Alignment) -> Option<Self> {
 }
 
 impl_alignable_uint!(u8, u16, u32, u64, usize);
+
+/// Placeholder string used when pointer hashing is not ready yet.
+const PTR_PLACEHOLDER: &str = if core::mem::size_of::<*const c_void>() == 8 {
+    "(____ptrval____)"
+} else {
+    "(ptrval)"
+};
+
+/// Macro to implement common methods for pointer wrapper types.
+macro_rules! impl_ptr_wrapper {
+    ($($name:ident),* $(,)?) => {
+        $(
+            impl $name {
+                /// Creates a new instance from a raw pointer.
+                #[inline]
+                pub fn from<T>(ptr: *const T) -> Self {
+                    Self(ptr.cast())
+                }
+
+                /// Creates a new instance from a mutable raw pointer.
+                #[inline]
+                pub fn from_mut<T>(ptr: *mut T) -> Self {
+                    Self(ptr.cast())
+                }
+
+                /// Returns the inner raw pointer.
+                #[inline]
+                pub fn as_ptr(&self) -> *const c_void {
+                    self.0
+                }
+            }
+
+            impl<T> From<*const T> for $name {
+                #[inline]
+                fn from(ptr: *const T) -> Self {
+                    Self::from(ptr)
+                }
+            }
+
+            impl<T> From<*mut T> for $name {
+                #[inline]
+                fn from(ptr: *mut T) -> Self {
+                    Self::from_mut(ptr)
+                }
+            }
+        )*
+    };
+}
+
+/// Helper function to hash a pointer and format it.
+///
+/// Returns `Ok(())` if the hash was successfully computed and formatted,
+/// or the placeholder string if hashing is not ready yet.
+fn format_hashed_ptr(ptr: *const c_void, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+    // SAFETY: We're calling the kernel's ptr_to_hashval function which handles
+    // hashing. This is safe as long as ptr is a valid pointer value.
+    unsafe {
+        let mut hashval: crate::ffi::c_ulong = 0;
+        let ret = bindings::ptr_to_hashval(ptr, core::ptr::addr_of_mut!(hashval));
+
+        if ret == 0 {
+            // Successfully got hash value, format it
+            write!(f, "{:p}", hashval as *const c_void)
+        } else {
+            // Hash not ready yet, print placeholder
+            f.write_str(PTR_PLACEHOLDER)
+        }
+    }
+}
+
+/// A pointer that will be hashed when printed (corresponds to `%p`).
+///
+/// This is the default behavior for kernel pointers - they are hashed to prevent
+/// leaking information about the kernel memory layout.
+///
+/// # Example
+///
+/// ```
+/// use kernel::ptr::HashedPtr;
+///
+/// let ptr = HashedPtr::from(0x12345678 as *const u8);
+/// pr_info!("Pointer: {:p}\n", ptr);
+/// ```
+#[repr(transparent)]
+#[derive(Copy, Clone, Debug)]
+pub struct HashedPtr(*const c_void);
+
+impl fmt::Pointer for HashedPtr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        let ptr = self.0;
+
+        // Handle NULL pointers - print them directly
+        if ptr.is_null() {
+            return write!(f, "{:p}", ptr);
+        }
+
+        format_hashed_ptr(ptr, f)
+    }
+}
+
+/// A pointer that will be restricted based on `kptr_restrict` when printed (corresponds to `%pK`).
+///
+/// This is intended for use in procfs/sysfs files that are read by userspace.
+/// The behavior depends on the `kptr_restrict` sysctl setting.
+///
+/// # Example
+///
+/// ```
+/// use kernel::ptr::RestrictedPtr;
+///
+/// let ptr = RestrictedPtr::from(0x12345678 as *const u8);
+/// seq_print!(seq_file, "Pointer: {:p}\n", ptr);
+/// ```
+#[repr(transparent)]
+#[derive(Copy, Clone, Debug)]
+pub struct RestrictedPtr(*const c_void);
+
+impl fmt::Pointer for RestrictedPtr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        let ptr = self.0;
+
+        // Handle NULL pointers
+        if ptr.is_null() {
+            return write!(f, "{:p}", ptr);
+        }
+
+        // Use kptr_restrict_value to handle all kptr_restrict cases.
+        // SAFETY: kptr_restrict_value handles capability checks and IRQ context.
+        // - Returns NULL if no permission, IRQ context, or kptr_restrict >= 2
+        // - Returns the original pointer if kptr_restrict == 0 (needs hashing)
+        // - Returns the original pointer if kptr_restrict == 1 with permission (print raw)
+        let restricted_ptr = unsafe { bindings::kptr_restrict_value(ptr) };
+
+        if restricted_ptr.is_null() {
+            // No permission, IRQ context, or kptr_restrict >= 2 - print 0
+            write!(f, "{:p}", core::ptr::null::<c_void>())
+        } else {
+            // restricted_ptr is non-null, meaning we should print something.
+            // SAFETY: Reading kptr_restrict is safe as it's a kernel variable.
+            let restrict = unsafe { bindings::kptr_restrict };
+
+            if restrict == 0 {
+                // kptr_restrict == 0: hash the pointer (same as %p)
+                format_hashed_ptr(ptr, f)
+            } else {
+                // kptr_restrict == 1 with permission: print the raw pointer directly (like %px)
+                // This matches C behavior: pointer_string() prints the raw address
+                write!(f, "{:p}", restricted_ptr)
+            }
+        }
+    }
+}
+
+/// A pointer that will be printed as its raw address (corresponds to `%px`).
+///
+/// **Warning**: This exposes the real kernel address and should only be used
+/// for debugging purposes. Consider using [`HashedPtr`] or [`RestrictedPtr`] instead.
+///
+/// # Example
+///
+/// ```
+/// use kernel::ptr::RawPtr;
+///
+/// let ptr = RawPtr::from(0x12345678 as *const u8);
+/// pr_info!("Debug pointer: {:p}\n", ptr);
+/// ```
+#[repr(transparent)]
+#[derive(Copy, Clone, Debug)]
+pub struct RawPtr(*const c_void);
+
+impl fmt::Pointer for RawPtr {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        // Directly format the raw address - no hashing or restriction
+        // This corresponds to %px behavior
+        write!(f, "{:p}", self.0)
+    }
+}
+
+// Implement common methods for all pointer wrapper types
+impl_ptr_wrapper!(HashedPtr, RestrictedPtr, RawPtr);
-- 
2.43.0


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

* [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr
  2025-12-24  8:13 [PATCH v3 0/4] rust: Add safe pointer formatting support Ke Sun
  2025-12-24  8:13 ` [PATCH v3 1/4] lib/vsprintf: Export ptr_to_hashval for Rust use Ke Sun
  2025-12-24  8:13 ` [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting Ke Sun
@ 2025-12-24  8:13 ` Ke Sun
  2025-12-24 20:58   ` kernel test robot
  2025-12-24  8:13 ` [PATCH v3 4/4] docs: rust: Add pointer formatting documentation Ke Sun
  3 siblings, 1 reply; 9+ messages in thread
From: Ke Sun @ 2025-12-24  8:13 UTC (permalink / raw)
  To: Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Tamir Duberstein, rust-for-linux,
	Ke Sun

Make raw pointers (*const T, *mut T) automatically use HashedPtr when
formatted with {:p}, providing safe default behavior for kernel pointers.

This allows users to format raw pointers directly:
    pr_info!("{:p}\n", ptr);  // Automatically hashed

While still allowing explicit use of wrapper types when needed:
    pr_info!("{:p}\n", RestrictedPtr::from(ptr));
    pr_info!("{:p}\n", RawPtr::from(ptr));

Changes:
- Remove Pointer from impl_fmt_adapter_forward! macro
- Add explicit Pointer implementations for Adapter<*const T> and
  Adapter<*mut T> that default to HashedPtr
- Add Pointer implementations for references to raw pointers
- Add impl_pointer_adapter_forward! macro to forward Pointer trait
  for wrapper types (HashedPtr, RestrictedPtr, RawPtr)

Signed-off-by: Ke Sun <sunke@kylinos.cn>
---
 rust/kernel/fmt.rs | 60 +++++++++++++++++++++++++++++++++++++++++++++-
 1 file changed, 59 insertions(+), 1 deletion(-)

diff --git a/rust/kernel/fmt.rs b/rust/kernel/fmt.rs
index 84d634201d90a..66493682bc7ca 100644
--- a/rust/kernel/fmt.rs
+++ b/rust/kernel/fmt.rs
@@ -28,7 +28,65 @@ fn fmt(&self, f: &mut Formatter<'_>) -> Result {
 }
 
 use core::fmt::{Binary, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex};
-impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, Pointer, LowerExp, UpperExp);
+impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, LowerExp, UpperExp);
+
+use crate::ptr::{HashedPtr, RestrictedPtr, RawPtr};
+// Special handling for Pointer: default to HashedPtr for raw pointers.
+// This overrides the default Pointer implementation for raw pointers to use hashing,
+// which is the safe default behavior for kernel pointers.
+impl<T> Pointer for Adapter<*const T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        let Self(ptr) = self;
+        Pointer::fmt(&HashedPtr::from(*ptr), f)
+    }
+}
+
+impl<T> Pointer for Adapter<*mut T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        let Self(ptr) = self;
+        Pointer::fmt(&HashedPtr::from_mut(*ptr), f)
+    }
+}
+
+// Handle references to raw pointers (needed when pointers are passed by reference in macros).
+impl<T> Pointer for Adapter<&*const T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        let Self(ptr) = self;
+        Pointer::fmt(&HashedPtr::from(**ptr), f)
+    }
+}
+
+impl<T> Pointer for Adapter<&*mut T> {
+    fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+        let Self(ptr) = self;
+        Pointer::fmt(&HashedPtr::from_mut(**ptr), f)
+    }
+}
+
+// For wrapper types that implement Pointer (like HashedPtr, RestrictedPtr, RawPtr),
+// forward to their implementation. This allows explicit wrapper types to use their
+// own formatting logic instead of being converted to HashedPtr.
+macro_rules! impl_pointer_adapter_forward {
+    ($($ty:ty),* $(,)?) => {
+        $(
+            impl Pointer for Adapter<$ty> {
+                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+                    let Self(t) = self;
+                    Pointer::fmt(t, f)
+                }
+            }
+
+            impl Pointer for Adapter<&$ty> {
+                fn fmt(&self, f: &mut Formatter<'_>) -> Result {
+                    let Self(t) = self;
+                    Pointer::fmt(*t, f)
+                }
+            }
+        )*
+    };
+}
+
+impl_pointer_adapter_forward!(HashedPtr, RestrictedPtr, RawPtr);
 
 /// A copy of [`core::fmt::Display`] that allows us to implement it for foreign types.
 ///
-- 
2.43.0


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

* [PATCH v3 4/4] docs: rust: Add pointer formatting documentation
  2025-12-24  8:13 [PATCH v3 0/4] rust: Add safe pointer formatting support Ke Sun
                   ` (2 preceding siblings ...)
  2025-12-24  8:13 ` [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr Ke Sun
@ 2025-12-24  8:13 ` Ke Sun
  3 siblings, 0 replies; 9+ messages in thread
From: Ke Sun @ 2025-12-24  8:13 UTC (permalink / raw)
  To: Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Tamir Duberstein, rust-for-linux,
	Ke Sun

Add a brief documentation for Rust pointer wrapper types (HashedPtr,
RestrictedPtr, RawPtr) that correspond to C kernel's printk format
specifiers %p, %pK, and %px.

The documentation provides:
- Overview of the three wrapper types
- Usage examples for each type
- When to use each type
- Security considerations

This complements the general pointer formatting documentation in
Documentation/core-api/printk-formats.rst.

Signed-off-by: Ke Sun <sunke@kylinos.cn>
---
 Documentation/rust/index.rst              |  1 +
 Documentation/rust/pointer-formatting.rst | 67 +++++++++++++++++++++++
 2 files changed, 68 insertions(+)
 create mode 100644 Documentation/rust/pointer-formatting.rst

diff --git a/Documentation/rust/index.rst b/Documentation/rust/index.rst
index ec62001c7d8c7..4f4f8b393031e 100644
--- a/Documentation/rust/index.rst
+++ b/Documentation/rust/index.rst
@@ -55,6 +55,7 @@ more details.
     coding-guidelines
     arch-support
     testing
+    pointer-formatting
 
 You can also find learning materials for Rust in its section in
 :doc:`../process/kernel-docs`.
diff --git a/Documentation/rust/pointer-formatting.rst b/Documentation/rust/pointer-formatting.rst
new file mode 100644
index 0000000000000..999634697ae12
--- /dev/null
+++ b/Documentation/rust/pointer-formatting.rst
@@ -0,0 +1,67 @@
+.. SPDX-License-Identifier: GPL-2.0
+
+Pointer Formatting in Rust
+===========================
+
+This document describes how to format kernel pointers safely in Rust code,
+corresponding to the C kernel's printk format specifiers ``%p``, ``%pK``, and ``%px``.
+
+For general information about pointer formatting in the kernel, please refer to
+:doc:`../core-api/printk-formats`.
+
+Overview
+--------
+
+The Rust kernel provides three wrapper types for formatting kernel pointers:
+
+- **``HashedPtr``** → ``%p`` (hashed, default)
+- **``RestrictedPtr``** → ``%pK`` (restricted, respects ``kptr_restrict``)
+- **``RawPtr``** → ``%px`` (raw address, debug only)
+
+When formatting raw pointers (``*const T`` or ``*mut T``) with ``{:p}``,
+they are automatically wrapped with ``HashedPtr``, providing safe default behavior.
+
+HashedPtr (%p)
+--------------
+
+Use ``HashedPtr`` for general kernel logging. Pointers are hashed before printing
+to prevent leaking information about the kernel memory layout.
+
+**Example**::
+
+    use kernel::ptr::HashedPtr;
+
+    pr_info!("Device pointer: {:p}\n", HashedPtr::from(ptr));
+
+RestrictedPtr (%pK)
+-------------------
+
+Use ``RestrictedPtr`` when producing content of a file read by userspace from
+e.g. procfs or sysfs (using e.g. ``seq_print!()``, not ``pr_info!()``). The behavior
+depends on the ``kptr_restrict`` sysctl setting.
+
+**Example**::
+
+    use kernel::ptr::RestrictedPtr;
+
+    seq_print!(seq_file, "Pointer: {:p}\n", RestrictedPtr::from(ptr));
+
+For more details about ``kptr_restrict``, see :doc:`../admin-guide/sysctl/kernel`.
+
+RawPtr (%px)
+------------
+
+**Warning**: This exposes the real kernel address and should **only** be used
+for debugging purposes.
+
+**Example**::
+
+    use kernel::ptr::RawPtr;
+
+    pr_info!("Debug pointer: {:p}\n", RawPtr::from(ptr));
+
+See Also
+--------
+
+- :doc:`../core-api/printk-formats` - General pointer formatting documentation
+- `rust/kernel/ptr.rs <srctree/rust/kernel/ptr.rs>`_ - Implementation
-- 
2.43.0


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

* Re: [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr
  2025-12-24  8:13 ` [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr Ke Sun
@ 2025-12-24 20:58   ` kernel test robot
  2025-12-25  2:50     ` Ke Sun
  0 siblings, 1 reply; 9+ messages in thread
From: kernel test robot @ 2025-12-24 20:58 UTC (permalink / raw)
  To: Ke Sun, Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: oe-kbuild-all, Boqun Feng, Gary Guo, Björn Roy Baron,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Tamir Duberstein,
	rust-for-linux, Ke Sun

Hi Ke,

kernel test robot noticed the following build errors:

[auto build test ERROR on 9448598b22c50c8a5bb77a9103e2d49f134c9578]

url:    https://github.com/intel-lab-lkp/linux/commits/Ke-Sun/lib-vsprintf-Export-ptr_to_hashval-for-Rust-use/20251224-161946
base:   9448598b22c50c8a5bb77a9103e2d49f134c9578
patch link:    https://lore.kernel.org/r/20251224081315.729684-4-sunke%40kylinos.cn
patch subject: [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20251224/202512242153.r68Pb25u-lkp@intel.com/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251224/202512242153.r68Pb25u-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202512242153.r68Pb25u-lkp@intel.com/

All errors (new ones prefixed by >>):

   PATH=/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   INFO PATH=/opt/cross/rustc-1.88.0-bindgen-0.72.1/cargo/bin:/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
   /usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS= -fno-crash-diagnostics -Wno-error=return-type -Wreturn-type -funsigned-char -Wundef W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck
   make: Entering directory '/kbuild/src/consumer'
   make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
>> Diff in rust/kernel/fmt.rs:30:
    use core::fmt::{Binary, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex};
    impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, LowerExp, UpperExp);
    
   -use crate::ptr::{HashedPtr, RestrictedPtr, RawPtr};
   +use crate::ptr::{HashedPtr, RawPtr, RestrictedPtr};
    // Special handling for Pointer: default to HashedPtr for raw pointers.
    // This overrides the default Pointer implementation for raw pointers to use hashing,
    // which is the safe default behavior for kernel pointers.
>> Diff in rust/kernel/fmt.rs:30:
    use core::fmt::{Binary, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex};
    impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, LowerExp, UpperExp);
    
   -use crate::ptr::{HashedPtr, RestrictedPtr, RawPtr};
   +use crate::ptr::{HashedPtr, RawPtr, RestrictedPtr};
    // Special handling for Pointer: default to HashedPtr for raw pointers.
    // This overrides the default Pointer implementation for raw pointers to use hashing,
    // which is the safe default behavior for kernel pointers.
   make[2]: *** [Makefile:1871: rustfmt] Error 123
   make[2]: Target 'rustfmtcheck' not remade because of errors.
   make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
   make[1]: *** [Makefile:248: __sub-make] Error 2
   make[1]: Target 'rustfmtcheck' not remade because of errors.
   make: *** [Makefile:248: __sub-make] Error 2
   make: Target 'rustfmtcheck' not remade because of errors.
   make: Leaving directory '/kbuild/src/consumer'

-- 
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

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

* Re: [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr
  2025-12-24 20:58   ` kernel test robot
@ 2025-12-25  2:50     ` Ke Sun
  0 siblings, 0 replies; 9+ messages in thread
From: Ke Sun @ 2025-12-25  2:50 UTC (permalink / raw)
  To: kernel test robot, Miguel Ojeda, Petr Mladek, Steven Rostedt,
	Timur Tabi, Danilo Krummrich, Benno Lossin
  Cc: oe-kbuild-all, Boqun Feng, Gary Guo, Björn Roy Baron,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Tamir Duberstein,
	rust-for-linux

I'll fix this rustfmt formatting issue in the next version, along with 
addressing other review comments.

On 12/25/25 04:58, kernel test robot wrote:
> Hi Ke,
>
> kernel test robot noticed the following build errors:
>
> [auto build test ERROR on 9448598b22c50c8a5bb77a9103e2d49f134c9578]
>
> url:    https://github.com/intel-lab-lkp/linux/commits/Ke-Sun/lib-vsprintf-Export-ptr_to_hashval-for-Rust-use/20251224-161946
> base:   9448598b22c50c8a5bb77a9103e2d49f134c9578
> patch link:    https://lore.kernel.org/r/20251224081315.729684-4-sunke%40kylinos.cn
> patch subject: [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr
> config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20251224/202512242153.r68Pb25u-lkp@intel.com/config)
> compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
> rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
> reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251224/202512242153.r68Pb25u-lkp@intel.com/reproduce)
>
> If you fix the issue in a separate patch/commit (i.e. not just a new version of
> the same patch/commit), kindly add following tags
> | Reported-by: kernel test robot <lkp@intel.com>
> | Closes: https://lore.kernel.org/oe-kbuild-all/202512242153.r68Pb25u-lkp@intel.com/
>
> All errors (new ones prefixed by >>):
>
>     PATH=/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
>     INFO PATH=/opt/cross/rustc-1.88.0-bindgen-0.72.1/cargo/bin:/opt/cross/clang-20/bin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
>     /usr/bin/timeout -k 100 12h /usr/bin/make KCFLAGS= -fno-crash-diagnostics -Wno-error=return-type -Wreturn-type -funsigned-char -Wundef W=1 --keep-going LLVM=1 -j32 -C source O=/kbuild/obj/consumer/x86_64-rhel-9.4-rust ARCH=x86_64 SHELL=/bin/bash rustfmtcheck
>     make: Entering directory '/kbuild/src/consumer'
>     make[1]: Entering directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
>>> Diff in rust/kernel/fmt.rs:30:
>      use core::fmt::{Binary, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex};
>      impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, LowerExp, UpperExp);
>      
>     -use crate::ptr::{HashedPtr, RestrictedPtr, RawPtr};
>     +use crate::ptr::{HashedPtr, RawPtr, RestrictedPtr};
>      // Special handling for Pointer: default to HashedPtr for raw pointers.
>      // This overrides the default Pointer implementation for raw pointers to use hashing,
>      // which is the safe default behavior for kernel pointers.
>>> Diff in rust/kernel/fmt.rs:30:
>      use core::fmt::{Binary, LowerExp, LowerHex, Octal, Pointer, UpperExp, UpperHex};
>      impl_fmt_adapter_forward!(Debug, LowerHex, UpperHex, Octal, Binary, LowerExp, UpperExp);
>      
>     -use crate::ptr::{HashedPtr, RestrictedPtr, RawPtr};
>     +use crate::ptr::{HashedPtr, RawPtr, RestrictedPtr};
>      // Special handling for Pointer: default to HashedPtr for raw pointers.
>      // This overrides the default Pointer implementation for raw pointers to use hashing,
>      // which is the safe default behavior for kernel pointers.
>     make[2]: *** [Makefile:1871: rustfmt] Error 123
>     make[2]: Target 'rustfmtcheck' not remade because of errors.
>     make[1]: Leaving directory '/kbuild/obj/consumer/x86_64-rhel-9.4-rust'
>     make[1]: *** [Makefile:248: __sub-make] Error 2
>     make[1]: Target 'rustfmtcheck' not remade because of errors.
>     make: *** [Makefile:248: __sub-make] Error 2
>     make: Target 'rustfmtcheck' not remade because of errors.
>     make: Leaving directory '/kbuild/src/consumer'
>

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

* Re: [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting
  2025-12-24  8:13 ` [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting Ke Sun
@ 2025-12-25  9:19   ` Dirk Behme
  2025-12-25 15:22   ` kernel test robot
  1 sibling, 0 replies; 9+ messages in thread
From: Dirk Behme @ 2025-12-25  9:19 UTC (permalink / raw)
  To: Ke Sun, Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: Boqun Feng, Gary Guo, Björn Roy Baron, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, Tamir Duberstein, rust-for-linux

On 24.12.25 09:13, Ke Sun wrote:
> Add three pointer wrapper types (HashedPtr, RestrictedPtr, RawPtr) to
> rust/kernel/ptr.rs that correspond to C kernel's printk format specifiers
> %p, %pK, and %px. These types provide type-safe pointer formatting that
> matches C kernel patterns.
> 
> These wrapper types implement core::fmt::Pointer and delegate to the
> corresponding kernel formatting functions, enabling safe pointer
> formatting in Rust code that prevents information leaks about kernel
> memory layout.
> 
> Users can explicitly use these types:
>     pr_info!("{:p}\n", HashedPtr::from(ptr));
>     seq_print!(seq_file, "{:p}\n", RestrictedPtr::from(ptr));
>     pr_info!("{:p}\n", RawPtr::from(ptr));
> 
> Changes:
> - Add HashedPtr for %p (hashed, default behavior)
> - Add RestrictedPtr for %pK (restricted, respects kptr_restrict)
> - Add RawPtr for %px (raw address, debug only)
> - Add helper function kptr_restrict_value() in rust/helpers/fmt.c
> - Add impl_ptr_wrapper! macro to reduce code duplication
> 
> Signed-off-by: Ke Sun <sunke@kylinos.cn>
> ---
>  rust/helpers/fmt.c     |  61 ++++++++++++++
>  rust/helpers/helpers.c |   3 +-
>  rust/kernel/ptr.rs     | 186 +++++++++++++++++++++++++++++++++++++++++
>  3 files changed, 249 insertions(+), 1 deletion(-)
>  create mode 100644 rust/helpers/fmt.c
....
> diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs
> index e3893ed04049d..deb4d72bcecca 100644
> --- a/rust/kernel/ptr.rs
> +++ b/rust/kernel/ptr.rs
> @@ -1,11 +1,17 @@
>  // SPDX-License-Identifier: GPL-2.0
>  
>  //! Types and functions to work with pointers and addresses.
> +//!
> +//! This module provides wrapper types for formatting kernel pointers that correspond to the
> +//! C kernel's printk format specifiers `%p`, `%pK`, and `%px`.
>  
> +use core::fmt;
>  use core::mem::align_of;
>  use core::num::NonZero;
>  
> +use crate::bindings;
>  use crate::build_assert;
> +use crate::ffi::c_void;
>  
>  /// Type representing an alignment, which is always a power of two.
>  ///
> @@ -225,3 +231,183 @@ fn align_up(self, alignment: Alignment) -> Option<Self> {
>  }
>  
>  impl_alignable_uint!(u8, u16, u32, u64, usize);
> +
> +/// Placeholder string used when pointer hashing is not ready yet.
> +const PTR_PLACEHOLDER: &str = if core::mem::size_of::<*const c_void>() == 8 {
> +    "(____ptrval____)"
> +} else {
> +    "(ptrval)"
> +};
> +
> +/// Macro to implement common methods for pointer wrapper types.
> +macro_rules! impl_ptr_wrapper {
> +    ($($name:ident),* $(,)?) => {
> +        $(
> +            impl $name {
> +                /// Creates a new instance from a raw pointer.
> +                #[inline]
> +                pub fn from<T>(ptr: *const T) -> Self {
> +                    Self(ptr.cast())
> +                }
> +
> +                /// Creates a new instance from a mutable raw pointer.
> +                #[inline]
> +                pub fn from_mut<T>(ptr: *mut T) -> Self {
> +                    Self(ptr.cast())
> +                }
> +
> +                /// Returns the inner raw pointer.
> +                #[inline]
> +                pub fn as_ptr(&self) -> *const c_void {
> +                    self.0
> +                }
> +            }
> +
> +            impl<T> From<*const T> for $name {
> +                #[inline]
> +                fn from(ptr: *const T) -> Self {
> +                    Self::from(ptr)
> +                }
> +            }
> +
> +            impl<T> From<*mut T> for $name {
> +                #[inline]
> +                fn from(ptr: *mut T) -> Self {
> +                    Self::from_mut(ptr)
> +                }
> +            }
> +        )*
> +    };
> +}
> +
> +/// Helper function to hash a pointer and format it.
> +///
> +/// Returns `Ok(())` if the hash was successfully computed and formatted,
> +/// or the placeholder string if hashing is not ready yet.
> +fn format_hashed_ptr(ptr: *const c_void, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +    // SAFETY: We're calling the kernel's ptr_to_hashval function which handles
> +    // hashing. This is safe as long as ptr is a valid pointer value.
> +    unsafe {

Would it be possible to limit the scope of the unsafe? E.g. to just

let ret = unsafe { bindings::ptr_to_hashval(ptr,
core::ptr::addr_of_mut!(hashval))};

> +        let mut hashval: crate::ffi::c_ulong = 0;
> +        let ret = bindings::ptr_to_hashval(ptr, core::ptr::addr_of_mut!(hashval));
> +
> +        if ret == 0 {
> +            // Successfully got hash value, format it
> +            write!(f, "{:p}", hashval as *const c_void)
> +        } else {
> +            // Hash not ready yet, print placeholder
> +            f.write_str(PTR_PLACEHOLDER)
> +        }

Whats about making the happy path the default and with this have less
indentation?

if ret != 0 {
     // Hash not ready yet, print placeholder
     return f.write_str(PTR_PLACEHOLDER);
}

// Successfully got hash value, format it
write!(f, "{:p}", hashval as *const c_void)


> +    }
> +}
> +
> +/// A pointer that will be hashed when printed (corresponds to `%p`).
> +///
> +/// This is the default behavior for kernel pointers - they are hashed to prevent
> +/// leaking information about the kernel memory layout.
> +///
> +/// # Example
> +///
> +/// ```
> +/// use kernel::ptr::HashedPtr;
> +///
> +/// let ptr = HashedPtr::from(0x12345678 as *const u8);
> +/// pr_info!("Pointer: {:p}\n", ptr);
> +/// ```
> +#[repr(transparent)]
> +#[derive(Copy, Clone, Debug)]
> +pub struct HashedPtr(*const c_void);
> +
> +impl fmt::Pointer for HashedPtr {
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        let ptr = self.0;
> +
> +        // Handle NULL pointers - print them directly
> +        if ptr.is_null() {
> +            return write!(f, "{:p}", ptr);
> +        }
> +
> +        format_hashed_ptr(ptr, f)
> +    }
> +}
> +
> +/// A pointer that will be restricted based on `kptr_restrict` when printed (corresponds to `%pK`).
> +///
> +/// This is intended for use in procfs/sysfs files that are read by userspace.
> +/// The behavior depends on the `kptr_restrict` sysctl setting.
> +///
> +/// # Example
> +///
> +/// ```
> +/// use kernel::ptr::RestrictedPtr;
> +///
> +/// let ptr = RestrictedPtr::from(0x12345678 as *const u8);
> +/// seq_print!(seq_file, "Pointer: {:p}\n", ptr);
> +/// ```

This example doesn't build:

error: cannot find macro `seq_print` in this scope
     --> rust/doctests_kernel_generated.rs:12492:1
      |
12492 | seq_print!(seq_file, "Pointer: {:p}\n", ptr);
      | ^^^^^^^^^
      |
help: consider importing this macro
      |
    3 + use kernel::seq_print;
      |

Adding that results in

error[E0425]: cannot find value `seq_file` in this scope
     --> rust/doctests_kernel_generated.rs:12493:12
      |
12493 | seq_print!(seq_file, "Pointer: {:p}\n", ptr);
      |            ^^^^^^^^ not found in this scope


> +#[repr(transparent)]
> +#[derive(Copy, Clone, Debug)]
> +pub struct RestrictedPtr(*const c_void);
> +
> +impl fmt::Pointer for RestrictedPtr {
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        let ptr = self.0;
> +
> +        // Handle NULL pointers
> +        if ptr.is_null() {
> +            return write!(f, "{:p}", ptr);
> +        }
> +
> +        // Use kptr_restrict_value to handle all kptr_restrict cases.
> +        // SAFETY: kptr_restrict_value handles capability checks and IRQ context.
> +        // - Returns NULL if no permission, IRQ context, or kptr_restrict >= 2
> +        // - Returns the original pointer if kptr_restrict == 0 (needs hashing)
> +        // - Returns the original pointer if kptr_restrict == 1 with permission (print raw)
> +        let restricted_ptr = unsafe { bindings::kptr_restrict_value(ptr) };
> +
> +        if restricted_ptr.is_null() {
> +            // No permission, IRQ context, or kptr_restrict >= 2 - print 0
> +            write!(f, "{:p}", core::ptr::null::<c_void>())
> +        } else {
> +            // restricted_ptr is non-null, meaning we should print something.
> +            // SAFETY: Reading kptr_restrict is safe as it's a kernel variable.
> +            let restrict = unsafe { bindings::kptr_restrict };
> +
> +            if restrict == 0 {
> +                // kptr_restrict == 0: hash the pointer (same as %p)
> +                format_hashed_ptr(ptr, f)
> +            } else {
> +                // kptr_restrict == 1 with permission: print the raw pointer directly (like %px)
> +                // This matches C behavior: pointer_string() prints the raw address
> +                write!(f, "{:p}", restricted_ptr)
> +            }
> +        }


Same if formatting like above here? E.g.

if restricted_ptr.is_null() {
    // No permission, IRQ context, or kptr_restrict >= 2 - print 0
    return write!(f, "{:p}", core::ptr::null::<c_void>());
}

// restricted_ptr is non-null, meaning we should print something.
// SAFETY: Reading kptr_restrict is safe as it's a kernel variable.
let restrict = unsafe { bindings::kptr_restrict };

if restrict == 0 {
    // kptr_restrict == 0: hash the pointer (same as %p)
    return format_hashed_ptr(ptr, f);
}

// kptr_restrict == 1 with permission: print the raw pointer directly
(like %px)
// This matches C behavior: pointer_string() prints the raw address
write!(f, "{:p}", restricted_ptr)


> +    }
> +}
> +
> +/// A pointer that will be printed as its raw address (corresponds to `%px`).
> +///
> +/// **Warning**: This exposes the real kernel address and should only be used
> +/// for debugging purposes. Consider using [`HashedPtr`] or [`RestrictedPtr`] instead.
> +///
> +/// # Example
> +///
> +/// ```
> +/// use kernel::ptr::RawPtr;
> +///
> +/// let ptr = RawPtr::from(0x12345678 as *const u8);
> +/// pr_info!("Debug pointer: {:p}\n", ptr);
> +/// ```
> +#[repr(transparent)]
> +#[derive(Copy, Clone, Debug)]
> +pub struct RawPtr(*const c_void);
> +
> +impl fmt::Pointer for RawPtr {
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        // Directly format the raw address - no hashing or restriction
> +        // This corresponds to %px behavior
> +        write!(f, "{:p}", self.0)
> +    }
> +}
> +
> +// Implement common methods for all pointer wrapper types
> +impl_ptr_wrapper!(HashedPtr, RestrictedPtr, RawPtr);


Btw, would all this work with e.g. some format specifiers? E.g. with
{:016p} ?

Cheers,

Dirk


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

* Re: [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting
  2025-12-24  8:13 ` [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting Ke Sun
  2025-12-25  9:19   ` Dirk Behme
@ 2025-12-25 15:22   ` kernel test robot
  1 sibling, 0 replies; 9+ messages in thread
From: kernel test robot @ 2025-12-25 15:22 UTC (permalink / raw)
  To: Ke Sun, Miguel Ojeda, Petr Mladek, Steven Rostedt, Timur Tabi,
	Danilo Krummrich, Benno Lossin
  Cc: llvm, oe-kbuild-all, Boqun Feng, Gary Guo, Björn Roy Baron,
	Andreas Hindborg, Alice Ryhl, Trevor Gross, Tamir Duberstein,
	rust-for-linux, Ke Sun

Hi Ke,

kernel test robot noticed the following build errors:

[auto build test ERROR on 9448598b22c50c8a5bb77a9103e2d49f134c9578]

url:    https://github.com/intel-lab-lkp/linux/commits/Ke-Sun/lib-vsprintf-Export-ptr_to_hashval-for-Rust-use/20251224-161946
base:   9448598b22c50c8a5bb77a9103e2d49f134c9578
patch link:    https://lore.kernel.org/r/20251224081315.729684-3-sunke%40kylinos.cn
patch subject: [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting
config: x86_64-rhel-9.4-rust (https://download.01.org/0day-ci/archive/20251225/202512252338.UQxvMW2X-lkp@intel.com/config)
compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261)
rustc: rustc 1.88.0 (6b00bc388 2025-06-23)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20251225/202512252338.UQxvMW2X-lkp@intel.com/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of
the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <lkp@intel.com>
| Closes: https://lore.kernel.org/oe-kbuild-all/202512252338.UQxvMW2X-lkp@intel.com/

All errors (new ones prefixed by >>):

>> error: cannot find macro `seq_print` in this scope
   --> rust/doctests_kernel_generated.rs:12267:1
   |
   12267 | seq_print!(seq_file, "Pointer: {:p}n", ptr);
   | ^^^^^^^^^
   |
   help: consider importing this macro
   |
   3     + use kernel::seq_print;
   |

-- 
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki

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

end of thread, other threads:[~2025-12-25 15:22 UTC | newest]

Thread overview: 9+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2025-12-24  8:13 [PATCH v3 0/4] rust: Add safe pointer formatting support Ke Sun
2025-12-24  8:13 ` [PATCH v3 1/4] lib/vsprintf: Export ptr_to_hashval for Rust use Ke Sun
2025-12-24  8:13 ` [PATCH v3 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting Ke Sun
2025-12-25  9:19   ` Dirk Behme
2025-12-25 15:22   ` kernel test robot
2025-12-24  8:13 ` [PATCH v3 3/4] rust: fmt: Default raw pointer formatting to HashedPtr Ke Sun
2025-12-24 20:58   ` kernel test robot
2025-12-25  2:50     ` Ke Sun
2025-12-24  8:13 ` [PATCH v3 4/4] docs: rust: Add pointer formatting documentation Ke Sun

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox