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, ZirconThread};
8use anyhow::Error;
9use starnix_logging::{log_error, log_warn};
10use starnix_sync::{ExecutorVmarManagerLock, LockDepMutex};
11use starnix_uapi::errors::Errno;
12use starnix_uapi::{errno, error};
13use std::os::unix::thread::JoinHandleExt;
14use std::sync::Arc;
15use std::sync::mpsc::sync_channel;
16use thread_create_vmars::ThreadCreateVmars;
17
18struct ExecutorVmarManager(LockDepMutex<ThreadCreateVmars, ExecutorVmarManagerLock>);
22
23pub fn execute_task_with_prerun_result<F, R, G>(
24 task_builder: TaskBuilder,
25 pre_run: F,
26 task_complete: G,
27 ptrace_state: Option<PtraceCoreState>,
28) -> Result<R, Errno>
29where
30 F: FnOnce(&mut CurrentTask) -> Result<R, Errno> + Send + Sync + 'static,
31 R: Send + Sync + 'static,
32 G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
33{
34 let (sender, receiver) = sync_channel::<Result<R, Errno>>(1);
35 execute_task(
36 task_builder,
37 move |current_task| match pre_run(current_task) {
38 Err(errno) => {
39 let _ = sender.send(Err(errno.clone()));
40 Err(errno)
41 }
42 Ok(value) => sender.send(Ok(value)).map_err(|error| {
43 log_error!("Unable to send `pre_run` result: {error:?}");
44 errno!(EINVAL)
45 }),
46 },
47 task_complete,
48 ptrace_state,
49 )?;
50 receiver.recv().map_err(|e| {
51 log_error!("Unable to retrieve result from `pre_run`: {e:?}");
52 errno!(EINVAL)
53 })?
54}
55
56pub fn execute_task<F, G>(
57 task_builder: TaskBuilder,
58 pre_run: F,
59 task_complete: G,
60 ptrace_state: Option<PtraceCoreState>,
61) -> Result<(), Errno>
62where
63 F: FnOnce(&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
70 let kernel = task_builder.task.kernel();
71 let create_vmars =
72 kernel.expando.get_or_init(|| ExecutorVmarManager(ThreadCreateVmars::new().into()));
73 let mut create_vmars = create_vmars.0.lock();
74
75 let old_handles = unsafe {
82 thrd_set_zx_create_handles(thrd_zx_create_handles {
83 process: process_handle,
84 machine_stack_vmar: create_vmars.machine_stack.probe()?.raw_handle(),
85 security_stack_vmar: create_vmars.security_stack.probe()?.raw_handle(),
86 thread_block_vmar: create_vmars.thread_block.probe()?.raw_handle(),
87 })
88 };
89 scopeguard::defer! {
90 unsafe {
95 thrd_set_zx_create_handles(old_handles);
96 };
97 };
98
99 if let Some(ptrace_state) = ptrace_state {
100 let _ = ptrace_attach_from_state(&task_builder.task, ptrace_state);
101 }
102
103 let ref_task = Arc::clone(&task_builder.task);
104 let running_state = ref_task.running_state().unwrap();
105
106 let (sender, receiver) = sync_channel::<TaskBuilder>(1);
109 let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
110 let mut current_task: CurrentTask = receiver
114 .recv()
115 .expect("caller should always send task builder before disconnecting")
116 .into();
117
118 std::mem::drop(receiver);
121
122 let pre_run_result = { pre_run(&mut current_task) };
123 if pre_run_result.is_err() {
124 if current_task.exit_status().is_none() {
127 log_error!("Pre run failed from {pre_run_result:?}. The task will not be run.");
128 }
129
130 std::mem::drop(task_complete);
133 } else {
134 let exit_status = enter_syscall_loop(&mut current_task);
135 current_task.write().set_exit_status(exit_status.clone());
136 task_complete(Ok(exit_status));
137 }
138
139 current_task.release(());
142
143 DelayedReleaser::finalize();
145 });
146 let join_handle = match result {
147 Ok(handle) => handle,
148 Err(e) => {
149 task_builder.release(());
150 match e.kind() {
151 std::io::ErrorKind::WouldBlock => return error!(EAGAIN),
152 other => panic!("unexpected error on thread spawn: {other}"),
153 }
154 }
155 };
156 std::mem::drop(create_vmars);
161
162 task_builder.task.write().set_spawned();
164
165 let pthread = join_handle.as_pthread_t();
171 #[allow(
172 clippy::undocumented_unsafe_blocks,
173 reason = "Force documented unsafe blocks in Starnix"
174 )]
175 let raw_thread_handle =
176 unsafe { zx::Unowned::<'_, zx::Thread>::from_raw_handle(thrd_get_zx_handle(pthread)) };
177 let thread = Arc::new(
178 raw_thread_handle
179 .duplicate_handle(zx::Rights::SAME_RIGHTS)
180 .expect("must have RIGHT_DUPLICATE on handle we created"),
181 );
182 running_state.thread.set(ZirconThread::new(thread)).expect("thread should only be set once");
183 if let Err(err) = ref_task.sync_scheduler_state_to_role() {
185 log_warn!(err:?; "Couldn't update freshly spawned thread's profile.");
186 }
187
188 ref_task.record_pid_koid_mapping();
190
191 sender
195 .send(task_builder)
196 .expect("receiver should not be disconnected because thread spawned successfully");
197
198 Ok(())
199}
200
201#[repr(C)]
202#[derive(Debug)]
203pub struct thrd_zx_create_handles {
204 pub process: zx::sys::zx_handle_t,
205 pub machine_stack_vmar: zx::sys::zx_handle_t,
206 pub security_stack_vmar: zx::sys::zx_handle_t,
207 pub thread_block_vmar: zx::sys::zx_handle_t,
208}
209unsafe extern "C" {
210 fn thrd_set_zx_create_handles(handles: thrd_zx_create_handles) -> thrd_zx_create_handles;
211
212 fn thrd_get_zx_handle(thread: u64) -> zx::sys::zx_handle_t;
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220 use crate::ptrace::StopState;
221 use crate::signals::SignalInfo;
222 use crate::testing::*;
223 use starnix_uapi::signals::{SIGCONT, SIGSTOP};
224
225 #[::fuchsia::test]
226 async fn test_block_if_stopped_stop_and_continue() {
227 spawn_kernel_and_run(async |task| {
228 assert!(!task.block_if_stopped());
230
231 task.thread_group().set_stopped(
233 StopState::GroupStopping,
234 Some(SignalInfo::kernel(SIGSTOP)),
235 false,
236 );
237
238 let thread = std::thread::spawn({
239 let task = task.weak_task();
240 move || {
241 let task = task.upgrade().expect("task must be alive");
242 while !task.read().is_blocked() {
244 std::thread::sleep(std::time::Duration::from_millis(10));
245 }
246
247 task.thread_group().set_stopped(
249 StopState::Waking,
250 Some(SignalInfo::kernel(SIGCONT)),
251 false,
252 );
253 }
254 });
255
256 assert!(task.block_if_stopped());
258
259 thread.join().expect("joined");
261
262 assert!(!task.block_if_stopped());
264 })
265 .await;
266 }
267
268 #[::fuchsia::test]
269 async fn test_block_if_stopped_stop_and_exit() {
270 spawn_kernel_and_run(async |task| {
271 assert!(!task.block_if_stopped());
273
274 task.thread_group().set_stopped(
276 StopState::GroupStopping,
277 Some(SignalInfo::kernel(SIGSTOP)),
278 false,
279 );
280
281 let thread = std::thread::spawn({
282 let task = task.weak_task();
283 move || {
284 let task = task.upgrade().expect("task must be alive");
285 while !task.read().is_blocked() {
287 std::thread::sleep(std::time::Duration::from_millis(10));
288 }
289
290 task.thread_group().kill(ExitStatus::Exit(1), None);
292 }
293 });
294
295 assert!(task.block_if_stopped());
297
298 thread.join().expect("joined");
300
301 assert!(!task.block_if_stopped());
303 })
304 .await;
305 }
306}