Skip to content

Commit 872702d

Browse files
Darksonnfbq
authored andcommitted
rust: task: add Task::current_raw
Introduces a safe function for getting a raw pointer to the current task. When writing bindings that need to access the current task, it is often more convenient to call a method that directly returns a raw pointer than to use the existing `Task::current` method. However, the only way to do that is `bindings::get_current()` which is unsafe since it calls into C. By introducing `Task::current_raw()`, it becomes possible to obtain a pointer to the current task without using unsafe. Link: https://lore.kernel.org/all/CAH5fLgjT48X-zYtidv31mox3C4_Ogoo_2cBOCmX0Ang3tAgGHA@mail.gmail.com/ Reviewed-by: Benno Lossin <benno.lossin@proton.me> Reviewed-by: Martin Rodriguez Reboredo <yakoyoku@gmail.com> Reviewed-by: Trevor Gross <tmgross@umich.edu> Signed-off-by: Alice Ryhl <aliceryhl@google.com> Link: https://lore.kernel.org/r/20240628-alice-file-v7-2-4d701f6335f3@google.com
1 parent 9695c1e commit 872702d

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

rust/kernel/task.rs

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,15 @@ unsafe impl Sync for Task {}
9797
type Pid = bindings::pid_t;
9898

9999
impl Task {
100+
/// Returns a raw pointer to the current task.
101+
///
102+
/// It is up to the user to use the pointer correctly.
103+
#[inline]
104+
pub fn current_raw() -> *mut bindings::task_struct {
105+
// SAFETY: Getting the current pointer is always safe.
106+
unsafe { bindings::get_current() }
107+
}
108+
100109
/// Returns a task reference for the currently executing task/thread.
101110
///
102111
/// The recommended way to get the current task/thread is to use the
@@ -119,14 +128,12 @@ impl Task {
119128
}
120129
}
121130

122-
// SAFETY: Just an FFI call with no additional safety requirements.
123-
let ptr = unsafe { bindings::get_current() };
124-
131+
let current = Task::current_raw();
125132
TaskRef {
126133
// SAFETY: If the current thread is still running, the current task is valid. Given
127134
// that `TaskRef` is not `Send`, we know it cannot be transferred to another thread
128135
// (where it could potentially outlive the caller).
129-
task: unsafe { &*ptr.cast() },
136+
task: unsafe { &*current.cast() },
130137
_not_send: NotThreadSafe,
131138
}
132139
}

0 commit comments

Comments
 (0)