Skip to main content

starnix_core/execution/
executor.rs

1// Copyright 2022 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use 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
20/// Wrapper for `ThreadCreateVmars` to be stored in the kernel expando.
21///
22/// This is a module-private singleton used to manage VMARs for thread creation.
23struct 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    // Set the process handle to the new task's process, so the new thread is spawned in that
74    // process.
75    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    // SAFETY: thread_set_zx_create_handles only manipulates the handles for the current thread and
83    // so there is no possibility of races. The process_handle is only used for diagnostic
84    // purposes. The remaining handles are defined by ThreadCreateVmars to not be valid and not
85    // destroyed until ThreadCreateVmars is destroyed. As ThreadCreateVmars has a lifetime of the
86    // kernel, it will not be destroyed until all threads are terminated, at which point all usages
87    // and references to these handles will have ended.
88    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        // SAFETY: thrd_set_zx_create_handles only manipulates handles for the current thread and
98        // so there is no possibility of races. This is resetting to the old values that were
99        // present before our previous call to thrd_set_zx_create_handles, which must have been safe
100        // to have been set.
101        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    // Spawn the process' thread. Note, this closure ends up executing in the process referred to by
118    // `process_handle`.
119    let (sender, receiver) = sync_channel::<TaskBuilder>(1);
120    let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
121        // It's safe to create a new lock context since we are on a new thread.
122        #[allow(
123            clippy::undocumented_unsafe_blocks,
124            reason = "Force documented unsafe blocks in Starnix"
125        )]
126        let locked = unsafe { Unlocked::new() };
127
128        // Note, cross-process shared resources allocated in this function that aren't freed by the
129        // Zircon kernel upon thread and/or process termination (like mappings in the shared region)
130        // should be freed using the delayed finalizer mechanism and Task drop.
131        let mut current_task: CurrentTask = receiver
132            .recv()
133            .expect("caller should always send task builder before disconnecting")
134            .into();
135
136        // We don't need the receiver anymore. If we don't drop the receiver now, we'll keep it
137        // allocated for the lifetime of the thread.
138        std::mem::drop(receiver);
139
140        let pre_run_result = { pre_run(locked, &mut current_task) };
141        if pre_run_result.is_err() {
142            // Only log if the pre run didn't exit the task. Otherwise, consider this is expected
143            // by the caller.
144            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            // Drop the task_complete callback to ensure that the closure isn't holding any
149            // releasables.
150            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        // `release` must be called as the absolute last action on this thread to ensure that
158        // any deferred release are done before it.
159        current_task.release(locked);
160
161        // Ensure that no releasables are registered after this point as we unwind the stack.
162        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    // The process thread spawned successfully. Mark the task as having spawned.
176    task_builder.task.write().set_spawned();
177
178    // Update the thread and task information before sending the task_builder to the spawned thread.
179    // This will make sure the mapping between linux tid and fuchsia koid is set before trace events
180    // are emitted from the linux code.
181
182    // Set the task's thread handle
183    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    // Now that the task has a thread handle, update the thread's role using the policy configured.
197    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    // Record the thread and process ids for tracing after the task_thread is unlocked.
202    ref_task.record_pid_koid_mapping();
203
204    // Wait to send the `TaskBuilder` to the spawned thread until we know that it
205    // spawned successfully, as we need to ensure the builder is always explicitly
206    // released.
207    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    // Gets the thread handle underlying a specific thread.
226    // In C the 'thread' parameter is thrd_t which on Fuchsia is the same as pthread_t.
227    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            // The task is not stopped.
242            assert!(!task.block_if_stopped(locked));
243
244            // Stop the task.
245            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                    // Wait for the task to have a waiter.
256                    while !task.read().is_blocked() {
257                        std::thread::sleep(std::time::Duration::from_millis(10));
258                    }
259
260                    // Continue the task.
261                    task.thread_group().set_stopped(
262                        StopState::Waking,
263                        Some(SignalInfo::kernel(SIGCONT)),
264                        false,
265                    );
266                }
267            });
268
269            // Block until continued.
270            assert!(task.block_if_stopped(locked));
271
272            // Join the thread, which will ensure set_stopped terminated.
273            thread.join().expect("joined");
274
275            // The task should not be blocked anymore.
276            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            // The task is neither stopped nor exited.
285            assert!(!task.block_if_stopped(locked));
286
287            // Stop the task.
288            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                    // Wait for the task to have a waiter.
304                    while !task.read().is_blocked() {
305                        std::thread::sleep(std::time::Duration::from_millis(10));
306                    }
307
308                    // exit the task.
309                    task.thread_group().kill(locked, ExitStatus::Exit(1), None);
310                }
311            });
312
313            // Block until continued.
314            assert!(task.block_if_stopped(locked));
315
316            // Join the task, which will ensure thread_group.exit terminated.
317            thread.join().expect("joined");
318
319            // The task should not be blocked because it is stopped.
320            assert!(!task.block_if_stopped(locked));
321        })
322        .await;
323    }
324}