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

From: Jann Horn

Date: Thu Feb 12 2026 - 17:12:29 EST


(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>
---
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