starnix_core/execution/
executor.rs1use crate::execution::loop_entry::enter_syscall_loop;
6use crate::ptrace::{PtraceCoreState, ptrace_attach_from_state};
7use crate::task::{CurrentTask, DelayedReleaser, ExitStatus, TaskBuilder};
8use anyhow::Error;
9use starnix_logging::{log_error, log_warn};
10use starnix_sync::{LockBefore, Locked, TaskRelease, Unlocked};
11use starnix_types::ownership::WeakRef;
12use starnix_uapi::errors::Errno;
13use starnix_uapi::{errno, error};
14use std::os::unix::thread::JoinHandleExt;
15use std::sync::Arc;
16use std::sync::mpsc::sync_channel;
17
18pub fn execute_task_with_prerun_result<L, F, R, G>(
19 locked: &mut Locked<L>,
20 task_builder: TaskBuilder,
21 pre_run: F,
22 task_complete: G,
23 ptrace_state: Option<PtraceCoreState>,
24) -> Result<R, Errno>
25where
26 L: LockBefore<TaskRelease>,
27 F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<R, Errno> + Send + Sync + 'static,
28 R: Send + Sync + 'static,
29 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
30{
31 let (sender, receiver) = sync_channel::<Result<R, Errno>>(1);
32 execute_task(
33 locked,
34 task_builder,
35 move |current_task, locked| match pre_run(current_task, locked) {
36 Err(errno) => {
37 let _ = sender.send(Err(errno.clone()));
38 Err(errno)
39 }
40 Ok(value) => sender.send(Ok(value)).map_err(|error| {
41 log_error!("Unable to send `pre_run` result: {error:?}");
42 errno!(EINVAL)
43 }),
44 },
45 task_complete,
46 ptrace_state,
47 )?;
48 receiver.recv().map_err(|e| {
49 log_error!("Unable to retrieve result from `pre_run`: {e:?}");
50 errno!(EINVAL)
51 })?
52}
53
54pub fn execute_task<L, F, G>(
55 locked: &mut Locked<L>,
56 task_builder: TaskBuilder,
57 pre_run: F,
58 task_complete: G,
59 ptrace_state: Option<PtraceCoreState>,
60) -> Result<(), Errno>
61where
62 L: LockBefore<TaskRelease>,
63 F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<(), Errno> + Send + Sync + 'static,
64 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
65{
66 let process_handle = task_builder.task.thread_group().process.raw_handle();
69 let old_process_handle = unsafe { thrd_set_zx_process(process_handle) };
72 scopeguard::defer! {
73 unsafe {
76 thrd_set_zx_process(old_process_handle);
77 };
78 };
79
80 let weak_task = WeakRef::from(&task_builder.task);
81 let ref_task = weak_task.upgrade().unwrap();
82 if let Some(ptrace_state) = ptrace_state {
83 let _ = ptrace_attach_from_state(
84 locked.cast_locked::<TaskRelease>(),
85 &task_builder.task,
86 ptrace_state,
87 );
88 }
89
90 let mut task_thread_guard = ref_task.thread.write();
92
93 let (sender, receiver) = sync_channel::<TaskBuilder>(1);
96 let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
97 #[allow(
99 clippy::undocumented_unsafe_blocks,
100 reason = "Force documented unsafe blocks in Starnix"
101 )]
102 let locked = unsafe { Unlocked::new() };
103
104 let mut current_task: CurrentTask = receiver
108 .recv()
109 .expect("caller should always send task builder before disconnecting")
110 .into();
111
112 std::mem::drop(receiver);
115
116 let pre_run_result = { pre_run(locked, &mut current_task) };
117 if pre_run_result.is_err() {
118 if current_task.exit_status().is_none() {
121 log_error!("Pre run failed from {pre_run_result:?}. The task will not be run.");
122 }
123
124 std::mem::drop(task_complete);
127 } else {
128 let exit_status = enter_syscall_loop(locked, &mut current_task);
129 current_task.write().set_exit_status(exit_status.clone());
130 task_complete(Ok(exit_status));
131 }
132
133 current_task.release(locked);
136
137 DelayedReleaser::finalize();
139 });
140 let join_handle = match result {
141 Ok(handle) => handle,
142 Err(e) => {
143 task_builder.release(locked);
144 match e.kind() {
145 std::io::ErrorKind::WouldBlock => return error!(EAGAIN),
146 other => panic!("unexpected error on thread spawn: {other}"),
147 }
148 }
149 };
150
151 let pthread = join_handle.as_pthread_t();
157 #[allow(
158 clippy::undocumented_unsafe_blocks,
159 reason = "Force documented unsafe blocks in Starnix"
160 )]
161 let raw_thread_handle =
162 unsafe { zx::Unowned::<'_, zx::Thread>::from_raw_handle(thrd_get_zx_handle(pthread)) };
163 *task_thread_guard = Some(Arc::new(
164 raw_thread_handle
165 .duplicate(zx::Rights::SAME_RIGHTS)
166 .expect("must have RIGHT_DUPLICATE on handle we created"),
167 ));
168 drop(task_thread_guard);
170 if let Err(err) = ref_task.sync_scheduler_state_to_role() {
171 log_warn!(err:?; "Couldn't update freshly spawned thread's profile.");
172 }
173
174 ref_task.record_pid_koid_mapping();
176
177 sender
181 .send(task_builder)
182 .expect("receiver should not be disconnected because thread spawned successfully");
183
184 Ok(())
185}
186
187unsafe extern "C" {
188 fn thrd_set_zx_process(handle: zx::sys::zx_handle_t) -> zx::sys::zx_handle_t;
190
191 fn thrd_get_zx_handle(thread: u64) -> zx::sys::zx_handle_t;
194}
195
196#[cfg(test)]
197mod tests {
198 use super::*;
199 use crate::ptrace::StopState;
200 use crate::signals::SignalInfo;
201 use crate::testing::*;
202 use starnix_uapi::signals::{SIGCONT, SIGSTOP};
203
204 #[::fuchsia::test]
205 async fn test_block_while_stopped_stop_and_continue() {
206 spawn_kernel_and_run(async |locked, task| {
207 task.block_while_stopped(locked);
209
210 task.thread_group().set_stopped(
212 StopState::GroupStopping,
213 Some(SignalInfo::default(SIGSTOP)),
214 false,
215 );
216
217 let thread = std::thread::spawn({
218 let task = task.weak_task();
219 move || {
220 let task = task.upgrade().expect("task must be alive");
221 while !task.read().is_blocked() {
223 std::thread::sleep(std::time::Duration::from_millis(10));
224 }
225
226 task.thread_group().set_stopped(
228 StopState::Waking,
229 Some(SignalInfo::default(SIGCONT)),
230 false,
231 );
232 }
233 });
234
235 task.block_while_stopped(locked);
237
238 thread.join().expect("joined");
240
241 task.block_while_stopped(locked);
243 })
244 .await;
245 }
246
247 #[::fuchsia::test]
248 async fn test_block_while_stopped_stop_and_exit() {
249 spawn_kernel_and_run(async |locked, task| {
250 task.block_while_stopped(locked);
252
253 task.thread_group().set_stopped(
255 StopState::GroupStopping,
256 Some(SignalInfo::default(SIGSTOP)),
257 false,
258 );
259
260 let thread = std::thread::spawn({
261 let task = task.weak_task();
262 move || {
263 #[allow(
264 clippy::undocumented_unsafe_blocks,
265 reason = "Force documented unsafe blocks in Starnix"
266 )]
267 let locked = unsafe { Unlocked::new() };
268 let task = task.upgrade().expect("task must be alive");
269 while !task.read().is_blocked() {
271 std::thread::sleep(std::time::Duration::from_millis(10));
272 }
273
274 task.thread_group().exit(locked, ExitStatus::Exit(1), None);
276 }
277 });
278
279 task.block_while_stopped(locked);
281
282 thread.join().expect("joined");
284
285 task.block_while_stopped(locked);
287 })
288 .await;
289 }
290}