Re: rust: wrong SAFETY comments in group_leader() and pid() + questions

Oleg Nesterov
2025-12-05T17:22:00Z

On 12/05, Alice Ryhl wrote:
>
> pub fn group_leader(&self) -> &Task {
> // SAFETY: The lifetime of the returned task reference is tied to
> // the lifetime of `self`, and given that a task has a reference to
> // its group leader, we know it must be valid for the lifetime of
> // the returned task reference.
> unsafe { &*bindings::task_group_leader(self.as_ptr()).cast::<Task>() }
> }

Thanks again Alice, but the comment still looks misleading to me...
OK, quite possibly this is because I don't understand what does the
"lifetime of the returned task reference" actually mean in the rust code.
Does it mean "lifetime of task_struct" of "lifetime of the process/thread" ?

Let me provide the artificial example. Suppose we have something like

struct task_struct *TASK = NULL;

void stupid_example(void)
{
TASK = get_task_struct(current);

do_exit(0);
}

and a non-leader task calls stupid_example().

After that the global TASK pointer is still valid, it is safe to
dereference it, task_struct itself can't go away.

But! Right after that TASK->group_leader can point to nowhere (to the freed memory)
if another thread does do_group_exit() or sys_execve().

So. Perhaps the the comment should say something like

SAFETY: The lifetime of the returned task reference is tied to
the lifetime of the THREAD represented by `self`

?

Oleg.