xref: /DragonOS/kernel/src/arch/x86_64/ipc/signal.rs (revision 40314b30ab2a7e1fd06a05a00f693e644e446035)
1 use core::{ffi::c_void, 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();
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 }
372 
373 pub struct X86_64SignalArch;
374 
375 impl SignalArch for X86_64SignalArch {
376     unsafe fn do_signal(frame: &mut TrapFrame) {
377         // 检查sigpending是否为0
378         if ProcessManager::current_pcb()
379             .sig_info()
380             .sig_pending()
381             .signal()
382             .bits()
383             == 0
384             || !frame.from_user()
385         {
386             // 若没有正在等待处理的信号,或者将要返回到的是内核态,则启用中断,然后返回
387             CurrentIrqArch::interrupt_enable();
388             return;
389         }
390 
391         // 做完上面的检查后,开中断
392         CurrentIrqArch::interrupt_enable();
393         let pcb = ProcessManager::current_pcb();
394         let sig_guard = pcb.sig_struct();
395         let mut sig_number: Signal;
396         let mut info: Option<SigInfo>;
397         let mut sigaction: Sigaction;
398         let reader = pcb.sig_info();
399         let sig_block: SigSet = reader.sig_block().clone();
400         drop(reader);
401         loop {
402             (sig_number, info) = pcb.sig_info_mut().dequeue_signal(&sig_block);
403             // 如果信号非法,则直接返回
404             if sig_number == Signal::INVALID {
405                 return;
406             }
407 
408             sigaction = sig_guard.handlers[sig_number as usize - 1];
409             match sigaction.action() {
410                 SigactionType::SaHandler(action_type) => match action_type {
411                     SaHandlerType::SigError => {
412                         kerror!("Trying to handle a Sigerror on Process:{:?}", pcb.pid());
413                         return;
414                     }
415                     SaHandlerType::SigDefault => {
416                         sigaction = Sigaction::default();
417                         break;
418                     }
419                     SaHandlerType::SigIgnore => continue,
420                     SaHandlerType::SigCustomized(_) => {
421                         break;
422                     }
423                 },
424                 SigactionType::SaSigaction(_) => todo!(),
425             }
426             // 如果当前动作是忽略这个信号,就继续循环。
427         }
428         // 所有的信号都处理完了
429         let reader = pcb.sig_info();
430         let oldset = reader.sig_block().clone();
431         //避免死锁
432         drop(reader);
433         drop(sig_guard);
434         let res: Result<i32, SystemError> =
435             handle_signal(sig_number, &mut sigaction, &info.unwrap(), &oldset, frame);
436         if res.is_err() {
437             kerror!(
438                 "Error occurred when handling signal: {}, pid={:?}, errcode={:?}",
439                 sig_number as i32,
440                 ProcessManager::current_pcb().pid(),
441                 res.unwrap_err()
442             );
443         }
444     }
445 
446     fn sys_rt_sigreturn(trap_frame: &mut TrapFrame) -> u64 {
447         let frame = (trap_frame.rsp as usize) as *mut SigFrame;
448 
449         // 如果当前的rsp不来自用户态,则认为产生了错误(或被SROP攻击)
450         if UserBufferWriter::new(frame, size_of::<SigFrame>(), true).is_err() {
451             kerror!("rsp doesn't from user level");
452             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
453                 .map_err(|e| e.to_posix_errno());
454             return trap_frame.rax;
455         }
456         let mut sigmask: SigSet = unsafe { (*frame).context.oldmask };
457         set_current_sig_blocked(&mut sigmask);
458         // 从用户栈恢复sigcontext
459         if !unsafe { &mut (*frame).context }.restore_sigcontext(trap_frame) {
460             kerror!("unable to restore sigcontext");
461             let _r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32)
462                 .map_err(|e| e.to_posix_errno());
463             // 如果这里返回 err 值的话会丢失上一个系统调用的返回值
464         }
465         // 由于系统调用的返回值会被系统调用模块被存放在rax寄存器,因此,为了还原原来的那个系统调用的返回值,我们需要在这里返回恢复后的rax的值
466         return trap_frame.rax;
467     }
468 }
469 
470 /// @brief 真正发送signal,执行自定义的处理函数
471 ///
472 /// @param sig 信号number
473 /// @param sigaction 信号响应动作
474 /// @param info 信号信息
475 /// @param oldset
476 /// @param regs 之前的系统调用将要返回的时候,要弹出的栈帧的拷贝
477 ///
478 /// @return Result<0,SystemError> 若Error, 则返回错误码,否则返回Ok(0)
479 fn handle_signal(
480     sig: Signal,
481     sigaction: &mut Sigaction,
482     info: &SigInfo,
483     oldset: &SigSet,
484     frame: &mut TrapFrame,
485 ) -> Result<i32, SystemError> {
486     // TODO 这里要补充一段逻辑,好像是为了保证引入线程之后的地址空间不会出问题。详见https://opengrok.ringotek.cn/xref/linux-6.1.9/arch/mips/kernel/signal.c#830
487 
488     // 设置栈帧
489     return setup_frame(sig, sigaction, info, oldset, frame);
490 }
491 
492 /// @brief 在用户栈上开辟一块空间,并且把内核栈的栈帧以及需要在用户态执行的代码给保存进去。
493 ///
494 /// @param regs 进入信号处理流程前,Restore all要弹出的内核栈栈帧
495 fn setup_frame(
496     sig: Signal,
497     sigaction: &mut Sigaction,
498     info: &SigInfo,
499     oldset: &SigSet,
500     trap_frame: &mut TrapFrame,
501 ) -> Result<i32, SystemError> {
502     let ret_code_ptr: *mut c_void;
503     let temp_handler: *mut c_void;
504     match sigaction.action() {
505         SigactionType::SaHandler(handler_type) => match handler_type {
506             SaHandlerType::SigDefault => {
507                 sig.handle_default();
508                 return Ok(0);
509             }
510             SaHandlerType::SigCustomized(handler) => {
511                 // 如果handler位于内核空间
512                 if handler >= MMArch::USER_END_VADDR {
513                     // 如果当前是SIGSEGV,则采用默认函数处理
514                     if sig == Signal::SIGSEGV {
515                         sig.handle_default();
516                         return Ok(0);
517                     } else {
518                         kerror!("attempting  to execute a signal handler from kernel");
519                         sig.handle_default();
520                         return Err(SystemError::EINVAL);
521                     }
522                 } else {
523                     // 为了与Linux的兼容性,64位程序必须由用户自行指定restorer
524                     if sigaction.flags().contains(SigFlags::SA_RESTORER) {
525                         ret_code_ptr = sigaction.restorer().unwrap().data() as *mut c_void;
526                     } else {
527                         kerror!(
528                             "pid-{:?} forgot to set SA_FLAG_RESTORER for signal {:?}",
529                             ProcessManager::current_pcb().pid(),
530                             sig as i32
531                         );
532                         let r = Syscall::kill(
533                             ProcessManager::current_pcb().pid(),
534                             Signal::SIGSEGV as i32,
535                         );
536                         if r.is_err() {
537                             kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
538                         }
539                         return Err(SystemError::EINVAL);
540                     }
541                     if sigaction.restorer().is_none() {
542                         kerror!(
543                             "restorer in process:{:?} is not defined",
544                             ProcessManager::current_pcb().pid()
545                         );
546                         return Err(SystemError::EINVAL);
547                     }
548                     temp_handler = handler.data() as *mut c_void;
549                 }
550             }
551             SaHandlerType::SigIgnore => {
552                 return Ok(0);
553             }
554             _ => {
555                 return Err(SystemError::EINVAL);
556             }
557         },
558         SigactionType::SaSigaction(_) => {
559             //TODO 这里应该是可以恢复栈的,等后续来做
560             kerror!("trying to recover from sigaction type instead of handler");
561             return Err(SystemError::EINVAL);
562         }
563     }
564     let frame: *mut SigFrame = get_stack(&trap_frame, size_of::<SigFrame>());
565     // kdebug!("frame=0x{:016x}", frame as usize);
566     // 要求这个frame的地址位于用户空间,因此进行校验
567     let r = UserBufferWriter::new(frame, size_of::<SigFrame>(), true);
568     if r.is_err() {
569         // 如果地址区域位于内核空间,则直接报错
570         // todo: 生成一个sigsegv
571         let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
572         if r.is_err() {
573             kerror!("In setup frame: generate SIGSEGV signal failed");
574         }
575         kerror!("In setup frame: access check failed");
576         return Err(SystemError::EFAULT);
577     }
578 
579     // 将siginfo拷贝到用户栈
580     info.copy_siginfo_to_user(unsafe { &mut ((*frame).info) as *mut SigInfo })
581         .map_err(|e| -> SystemError {
582             let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
583             if r.is_err() {
584                 kerror!("In copy_siginfo_to_user: generate SIGSEGV signal failed");
585             }
586             return e;
587         })?;
588 
589     // todo: 拷贝处理程序备用栈的地址、大小、ss_flags
590 
591     unsafe {
592         (*frame)
593             .context
594             .setup_sigcontext(oldset, &trap_frame)
595             .map_err(|e: SystemError| -> SystemError {
596                 let r = Syscall::kill(ProcessManager::current_pcb().pid(), Signal::SIGSEGV as i32);
597                 if r.is_err() {
598                     kerror!("In setup_sigcontext: generate SIGSEGV signal failed");
599                 }
600                 return e;
601             })?
602     };
603 
604     unsafe {
605         // 在开头检验过sigaction.restorer是否为空了,实际上libc会保证 restorer始终不为空
606         (*frame).ret_code_ptr = ret_code_ptr;
607     }
608 
609     unsafe { (*frame).handler = temp_handler };
610     // 传入信号处理函数的第一个参数
611     trap_frame.rdi = sig as u64;
612     trap_frame.rsi = unsafe { &(*frame).info as *const SigInfo as u64 };
613     trap_frame.rsp = frame as u64;
614     trap_frame.rip = unsafe { (*frame).handler as u64 };
615     // 设置cs和ds寄存器
616     trap_frame.cs = (USER_CS.bits() | 0x3) as u64;
617     trap_frame.ds = (USER_DS.bits() | 0x3) as u64;
618 
619     // 禁用中断
620     // trap_frame.rflags &= !(0x200);
621 
622     return Ok(0);
623 }
624 
625 #[inline(always)]
626 fn get_stack(frame: &TrapFrame, size: usize) -> *mut SigFrame {
627     // TODO:在 linux 中会根据 Sigaction 中的一个flag 的值来确定是否使用pcb中的 signal 处理程序备用堆栈,现在的
628     // pcb中也没有这个备用堆栈
629 
630     // 默认使用 用户栈的栈顶指针-128字节的红区-sigframe的大小 并且16字节对齐
631     let mut rsp: usize = (frame.rsp as usize) - 128 - size;
632     // 按照要求进行对齐,别问为什么减8,不减8就是错的,可以看
633     // https://sourcegraph.com/github.com/torvalds/linux@dd72f9c7e512da377074d47d990564959b772643/-/blob/arch/x86/kernel/signal.c?L124
634     // 我猜测是跟x86汇编的某些弹栈行为有关系,它可能会出于某种原因递增 rsp
635     rsp &= (!(STACK_ALIGN - 1)) as usize - 8;
636     // rsp &= (!(STACK_ALIGN - 1)) as usize;
637     return rsp as *mut SigFrame;
638 }
639 
640 /// 信号默认处理函数——终止进程
641 fn sig_terminate(sig: Signal) {
642     ProcessManager::exit(sig as usize);
643 }
644 
645 /// 信号默认处理函数——终止进程并生成 core dump
646 fn sig_terminate_dump(sig: Signal) {
647     ProcessManager::exit(sig as usize);
648     // TODO 生成 coredump 文件
649 }
650 
651 /// 信号默认处理函数——暂停进程
652 fn sig_stop(sig: Signal) {
653     let guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
654     ProcessManager::mark_stop().unwrap_or_else(|e| {
655         kerror!(
656             "sleep error :{:?},failed to sleep process :{:?}, with signal :{:?}",
657             e,
658             ProcessManager::current_pcb(),
659             sig
660         );
661     });
662     drop(guard);
663     sched();
664     // TODO 暂停进程
665 }
666 /// 信号默认处理函数——继续进程
667 fn sig_continue(sig: Signal) {
668     ProcessManager::wakeup_stop(&ProcessManager::current_pcb()).unwrap_or_else(|_| {
669         kerror!(
670             "Failed to wake up process pid = {:?} with signal :{:?}",
671             ProcessManager::current_pcb().pid(),
672             sig
673         );
674     });
675 }
676 /// 信号默认处理函数——忽略
677 fn sig_ignore(_sig: Signal) {
678     return;
679 }
680