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::{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
18/// Wrapper for `ThreadCreateVmars` to be stored in the kernel expando.
19///
20/// This is a module-private singleton used to manage VMARs for thread creation.
21struct 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    // Set the process handle to the new task's process, so the new thread is spawned in that
67    // process.
68    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    // SAFETY: thread_set_zx_create_handles only manipulates the handles for the current thread and
76    // so there is no possibility of races. The process_handle is only used for diagnostic
77    // purposes. The remaining handles are defined by ThreadCreateVmars to not be valid and not
78    // destroyed until ThreadCreateVmars is destroyed. As ThreadCreateVmars has a lifetime of the
79    // kernel, it will not be destroyed until all threads are terminated, at which point all usages
80    // and references to these handles will have ended.
81    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        // SAFETY: thrd_set_zx_create_handles only manipulates handles for the current thread and
91        // so there is no possibility of races. This is resetting to the old values that were
92        // present before our previous call to thrd_set_zx_create_handles, which must have been safe
93        // to have been set.
94        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    // Spawn the process' thread. Note, this closure ends up executing in the process referred to by
107    // `process_handle`.
108    let (sender, receiver) = sync_channel::<TaskBuilder>(1);
109    let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
110        // Note, cross-process shared resources allocated in this function that aren't freed by the
111        // Zircon kernel upon thread and/or process termination (like mappings in the shared region)
112        // should be freed using the delayed finalizer mechanism and Task drop.
113        let mut current_task: CurrentTask = receiver
114            .recv()
115            .expect("caller should always send task builder before disconnecting")
116            .into();
117
118        // We don't need the receiver anymore. If we don't drop the receiver now, we'll keep it
119        // allocated for the lifetime of the thread.
120        std::mem::drop(receiver);
121
122        let pre_run_result = { pre_run(&mut current_task) };
123        if pre_run_result.is_err() {
124            // Only log if the pre run didn't exit the task. Otherwise, consider this is expected
125            // by the caller.
126            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            // Drop the task_complete callback to ensure that the closure isn't holding any
131            // releasables.
132            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        // `release` must be called as the absolute last action on this thread to ensure that
140        // any deferred release are done before it.
141        current_task.release(());
142
143        // Ensure that no releasables are registered after this point as we unwind the stack.
144        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    // Drop the VMAR manager lock immediately after thread creation completes to avoid holding
157    // the mutex across post-spawn operations (like setting thread roles and handle duplication).
158    // Local ownership of `task_builder` guarantees that the task and its VMAR remain valid
159    // and safe from destruction or concurrent mutation throughout post-spawn setup.
160    std::mem::drop(create_vmars);
161
162    // The process thread spawned successfully. Mark the task as having spawned.
163    task_builder.task.write().set_spawned();
164
165    // Update the thread and task information before sending the task_builder to the spawned thread.
166    // This will make sure the mapping between linux tid and fuchsia koid is set before trace events
167    // are emitted from the linux code.
168
169    // Set the task's thread handle
170    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    // Now that the task has a thread handle, update the thread's role using the policy configured.
184    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    // Record the thread and process ids for tracing after the task_thread is unlocked.
189    ref_task.record_pid_koid_mapping();
190
191    // Wait to send the `TaskBuilder` to the spawned thread until we know that it
192    // spawned successfully, as we need to ensure the builder is always explicitly
193    // released.
194    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    // Gets the thread handle underlying a specific thread.
213    // In C the 'thread' parameter is thrd_t which on Fuchsia is the same as pthread_t.
214    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            // The task is not stopped.
229            assert!(!task.block_if_stopped());
230
231            // Stop the task.
232            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                    // Wait for the task to have a waiter.
243                    while !task.read().is_blocked() {
244                        std::thread::sleep(std::time::Duration::from_millis(10));
245                    }
246
247                    // Continue the task.
248                    task.thread_group().set_stopped(
249                        StopState::Waking,
250                        Some(SignalInfo::kernel(SIGCONT)),
251                        false,
252                    );
253                }
254            });
255
256            // Block until continued.
257            assert!(task.block_if_stopped());
258
259            // Join the thread, which will ensure set_stopped terminated.
260            thread.join().expect("joined");
261
262            // The task should not be blocked anymore.
263            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            // The task is neither stopped nor exited.
272            assert!(!task.block_if_stopped());
273
274            // Stop the task.
275            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                    // Wait for the task to have a waiter.
286                    while !task.read().is_blocked() {
287                        std::thread::sleep(std::time::Duration::from_millis(10));
288                    }
289
290                    // exit the task.
291                    task.thread_group().kill(ExitStatus::Exit(1), None);
292                }
293            });
294
295            // Block until continued.
296            assert!(task.block_if_stopped());
297
298            // Join the task, which will ensure thread_group.exit terminated.
299            thread.join().expect("joined");
300
301            // The task should not be blocked because it is stopped.
302            assert!(!task.block_if_stopped());
303        })
304        .await;
305    }
306}