Skip to main content

starnix_core/arch/x64/
signal_handling.rs

1// Copyright 2023 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::signals::{SignalInfo, SignalState};
6use crate::task::{ArchExtendedPstateStorage, CurrentTask, Task};
7use starnix_logging::log_debug;
8use starnix_registers::{RegisterState, RegisterStorageEnum};
9use starnix_types::arch::ArchWidth;
10use starnix_uapi::errors::Errno;
11use starnix_uapi::signals::SigSet;
12use starnix_uapi::user_address::UserAddress;
13use starnix_uapi::{
14    self as uapi, error, sigaction_t, sigaltstack, sigcontext, siginfo_t, ucontext,
15};
16use static_assertions::const_assert_eq;
17
18/// The size of the red zone.
19///
20/// From the AMD64 ABI:
21///   > The 128-byte area beyond the location pointed to
22///   > by %rsp is considered to be reserved and shall not be modified by signal or
23///   > interrupt handlers. Therefore, functions may use this area for temporary
24///   > data that is not needed across function calls. In particular, leaf functions
25///   > may use this area for their entire stack frame, rather than adjusting the
26///   > stack pointer in the prologue and epilogue. This area is known as the red
27///   > zone.
28pub const RED_ZONE_SIZE: u64 = 128;
29
30/// A `SignalStackFrame` contains all the state that is stored on the stack prior
31/// to executing a signal handler.
32///
33/// The ordering of the fields is significant, as it is part of the syscall ABI. In particular,
34/// restorer_address must be the first field, since that is where the signal handler will return
35/// after it finishes executing.
36#[repr(C)]
37pub struct SignalStackFrame {
38    /// The address of the signal handler function.
39    ///
40    /// Must be the first field, to be positioned to serve as the return address.
41    restorer_address: u64,
42
43    /// Information about the signal.
44    pub siginfo_bytes: [u8; std::mem::size_of::<siginfo_t>()],
45
46    /// The state of the thread at the time the signal was handled.
47    pub context: ucontext,
48
49    /// Extended CPU state, i.e, FPU, SSE & AVX registers.
50    xstate: XState,
51}
52
53/// CPU state that needs to restored when returning from the signal handler and that is not
54/// include in the `ucontext`. Currently it contains just `uapi::_xstate` that stores  X87, SSE
55/// and AVX registers. This matches the set of extensions supported by Zircon. In the future it
56/// may be extended with a buffer for other extensions (e.g. AVX-512). That buffer should be added
57/// between `xstate` and `xstate_magic2`.
58/// See https://github.com/google/gvisor/blob/master/pkg/sentry/arch/fpu/fpu_amd64_unsafe.go
59/// for the corresponding code in GVisor.
60#[repr(C, packed)]
61struct XState {
62    base_xstate: uapi::_xstate,
63
64    // Magic value marking the end of the `xstate`. Should be set to `FP_XSTATE_MAGIC2`.
65    xstate_magic2: u32,
66}
67
68// There should be no padding in front of `xstate_magic2`.
69const_assert_eq!(
70    std::mem::size_of::<XState>(),
71    std::mem::size_of::<uapi::_xstate>() + std::mem::size_of::<u32>()
72);
73
74pub const SIG_STACK_SIZE: usize = std::mem::size_of::<SignalStackFrame>();
75
76impl SignalStackFrame {
77    pub fn new(
78        _task: &Task,
79        arch_width: ArchWidth,
80        registers: &RegisterState<RegisterStorageEnum>,
81        extended_pstate: &ArchExtendedPstateStorage,
82        signal_state: &SignalState,
83        siginfo: &SignalInfo,
84        action: sigaction_t,
85        stack_pointer: UserAddress,
86    ) -> Result<SignalStackFrame, Errno> {
87        let fpstate_addr = (uapi::uaddr {
88            addr: stack_pointer.ptr() as u64
89                + memoffset::offset_of!(SignalStackFrame, xstate) as u64,
90        })
91        .into();
92        let context = ucontext {
93            uc_mcontext: sigcontext {
94                r8: registers.r8,
95                r9: registers.r9,
96                r10: registers.r10,
97                r11: registers.r11,
98                r12: registers.r12,
99                r13: registers.r13,
100                r14: registers.r14,
101                r15: registers.r15,
102                rdi: registers.rdi,
103                rsi: registers.rsi,
104                rbp: registers.rbp,
105                rbx: registers.rbx,
106                rdx: registers.rdx,
107                rax: registers.rax,
108                rcx: registers.rcx,
109                rsp: registers.rsp,
110                rip: registers.ip,
111                eflags: registers.flags,
112                oldmask: signal_state.mask().into(),
113                fpstate: fpstate_addr,
114                ..Default::default()
115            },
116            uc_stack: signal_state
117                .alt_stack
118                .map(|stack| sigaltstack {
119                    ss_sp: stack.ss_sp.into(),
120                    ss_flags: stack.ss_flags as i32,
121                    ss_size: stack.ss_size as u64,
122                    ..Default::default()
123                })
124                .unwrap_or_default(),
125            uc_sigmask: signal_state.mask().into(),
126            ..Default::default()
127        };
128        Ok(SignalStackFrame {
129            context,
130            siginfo_bytes: siginfo.as_siginfo_bytes(arch_width)?,
131            restorer_address: action.sa_restorer.addr,
132            xstate: get_xstate(extended_pstate),
133        })
134    }
135
136    pub fn as_bytes(&self) -> &[u8; SIG_STACK_SIZE] {
137        #[allow(
138            clippy::undocumented_unsafe_blocks,
139            reason = "Force documented unsafe blocks in Starnix"
140        )]
141        unsafe {
142            std::mem::transmute(self)
143        }
144    }
145
146    pub fn from_bytes(bytes: [u8; SIG_STACK_SIZE]) -> SignalStackFrame {
147        #[allow(
148            clippy::undocumented_unsafe_blocks,
149            reason = "Force documented unsafe blocks in Starnix"
150        )]
151        unsafe {
152            std::mem::transmute(bytes)
153        }
154    }
155
156    pub fn get_signal_mask(&self, _is_arch32: bool) -> SigSet {
157        self.context.uc_sigmask.into()
158    }
159}
160
161/// Aligns the stack pointer to be 16 byte aligned, and then misaligns it by 8 bytes.
162///
163/// This is done because x86-64 functions expect the stack to be misaligned by 8 bytes,
164/// as if the stack was 16 byte aligned and then someone used a call instruction. This
165/// is due to alignment-requiring SSE instructions.
166pub fn align_stack_pointer(pointer: u64) -> u64 {
167    pointer - (pointer % 16 + 8)
168}
169
170fn get_xstate(extended_pstate: &ArchExtendedPstateStorage) -> XState {
171    let extended_pstate = match extended_pstate {
172        ArchExtendedPstateStorage::State64(extended_pstate) => extended_pstate,
173    };
174    const_assert_eq!(std::mem::size_of::<uapi::_xstate>(), extended_pstate::X64_XSAVE_AREA_SIZE);
175
176    #[allow(
177        clippy::undocumented_unsafe_blocks,
178        reason = "Force documented unsafe blocks in Starnix"
179    )]
180    let mut xstate = XState {
181        // `_xstate` layout matches the layout of the XSAVE area.
182        base_xstate: unsafe { std::mem::transmute(extended_pstate.get_x64_xsave_area()) },
183        xstate_magic2: uapi::FP_XSTATE_MAGIC2,
184    };
185
186    xstate.base_xstate.fpstate.__bindgen_anon_1.sw_reserved = uapi::_fpx_sw_bytes {
187        // `FP_XSTATE_MAGIC1` is used to indicate that the signal stack contains the `xstate`,
188        // which includes not just the default X87 registers (included in `fpstate`), but also
189        // other extensions, such as SSE and AVX. The end of the `xstate` buffer is marked with
190        // `FP_XSTATE_MAGIC2`.
191        magic1: uapi::FP_XSTATE_MAGIC1,
192        extended_size: std::mem::size_of::<XState>() as u32,
193        // TODO: CPU features should be detected dynamically.
194        xfeatures: extended_pstate::X64_SUPPORTED_XSAVE_FEATURES,
195        xstate_size: std::mem::size_of::<uapi::_xstate>() as u32,
196        ..Default::default()
197    };
198
199    xstate
200}
201
202pub fn restore_registers(
203    current_task: &mut CurrentTask,
204    signal_stack_frame: &SignalStackFrame,
205    _stack_pointer: UserAddress,
206) -> Result<(), Errno> {
207    let uctx = &signal_stack_frame.context.uc_mcontext;
208    // Restore the register state from before executing the signal handler.
209    let restored_regs = zx::sys::zx_restricted_state_t {
210        r8: uctx.r8,
211        r9: uctx.r9,
212        r10: uctx.r10,
213        r11: uctx.r11,
214        r12: uctx.r12,
215        r13: uctx.r13,
216        r14: uctx.r14,
217        r15: uctx.r15,
218        rax: uctx.rax,
219        rbx: uctx.rbx,
220        rcx: uctx.rcx,
221        rdx: uctx.rdx,
222        rsi: uctx.rsi,
223        rdi: uctx.rdi,
224        rbp: uctx.rbp,
225        rsp: uctx.rsp,
226        ip: uctx.rip,
227        flags: uctx.eflags,
228        fs_base: current_task.thread_state.registers.fs_base,
229        gs_base: current_task.thread_state.registers.gs_base,
230    };
231    current_task.thread_state.registers.load(restored_regs);
232
233    let xstate = &signal_stack_frame.xstate;
234    #[allow(
235        clippy::undocumented_unsafe_blocks,
236        reason = "Force documented unsafe blocks in Starnix"
237    )]
238    let fpx_sw_bytes = unsafe { xstate.base_xstate.fpstate.__bindgen_anon_1.sw_reserved };
239    if fpx_sw_bytes.magic1 != uapi::FP_XSTATE_MAGIC1
240        || fpx_sw_bytes.extended_size != std::mem::size_of::<XState>() as u32
241        || fpx_sw_bytes.xfeatures != extended_pstate::X64_SUPPORTED_XSAVE_FEATURES
242        || fpx_sw_bytes.xstate_size != std::mem::size_of::<uapi::_xstate>() as u32
243        || xstate.xstate_magic2 != uapi::FP_XSTATE_MAGIC2
244    {
245        log_debug!("Invalid xstate found in signal stack frame.");
246        return error!(EINVAL);
247    }
248
249    let extended_pstate = match &mut current_task.thread_state.extended_pstate {
250        ArchExtendedPstateStorage::State64(state) => state,
251    };
252    #[allow(
253        clippy::undocumented_unsafe_blocks,
254        reason = "Force documented unsafe blocks in Starnix"
255    )]
256    extended_pstate.set_x64_xsave_area(unsafe { std::mem::transmute(xstate.base_xstate) });
257
258    Ok(())
259}
260
261#[cfg(test)]
262mod tests {
263    use super::*;
264    use crate::mm::memory::MemoryObject;
265    use crate::mm::{DesiredAddress, MappingName, MappingOptions, ProtectionFlags};
266    use crate::signals::{SignalDetail, dequeue_signal, restore_from_signal_handler};
267    use crate::task::CurrentTask;
268    use crate::testing::spawn_kernel_and_run;
269    use starnix_uapi::errors::{EINTR, ERESTARTSYS};
270    use starnix_uapi::file_mode::Access;
271    use starnix_uapi::signals::{SIGUSR1, SIGUSR2};
272    use starnix_uapi::{__NR_rt_sigreturn, SA_RESTART, SA_RESTORER, SA_SIGINFO, SI_USER};
273    use std::future::Future;
274
275    const SYSCALL_INSTRUCTION_ADDRESS: UserAddress = UserAddress::const_from(100);
276    const SYSCALL_NUMBER: u64 = 42;
277    const SYSCALL_ARGS: (u64, u64, u64, u64, u64, u64) = (20, 21, 22, 23, 24, 25);
278    const SA_RESTORER_ADDRESS: UserAddress = UserAddress::const_from(0xDEADBEEF);
279    const SA_HANDLER_ADDRESS: UserAddress = UserAddress::const_from(0x00BADDAD);
280
281    const SYSCALL2_INSTRUCTION_ADDRESS: UserAddress = UserAddress::const_from(200);
282    const SYSCALL2_NUMBER: u64 = 84;
283    const SYSCALL2_ARGS: (u64, u64, u64, u64, u64, u64) = (30, 31, 32, 33, 34, 35);
284    const SA_HANDLER2_ADDRESS: UserAddress = UserAddress::const_from(0xBADDAD00);
285
286    #[fuchsia::test]
287    async fn syscall_restart_adjusts_instruction_pointer_and_rax() {
288        spawn_kernel_and_run_with_stack(|current_task| {
289            // Register the signal action.
290            current_task.thread_group().signal_actions.set(
291                SIGUSR1,
292                sigaction_t {
293                    sa_flags: (SA_RESTORER | SA_RESTART | SA_SIGINFO) as u64,
294                    sa_handler: SA_HANDLER_ADDRESS.into(),
295                    sa_restorer: SA_RESTORER_ADDRESS.into(),
296                    ..sigaction_t::default()
297                },
298            );
299
300            // Simulate a syscall that should be restarted by setting up the register state to what it
301            // was after the interrupted syscall. `rax` should have the return value (-ERESTARTSYS);
302            // `rdi`, `rsi`, `rdx`, `r10`, `r8`, `r9`, should be the syscall arguments;
303            // `orig_rax` should hold the syscall number;
304            // and the instruction pointer should be 2 bytes after the syscall instruction.
305            current_task.thread_state.restart_code = Some(ERESTARTSYS);
306            current_task.thread_state.registers.rax = ERESTARTSYS.return_value();
307            current_task.thread_state.registers.rdi = SYSCALL_ARGS.0;
308            current_task.thread_state.registers.rsi = SYSCALL_ARGS.1;
309            current_task.thread_state.registers.rdx = SYSCALL_ARGS.2;
310            current_task.thread_state.registers.r10 = SYSCALL_ARGS.3;
311            current_task.thread_state.registers.r8 = SYSCALL_ARGS.4;
312            current_task.thread_state.registers.r9 = SYSCALL_ARGS.5;
313            current_task.thread_state.registers.orig_rax = SYSCALL_NUMBER;
314            current_task.thread_state.registers.ip =
315                (SYSCALL_INSTRUCTION_ADDRESS + 2u64).unwrap().ptr() as u64;
316
317            // Queue the signal that interrupted the syscall.
318            current_task.write().enqueue_signal(SignalInfo::with_detail(
319                SIGUSR1,
320                SI_USER as i32,
321                SignalDetail::None,
322            ));
323
324            // Process the signal.
325            dequeue_signal(current_task);
326
327            // The instruction pointer should have changed to the signal handling address.
328            assert_eq!(current_task.thread_state.registers.ip, SA_HANDLER_ADDRESS.ptr() as u64);
329
330            // The syscall arguments should be overwritten with signal handling args.
331            assert_ne!(current_task.thread_state.registers.rdi, SYSCALL_ARGS.0);
332            assert_ne!(current_task.thread_state.registers.rsi, SYSCALL_ARGS.1);
333            assert_ne!(current_task.thread_state.registers.rdx, SYSCALL_ARGS.2);
334
335            // Now we assume that execution of the signal handler completed with a call to
336            // `sys_rt_sigreturn`, which would set `rax` to that syscall number.
337            current_task.thread_state.registers.rax = __NR_rt_sigreturn as u64;
338            current_task.thread_state.registers.rsp += 8; // The stack was popped returning from the signal handler.
339
340            restore_from_signal_handler(current_task).expect("failed to restore state");
341
342            // The state of the task is now such that when switching back to userspace, the instruction
343            // pointer will point at the original syscall instruction, with the arguments correctly
344            // restored into the registers.
345            assert_eq!(current_task.thread_state.registers.rax, SYSCALL_NUMBER);
346            assert_eq!(current_task.thread_state.registers.rdi, SYSCALL_ARGS.0);
347            assert_eq!(current_task.thread_state.registers.rsi, SYSCALL_ARGS.1);
348            assert_eq!(current_task.thread_state.registers.rdx, SYSCALL_ARGS.2);
349            assert_eq!(current_task.thread_state.registers.r10, SYSCALL_ARGS.3);
350            assert_eq!(current_task.thread_state.registers.r8, SYSCALL_ARGS.4);
351            assert_eq!(current_task.thread_state.registers.r9, SYSCALL_ARGS.5);
352            assert_eq!(
353                current_task.thread_state.registers.ip,
354                SYSCALL_INSTRUCTION_ADDRESS.ptr() as u64
355            );
356        })
357        .await;
358    }
359
360    #[fuchsia::test]
361    async fn syscall_nested_restart() {
362        spawn_kernel_and_run_with_stack(|current_task| {
363            // Register the signal actions.
364            current_task.thread_group().signal_actions.set(
365                SIGUSR1,
366                sigaction_t {
367                    sa_flags: (SA_RESTORER | SA_RESTART | SA_SIGINFO) as u64,
368                    sa_handler: SA_HANDLER_ADDRESS.into(),
369                    sa_restorer: SA_RESTORER_ADDRESS.into(),
370                    ..sigaction_t::default()
371                },
372            );
373            current_task.thread_group().signal_actions.set(
374                SIGUSR2,
375                sigaction_t {
376                    sa_flags: (SA_RESTORER | SA_RESTART | SA_SIGINFO) as u64,
377                    sa_handler: SA_HANDLER2_ADDRESS.into(),
378                    sa_restorer: SA_RESTORER_ADDRESS.into(),
379                    ..sigaction_t::default()
380                },
381            );
382
383            // Simulate a syscall that should be restarted by setting up the register state to what it
384            // was after the interrupted syscall. `rax` should have the return value (-ERESTARTSYS);
385            // `rdi`, `rsi`, `rdx`, `r10`, `r8`, `r9`, should be the syscall arguments;
386            // `orig_rax` should hold the syscall number;
387            // and the instruction pointer should be 2 bytes after the syscall instruction.
388            current_task.thread_state.restart_code = Some(ERESTARTSYS);
389            current_task.thread_state.registers.rax = ERESTARTSYS.return_value();
390            current_task.thread_state.registers.rdi = SYSCALL_ARGS.0;
391            current_task.thread_state.registers.rsi = SYSCALL_ARGS.1;
392            current_task.thread_state.registers.rdx = SYSCALL_ARGS.2;
393            current_task.thread_state.registers.r10 = SYSCALL_ARGS.3;
394            current_task.thread_state.registers.r8 = SYSCALL_ARGS.4;
395            current_task.thread_state.registers.r9 = SYSCALL_ARGS.5;
396            current_task.thread_state.registers.orig_rax = SYSCALL_NUMBER;
397            current_task.thread_state.registers.ip =
398                (SYSCALL_INSTRUCTION_ADDRESS + 2u64).unwrap().ptr() as u64;
399
400            // Queue the signal that interrupted the syscall.
401            current_task.write().enqueue_signal(SignalInfo::with_detail(
402                SIGUSR1,
403                SI_USER as i32,
404                SignalDetail::None,
405            ));
406
407            // Process the signal.
408            dequeue_signal(current_task);
409
410            // The instruction pointer should have changed to the signal handling address.
411            assert_eq!(current_task.thread_state.registers.ip, SA_HANDLER_ADDRESS.ptr() as u64);
412
413            // The syscall arguments should be overwritten with signal handling args.
414            assert_ne!(current_task.thread_state.registers.rdi, SYSCALL_ARGS.0);
415            assert_ne!(current_task.thread_state.registers.rsi, SYSCALL_ARGS.1);
416            assert_ne!(current_task.thread_state.registers.rdx, SYSCALL_ARGS.2);
417
418            // Simulate another syscall being interrupted.
419            current_task.thread_state.restart_code = Some(ERESTARTSYS);
420            current_task.thread_state.registers.rax = ERESTARTSYS.return_value();
421            current_task.thread_state.registers.rdi = SYSCALL2_ARGS.0;
422            current_task.thread_state.registers.rsi = SYSCALL2_ARGS.1;
423            current_task.thread_state.registers.rdx = SYSCALL2_ARGS.2;
424            current_task.thread_state.registers.r10 = SYSCALL2_ARGS.3;
425            current_task.thread_state.registers.r8 = SYSCALL2_ARGS.4;
426            current_task.thread_state.registers.r9 = SYSCALL2_ARGS.5;
427            current_task.thread_state.registers.orig_rax = SYSCALL2_NUMBER;
428            current_task.thread_state.registers.ip =
429                (SYSCALL2_INSTRUCTION_ADDRESS + 2u64).unwrap().ptr() as u64;
430
431            // Queue the signal that interrupted the syscall.
432            current_task.write().enqueue_signal(SignalInfo::with_detail(
433                SIGUSR2,
434                SI_USER as i32,
435                SignalDetail::None,
436            ));
437
438            // Process the signal.
439            dequeue_signal(current_task);
440
441            // The instruction pointer should have changed to the signal handling address.
442            assert_eq!(current_task.thread_state.registers.ip, SA_HANDLER2_ADDRESS.ptr() as u64);
443
444            // The syscall arguments should be overwritten with signal handling args.
445            assert_ne!(current_task.thread_state.registers.rdi, SYSCALL2_ARGS.0);
446            assert_ne!(current_task.thread_state.registers.rsi, SYSCALL2_ARGS.1);
447            assert_ne!(current_task.thread_state.registers.rdx, SYSCALL2_ARGS.2);
448
449            // Now we assume that execution of the second signal handler completed with a call to
450            // `sys_rt_sigreturn`, which would set `rax` to that syscall number.
451            current_task.thread_state.registers.rax = __NR_rt_sigreturn as u64;
452            current_task.thread_state.registers.rsp += 8; // The stack was popped returning from the signal handler.
453
454            restore_from_signal_handler(current_task).expect("failed to restore state");
455
456            // The state of the task is now such that when switching back to userspace, the instruction
457            // pointer will point at the original syscall instruction, with the arguments correctly
458            // restored into the registers.
459            assert_eq!(current_task.thread_state.registers.rax, SYSCALL2_NUMBER);
460            assert_eq!(current_task.thread_state.registers.rdi, SYSCALL2_ARGS.0);
461            assert_eq!(current_task.thread_state.registers.rsi, SYSCALL2_ARGS.1);
462            assert_eq!(current_task.thread_state.registers.rdx, SYSCALL2_ARGS.2);
463            assert_eq!(current_task.thread_state.registers.r10, SYSCALL2_ARGS.3);
464            assert_eq!(current_task.thread_state.registers.r8, SYSCALL2_ARGS.4);
465            assert_eq!(current_task.thread_state.registers.r9, SYSCALL2_ARGS.5);
466            assert_eq!(
467                current_task.thread_state.registers.ip,
468                SYSCALL2_INSTRUCTION_ADDRESS.ptr() as u64
469            );
470
471            // Now we assume that execution of the first signal handler completed with a call to
472            // `sys_rt_sigreturn`, which would set `rax` to that syscall number.
473            current_task.thread_state.registers.rax = __NR_rt_sigreturn as u64;
474            current_task.thread_state.registers.rsp += 8; // The stack was popped returning from the signal handler.
475
476            restore_from_signal_handler(current_task).expect("failed to restore state");
477
478            // The state of the task is now such that when switching back to userspace, the instruction
479            // pointer will point at the original syscall instruction, with the arguments correctly
480            // restored into the registers.
481            assert_eq!(current_task.thread_state.registers.rax, SYSCALL_NUMBER);
482            assert_eq!(current_task.thread_state.registers.rdi, SYSCALL_ARGS.0);
483            assert_eq!(current_task.thread_state.registers.rsi, SYSCALL_ARGS.1);
484            assert_eq!(current_task.thread_state.registers.rdx, SYSCALL_ARGS.2);
485            assert_eq!(current_task.thread_state.registers.r10, SYSCALL_ARGS.3);
486            assert_eq!(current_task.thread_state.registers.r8, SYSCALL_ARGS.4);
487            assert_eq!(current_task.thread_state.registers.r9, SYSCALL_ARGS.5);
488            assert_eq!(
489                current_task.thread_state.registers.ip,
490                SYSCALL_INSTRUCTION_ADDRESS.ptr() as u64
491            );
492        })
493        .await;
494    }
495
496    #[fuchsia::test]
497    async fn syscall_does_not_restart_if_signal_action_has_no_sa_restart_flag() {
498        spawn_kernel_and_run_with_stack(|current_task| {
499            // Register the signal action.
500            current_task.thread_group().signal_actions.set(
501                SIGUSR1,
502                sigaction_t {
503                    sa_flags: (SA_RESTORER | SA_SIGINFO) as u64,
504                    sa_handler: SA_HANDLER_ADDRESS.into(),
505                    sa_restorer: SA_RESTORER_ADDRESS.into(),
506                    ..sigaction_t::default()
507                },
508            );
509
510            // Simulate a syscall that should be restarted by setting up the register state to what it
511            // was after the interrupted syscall. `rax` should have the return value (-ERESTARTSYS);
512            // `rdi`, `rsi`, `rdx`, `r10`, `r8`, `r9`, should be the syscall arguments;
513            // `orig_rax` should hold the syscall number;
514            // and the instruction pointer should be 2 bytes after the syscall instruction.
515            current_task.thread_state.restart_code = Some(ERESTARTSYS);
516            current_task.thread_state.registers.rax = ERESTARTSYS.return_value();
517            current_task.thread_state.registers.rdi = SYSCALL_ARGS.0;
518            current_task.thread_state.registers.rsi = SYSCALL_ARGS.1;
519            current_task.thread_state.registers.rdx = SYSCALL_ARGS.2;
520            current_task.thread_state.registers.r10 = SYSCALL_ARGS.3;
521            current_task.thread_state.registers.r8 = SYSCALL_ARGS.4;
522            current_task.thread_state.registers.r9 = SYSCALL_ARGS.5;
523            current_task.thread_state.registers.orig_rax = SYSCALL_NUMBER;
524            current_task.thread_state.registers.ip =
525                (SYSCALL_INSTRUCTION_ADDRESS + 2u64).unwrap().ptr() as u64;
526
527            // Queue the signal that interrupted the syscall.
528            current_task.write().enqueue_signal(SignalInfo::with_detail(
529                SIGUSR1,
530                SI_USER as i32,
531                SignalDetail::None,
532            ));
533
534            // Process the signal.
535            dequeue_signal(current_task);
536
537            // The instruction pointer should have changed to the signal handling address.
538            assert_eq!(current_task.thread_state.registers.ip, SA_HANDLER_ADDRESS.ptr() as u64);
539
540            // The syscall arguments should be overwritten with signal handling args.
541            assert_ne!(current_task.thread_state.registers.rdi, SYSCALL_ARGS.0);
542            assert_ne!(current_task.thread_state.registers.rsi, SYSCALL_ARGS.1);
543            assert_ne!(current_task.thread_state.registers.rdx, SYSCALL_ARGS.2);
544
545            // Now we assume that execution of the signal handler completed with a call to
546            // `sys_rt_sigreturn`, which would set `rax` to that syscall number.
547            current_task.thread_state.registers.rax = __NR_rt_sigreturn as u64;
548            current_task.thread_state.registers.rsp += 8; // The stack was popped returning from the signal handler.
549
550            restore_from_signal_handler(current_task).expect("failed to restore state");
551
552            // The state of the task is now such that when switching back to userspace, the instruction
553            // pointer will point at the original syscall instruction, with the arguments correctly
554            // restored into the registers.
555            assert_eq!(current_task.thread_state.registers.rax, EINTR.return_value());
556            assert_eq!(
557                current_task.thread_state.registers.ip,
558                (SYSCALL_INSTRUCTION_ADDRESS + 2u64).unwrap().ptr() as u64
559            );
560        })
561        .await;
562    }
563
564    /// Creates a kernel and initial task, giving the task a stack.
565    fn spawn_kernel_and_run_with_stack<F>(callback: F) -> impl Future<Output = ()>
566    where
567        F: FnOnce(&mut CurrentTask) + Send + Sync + 'static,
568    {
569        spawn_kernel_and_run(async |current_task| {
570            const STACK_SIZE: usize = 0x1000;
571
572            // Give the task a stack.
573            let prot_flags = ProtectionFlags::READ | ProtectionFlags::WRITE;
574            let stack_base = current_task
575                .mm()
576                .unwrap()
577                .map_memory(
578                    DesiredAddress::Any,
579                    MemoryObject::from(
580                        zx::Vmo::create(STACK_SIZE as u64).expect("failed to create stack VMO"),
581                    )
582                    .into(),
583                    0,
584                    STACK_SIZE,
585                    prot_flags,
586                    Access::rwx(),
587                    MappingOptions::empty(),
588                    MappingName::Stack,
589                )
590                .expect("failed to map stack VMO");
591            let stack_address = (stack_base + (STACK_SIZE - 8)).expect("OOB memory access.");
592            current_task.thread_state.registers.rsp = stack_address.ptr() as u64;
593
594            callback(current_task);
595        })
596    }
597}