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