1use 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, Mutex, 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;
17use thread_create_vmars::ThreadCreateVmars;
18
19struct ExecutorVmarManager(Mutex<ThreadCreateVmars>);
23
24pub fn execute_task_with_prerun_result<L, F, R, G>(
25 locked: &mut Locked<L>,
26 task_builder: TaskBuilder,
27 pre_run: F,
28 task_complete: G,
29 ptrace_state: Option<PtraceCoreState>,
30) -> Result<R, Errno>
31where
32 L: LockBefore<TaskRelease>,
33 F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<R, Errno> + Send + Sync + 'static,
34 R: Send + Sync + 'static,
35 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
36{
37 let (sender, receiver) = sync_channel::<Result<R, Errno>>(1);
38 execute_task(
39 locked,
40 task_builder,
41 move |current_task, locked| match pre_run(current_task, locked) {
42 Err(errno) => {
43 let _ = sender.send(Err(errno.clone()));
44 Err(errno)
45 }
46 Ok(value) => sender.send(Ok(value)).map_err(|error| {
47 log_error!("Unable to send `pre_run` result: {error:?}");
48 errno!(EINVAL)
49 }),
50 },
51 task_complete,
52 ptrace_state,
53 )?;
54 receiver.recv().map_err(|e| {
55 log_error!("Unable to retrieve result from `pre_run`: {e:?}");
56 errno!(EINVAL)
57 })?
58}
59
60pub fn execute_task<L, F, G>(
61 locked: &mut Locked<L>,
62 task_builder: TaskBuilder,
63 pre_run: F,
64 task_complete: G,
65 ptrace_state: Option<PtraceCoreState>,
66) -> Result<(), Errno>
67where
68 L: LockBefore<TaskRelease>,
69 F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<(), Errno> + Send + Sync + 'static,
70 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
71{
72 let process_handle = task_builder.task.thread_group().process.raw_handle();
75
76 let kernel = task_builder.task.kernel();
77 let create_vmars =
78 kernel.expando.get_or_init(|| ExecutorVmarManager(Mutex::new(ThreadCreateVmars::new())));
79 let mut create_vmars = create_vmars.0.lock();
80
81 let old_handles = unsafe {
88 thrd_set_zx_create_handles(thrd_zx_create_handles {
89 process: process_handle,
90 machine_stack_vmar: create_vmars.machine_stack.probe()?.raw_handle(),
91 security_stack_vmar: create_vmars.security_stack.probe()?.raw_handle(),
92 thread_block_vmar: create_vmars.thread_block.probe()?.raw_handle(),
93 })
94 };
95 scopeguard::defer! {
96 unsafe {
101 thrd_set_zx_create_handles(old_handles);
102 };
103 };
104
105 let weak_task = WeakRef::from(&task_builder.task);
106 let ref_task = weak_task.upgrade().unwrap();
107 if let Some(ptrace_state) = ptrace_state {
108 let _ = ptrace_attach_from_state(
109 locked.cast_locked::<TaskRelease>(),
110 &task_builder.task,
111 ptrace_state,
112 );
113 }
114
115 let mut task_thread_guard = ref_task.thread.write();
117
118 let (sender, receiver) = sync_channel::<TaskBuilder>(1);
121 let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
122 #[allow(
124 clippy::undocumented_unsafe_blocks,
125 reason = "Force documented unsafe blocks in Starnix"
126 )]
127 let locked = unsafe { Unlocked::new() };
128
129 let mut current_task: CurrentTask = receiver
133 .recv()
134 .expect("caller should always send task builder before disconnecting")
135 .into();
136
137 std::mem::drop(receiver);
140
141 let pre_run_result = { pre_run(locked, &mut current_task) };
142 if pre_run_result.is_err() {
143 if current_task.exit_status().is_none() {
146 log_error!("Pre run failed from {pre_run_result:?}. The task will not be run.");
147 }
148
149 std::mem::drop(task_complete);
152 } else {
153 let exit_status = enter_syscall_loop(locked, &mut current_task);
154 current_task.write().set_exit_status(exit_status.clone());
155 task_complete(Ok(exit_status));
156 }
157
158 current_task.release(locked);
161
162 DelayedReleaser::finalize();
164 });
165 let join_handle = match result {
166 Ok(handle) => handle,
167 Err(e) => {
168 task_builder.release(locked);
169 match e.kind() {
170 std::io::ErrorKind::WouldBlock => return error!(EAGAIN),
171 other => panic!("unexpected error on thread spawn: {other}"),
172 }
173 }
174 };
175
176 let pthread = join_handle.as_pthread_t();
182 #[allow(
183 clippy::undocumented_unsafe_blocks,
184 reason = "Force documented unsafe blocks in Starnix"
185 )]
186 let raw_thread_handle =
187 unsafe { zx::Unowned::<'_, zx::Thread>::from_raw_handle(thrd_get_zx_handle(pthread)) };
188 *task_thread_guard = Some(Arc::new(
189 raw_thread_handle
190 .duplicate(zx::Rights::SAME_RIGHTS)
191 .expect("must have RIGHT_DUPLICATE on handle we created"),
192 ));
193 drop(task_thread_guard);
195 if let Err(err) = ref_task.sync_scheduler_state_to_role() {
196 log_warn!(err:?; "Couldn't update freshly spawned thread's profile.");
197 }
198
199 ref_task.record_pid_koid_mapping();
201
202 sender
206 .send(task_builder)
207 .expect("receiver should not be disconnected because thread spawned successfully");
208
209 Ok(())
210}
211
212#[repr(C)]
213#[derive(Debug)]
214pub struct thrd_zx_create_handles {
215 pub process: zx::sys::zx_handle_t,
216 pub machine_stack_vmar: zx::sys::zx_handle_t,
217 pub security_stack_vmar: zx::sys::zx_handle_t,
218 pub thread_block_vmar: zx::sys::zx_handle_t,
219}
220unsafe extern "C" {
221 fn thrd_set_zx_create_handles(handles: thrd_zx_create_handles) -> thrd_zx_create_handles;
222
223 fn thrd_get_zx_handle(thread: u64) -> zx::sys::zx_handle_t;
226}
227
228#[cfg(test)]
229mod tests {
230 use super::*;
231 use crate::ptrace::StopState;
232 use crate::signals::SignalInfo;
233 use crate::testing::*;
234 use starnix_uapi::signals::{SIGCONT, SIGSTOP};
235
236 #[::fuchsia::test]
237 async fn test_block_while_stopped_stop_and_continue() {
238 spawn_kernel_and_run(async |locked, task| {
239 task.block_while_stopped(locked);
241
242 task.thread_group().set_stopped(
244 StopState::GroupStopping,
245 Some(SignalInfo::kernel(SIGSTOP)),
246 false,
247 );
248
249 let thread = std::thread::spawn({
250 let task = task.weak_task();
251 move || {
252 let task = task.upgrade().expect("task must be alive");
253 while !task.read().is_blocked() {
255 std::thread::sleep(std::time::Duration::from_millis(10));
256 }
257
258 task.thread_group().set_stopped(
260 StopState::Waking,
261 Some(SignalInfo::kernel(SIGCONT)),
262 false,
263 );
264 }
265 });
266
267 task.block_while_stopped(locked);
269
270 thread.join().expect("joined");
272
273 task.block_while_stopped(locked);
275 })
276 .await;
277 }
278
279 #[::fuchsia::test]
280 async fn test_block_while_stopped_stop_and_exit() {
281 spawn_kernel_and_run(async |locked, task| {
282 task.block_while_stopped(locked);
284
285 task.thread_group().set_stopped(
287 StopState::GroupStopping,
288 Some(SignalInfo::kernel(SIGSTOP)),
289 false,
290 );
291
292 let thread = std::thread::spawn({
293 let task = task.weak_task();
294 move || {
295 #[allow(
296 clippy::undocumented_unsafe_blocks,
297 reason = "Force documented unsafe blocks in Starnix"
298 )]
299 let locked = unsafe { Unlocked::new() };
300 let task = task.upgrade().expect("task must be alive");
301 while !task.read().is_blocked() {
303 std::thread::sleep(std::time::Duration::from_millis(10));
304 }
305
306 task.thread_group().exit(locked, ExitStatus::Exit(1), None);
308 }
309 });
310
311 task.block_while_stopped(locked);
313
314 thread.join().expect("joined");
316
317 task.block_while_stopped(locked);
319 })
320 .await;
321 }
322}