public inbox for rust-for-linux@vger.kernel.org
 help / color / mirror / Atom feed
From: Dirk Behme <dirk.behme@de.bosch.com>
To: Ke Sun <sunke@kylinos.cn>, Dirk Behme <dirk.behme@gmail.com>,
	Boqun Feng <boqun.feng@gmail.com>,
	Miguel Ojeda <ojeda@kernel.org>, Petr Mladek <pmladek@suse.com>,
	Steven Rostedt <rostedt@goodmis.org>,
	Timur Tabi <ttabi@nvidia.com>, Danilo Krummrich <dakr@kernel.org>,
	Benno Lossin <lossin@kernel.org>,
	Alice Ryhl <aliceryhl@google.com>
Cc: "John Ogness" <john.ogness@linutronix.de>,
	"Andy Shevchenko" <andriy.shevchenko@linux.intel.com>,
	"Rasmus Villemoes" <linux@rasmusvillemoes.dk>,
	"Andrew Morton" <akpm@linux-foundation.org>,
	"Gary Guo" <gary@garyguo.net>,
	"Björn Roy Baron" <bjorn3_gh@protonmail.com>,
	"Andreas Hindborg" <a.hindborg@kernel.org>,
	"Trevor Gross" <tmgross@umich.edu>,
	"Tamir Duberstein" <tamird@gmail.com>,
	"Ke Sun" <sk.alvin.x@gmail.com>,
	rust-for-linux@vger.kernel.org
Subject: Re: [PATCH v8 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting
Date: Fri, 2 Jan 2026 08:57:16 +0100	[thread overview]
Message-ID: <4ef1abd2-e9df-4e75-b203-5b7fece3bb7e@de.bosch.com> (raw)
In-Reply-To: <20260101081605.1300953-3-sunke@kylinos.cn>

On 01/01/2026 09:16, Ke Sun wrote:
> Add two pointer wrapper types (HashedPtr, RawPtr) to rust/kernel/ptr.rs
> that correspond to C kernel's printk format specifiers %p 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(ptr));
>      pr_info!("{:p}\n", RawPtr(ptr));
> 
> HashedPtr uses ptr_to_hashval() to hash pointers before printing,
> providing the default safe behavior for kernel pointers. RawPtr prints
> the raw address and should only be used for debugging purposes.
> 
> Signed-off-by: Ke Sun <sunke@kylinos.cn>
> Suggested-by: Dirk Behme <dirk.behme@gmail.com>
> Suggested-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
> ---
>   rust/kernel/ptr.rs | 133 ++++++++++++++++++++++++++++++++++++++++++++-
>   1 file changed, 130 insertions(+), 3 deletions(-)
> 
> diff --git a/rust/kernel/ptr.rs b/rust/kernel/ptr.rs
> index e3893ed04049d..77132eaaef73b 100644
> --- a/rust/kernel/ptr.rs
> +++ b/rust/kernel/ptr.rs
> @@ -1,11 +1,22 @@
>   // 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` and `%px`.
>   
> -use core::mem::align_of;
> -use core::num::NonZero;
> +use core::{
> +    fmt,
> +    fmt::Pointer,
> +    mem::align_of,
> +    num::NonZero, //
> +};
>   
> -use crate::build_assert;
> +use crate::{
> +    bindings,
> +    build_assert,
> +    prelude::*, //
> +};
>   
>   /// Type representing an alignment, which is always a power of two.
>   ///
> @@ -225,3 +236,119 @@ 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 size_of::<*const c_void>() == 8 {
> +    "(____ptrval____)"
> +} else {
> +    "(ptrval)"
> +};
> +
> +/// 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 {
> +    let mut hashval: crate::ffi::c_ulong = 0;
> +    // 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.
> +    let ret = unsafe { bindings::ptr_to_hashval(ptr, &mut hashval) };
> +
> +    if ret != 0 {
> +        // Hash not ready yet, print placeholder with formatting options applied
> +        // Using `pad()` ensures width, alignment, and padding options are respected
> +        return f.pad(PTR_PLACEHOLDER);
> +    }
> +
> +    // Successfully got hash value, format it using Pointer::fmt to preserve
> +    // formatting options (width, alignment, padding, etc.)
> +    Pointer::fmt(&(hashval as *const c_void), f)
> +}
> +
> +/// 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::{
> +///     prelude::fmt,
> +///     ptr::HashedPtr,
> +///     str::CString, //
> +/// };
> +///
> +/// let ptr = HashedPtr(0x12345678 as *const u8);
> +/// pr_info!("Hashed pointer: {:016p}\n", ptr);
> +///
> +/// // Width option test
> +/// let cstr = CString::try_from_fmt(fmt!("{:30p}", ptr))?;
> +/// let width_30 = cstr.to_str()?;
> +/// assert_eq!(width_30.len(), 30);
> +/// # Ok::<(), kernel::error::Error>(())
> +/// ```
> +#[repr(transparent)]
> +#[derive(Copy, Clone)]
> +pub struct HashedPtr<T>(pub *const T);
> +
> +impl<T> fmt::Pointer for HashedPtr<T> {
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        // Handle NULL pointers - print them directly
> +        let ptr = self.0.cast::<c_void>();
> +        if ptr.is_null() {
> +            return Pointer::fmt(&ptr, f);
> +        }
> +
> +        format_hashed_ptr(ptr, f)
> +    }
> +}
> +
> +/// 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`] instead for production code.
> +///
> +/// # Example
> +///
> +/// ```
> +/// use kernel::{
> +///     prelude::fmt,
> +///     ptr::RawPtr,
> +///     str::CString, //
> +/// };
> +///
> +/// let ptr = RawPtr(0x12345678 as *const u8);
> +///
> +/// // Basic formatting
> +/// let cstr = CString::try_from_fmt(fmt!("{:p}", ptr))?;
> +/// let formatted = cstr.to_str()?;
> +/// assert_eq!(formatted, "0x12345678");
> +///
> +/// // Right align with zero padding, width 30
> +/// let cstr = CString::try_from_fmt(fmt!("{:0>30p}", ptr))?;
> +/// let right_zero = cstr.to_str()?;
> +/// assert_eq!(right_zero, "000000000000000000000x12345678");
> +///
> +/// // Left align with zero padding, width 30
> +/// let cstr = CString::try_from_fmt(fmt!("{:0<30p}", ptr))?;
> +/// let left_zero = cstr.to_str()?;
> +/// assert_eq!(left_zero, "0x1234567800000000000000000000");
> +///
> +/// // Center align with zero padding, width 30
> +/// let cstr = CString::try_from_fmt(fmt!("{:0^30p}", ptr))?;
> +/// let center_zero = cstr.to_str()?;
> +/// assert_eq!(center_zero, "00000000000x123456780000000000");
> +/// # Ok::<(), kernel::error::Error>(())
> +/// ```
> +#[repr(transparent)]
> +#[derive(Copy, Clone)]
> +pub struct RawPtr<T>(pub *const T);


In the thread "[PATCH] gpu: nova-core: bitfield: use &mut self setters 
instead of builder pattern" [1] Gary proposed to add `#[must_use]`. 
Would that be an option here as well?

Thanks

Dirk

[1] 
https://lore.kernel.org/rust-for-linux/20260101042851.08576bdb.gary@garyguo.net/

> +
> +impl<T> fmt::Pointer for RawPtr<T> {
> +    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
> +        // Directly format the raw address - no hashing or restriction.
> +        // This corresponds to %px behavior.
> +        Pointer::fmt(&self.0.cast::<c_void>(), f)
> +    }
> +}


  reply	other threads:[~2026-01-02  7:57 UTC|newest]

Thread overview: 20+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-01-01  8:16 [PATCH v8 0/4] rust: Add safe pointer formatting support Ke Sun
2026-01-01  8:16 ` [PATCH v8 1/4] lib/vsprintf: Export ptr_to_hashval() for Rust kernel crate use Ke Sun
2026-01-02 12:15   ` Andy Shevchenko
2026-01-01  8:16 ` [PATCH v8 2/4] rust: kernel: Add pointer wrapper types for safe pointer formatting Ke Sun
2026-01-02  7:57   ` Dirk Behme [this message]
2026-01-02 11:06     ` Gary Guo
2026-01-02 11:13   ` Gary Guo
2026-01-02 12:17   ` Andy Shevchenko
2026-01-02 12:33     ` Danilo Krummrich
2026-01-02 12:43       ` Ke Sun
2026-01-01  8:16 ` [PATCH v8 3/4] rust: fmt: Default raw pointer formatting to HashedPtr Ke Sun
2026-01-02 11:17   ` Gary Guo
2026-01-02 17:39   ` Petr Mladek
2026-01-05  8:19     ` Alice Ryhl
2026-01-06  3:06       ` Ke Sun
2026-01-06 16:45       ` Petr Mladek
2026-01-06 17:18         ` Alice Ryhl
2026-01-06 21:00           ` Andy Shevchenko
2026-01-06 21:06             ` Alice Ryhl
2026-01-01  8:16 ` [PATCH v8 4/4] docs: rust: Add pointer formatting documentation Ke Sun

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

  Avoid top-posting and favor interleaved quoting:
  https://en.wikipedia.org/wiki/Posting_style#Interleaved_style

* Reply using the --to, --cc, and --in-reply-to
  switches of git-send-email(1):

  git send-email \
    --in-reply-to=4ef1abd2-e9df-4e75-b203-5b7fece3bb7e@de.bosch.com \
    --to=dirk.behme@de.bosch.com \
    --cc=a.hindborg@kernel.org \
    --cc=akpm@linux-foundation.org \
    --cc=aliceryhl@google.com \
    --cc=andriy.shevchenko@linux.intel.com \
    --cc=bjorn3_gh@protonmail.com \
    --cc=boqun.feng@gmail.com \
    --cc=dakr@kernel.org \
    --cc=dirk.behme@gmail.com \
    --cc=gary@garyguo.net \
    --cc=john.ogness@linutronix.de \
    --cc=linux@rasmusvillemoes.dk \
    --cc=lossin@kernel.org \
    --cc=ojeda@kernel.org \
    --cc=pmladek@suse.com \
    --cc=rostedt@goodmis.org \
    --cc=rust-for-linux@vger.kernel.org \
    --cc=sk.alvin.x@gmail.com \
    --cc=sunke@kylinos.cn \
    --cc=tamird@gmail.com \
    --cc=tmgross@umich.edu \
    --cc=ttabi@nvidia.com \
    /path/to/YOUR_REPLY

  https://kernel.org/pub/software/scm/git/docs/git-send-email.html

* If your mail client supports setting the In-Reply-To header
  via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox