xref: /DragonOS/kernel/src/arch/x86_64/ipc/signal.rs (revision 83ed0ebc293d5a10245089f627f52770fd5b9dd4)
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 /// SIGCHLD si_codes
281 #[derive(Debug, Clone, Copy, PartialEq, Eq, ToPrimitive)]
282 #[allow(dead_code)]
283 pub enum SigChildCode {
284     /// child has exited
285     ///
286     /// CLD_EXITED
287     Exited = 1,
288     /// child was killed
289     ///
290     /// CLD_KILLED
291     Killed = 2,
292     /// child terminated abnormally
293     ///
294     /// CLD_DUMPED
295     Dumped = 3,
296     /// traced child has trapped
297     ///
298     /// CLD_TRAPPED
299     Trapped = 4,
300     /// child has stopped
301     ///
302     /// CLD_STOPPED
303     Stopped = 5,
304     /// stopped child has continued
305     ///
306     /// CLD_CONTINUED
307     Continued = 6,
308 }
309 
310 impl Into<i32> for SigChildCode {
311     fn into(self) -> i32 {
312         self as i32
313     }
314 }
315 
316 #[repr(C, align(16))]
317 #[derive(Debug, Clone, Copy)]
318 pub struct SigFrame {
319     // pub pedding: u64,
320     /// 指向restorer的地址的指针。(该变量必须放在sigframe的第一位,因为这样才能在handler返回的时候,跳转到对应的代码,执行sigreturn)
321     pub ret_code_ptr: *mut core::ffi::c_void,
322     pub handler: *mut c_void,
323     pub info: SigInfo,
324     pub context: SigContext,
325 }
326 
327 #[repr(C, align(16))]
328 #[derive(Debug, Clone, Copy)]
329 pub struct SigContext {
330     /// sigcontext的标志位
331     pub sc_flags: u64,
332     pub sc_stack: SigStack, // 信号处理程序备用栈信息
333     pub frame: TrapFrame,   // 暂存的系统调用/中断返回时,原本要弹出的内核栈帧
334     // pub trap_num: u64,    // 用来保存线程结构体中的trap_num字段
335     pub oldmask: SigSet, // 暂存的执行信号处理函数之前的,被设置block的信号
336     pub cr2: u64,        // 用来保存线程结构体中的cr2字段
337     // pub err_code: u64,    // 用来保存线程结构体中的err_code字段
338     pub reserved_for_x87_state: Option<FpState>,
339     pub reserved: [u64; 8],
340 }
341 
342 impl SigContext {
343     /// 设置sigcontext
344     ///
345     /// ## 参数
346     ///
347     /// - `mask` 要被暂存的信号mask标志位
348     /// - `regs` 进入信号处理流程前,Restore all要弹出的内核栈栈帧
349     ///
350     /// ## 返回值
351     ///
352     /// - `Ok(0)`
353     /// - `Err(Systemerror)` (暂时不会返回错误)
354     pub fn setup_sigcontext(
355         &mut self,
356         mask: &SigSet,
357         frame: &TrapFrame,
358     ) -> Result<i32, SystemError> {
359         //TODO 引入线程后补上
360         // let current_thread = ProcessManager::current_pcb().thread;
361         let pcb = ProcessManager::current_pcb();
362         let mut archinfo_guard = pcb.arch_info_irqsave();
363         self.oldmask = *mask;
364         self.frame = frame.clone();
365         // context.trap_num = unsafe { (*current_thread).trap_num };
366         // context.err_code = unsafe { (*current_thread).err_code };
367         // context.cr2 = unsafe { (*current_thread).cr2 };
368         self.reserved_for_x87_state = archinfo_guard.fp_state().clone();
369 
370         // 保存完毕后,清空fp_state,以免下次save的时候,出现SIMD exception
371         archinfo_guard.clear_fp_state();
372         return Ok(0);
373     }
374 
375     /// 指定的sigcontext恢复到当前进程的内核栈帧中,并将当前线程结构体的几个参数进行恢复
376     ///
377     /// ## 参数
378     /// - `frame` 目标栈帧(也就是把context恢复到这个栈帧中)
379     ///
380     /// ##返回值
381     /// - `true` -> 成功恢复
382     /// - `false` -> 执行失败
383     pub fn restore_sigcontext(&mut self, frame: &mut TrapFrame) -> bool {
384         let guard = ProcessManager::current_pcb();
385         let mut arch_info = guard.arch_info();
386         (*frame) = self.frame.clone();
387         // (*current_thread).trap_num = (*context).trap_num;
388         *arch_info.cr2_mut() = self.cr2 as usize;
389         // (*current_thread).err_code = (*context).err_code;
390         // 如果当前进程有fpstate,则将其恢复到pcb的fp_state中
391         *arch_info.fp_state_mut() = self.reserved_for_x87_state.clone();
392         arch_info.restore_fp_state();
393         return true;
394     }
395 }
396 /// @brief 信号处理备用栈的信息
397 #[derive(Debug, Clone, Copy)]
398 pub struct SigStack {
399     pub sp: *mut c_void,
400     pub flags: u32,
401     pub size: u32,
402     pub fpstate: FpState,
403 }
404 
405 #[no_mangle]
406 unsafe extern "C" fn do_signal(frame: &mut TrapFrame) {
407     X86_64SignalArch::do_signal(frame);
408     return;
409 }
410 
411 pub struct X86_64SignalArch;
412 
413 impl SignalArch for X86_64SignalArch {
414     unsafe fn do_signal(frame: &mut TrapFrame) {
415         let pcb = ProcessManager::current_pcb();
416         let siginfo = pcb.try_siginfo(5);
417 
418         if unlikely(siginfo.is_none()) {
419             return;
420         }
421 
422         let siginfo_read_guard = siginfo.unwrap();
423 
424         // 检查sigpending是否为0
425         if siginfo_read_guard.sig_pending().signal().bits() == 0 || !frame.from_user() {
426             // 若没有正在等待处理的信号,或者将要返回到的是内核态,则返回
427             return;
428         }
429 
430         let pcb = ProcessManager::current_pcb();
431 
432         let mut sig_number: Signal;
433         let mut info: Option<SigInfo>;
434         let mut sigaction: Sigaction;
435         let sig_block: SigSet = siginfo_read_guard.sig_block().clone();
436         drop(siginfo_read_guard);
437 
438         let sig_guard = pcb.try_sig_struct_irq(5);
439         if unlikely(sig_guard.is_none()) {
440             return;
441         }
442         let siginfo_mut = pcb.try_siginfo_mut(5);
443         if unlikely(siginfo_mut.is_none()) {
444             return;
445         }
446 
447         let sig_guard = sig_guard.unwrap();
448         let mut siginfo_mut_guard = siginfo_mut.unwrap();
449         loop {
450             (sig_number, info) = siginfo_mut_guard.dequeue_signal(&sig_block);
451             // 如果信号非法,则直接返回
452             if sig_number == Signal::INVALID {
453                 return;
454             }
455 
456             sigaction = sig_guard.handlers[sig_number as usize - 1];
457 
458             match sigaction.action() {
459                 SigactionType::SaHandler(action_type) => match action_type {
460                     SaHandlerType::SigError => {
461                         kerror!("Trying to handle a Sigerror on Process:{:?}", pcb.pid());
462                         return;
463                     }
464                     SaHandlerType::SigDefault => {
465                         sigaction = Sigaction::default();
466                         break;
467                     }
468                     SaHandlerType::SigIgnore => continue,
469                     SaHandlerType::SigCustomized(_) => {
470                         break;
471                     }
472                 },
473                 SigactionType::SaSigaction(_) => todo!(),
474             }
475             // 如果当前动作是忽略这个信号,就继续循环。
476         }
477 
478         let oldset = siginfo_mut_guard.sig_block().clone();
479         //避免死锁
480         drop(siginfo_mut_guard);
481         drop(sig_guard);
482 
483         // 做完上面的检查后,开中断
484         CurrentIrqArch::interrupt_enable();
485         let res: Result<i32, SystemError> =
486             handle_signal(sig_number, &mut sigaction, &info.unwrap(), &oldset, frame);
487         if res.is_err() {
488             kerror!(
489                 "Error occurred when handling signal: {}, pid={:?}, errcode={:?}",
490                 sig_number as i32,
491                 ProcessManager::current_pcb().pid(),
492                 res.unwrap_err()
493             );
494         }
495     }
496 
497     fn sys_rt_sigreturn(trap_frame: &mut TrapFrame) -> u64 {
498         let frame = (trap_frame.rsp as usize) as *mut SigFrame;
499 
500         // 如果当前的rsp不来自用户态,则认为产生了错误(或被SROP攻击)
501         if UserBufferWriter::new(frame, size_of::<SigFrame>(), true).is_err() {
502             kerror!("rsp doesn't from user level");
503             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
504                 .map_err(|e| e.to_posix_errno());
505             return trap_frame.rax;
506         }
507         let mut sigmask: SigSet = unsafe { (*frame).context.oldmask };
508         set_current_sig_blocked(&mut sigmask);
509         // 从用户栈恢复sigcontext
510         if !unsafe { &mut (*frame).context }.restore_sigcontext(trap_frame) {
511             kerror!("unable to restore sigcontext");
512             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
513                 .map_err(|e| e.to_posix_errno());
514             // 如果这里返回 err 值的话会丢失上一个系统调用的返回值
515         }
516         // 由于系统调用的返回值会被系统调用模块被存放在rax寄存器,因此,为了还原原来的那个系统调用的返回值,我们需要在这里返回恢复后的rax的值
517         return trap_frame.rax;
518     }
519 }
520 
521 /// @brief 真正发送signal,执行自定义的处理函数
522 ///
523 /// @param sig 信号number
524 /// @param sigaction 信号响应动作
525 /// @param info 信号信息
526 /// @param oldset
527 /// @param regs 之前的系统调用将要返回的时候,要弹出的栈帧的拷贝
528 ///
529 /// @return Result<0,SystemError> 若Error, 则返回错误码,否则返回Ok(0)
530 fn handle_signal(
531     sig: Signal,
532     sigaction: &mut Sigaction,
533     info: &SigInfo,
534     oldset: &SigSet,
535     frame: &mut TrapFrame,
536 ) -> Result<i32, SystemError> {
537     // TODO 这里要补充一段逻辑,好像是为了保证引入线程之后的地址空间不会出问题。详见https://opengrok.ringotek.cn/xref/linux-6.1.9/arch/mips/kernel/signal.c#830
538 
539     // 设置栈帧
540     return setup_frame(sig, sigaction, info, oldset, frame);
541 }
542 
543 /// @brief 在用户栈上开辟一块空间,并且把内核栈的栈帧以及需要在用户态执行的代码给保存进去。
544 ///
545 /// @param regs 进入信号处理流程前,Restore all要弹出的内核栈栈帧
546 fn setup_frame(
547     sig: Signal,
548     sigaction: &mut Sigaction,
549     info: &SigInfo,
550     oldset: &SigSet,
551     trap_frame: &mut TrapFrame,
552 ) -> Result<i32, SystemError> {
553     let ret_code_ptr: *mut c_void;
554     let temp_handler: *mut c_void;
555     match sigaction.action() {
556         SigactionType::SaHandler(handler_type) => match handler_type {
557             SaHandlerType::SigDefault => {
558                 sig.handle_default();
559                 return Ok(0);
560             }
561             SaHandlerType::SigCustomized(handler) => {
562                 // 如果handler位于内核空间
563                 if handler >= MMArch::USER_END_VADDR {
564                     // 如果当前是SIGSEGV,则采用默认函数处理
565                     if sig == Signal::SIGSEGV {
566                         sig.handle_default();
567                         return Ok(0);
568                     } else {
569                         kerror!("attempting  to execute a signal handler from kernel");
570                         sig.handle_default();
571                         return Err(SystemError::EINVAL);
572                     }
573                 } else {
574                     // 为了与Linux的兼容性,64位程序必须由用户自行指定restorer
575                     if sigaction.flags().contains(SigFlags::SA_RESTORER) {
576                         ret_code_ptr = sigaction.restorer().unwrap().data() as *mut c_void;
577                     } else {
578                         kerror!(
579                             "pid-{:?} forgot to set SA_FLAG_RESTORER for signal {:?}",
580                             ProcessManager::current_pcb().pid(),
581                             sig as i32
582                         );
583                         let r = Syscall::kill(
584                             ProcessManager::current_pcb().pid(),
585                             Signal::SIGSEGV as i32,
586                         );
587                         if r.is_err() {
588                             kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
589                         }
590                         return Err(SystemError::EINVAL);
591                     }
592                     if sigaction.restorer().is_none() {
593                         kerror!(
594                             "restorer in process:{:?} is not defined",
595                             ProcessManager::current_pcb().pid()
596                         );
597                         return Err(SystemError::EINVAL);
598                     }
599                     temp_handler = handler.data() as *mut c_void;
600                 }
601             }
602             SaHandlerType::SigIgnore => {
603                 return Ok(0);
604             }
605             _ => {
606                 return Err(SystemError::EINVAL);
607             }
608         },
609         SigactionType::SaSigaction(_) => {
610             //TODO 这里应该是可以恢复栈的,等后续来做
611             kerror!("trying to recover from sigaction type instead of handler");
612             return Err(SystemError::EINVAL);
613         }
614     }
615     let frame: *mut SigFrame = get_stack(&trap_frame, size_of::<SigFrame>());
616     // kdebug!("frame=0x{:016x}", frame as usize);
617     // 要求这个frame的地址位于用户空间,因此进行校验
618     let r: Result<UserBufferWriter<'_>, SystemError> =
619         UserBufferWriter::new(frame, size_of::<SigFrame>(), true);
620     if r.is_err() {
621         // 如果地址区域位于内核空间,则直接报错
622         // todo: 生成一个sigsegv
623         let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
624         if r.is_err() {
625             kerror!("In setup frame: generate SIGSEGV signal failed");
626         }
627         kerror!("In setup frame: access check failed");
628         return Err(SystemError::EFAULT);
629     }
630 
631     // 将siginfo拷贝到用户栈
632     info.copy_siginfo_to_user(unsafe { &mut ((*frame).info) as *mut SigInfo })
633         .map_err(|e| -> SystemError {
634             let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
635             if r.is_err() {
636                 kerror!("In copy_siginfo_to_user: generate SIGSEGV signal failed");
637             }
638             return e;
639         })?;
640 
641     // todo: 拷贝处理程序备用栈的地址、大小、ss_flags
642 
643     unsafe {
644         (*frame)
645             .context
646             .setup_sigcontext(oldset, &trap_frame)
647             .map_err(|e: SystemError| -> SystemError {
648                 let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
649                 if r.is_err() {
650                     kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
651                 }
652                 return e;
653             })?
654     };
655 
656     unsafe {
657         // 在开头检验过sigaction.restorer是否为空了,实际上libc会保证 restorer始终不为空
658         (*frame).ret_code_ptr = ret_code_ptr;
659     }
660 
661     unsafe { (*frame).handler = temp_handler };
662     // 传入信号处理函数的第一个参数
663     trap_frame.rdi = sig as u64;
664     trap_frame.rsi = unsafe { &(*frame).info as *const SigInfo as u64 };
665     trap_frame.rsp = frame as u64;
666     trap_frame.rip = unsafe { (*frame).handler as u64 };
667     // 设置cs和ds寄存器
668     trap_frame.cs = (USER_CS.bits() | 0x3) as u64;
669     trap_frame.ds = (USER_DS.bits() | 0x3) as u64;
670 
671     // 禁用中断
672     // trap_frame.rflags &= !(0x200);
673 
674     return Ok(0);
675 }
676 
677 #[inline(always)]
678 fn get_stack(frame: &TrapFrame, size: usize) -> *mut SigFrame {
679     // TODO:在 linux 中会根据 Sigaction 中的一个flag 的值来确定是否使用pcb中的 signal 处理程序备用堆栈,现在的
680     // pcb中也没有这个备用堆栈
681 
682     // 默认使用 用户栈的栈顶指针-128字节的红区-sigframe的大小 并且16字节对齐
683     let mut rsp: usize = (frame.rsp as usize) - 128 - size;
684     // 按照要求进行对齐,别问为什么减8,不减8就是错的,可以看
685     // https://sourcegraph.com/github.com/torvalds/linux@dd72f9c7e512da377074d47d990564959b772643/-/blob/arch/x86/kernel/signal.c?L124
686     // 我猜测是跟x86汇编的某些弹栈行为有关系,它可能会出于某种原因递增 rsp
687     rsp &= (!(STACK_ALIGN - 1)) as usize - 8;
688     // rsp &= (!(STACK_ALIGN - 1)) as usize;
689     return rsp as *mut SigFrame;
690 }
691 
692 /// 信号默认处理函数——终止进程
693 fn sig_terminate(sig: Signal) {
694     ProcessManager::exit(sig as usize);
695 }
696 
697 /// 信号默认处理函数——终止进程并生成 core dump
698 fn sig_terminate_dump(sig: Signal) {
699     ProcessManager::exit(sig as usize);
700     // TODO 生成 coredump 文件
701 }
702 
703 /// 信号默认处理函数——暂停进程
704 fn sig_stop(sig: Signal) {
705     let guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
706     ProcessManager::mark_stop().unwrap_or_else(|e| {
707         kerror!(
708             "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}",
709             e,
710             ProcessManager::current_pcb(),
711             sig
712         );
713     });
714     drop(guard);
715     sched();
716     // TODO 暂停进程
717 }
718 /// 信号默认处理函数——继续进程
719 fn sig_continue(sig: Signal) {
720     ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| {
721         kerror!(
722             "Failed to wake up process pid = {:?} with signal :{:?}",
723             ProcessManager::current_pcb().pid(),
724             sig
725         );
726     });
727 }
728 /// 信号默认处理函数——忽略
729 fn sig_ignore(_sig: Signal) {
730     return;
731 }
732