xref: /DragonOS/kernel/src/arch/x86_64/ipc/signal.rs (revision 7b32f5080f42bcbf7d2421013f3ea53c776a063c)
1 use core::{ffi::c_void, intrinsics::unlikely, mem::size_of};
2 
3 use crate::{
4     arch::{
5         fpu::FpState,
6         interrupt::TrapFrame,
7         process::table::{USER_CS, USER_DS},
8         sched::sched,
9         CurrentIrqArch, MMArch,
10     },
11     exception::InterruptArch,
12     ipc::{
13         signal::set_current_sig_blocked,
14         signal_types::{SaHandlerType, SigInfo, Sigaction, SigactionType, SignalArch},
15     },
16     kerror,
17     mm::MemoryManagementArch,
18     process::ProcessManager,
19     syscall::{user_access::UserBufferWriter, Syscall, SystemError},
20 };
21 
22 /// 信号处理的栈的栈指针的最小对齐数量
23 pub const STACK_ALIGN: u64 = 16;
24 /// 信号最大值
25 pub const MAX_SIG_NUM: usize = 64;
26 #[allow(dead_code)]
27 #[derive(Debug, Clone, Copy, Eq)]
28 #[repr(usize)]
29 #[allow(non_camel_case_types)]
30 pub enum Signal {
31     INVALID = 0,
32     SIGHUP = 1,
33     SIGINT,
34     SIGQUIT,
35     SIGILL,
36     SIGTRAP,
37     /// SIGABRT和SIGIOT共用这个号码
38     SIGABRT_OR_IOT,
39     SIGBUS,
40     SIGFPE,
41     SIGKILL,
42     SIGUSR1,
43 
44     SIGSEGV = 11,
45     SIGUSR2,
46     SIGPIPE,
47     SIGALRM,
48     SIGTERM,
49     SIGSTKFLT,
50     SIGCHLD,
51     SIGCONT,
52     SIGSTOP,
53     SIGTSTP,
54 
55     SIGTTIN = 21,
56     SIGTTOU,
57     SIGURG,
58     SIGXCPU,
59     SIGXFSZ,
60     SIGVTALRM,
61     SIGPROF,
62     SIGWINCH,
63     /// SIGIO和SIGPOLL共用这个号码
64     SIGIO_OR_POLL,
65     SIGPWR,
66 
67     SIGSYS = 31,
68 
69     SIGRTMIN = 32,
70     SIGRTMAX = 64,
71 }
72 
73 /// 为Signal实现判断相等的trait
74 impl PartialEq for Signal {
75     fn eq(&self, other: &Signal) -> bool {
76         *self as usize == *other as usize
77     }
78 }
79 
80 impl From<usize> for Signal {
81     fn from(value: usize) -> Self {
82         if value <= MAX_SIG_NUM {
83             let ret: Signal = unsafe { core::mem::transmute(value) };
84             return ret;
85         } else {
86             kerror!("Try to convert an invalid number to Signal");
87             return Signal::INVALID;
88         }
89     }
90 }
91 
92 impl Into<usize> for Signal {
93     fn into(self) -> usize {
94         self as usize
95     }
96 }
97 
98 impl From<i32> for Signal {
99     fn from(value: i32) -> Self {
100         if value < 0 {
101             kerror!("Try to convert an invalid number to Signal");
102             return Signal::INVALID;
103         } else {
104             return Self::from(value as usize);
105         }
106     }
107 }
108 
109 impl Into<SigSet> for Signal {
110     fn into(self) -> SigSet {
111         SigSet {
112             bits: (1 << (self as usize - 1) as u64),
113         }
114     }
115 }
116 impl Signal {
117     /// 判断一个数字是否为可用的信号
118     #[inline]
119     pub fn is_valid(&self) -> bool {
120         return (*self) as usize <= MAX_SIG_NUM;
121     }
122 
123     /// const convertor between `Signal` and `SigSet`
124     pub const fn into_sigset(self) -> SigSet {
125         SigSet {
126             bits: (1 << (self as usize - 1) as u64),
127         }
128     }
129 
130     /// 判断一个信号是不是实时信号
131     ///
132     /// ## 返回值
133     ///
134     /// - `true` 这个信号是实时信号
135     /// - `false` 这个信号不是实时信号
136     #[inline]
137     pub fn is_rt_signal(&self) -> bool {
138         return (*self) as usize >= Signal::SIGRTMIN.into();
139     }
140 
141     /// 调用信号的默认处理函数
142     pub fn handle_default(&self) {
143         match self {
144             Signal::INVALID => {
145                 kerror!("attempting to handler an Invalid");
146             }
147             Signal::SIGHUP => sig_terminate(self.clone()),
148             Signal::SIGINT => sig_terminate(self.clone()),
149             Signal::SIGQUIT => sig_terminate_dump(self.clone()),
150             Signal::SIGILL => sig_terminate_dump(self.clone()),
151             Signal::SIGTRAP => sig_terminate_dump(self.clone()),
152             Signal::SIGABRT_OR_IOT => sig_terminate_dump(self.clone()),
153             Signal::SIGBUS => sig_terminate_dump(self.clone()),
154             Signal::SIGFPE => sig_terminate_dump(self.clone()),
155             Signal::SIGKILL => sig_terminate(self.clone()),
156             Signal::SIGUSR1 => sig_terminate(self.clone()),
157             Signal::SIGSEGV => sig_terminate_dump(self.clone()),
158             Signal::SIGUSR2 => sig_terminate(self.clone()),
159             Signal::SIGPIPE => sig_terminate(self.clone()),
160             Signal::SIGALRM => sig_terminate(self.clone()),
161             Signal::SIGTERM => sig_terminate(self.clone()),
162             Signal::SIGSTKFLT => sig_terminate(self.clone()),
163             Signal::SIGCHLD => sig_ignore(self.clone()),
164             Signal::SIGCONT => sig_continue(self.clone()),
165             Signal::SIGSTOP => sig_stop(self.clone()),
166             Signal::SIGTSTP => sig_stop(self.clone()),
167             Signal::SIGTTIN => sig_stop(self.clone()),
168             Signal::SIGTTOU => sig_stop(self.clone()),
169             Signal::SIGURG => sig_ignore(self.clone()),
170             Signal::SIGXCPU => sig_terminate_dump(self.clone()),
171             Signal::SIGXFSZ => sig_terminate_dump(self.clone()),
172             Signal::SIGVTALRM => sig_terminate(self.clone()),
173             Signal::SIGPROF => sig_terminate(self.clone()),
174             Signal::SIGWINCH => sig_ignore(self.clone()),
175             Signal::SIGIO_OR_POLL => sig_terminate(self.clone()),
176             Signal::SIGPWR => sig_terminate(self.clone()),
177             Signal::SIGSYS => sig_terminate(self.clone()),
178             Signal::SIGRTMIN => sig_terminate(self.clone()),
179             Signal::SIGRTMAX => sig_terminate(self.clone()),
180         }
181     }
182 }
183 
184 /// siginfo中的si_code的可选值
185 /// 请注意,当这个值小于0时,表示siginfo来自用户态,否则来自内核态
186 #[derive(Copy, Debug, Clone)]
187 #[repr(i32)]
188 pub enum SigCode {
189     /// sent by kill, sigsend, raise
190     User = 0,
191     /// sent by kernel from somewhere
192     Kernel = 0x80,
193     /// 通过sigqueue发送
194     Queue = -1,
195     /// 定时器过期时发送
196     Timer = -2,
197     /// 当实时消息队列的状态发生改变时发送
198     Mesgq = -3,
199     /// 当异步IO完成时发送
200     AsyncIO = -4,
201     /// sent by queued SIGIO
202     SigIO = -5,
203 }
204 
205 impl SigCode {
206     /// 为SigCode这个枚举类型实现从i32转换到枚举类型的转换函数
207     #[allow(dead_code)]
208     pub fn from_i32(x: i32) -> SigCode {
209         match x {
210             0 => Self::User,
211             0x80 => Self::Kernel,
212             -1 => Self::Queue,
213             -2 => Self::Timer,
214             -3 => Self::Mesgq,
215             -4 => Self::AsyncIO,
216             -5 => Self::SigIO,
217             _ => panic!("signal code not valid"),
218         }
219     }
220 }
221 
222 bitflags! {
223     #[repr(C,align(8))]
224     #[derive(Default)]
225     pub struct SigFlags:u32{
226         const SA_NOCLDSTOP =  1;
227         const SA_NOCLDWAIT = 2;
228         const SA_SIGINFO   = 4;
229         const SA_ONSTACK   = 0x08000000;
230         const SA_RESTART   = 0x10000000;
231         const SA_NODEFER  = 0x40000000;
232         const SA_RESETHAND = 0x80000000;
233         const SA_RESTORER   =0x04000000;
234         const SA_ALL = Self::SA_NOCLDSTOP.bits()|Self::SA_NOCLDWAIT.bits()|Self::SA_NODEFER.bits()|Self::SA_ONSTACK.bits()|Self::SA_RESETHAND.bits()|Self::SA_RESTART.bits()|Self::SA_SIGINFO.bits()|Self::SA_RESTORER.bits();
235     }
236 
237     /// 请注意,sigset 这个bitmap, 第0位表示sig=1的信号。也就是说,Signal-1才是sigset_t中对应的位
238     #[derive(Default)]
239     pub struct SigSet:u64{
240         const SIGHUP   =  1<<0;
241         const SIGINT   =  1<<1;
242         const SIGQUIT  =  1<<2;
243         const SIGILL   =  1<<3;
244         const SIGTRAP  =  1<<4;
245         /// SIGABRT和SIGIOT共用这个号码
246         const SIGABRT_OR_IOT    =    1<<5;
247         const SIGBUS   =  1<<6;
248         const SIGFPE   =  1<<7;
249         const SIGKILL  =  1<<8;
250         const SIGUSR   =  1<<9;
251         const SIGSEGV  =  1<<10;
252         const SIGUSR2  =  1<<11;
253         const SIGPIPE  =  1<<12;
254         const SIGALRM  =  1<<13;
255         const SIGTERM  =  1<<14;
256         const SIGSTKFLT=  1<<15;
257         const SIGCHLD  =  1<<16;
258         const SIGCONT  =  1<<17;
259         const SIGSTOP  =  1<<18;
260         const SIGTSTP  =  1<<19;
261         const SIGTTIN  =  1<<20;
262         const SIGTTOU  =  1<<21;
263         const SIGURG   =  1<<22;
264         const SIGXCPU  =  1<<23;
265         const SIGXFSZ  =  1<<24;
266         const SIGVTALRM=  1<<25;
267         const SIGPROF  =  1<<26;
268         const SIGWINCH =  1<<27;
269         /// SIGIO和SIGPOLL共用这个号码
270         const SIGIO_OR_POLL    =   1<<28;
271         const SIGPWR   =  1<<29;
272         const SIGSYS   =  1<<30;
273         const SIGRTMIN =  1<<31;
274         // TODO 写上实时信号
275         const SIGRTMAX =  1<<MAX_SIG_NUM-1;
276     }
277 }
278 
279 #[repr(C, align(16))]
280 #[derive(Debug, Clone, Copy)]
281 pub struct SigFrame {
282     // pub pedding: u64,
283     /// 指向restorer的地址的指针。(该变量必须放在sigframe的第一位,因为这样才能在handler返回的时候,跳转到对应的代码,执行sigreturn)
284     pub ret_code_ptr: *mut core::ffi::c_void,
285     pub handler: *mut c_void,
286     pub info: SigInfo,
287     pub context: SigContext,
288 }
289 
290 #[repr(C, align(16))]
291 #[derive(Debug, Clone, Copy)]
292 pub struct SigContext {
293     /// sigcontext的标志位
294     pub sc_flags: u64,
295     pub sc_stack: SigStack, // 信号处理程序备用栈信息
296     pub frame: TrapFrame,   // 暂存的系统调用/中断返回时,原本要弹出的内核栈帧
297     // pub trap_num: u64,    // 用来保存线程结构体中的trap_num字段
298     pub oldmask: SigSet, // 暂存的执行信号处理函数之前的,被设置block的信号
299     pub cr2: u64,        // 用来保存线程结构体中的cr2字段
300     // pub err_code: u64,    // 用来保存线程结构体中的err_code字段
301     pub reserved_for_x87_state: Option<FpState>,
302     pub reserved: [u64; 8],
303 }
304 
305 impl SigContext {
306     /// 设置sigcontext
307     ///
308     /// ## 参数
309     ///
310     /// - `mask` 要被暂存的信号mask标志位
311     /// - `regs` 进入信号处理流程前,Restore all要弹出的内核栈栈帧
312     ///
313     /// ## 返回值
314     ///
315     /// - `Ok(0)`
316     /// - `Err(Systemerror)` (暂时不会返回错误)
317     pub fn setup_sigcontext(
318         &mut self,
319         mask: &SigSet,
320         frame: &TrapFrame,
321     ) -> Result<i32, SystemError> {
322         //TODO 引入线程后补上
323         // let current_thread = ProcessManager::current_pcb().thread;
324         let pcb = ProcessManager::current_pcb();
325         let mut archinfo_guard = pcb.arch_info_irqsave();
326         self.oldmask = *mask;
327         self.frame = frame.clone();
328         // context.trap_num = unsafe { (*current_thread).trap_num };
329         // context.err_code = unsafe { (*current_thread).err_code };
330         // context.cr2 = unsafe { (*current_thread).cr2 };
331         self.reserved_for_x87_state = archinfo_guard.fp_state().clone();
332 
333         // 保存完毕后,清空fp_state,以免下次save的时候,出现SIMD exception
334         archinfo_guard.clear_fp_state();
335         return Ok(0);
336     }
337 
338     /// 指定的sigcontext恢复到当前进程的内核栈帧中,并将当前线程结构体的几个参数进行恢复
339     ///
340     /// ## 参数
341     /// - `frame` 目标栈帧(也就是把context恢复到这个栈帧中)
342     ///
343     /// ##返回值
344     /// - `true` -> 成功恢复
345     /// - `false` -> 执行失败
346     pub fn restore_sigcontext(&mut self, frame: &mut TrapFrame) -> bool {
347         let guard = ProcessManager::current_pcb();
348         let mut arch_info = guard.arch_info();
349         (*frame) = self.frame.clone();
350         // (*current_thread).trap_num = (*context).trap_num;
351         *arch_info.cr2_mut() = self.cr2 as usize;
352         // (*current_thread).err_code = (*context).err_code;
353         // 如果当前进程有fpstate,则将其恢复到pcb的fp_state中
354         *arch_info.fp_state_mut() = self.reserved_for_x87_state.clone();
355         arch_info.restore_fp_state();
356         return true;
357     }
358 }
359 /// @brief 信号处理备用栈的信息
360 #[derive(Debug, Clone, Copy)]
361 pub struct SigStack {
362     pub sp: *mut c_void,
363     pub flags: u32,
364     pub size: u32,
365     pub fpstate: FpState,
366 }
367 
368 #[no_mangle]
369 unsafe extern "C" fn do_signal(frame: &mut TrapFrame) {
370     X86_64SignalArch::do_signal(frame);
371     return;
372 }
373 
374 pub struct X86_64SignalArch;
375 
376 impl SignalArch for X86_64SignalArch {
377     unsafe fn do_signal(frame: &mut TrapFrame) {
378         let pcb = ProcessManager::current_pcb();
379         let siginfo = pcb.try_siginfo(5);
380 
381         if unlikely(siginfo.is_none()) {
382             return;
383         }
384 
385         let siginfo_read_guard = siginfo.unwrap();
386 
387         // 检查sigpending是否为0
388         if siginfo_read_guard.sig_pending().signal().bits() == 0 || !frame.from_user() {
389             // 若没有正在等待处理的信号,或者将要返回到的是内核态,则返回
390             return;
391         }
392 
393         let pcb = ProcessManager::current_pcb();
394 
395         let mut sig_number: Signal;
396         let mut info: Option<SigInfo>;
397         let mut sigaction: Sigaction;
398         let sig_block: SigSet = siginfo_read_guard.sig_block().clone();
399         drop(siginfo_read_guard);
400 
401         let sig_guard = pcb.try_sig_struct_irq(5);
402         if unlikely(sig_guard.is_none()) {
403             return;
404         }
405         let siginfo_mut = pcb.try_siginfo_mut(5);
406         if unlikely(siginfo_mut.is_none()) {
407             return;
408         }
409 
410         let sig_guard = sig_guard.unwrap();
411         let mut siginfo_mut_guard = siginfo_mut.unwrap();
412         loop {
413             (sig_number, info) = siginfo_mut_guard.dequeue_signal(&sig_block);
414             // 如果信号非法,则直接返回
415             if sig_number == Signal::INVALID {
416                 return;
417             }
418 
419             sigaction = sig_guard.handlers[sig_number as usize - 1];
420 
421             match sigaction.action() {
422                 SigactionType::SaHandler(action_type) => match action_type {
423                     SaHandlerType::SigError => {
424                         kerror!("Trying to handle a Sigerror on Process:{:?}", pcb.pid());
425                         return;
426                     }
427                     SaHandlerType::SigDefault => {
428                         sigaction = Sigaction::default();
429                         break;
430                     }
431                     SaHandlerType::SigIgnore => continue,
432                     SaHandlerType::SigCustomized(_) => {
433                         break;
434                     }
435                 },
436                 SigactionType::SaSigaction(_) => todo!(),
437             }
438             // 如果当前动作是忽略这个信号,就继续循环。
439         }
440 
441         let oldset = siginfo_mut_guard.sig_block().clone();
442         //避免死锁
443         drop(siginfo_mut_guard);
444         drop(sig_guard);
445 
446         // 做完上面的检查后,开中断
447         CurrentIrqArch::interrupt_enable();
448         let res: Result<i32, SystemError> =
449             handle_signal(sig_number, &mut sigaction, &info.unwrap(), &oldset, frame);
450         if res.is_err() {
451             kerror!(
452                 "Error occurred when handling signal: {}, pid={:?}, errcode={:?}",
453                 sig_number as i32,
454                 ProcessManager::current_pcb().pid(),
455                 res.unwrap_err()
456             );
457         }
458     }
459 
460     fn sys_rt_sigreturn(trap_frame: &mut TrapFrame) -> u64 {
461         let frame = (trap_frame.rsp as usize) as *mut SigFrame;
462 
463         // 如果当前的rsp不来自用户态,则认为产生了错误(或被SROP攻击)
464         if UserBufferWriter::new(frame, size_of::<SigFrame>(), true).is_err() {
465             kerror!("rsp doesn't from user level");
466             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
467                 .map_err(|e| e.to_posix_errno());
468             return trap_frame.rax;
469         }
470         let mut sigmask: SigSet = unsafe { (*frame).context.oldmask };
471         set_current_sig_blocked(&mut sigmask);
472         // 从用户栈恢复sigcontext
473         if !unsafe { &mut (*frame).context }.restore_sigcontext(trap_frame) {
474             kerror!("unable to restore sigcontext");
475             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
476                 .map_err(|e| e.to_posix_errno());
477             // 如果这里返回 err 值的话会丢失上一个系统调用的返回值
478         }
479         // 由于系统调用的返回值会被系统调用模块被存放在rax寄存器,因此,为了还原原来的那个系统调用的返回值,我们需要在这里返回恢复后的rax的值
480         return trap_frame.rax;
481     }
482 }
483 
484 /// @brief 真正发送signal,执行自定义的处理函数
485 ///
486 /// @param sig 信号number
487 /// @param sigaction 信号响应动作
488 /// @param info 信号信息
489 /// @param oldset
490 /// @param regs 之前的系统调用将要返回的时候,要弹出的栈帧的拷贝
491 ///
492 /// @return Result<0,SystemError> 若Error, 则返回错误码,否则返回Ok(0)
493 fn handle_signal(
494     sig: Signal,
495     sigaction: &mut Sigaction,
496     info: &SigInfo,
497     oldset: &SigSet,
498     frame: &mut TrapFrame,
499 ) -> Result<i32, SystemError> {
500     // TODO 这里要补充一段逻辑,好像是为了保证引入线程之后的地址空间不会出问题。详见https://opengrok.ringotek.cn/xref/linux-6.1.9/arch/mips/kernel/signal.c#830
501 
502     // 设置栈帧
503     return setup_frame(sig, sigaction, info, oldset, frame);
504 }
505 
506 /// @brief 在用户栈上开辟一块空间,并且把内核栈的栈帧以及需要在用户态执行的代码给保存进去。
507 ///
508 /// @param regs 进入信号处理流程前,Restore all要弹出的内核栈栈帧
509 fn setup_frame(
510     sig: Signal,
511     sigaction: &mut Sigaction,
512     info: &SigInfo,
513     oldset: &SigSet,
514     trap_frame: &mut TrapFrame,
515 ) -> Result<i32, SystemError> {
516     let ret_code_ptr: *mut c_void;
517     let temp_handler: *mut c_void;
518     match sigaction.action() {
519         SigactionType::SaHandler(handler_type) => match handler_type {
520             SaHandlerType::SigDefault => {
521                 sig.handle_default();
522                 return Ok(0);
523             }
524             SaHandlerType::SigCustomized(handler) => {
525                 // 如果handler位于内核空间
526                 if handler >= MMArch::USER_END_VADDR {
527                     // 如果当前是SIGSEGV,则采用默认函数处理
528                     if sig == Signal::SIGSEGV {
529                         sig.handle_default();
530                         return Ok(0);
531                     } else {
532                         kerror!("attempting  to execute a signal handler from kernel");
533                         sig.handle_default();
534                         return Err(SystemError::EINVAL);
535                     }
536                 } else {
537                     // 为了与Linux的兼容性,64位程序必须由用户自行指定restorer
538                     if sigaction.flags().contains(SigFlags::SA_RESTORER) {
539                         ret_code_ptr = sigaction.restorer().unwrap().data() as *mut c_void;
540                     } else {
541                         kerror!(
542                             "pid-{:?} forgot to set SA_FLAG_RESTORER for signal {:?}",
543                             ProcessManager::current_pcb().pid(),
544                             sig as i32
545                         );
546                         let r = Syscall::kill(
547                             ProcessManager::current_pcb().pid(),
548                             Signal::SIGSEGV as i32,
549                         );
550                         if r.is_err() {
551                             kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
552                         }
553                         return Err(SystemError::EINVAL);
554                     }
555                     if sigaction.restorer().is_none() {
556                         kerror!(
557                             "restorer in process:{:?} is not defined",
558                             ProcessManager::current_pcb().pid()
559                         );
560                         return Err(SystemError::EINVAL);
561                     }
562                     temp_handler = handler.data() as *mut c_void;
563                 }
564             }
565             SaHandlerType::SigIgnore => {
566                 return Ok(0);
567             }
568             _ => {
569                 return Err(SystemError::EINVAL);
570             }
571         },
572         SigactionType::SaSigaction(_) => {
573             //TODO 这里应该是可以恢复栈的,等后续来做
574             kerror!("trying to recover from sigaction type instead of handler");
575             return Err(SystemError::EINVAL);
576         }
577     }
578     let frame: *mut SigFrame = get_stack(&trap_frame, size_of::<SigFrame>());
579     // kdebug!("frame=0x{:016x}", frame as usize);
580     // 要求这个frame的地址位于用户空间,因此进行校验
581     let r: Result<UserBufferWriter<'_>, SystemError> =
582         UserBufferWriter::new(frame, size_of::<SigFrame>(), true);
583     if r.is_err() {
584         // 如果地址区域位于内核空间,则直接报错
585         // todo: 生成一个sigsegv
586         let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
587         if r.is_err() {
588             kerror!("In setup frame: generate SIGSEGV signal failed");
589         }
590         kerror!("In setup frame: access check failed");
591         return Err(SystemError::EFAULT);
592     }
593 
594     // 将siginfo拷贝到用户栈
595     info.copy_siginfo_to_user(unsafe { &mut ((*frame).info) as *mut SigInfo })
596         .map_err(|e| -> SystemError {
597             let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
598             if r.is_err() {
599                 kerror!("In copy_siginfo_to_user: generate SIGSEGV signal failed");
600             }
601             return e;
602         })?;
603 
604     // todo: 拷贝处理程序备用栈的地址、大小、ss_flags
605 
606     unsafe {
607         (*frame)
608             .context
609             .setup_sigcontext(oldset, &trap_frame)
610             .map_err(|e: SystemError| -> SystemError {
611                 let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
612                 if r.is_err() {
613                     kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
614                 }
615                 return e;
616             })?
617     };
618 
619     unsafe {
620         // 在开头检验过sigaction.restorer是否为空了,实际上libc会保证 restorer始终不为空
621         (*frame).ret_code_ptr = ret_code_ptr;
622     }
623 
624     unsafe { (*frame).handler = temp_handler };
625     // 传入信号处理函数的第一个参数
626     trap_frame.rdi = sig as u64;
627     trap_frame.rsi = unsafe { &(*frame).info as *const SigInfo as u64 };
628     trap_frame.rsp = frame as u64;
629     trap_frame.rip = unsafe { (*frame).handler as u64 };
630     // 设置cs和ds寄存器
631     trap_frame.cs = (USER_CS.bits() | 0x3) as u64;
632     trap_frame.ds = (USER_DS.bits() | 0x3) as u64;
633 
634     // 禁用中断
635     // trap_frame.rflags &= !(0x200);
636 
637     return Ok(0);
638 }
639 
640 #[inline(always)]
641 fn get_stack(frame: &TrapFrame, size: usize) -> *mut SigFrame {
642     // TODO:在 linux 中会根据 Sigaction 中的一个flag 的值来确定是否使用pcb中的 signal 处理程序备用堆栈,现在的
643     // pcb中也没有这个备用堆栈
644 
645     // 默认使用 用户栈的栈顶指针-128字节的红区-sigframe的大小 并且16字节对齐
646     let mut rsp: usize = (frame.rsp as usize) - 128 - size;
647     // 按照要求进行对齐,别问为什么减8,不减8就是错的,可以看
648     // https://sourcegraph.com/github.com/torvalds/linux@dd72f9c7e512da377074d47d990564959b772643/-/blob/arch/x86/kernel/signal.c?L124
649     // 我猜测是跟x86汇编的某些弹栈行为有关系,它可能会出于某种原因递增 rsp
650     rsp &= (!(STACK_ALIGN - 1)) as usize - 8;
651     // rsp &= (!(STACK_ALIGN - 1)) as usize;
652     return rsp as *mut SigFrame;
653 }
654 
655 /// 信号默认处理函数——终止进程
656 fn sig_terminate(sig: Signal) {
657     ProcessManager::exit(sig as usize);
658 }
659 
660 /// 信号默认处理函数——终止进程并生成 core dump
661 fn sig_terminate_dump(sig: Signal) {
662     ProcessManager::exit(sig as usize);
663     // TODO 生成 coredump 文件
664 }
665 
666 /// 信号默认处理函数——暂停进程
667 fn sig_stop(sig: Signal) {
668     let guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
669     ProcessManager::mark_stop().unwrap_or_else(|e| {
670         kerror!(
671             "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}",
672             e,
673             ProcessManager::current_pcb(),
674             sig
675         );
676     });
677     drop(guard);
678     sched();
679     // TODO 暂停进程
680 }
681 /// 信号默认处理函数——继续进程
682 fn sig_continue(sig: Signal) {
683     ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| {
684         kerror!(
685             "Failed to wake up process pid = {:?} with signal :{:?}",
686             ProcessManager::current_pcb().pid(),
687             sig
688         );
689     });
690 }
691 /// 信号默认处理函数——忽略
692 fn sig_ignore(_sig: Signal) {
693     return;
694 }
695