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};
8use anyhow::Error;
9use starnix_logging::{log_error, log_warn};
10use starnix_sync::{LockBefore, Locked, 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;
17
18pub fn execute_task_with_prerun_result<L, F, R, G>(
19    locked: &mut Locked<L>,
20    task_builder: TaskBuilder,
21    pre_run: F,
22    task_complete: G,
23    ptrace_state: Option<PtraceCoreState>,
24) -> Result<R, Errno>
25where
26    L: LockBefore<TaskRelease>,
27    F: FnOnce(&mut Locked<Unlocked>, &mut CurrentTask) -> Result<R, Errno> + Send + Sync + 'static,
28    R: Send + Sync + 'static,
29    G: FnOnce(Result<ExitStatus, Error>) + Send + Sync + 'static,
30{
31    let (sender, receiver) = sync_channel::<Result<R, Errno>>(1);
32    execute_task(
33        locked,
34        task_builder,
35        move |current_task, locked| match pre_run(current_task, locked) {
36            Err(errno) => {
37                let _ = sender.send(Err(errno.clone()));
38                Err(errno)
39            }
40            Ok(value) => sender.send(Ok(value)).map_err(|error| {
41                log_error!("Unable to send `pre_run` result: {error:?}");
42                errno!(EINVAL)
43            }),
44        },
45        task_complete,
46        ptrace_state,
47    )?;
48    receiver.recv().map_err(|e| {
49        log_error!("Unable to retrieve result from `pre_run`: {e:?}");
50        errno!(EINVAL)
51    })?
52}
53
54pub fn execute_task<L, F, G>(
55    locked: &mut Locked<L>,
56    task_builder: TaskBuilder,
57    pre_run: F,
58    task_complete: G,
59    ptrace_state: Option<PtraceCoreState>,
60) -> Result<(), Errno>
61where
62    L: LockBefore<TaskRelease>,
63    F: FnOnce(&mut Locked<Unlocked>, &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    // SAFETY: thrd_set_zx_process is a safe function that only sets the process handle for the
70    // current thread. Which handle is used here is only for diagnostics.
71    let old_process_handle = unsafe { thrd_set_zx_process(process_handle) };
72    scopeguard::defer! {
73        // SAFETY: thrd_set_zx_process is a safe function that only sets the process handle for the
74        // current thread. Which handle is used here is only for diagnostics.
75        unsafe {
76            thrd_set_zx_process(old_process_handle);
77        };
78    };
79
80    let weak_task = WeakRef::from(&task_builder.task);
81    let ref_task = weak_task.upgrade().unwrap();
82    if let Some(ptrace_state) = ptrace_state {
83        let _ = ptrace_attach_from_state(
84            locked.cast_locked::<TaskRelease>(),
85            &task_builder.task,
86            ptrace_state,
87        );
88    }
89
90    // Hold a lock on the task's thread slot until we have a chance to initialize it.
91    let mut task_thread_guard = ref_task.thread.write();
92
93    // Spawn the process' thread. Note, this closure ends up executing in the process referred to by
94    // `process_handle`.
95    let (sender, receiver) = sync_channel::<TaskBuilder>(1);
96    let result = std::thread::Builder::new().name("user-thread".to_string()).spawn(move || {
97        // It's safe to create a new lock context since we are on a new thread.
98        #[allow(
99            clippy::undocumented_unsafe_blocks,
100            reason = "Force documented unsafe blocks in Starnix"
101        )]
102        let locked = unsafe { Unlocked::new() };
103
104        // Note, cross-process shared resources allocated in this function that aren't freed by the
105        // Zircon kernel upon thread and/or process termination (like mappings in the shared region)
106        // should be freed using the delayed finalizer mechanism and Task drop.
107        let mut current_task: CurrentTask = receiver
108            .recv()
109            .expect("caller should always send task builder before disconnecting")
110            .into();
111
112        // We don't need the receiver anymore. If we don't drop the receiver now, we'll keep it
113        // allocated for the lifetime of the thread.
114        std::mem::drop(receiver);
115
116        let pre_run_result = { pre_run(locked, &mut current_task) };
117        if pre_run_result.is_err() {
118            // Only log if the pre run didn't exit the task. Otherwise, consider this is expected
119            // by the caller.
120            if current_task.exit_status().is_none() {
121                log_error!("Pre run failed from {pre_run_result:?}. The task will not be run.");
122            }
123
124            // Drop the task_complete callback to ensure that the closure isn't holding any
125            // releasables.
126            std::mem::drop(task_complete);
127        } else {
128            let exit_status = enter_syscall_loop(locked, &mut current_task);
129            current_task.write().set_exit_status(exit_status.clone());
130            task_complete(Ok(exit_status));
131        }
132
133        // `release` must be called as the absolute last action on this thread to ensure that
134        // any deferred release are done before it.
135        current_task.release(locked);
136
137        // Ensure that no releasables are registered after this point as we unwind the stack.
138        DelayedReleaser::finalize();
139    });
140    let join_handle = match result {
141        Ok(handle) => handle,
142        Err(e) => {
143            task_builder.release(locked);
144            match e.kind() {
145                std::io::ErrorKind::WouldBlock => return error!(EAGAIN),
146                other => panic!("unexpected error on thread spawn: {other}"),
147            }
148        }
149    };
150
151    // Update the thread and task information before sending the task_builder to the spawned thread.
152    // This will make sure the mapping between linux tid and fuchsia koid is set before trace events
153    // are emitted from the linux code.
154
155    // Set the task's thread handle
156    let pthread = join_handle.as_pthread_t();
157    #[allow(
158        clippy::undocumented_unsafe_blocks,
159        reason = "Force documented unsafe blocks in Starnix"
160    )]
161    let raw_thread_handle =
162        unsafe { zx::Unowned::<'_, zx::Thread>::from_raw_handle(thrd_get_zx_handle(pthread)) };
163    *task_thread_guard = Some(Arc::new(
164        raw_thread_handle
165            .duplicate(zx::Rights::SAME_RIGHTS)
166            .expect("must have RIGHT_DUPLICATE on handle we created"),
167    ));
168    // Now that the task has a thread handle, update the thread's role using the policy configured.
169    drop(task_thread_guard);
170    if let Err(err) = ref_task.sync_scheduler_state_to_role() {
171        log_warn!(err:?; "Couldn't update freshly spawned thread's profile.");
172    }
173
174    // Record the thread and process ids for tracing after the task_thread is unlocked.
175    ref_task.record_pid_koid_mapping();
176
177    // Wait to send the `TaskBuilder` to the spawned thread until we know that it
178    // spawned successfully, as we need to ensure the builder is always explicitly
179    // released.
180    sender
181        .send(task_builder)
182        .expect("receiver should not be disconnected because thread spawned successfully");
183
184    Ok(())
185}
186
187unsafe extern "C" {
188    /// Sets the process handle used to create new threads, for the current thread.
189    fn thrd_set_zx_process(handle: zx::sys::zx_handle_t) -> zx::sys::zx_handle_t;
190
191    // Gets the thread handle underlying a specific thread.
192    // In C the 'thread' parameter is thrd_t which on Fuchsia is the same as pthread_t.
193    fn thrd_get_zx_handle(thread: u64) -> zx::sys::zx_handle_t;
194}
195
196#[cfg(test)]
197mod tests {
198    use super::*;
199    use crate::ptrace::StopState;
200    use crate::signals::SignalInfo;
201    use crate::testing::*;
202    use starnix_uapi::signals::{SIGCONT, SIGSTOP};
203
204    #[::fuchsia::test]
205    async fn test_block_while_stopped_stop_and_continue() {
206        spawn_kernel_and_run(async |locked, task| {
207            // block_while_stopped must immediately returned if the task is not stopped.
208            task.block_while_stopped(locked);
209
210            // Stop the task.
211            task.thread_group().set_stopped(
212                StopState::GroupStopping,
213                Some(SignalInfo::default(SIGSTOP)),
214                false,
215            );
216
217            let thread = std::thread::spawn({
218                let task = task.weak_task();
219                move || {
220                    let task = task.upgrade().expect("task must be alive");
221                    // Wait for the task to have a waiter.
222                    while !task.read().is_blocked() {
223                        std::thread::sleep(std::time::Duration::from_millis(10));
224                    }
225
226                    // Continue the task.
227                    task.thread_group().set_stopped(
228                        StopState::Waking,
229                        Some(SignalInfo::default(SIGCONT)),
230                        false,
231                    );
232                }
233            });
234
235            // Block until continued.
236            task.block_while_stopped(locked);
237
238            // Join the thread, which will ensure set_stopped terminated.
239            thread.join().expect("joined");
240
241            // The task should not be blocked anymore.
242            task.block_while_stopped(locked);
243        })
244        .await;
245    }
246
247    #[::fuchsia::test]
248    async fn test_block_while_stopped_stop_and_exit() {
249        spawn_kernel_and_run(async |locked, task| {
250            // block_while_stopped must immediately returned if the task is neither stopped nor exited.
251            task.block_while_stopped(locked);
252
253            // Stop the task.
254            task.thread_group().set_stopped(
255                StopState::GroupStopping,
256                Some(SignalInfo::default(SIGSTOP)),
257                false,
258            );
259
260            let thread = std::thread::spawn({
261                let task = task.weak_task();
262                move || {
263                    #[allow(
264                        clippy::undocumented_unsafe_blocks,
265                        reason = "Force documented unsafe blocks in Starnix"
266                    )]
267                    let locked = unsafe { Unlocked::new() };
268                    let task = task.upgrade().expect("task must be alive");
269                    // Wait for the task to have a waiter.
270                    while !task.read().is_blocked() {
271                        std::thread::sleep(std::time::Duration::from_millis(10));
272                    }
273
274                    // exit the task.
275                    task.thread_group().exit(locked, ExitStatus::Exit(1), None);
276                }
277            });
278
279            // Block until continued.
280            task.block_while_stopped(locked);
281
282            // Join the task, which will ensure thread_group.exit terminated.
283            thread.join().expect("joined");
284
285            // The task should not be blocked because it is stopped.
286            task.block_while_stopped(locked);
287        })
288        .await;
289    }
290}