1use crate::execution::loop_entry::enter_syscall_loop;
6use crate::ptrace::{PtraceCoreState, ptrace_attach_from_state};
7use crate::task::{CurrentTask, DelayedReleaser, ExitStatus, TaskBuilder, ZirconThread};
8use anyhow::Error;
9use starnix_logging::{log_error, log_warn};
10use starnix_sync::{
11 ExecutorVmarManagerLock, LockBefore, LockDepMutex, Locked, TaskRelease, Unlocked,
12};
13use starnix_uapi::errors::Errno;
14use starnix_uapi::{errno, error};
15use std::os::unix::thread::JoinHandleExt;
16use std::sync::Arc;
17use std::sync::mpsc::sync_channel;
18use thread_create_vmars::ThreadCreateVmars;
19
20struct ExecutorVmarManager(LockDepMutex<ThreadCreateVmars, ExecutorVmarManagerLock>);
24
25pub fn execute_task_with_prerun_result<L, F, R, G>(
26 locked: &mut Locked<L>,
27 task_builder: TaskBuilder,
28 pre_run: F,
29 task_complete: G,
30 ptrace_state: Option<PtraceCoreState>,
31) -> Result<R, Errno>
32where
33 L: LockBefore<TaskRelease>,
34 F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<R, Errno> + Send + Sync + 'static,
35 R: Send + Sync + 'static,
36 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
37{
38 let (sender, receiver) = sync_channel::<Result<R, Errno>>(1);
39 execute_task(
40 locked,
41 task_builder,
42 move |current_task, locked| match pre_run(current_task, locked) {
43 Err(errno) => {
44 let _ = sender.send(Err(errno.clone()));
45 Err(errno)
46 }
47 Ok(value) => sender.send(Ok(value)).map_err(|error| {
48 log_error!("Unable to send `pre_run` result: {error:?}");
49 errno!(EINVAL)
50 }),
51 },
52 task_complete,
53 ptrace_state,
54 )?;
55 receiver.recv().map_err(|e| {
56 log_error!("Unable to retrieve result from `pre_run`: {e:?}");
57 errno!(EINVAL)
58 })?
59}
60
61pub fn execute_task<L, F, G>(
62 locked: &mut Locked<L>,
63 task_builder: TaskBuilder,
64 pre_run: F,
65 task_complete: G,
66 ptrace_state: Option<PtraceCoreState>,
67) -> Result<(), Errno>
68where
69 L: LockBefore<TaskRelease>,
70 F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<(), Errno> + Send + Sync + 'static,
71 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
72{
73 let process_handle = task_builder.task.thread_group().process.raw_handle();
76
77 let kernel = task_builder.task.kernel();
78 let create_vmars =
79 kernel.expando.get_or_init(|| ExecutorVmarManager(ThreadCreateVmars::new().into()));
80 let mut create_vmars = create_vmars.0.lock();
81
82 let old_handles = unsafe {
89 thrd_set_zx_create_handles(thrd_zx_create_handles {
90 process: process_handle,
91 machine_stack_vmar: create_vmars.machine_stack.probe()?.raw_handle(),
92 security_stack_vmar: create_vmars.security_stack.probe()?.raw_handle(),
93 thread_block_vmar: create_vmars.thread_block.probe()?.raw_handle(),
94 })
95 };
96 scopeguard::defer! {
97 unsafe {
102 thrd_set_zx_create_handles(old_handles);
103 };
104 };
105
106 if let Some(ptrace_state) = ptrace_state {
107 let _ = ptrace_attach_from_state(
108 locked.cast_locked::<TaskRelease>(),
109 &task_builder.task,
110 ptrace_state,
111 );
112 }
113
114 let ref_task = Arc::clone(&task_builder.task);
115 let running_state = ref_task.running_state().unwrap();
116
117 let (sender, receiver) = sync_channel::<TaskBuilder>(1);
120 let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
121 #[allow(
123 clippy::undocumented_unsafe_blocks,
124 reason = "Force documented unsafe blocks in Starnix"
125 )]
126 let locked = unsafe { Unlocked::new() };
127
128 let mut current_task: CurrentTask = receiver
132 .recv()
133 .expect("caller should always send task builder before disconnecting")
134 .into();
135
136 std::mem::drop(receiver);
139
140 let pre_run_result = { pre_run(locked, &mut current_task) };
141 if pre_run_result.is_err() {
142 if current_task.exit_status().is_none() {
145 log_error!("Pre run failed from {pre_run_result:?}. The task will not be run.");
146 }
147
148 std::mem::drop(task_complete);
151 } else {
152 let exit_status = enter_syscall_loop(locked, &mut current_task);
153 current_task.write().set_exit_status(exit_status.clone());
154 task_complete(Ok(exit_status));
155 }
156
157 current_task.release(locked);
160
161 DelayedReleaser::finalize();
163 });
164 let join_handle = match result {
165 Ok(handle) => handle,
166 Err(e) => {
167 task_builder.release(locked);
168 match e.kind() {
169 std::io::ErrorKind::WouldBlock => return error!(EAGAIN),
170 other => panic!("unexpected error on thread spawn: {other}"),
171 }
172 }
173 };
174
175 task_builder.task.write().set_spawned();
177
178 let pthread = join_handle.as_pthread_t();
184 #[allow(
185 clippy::undocumented_unsafe_blocks,
186 reason = "Force documented unsafe blocks in Starnix"
187 )]
188 let raw_thread_handle =
189 unsafe { zx::Unowned::<'_, zx::Thread>::from_raw_handle(thrd_get_zx_handle(pthread)) };
190 let thread = Arc::new(
191 raw_thread_handle
192 .duplicate_handle(zx::Rights::SAME_RIGHTS)
193 .expect("must have RIGHT_DUPLICATE on handle we created"),
194 );
195 running_state.thread.set(ZirconThread::new(thread)).expect("thread should only be set once");
196 if let Err(err) = ref_task.sync_scheduler_state_to_role() {
198 log_warn!(err:?; "Couldn't update freshly spawned thread's profile.");
199 }
200
201 ref_task.record_pid_koid_mapping();
203
204 sender
208 .send(task_builder)
209 .expect("receiver should not be disconnected because thread spawned successfully");
210
211 Ok(())
212}
213
214#[repr(C)]
215#[derive(Debug)]
216pub struct thrd_zx_create_handles {
217 pub process: zx::sys::zx_handle_t,
218 pub machine_stack_vmar: zx::sys::zx_handle_t,
219 pub security_stack_vmar: zx::sys::zx_handle_t,
220 pub thread_block_vmar: zx::sys::zx_handle_t,
221}
222unsafe extern "C" {
223 fn thrd_set_zx_create_handles(handles: thrd_zx_create_handles) -> thrd_zx_create_handles;
224
225 fn thrd_get_zx_handle(thread: u64) -> zx::sys::zx_handle_t;
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use crate::ptrace::StopState;
234 use crate::signals::SignalInfo;
235 use crate::testing::*;
236 use starnix_uapi::signals::{SIGCONT, SIGSTOP};
237
238 #[::fuchsia::test]
239 async fn test_block_if_stopped_stop_and_continue() {
240 spawn_kernel_and_run(async |locked, task| {
241 assert!(!task.block_if_stopped(locked));
243
244 task.thread_group().set_stopped(
246 StopState::GroupStopping,
247 Some(SignalInfo::kernel(SIGSTOP)),
248 false,
249 );
250
251 let thread = std::thread::spawn({
252 let task = task.weak_task();
253 move || {
254 let task = task.upgrade().expect("task must be alive");
255 while !task.read().is_blocked() {
257 std::thread::sleep(std::time::Duration::from_millis(10));
258 }
259
260 task.thread_group().set_stopped(
262 StopState::Waking,
263 Some(SignalInfo::kernel(SIGCONT)),
264 false,
265 );
266 }
267 });
268
269 assert!(task.block_if_stopped(locked));
271
272 thread.join().expect("joined");
274
275 assert!(!task.block_if_stopped(locked));
277 })
278 .await;
279 }
280
281 #[::fuchsia::test]
282 async fn test_block_if_stopped_stop_and_exit() {
283 spawn_kernel_and_run(async |locked, task| {
284 assert!(!task.block_if_stopped(locked));
286
287 task.thread_group().set_stopped(
289 StopState::GroupStopping,
290 Some(SignalInfo::kernel(SIGSTOP)),
291 false,
292 );
293
294 let thread = std::thread::spawn({
295 let task = task.weak_task();
296 move || {
297 #[allow(
298 clippy::undocumented_unsafe_blocks,
299 reason = "Force documented unsafe blocks in Starnix"
300 )]
301 let locked = unsafe { Unlocked::new() };
302 let task = task.upgrade().expect("task must be alive");
303 while !task.read().is_blocked() {
305 std::thread::sleep(std::time::Duration::from_millis(10));
306 }
307
308 task.thread_group().kill(locked, ExitStatus::Exit(1), None);
310 }
311 });
312
313 assert!(task.block_if_stopped(locked));
315
316 thread.join().expect("joined");
318
319 assert!(!task.block_if_stopped(locked));
321 })
322 .await;
323 }
324}