Re: [PATCH v2 2/2] rust: task: use atomic read for pid()

From: Boqun Feng

Date: Fri Feb 13 2026 - 11:49:55 EST


On Thu, Feb 12, 2026 at 11:12:07PM +0100, Jann Horn wrote:
> (Note: This is not a bugfix, it just cleans up an incorrect assumption.)
>
> Task::pid() wrongly assumes that task::pid remains constant until the task
> refcount drops to zero.
>
> However, Linux has a special quirk where, when execve() is called by a
> thread other than the thread group leader (the main thread), the thread
> calling execve() swaps its identity with the thread group leader's,
> becoming the new thread group leader. This means task::pid can't be assumed
> to be immutable for non-current tasks.
> (The actual swapping of PIDs is implemented in exchange_tids().)
>
> Signed-off-by: Jann Horn <jannh@xxxxxxxxxx>

Reviewed-by: Boqun Feng <boqun@xxxxxxxxxx>

Regards,
Boqun

> ---
> rust/kernel/task.rs | 12 +++++++++---
> 1 file changed, 9 insertions(+), 3 deletions(-)
>
> diff --git a/rust/kernel/task.rs b/rust/kernel/task.rs
> index 91ad88cdfd3b..de0d90b47862 100644
> --- a/rust/kernel/task.rs
> +++ b/rust/kernel/task.rs
> @@ -10,6 +10,8 @@
> mm::MmWithUser,
> pid_namespace::PidNamespace,
> sync::aref::ARef,
> + sync::atomic::ordering::Relaxed,
> + sync::atomic::Atomic,
> types::{NotThreadSafe, Opaque},
> };
> use core::{
> @@ -206,9 +208,13 @@ pub fn as_ptr(&self) -> *mut bindings::task_struct {
>
> /// Returns the PID of the given task.
> pub fn pid(&self) -> Pid {
> - // SAFETY: The pid of a task never changes after initialization, so reading this field is
> - // not a data race.
> - unsafe { *ptr::addr_of!((*self.as_ptr()).pid) }
> + // SAFETY: The pid of a task almost never changes after initialization,
> + // so reading this field is usually not a data race.
> + // The exception is a race where the task is part of a process that
> + // goes through execve(), see exchange_tids().
> + // A temporary mutable pointer is created, but only actually used for
> + // a load.
> + unsafe { Atomic::from_ptr(&raw mut (*self.as_ptr()).pid).load(Relaxed) }
> }
>
> /// Returns the UID of the given task.
>
> --
> 2.53.0.273.g2a3d683680-goog
>