Skip to content

Commit aa7531b

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/ Signed-off-by: Alice Ryhl <[email protected]> Link: https://lore.kernel.org/r/[email protected]
1 parent 32547ac commit aa7531b

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
@@ -98,6 +98,15 @@ unsafe impl Sync for Task {}
9898
type Pid = bindings::pid_t;
9999

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

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

0 commit comments

Comments
 (0)