xref: /DragonOS/kernel/src/process/mod.rs (revision b5b571e02693d91eb6918d3b7561e088c3e7ee81) !
1 use core::{
2     hash::Hash,
3     hint::spin_loop,
4     intrinsics::{likely, unlikely},
5     mem::ManuallyDrop,
6     sync::atomic::{compiler_fence, AtomicBool, AtomicIsize, AtomicUsize, Ordering},
7 };
8 
9 use alloc::{
10     string::{String, ToString},
11     sync::{Arc, Weak},
12     vec::Vec,
13 };
14 use hashbrown::HashMap;
15 use system_error::SystemError;
16 
17 use crate::{
18     arch::{
19         ipc::signal::{AtomicSignal, SigSet, Signal},
20         process::ArchPCBInfo,
21         sched::sched,
22         CurrentIrqArch,
23     },
24     driver::tty::tty_core::TtyCore,
25     exception::InterruptArch,
26     filesystem::{
27         procfs::procfs_unregister_pid,
28         vfs::{file::FileDescriptorVec, FileType},
29     },
30     ipc::signal_types::{SigInfo, SigPending, SignalStruct},
31     kdebug, kinfo,
32     libs::{
33         align::AlignedBox,
34         casting::DowncastArc,
35         futex::{
36             constant::{FutexFlag, FUTEX_BITSET_MATCH_ANY},
37             futex::Futex,
38         },
39         lock_free_flags::LockFreeFlags,
40         rwlock::{RwLock, RwLockReadGuard, RwLockUpgradableGuard, RwLockWriteGuard},
41         spinlock::{SpinLock, SpinLockGuard},
42         wait_queue::WaitQueue,
43     },
44     mm::{percpu::PerCpuVar, set_IDLE_PROCESS_ADDRESS_SPACE, ucontext::AddressSpace, VirtAddr},
45     net::socket::SocketInode,
46     sched::{
47         completion::Completion,
48         core::{sched_enqueue, CPU_EXECUTING},
49         SchedPolicy, SchedPriority,
50     },
51     smp::{
52         cpu::{AtomicProcessorId, ProcessorId},
53         kick_cpu,
54     },
55     syscall::{user_access::clear_user, Syscall},
56 };
57 
58 use self::kthread::WorkerPrivate;
59 
60 pub mod abi;
61 pub mod c_adapter;
62 pub mod exec;
63 pub mod exit;
64 pub mod fork;
65 pub mod idle;
66 pub mod kthread;
67 pub mod pid;
68 pub mod resource;
69 pub mod stdio;
70 pub mod syscall;
71 pub mod utils;
72 
73 /// 系统中所有进程的pcb
74 static ALL_PROCESS: SpinLock<Option<HashMap<Pid, Arc<ProcessControlBlock>>>> = SpinLock::new(None);
75 
76 pub static mut SWITCH_RESULT: Option<PerCpuVar<SwitchResult>> = None;
77 
78 /// 一个只改变1次的全局变量,标志进程管理器是否已经初始化完成
79 static mut __PROCESS_MANAGEMENT_INIT_DONE: bool = false;
80 
81 #[derive(Debug)]
82 pub struct SwitchResult {
83     pub prev_pcb: Option<Arc<ProcessControlBlock>>,
84     pub next_pcb: Option<Arc<ProcessControlBlock>>,
85 }
86 
87 impl SwitchResult {
88     pub fn new() -> Self {
89         Self {
90             prev_pcb: None,
91             next_pcb: None,
92         }
93     }
94 }
95 
96 #[derive(Debug)]
97 pub struct ProcessManager;
98 impl ProcessManager {
99     #[inline(never)]
100     fn init() {
101         static INIT_FLAG: AtomicBool = AtomicBool::new(false);
102         if INIT_FLAG
103             .compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
104             .is_err()
105         {
106             panic!("ProcessManager has been initialized!");
107         }
108 
109         unsafe {
110             compiler_fence(Ordering::SeqCst);
111             kdebug!("To create address space for INIT process.");
112             // test_buddy();
113             set_IDLE_PROCESS_ADDRESS_SPACE(
114                 AddressSpace::new(true).expect("Failed to create address space for INIT process."),
115             );
116             kdebug!("INIT process address space created.");
117             compiler_fence(Ordering::SeqCst);
118         };
119 
120         ALL_PROCESS.lock_irqsave().replace(HashMap::new());
121         Self::arch_init();
122         kdebug!("process arch init done.");
123         Self::init_idle();
124         kdebug!("process idle init done.");
125 
126         unsafe { __PROCESS_MANAGEMENT_INIT_DONE = true };
127         kinfo!("Process Manager initialized.");
128     }
129 
130     /// 判断进程管理器是否已经初始化完成
131     pub fn initialized() -> bool {
132         unsafe { __PROCESS_MANAGEMENT_INIT_DONE }
133     }
134 
135     /// 获取当前进程的pcb
136     pub fn current_pcb() -> Arc<ProcessControlBlock> {
137         if unlikely(unsafe { !__PROCESS_MANAGEMENT_INIT_DONE }) {
138             kerror!("unsafe__PROCESS_MANAGEMENT_INIT_DONE == false");
139             loop {
140                 spin_loop();
141             }
142         }
143         return ProcessControlBlock::arch_current_pcb();
144     }
145 
146     /// 获取当前进程的pid
147     ///
148     /// 如果进程管理器未初始化完成,那么返回0
149     pub fn current_pid() -> Pid {
150         if unlikely(unsafe { !__PROCESS_MANAGEMENT_INIT_DONE }) {
151             return Pid(0);
152         }
153 
154         return ProcessManager::current_pcb().pid();
155     }
156 
157     /// 增加当前进程的锁持有计数
158     #[inline(always)]
159     pub fn preempt_disable() {
160         if likely(unsafe { __PROCESS_MANAGEMENT_INIT_DONE }) {
161             ProcessManager::current_pcb().preempt_disable();
162         }
163     }
164 
165     /// 减少当前进程的锁持有计数
166     #[inline(always)]
167     pub fn preempt_enable() {
168         if likely(unsafe { __PROCESS_MANAGEMENT_INIT_DONE }) {
169             ProcessManager::current_pcb().preempt_enable();
170         }
171     }
172 
173     /// 根据pid获取进程的pcb
174     ///
175     /// ## 参数
176     ///
177     /// - `pid` : 进程的pid
178     ///
179     /// ## 返回值
180     ///
181     /// 如果找到了对应的进程,那么返回该进程的pcb,否则返回None
182     pub fn find(pid: Pid) -> Option<Arc<ProcessControlBlock>> {
183         return ALL_PROCESS.lock_irqsave().as_ref()?.get(&pid).cloned();
184     }
185 
186     /// 向系统中添加一个进程的pcb
187     ///
188     /// ## 参数
189     ///
190     /// - `pcb` : 进程的pcb
191     ///
192     /// ## 返回值
193     ///
194     /// 无
195     pub fn add_pcb(pcb: Arc<ProcessControlBlock>) {
196         ALL_PROCESS
197             .lock_irqsave()
198             .as_mut()
199             .unwrap()
200             .insert(pcb.pid(), pcb.clone());
201     }
202 
203     /// 唤醒一个进程
204     pub fn wakeup(pcb: &Arc<ProcessControlBlock>) -> Result<(), SystemError> {
205         let _guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
206         let state = pcb.sched_info().inner_lock_read_irqsave().state();
207         if state.is_blocked() {
208             let mut writer = pcb.sched_info().inner_lock_write_irqsave();
209             let state = writer.state();
210             if state.is_blocked() {
211                 writer.set_state(ProcessState::Runnable);
212                 // avoid deadlock
213                 drop(writer);
214 
215                 sched_enqueue(pcb.clone(), true);
216                 return Ok(());
217             } else if state.is_exited() {
218                 return Err(SystemError::EINVAL);
219             } else {
220                 return Ok(());
221             }
222         } else if state.is_exited() {
223             return Err(SystemError::EINVAL);
224         } else {
225             return Ok(());
226         }
227     }
228 
229     /// 唤醒暂停的进程
230     pub fn wakeup_stop(pcb: &Arc<ProcessControlBlock>) -> Result<(), SystemError> {
231         let _guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
232         let state = pcb.sched_info().inner_lock_read_irqsave().state();
233         if let ProcessState::Stopped = state {
234             let mut writer = pcb.sched_info().inner_lock_write_irqsave();
235             let state = writer.state();
236             if let ProcessState::Stopped = state {
237                 writer.set_state(ProcessState::Runnable);
238                 // avoid deadlock
239                 drop(writer);
240 
241                 sched_enqueue(pcb.clone(), true);
242                 return Ok(());
243             } else if state.is_runnable() {
244                 return Ok(());
245             } else {
246                 return Err(SystemError::EINVAL);
247             }
248         } else if state.is_runnable() {
249             return Ok(());
250         } else {
251             return Err(SystemError::EINVAL);
252         }
253     }
254 
255     /// 标志当前进程永久睡眠,但是发起调度的工作,应该由调用者完成
256     ///
257     /// ## 注意
258     ///
259     /// - 进入当前函数之前,不能持有sched_info的锁
260     /// - 进入当前函数之前,必须关闭中断
261     /// - 进入当前函数之后必须保证逻辑的正确性,避免被重复加入调度队列
262     pub fn mark_sleep(interruptable: bool) -> Result<(), SystemError> {
263         assert!(
264             !CurrentIrqArch::is_irq_enabled(),
265             "interrupt must be disabled before enter ProcessManager::mark_sleep()"
266         );
267 
268         let pcb = ProcessManager::current_pcb();
269         let mut writer = pcb.sched_info().inner_lock_write_irqsave();
270         if !matches!(writer.state(), ProcessState::Exited(_)) {
271             writer.set_state(ProcessState::Blocked(interruptable));
272             pcb.flags().insert(ProcessFlags::NEED_SCHEDULE);
273             drop(writer);
274 
275             return Ok(());
276         }
277         return Err(SystemError::EINTR);
278     }
279 
280     /// 标志当前进程为停止状态,但是发起调度的工作,应该由调用者完成
281     ///
282     /// ## 注意
283     ///
284     /// - 进入当前函数之前,不能持有sched_info的锁
285     /// - 进入当前函数之前,必须关闭中断
286     pub fn mark_stop() -> Result<(), SystemError> {
287         assert!(
288             !CurrentIrqArch::is_irq_enabled(),
289             "interrupt must be disabled before enter ProcessManager::mark_stop()"
290         );
291 
292         let pcb = ProcessManager::current_pcb();
293         let mut writer = pcb.sched_info().inner_lock_write_irqsave();
294         if !matches!(writer.state(), ProcessState::Exited(_)) {
295             writer.set_state(ProcessState::Stopped);
296             pcb.flags().insert(ProcessFlags::NEED_SCHEDULE);
297             drop(writer);
298 
299             return Ok(());
300         }
301         return Err(SystemError::EINTR);
302     }
303     /// 当子进程退出后向父进程发送通知
304     fn exit_notify() {
305         let current = ProcessManager::current_pcb();
306         // 让INIT进程收养所有子进程
307         if current.pid() != Pid(1) {
308             unsafe {
309                 current
310                     .adopt_childen()
311                     .unwrap_or_else(|e| panic!("adopte_childen failed: error: {e:?}"))
312             };
313             let r = current.parent_pcb.read_irqsave().upgrade();
314             if r.is_none() {
315                 return;
316             }
317             let parent_pcb = r.unwrap();
318             let r = Syscall::kill(parent_pcb.pid(), Signal::SIGCHLD as i32);
319             if r.is_err() {
320                 kwarn!(
321                     "failed to send kill signal to {:?}'s parent pcb {:?}",
322                     current.pid(),
323                     parent_pcb.pid()
324                 );
325             }
326             // todo: 这里需要向父进程发送SIGCHLD信号
327             // todo: 这里还需要根据线程组的信息,决定信号的发送
328         }
329     }
330 
331     /// 退出当前进程
332     ///
333     /// ## 参数
334     ///
335     /// - `exit_code` : 进程的退出码
336     pub fn exit(exit_code: usize) -> ! {
337         // 关中断
338         unsafe { CurrentIrqArch::interrupt_disable() };
339         let pcb = ProcessManager::current_pcb();
340         let pid = pcb.pid();
341         pcb.sched_info
342             .inner_lock_write_irqsave()
343             .set_state(ProcessState::Exited(exit_code));
344         pcb.wait_queue.wakeup(Some(ProcessState::Blocked(true)));
345 
346         // 进行进程退出后的工作
347         let thread = pcb.thread.write_irqsave();
348         if let Some(addr) = thread.set_child_tid {
349             unsafe { clear_user(addr, core::mem::size_of::<i32>()).expect("clear tid failed") };
350         }
351 
352         if let Some(addr) = thread.clear_child_tid {
353             if Arc::strong_count(&pcb.basic().user_vm().expect("User VM Not found")) > 1 {
354                 let _ =
355                     Futex::futex_wake(addr, FutexFlag::FLAGS_MATCH_NONE, 1, FUTEX_BITSET_MATCH_ANY);
356             }
357             unsafe { clear_user(addr, core::mem::size_of::<i32>()).expect("clear tid failed") };
358         }
359 
360         // 如果是vfork出来的进程,则需要处理completion
361         if thread.vfork_done.is_some() {
362             thread.vfork_done.as_ref().unwrap().complete_all();
363         }
364         drop(thread);
365         unsafe { pcb.basic_mut().set_user_vm(None) };
366         drop(pcb);
367         ProcessManager::exit_notify();
368         unsafe { CurrentIrqArch::interrupt_enable() };
369 
370         sched();
371         kerror!("pid {pid:?} exited but sched again!");
372         #[allow(clippy::empty_loop)]
373         loop {
374             spin_loop();
375         }
376     }
377 
378     pub unsafe fn release(pid: Pid) {
379         let pcb = ProcessManager::find(pid);
380         if pcb.is_some() {
381             // let pcb = pcb.unwrap();
382             // 判断该pcb是否在全局没有任何引用
383             // TODO: 当前,pcb的Arc指针存在泄露问题,引用计数不正确,打算在接下来实现debug专用的Arc,方便调试,然后解决这个bug。
384             //          因此目前暂时注释掉,使得能跑
385             // if Arc::strong_count(&pcb) <= 2 {
386             //     drop(pcb);
387             //     ALL_PROCESS.lock().as_mut().unwrap().remove(&pid);
388             // } else {
389             //     // 如果不为1就panic
390             //     let msg = format!("pcb '{:?}' is still referenced, strong count={}",pcb.pid(),  Arc::strong_count(&pcb));
391             //     kerror!("{}", msg);
392             //     panic!()
393             // }
394 
395             ALL_PROCESS.lock_irqsave().as_mut().unwrap().remove(&pid);
396         }
397     }
398 
399     /// 上下文切换完成后的钩子函数
400     unsafe fn switch_finish_hook() {
401         // kdebug!("switch_finish_hook");
402         let prev_pcb = SWITCH_RESULT
403             .as_mut()
404             .unwrap()
405             .get_mut()
406             .prev_pcb
407             .take()
408             .expect("prev_pcb is None");
409         let next_pcb = SWITCH_RESULT
410             .as_mut()
411             .unwrap()
412             .get_mut()
413             .next_pcb
414             .take()
415             .expect("next_pcb is None");
416 
417         // 由于进程切换前使用了SpinLockGuard::leak(),所以这里需要手动释放锁
418         prev_pcb.arch_info.force_unlock();
419         next_pcb.arch_info.force_unlock();
420     }
421 
422     /// 如果目标进程正在目标CPU上运行,那么就让这个cpu陷入内核态
423     ///
424     /// ## 参数
425     ///
426     /// - `pcb` : 进程的pcb
427     #[allow(dead_code)]
428     pub fn kick(pcb: &Arc<ProcessControlBlock>) {
429         ProcessManager::current_pcb().preempt_disable();
430         let cpu_id = pcb.sched_info().on_cpu();
431 
432         if let Some(cpu_id) = cpu_id {
433             if pcb.pid() == CPU_EXECUTING.get(cpu_id) {
434                 kick_cpu(cpu_id).expect("ProcessManager::kick(): Failed to kick cpu");
435             }
436         }
437 
438         ProcessManager::current_pcb().preempt_enable();
439     }
440 }
441 
442 /// 上下文切换的钩子函数,当这个函数return的时候,将会发生上下文切换
443 #[cfg(target_arch = "x86_64")]
444 #[inline(never)]
445 pub unsafe extern "sysv64" fn switch_finish_hook() {
446     ProcessManager::switch_finish_hook();
447 }
448 #[cfg(target_arch = "riscv64")]
449 pub unsafe extern "C" fn switch_finish_hook() {
450     ProcessManager::switch_finish_hook();
451 }
452 
453 int_like!(Pid, AtomicPid, usize, AtomicUsize);
454 
455 impl ToString for Pid {
456     fn to_string(&self) -> String {
457         self.0.to_string()
458     }
459 }
460 
461 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
462 pub enum ProcessState {
463     /// The process is running on a CPU or in a run queue.
464     Runnable,
465     /// The process is waiting for an event to occur.
466     /// 其中的bool表示该等待过程是否可以被打断。
467     /// - 如果该bool为true,那么,硬件中断/信号/其他系统事件都可以打断该等待过程,使得该进程重新进入Runnable状态。
468     /// - 如果该bool为false,那么,这个进程必须被显式的唤醒,才能重新进入Runnable状态。
469     Blocked(bool),
470     /// 进程被信号终止
471     Stopped,
472     /// 进程已经退出,usize表示进程的退出码
473     Exited(usize),
474 }
475 
476 #[allow(dead_code)]
477 impl ProcessState {
478     #[inline(always)]
479     pub fn is_runnable(&self) -> bool {
480         return matches!(self, ProcessState::Runnable);
481     }
482 
483     #[inline(always)]
484     pub fn is_blocked(&self) -> bool {
485         return matches!(self, ProcessState::Blocked(_));
486     }
487 
488     #[inline(always)]
489     pub fn is_blocked_interruptable(&self) -> bool {
490         return matches!(self, ProcessState::Blocked(true));
491     }
492 
493     /// Returns `true` if the process state is [`Exited`].
494     #[inline(always)]
495     pub fn is_exited(&self) -> bool {
496         return matches!(self, ProcessState::Exited(_));
497     }
498 
499     /// Returns `true` if the process state is [`Stopped`].
500     ///
501     /// [`Stopped`]: ProcessState::Stopped
502     #[inline(always)]
503     pub fn is_stopped(&self) -> bool {
504         matches!(self, ProcessState::Stopped)
505     }
506 
507     /// Returns exit code if the process state is [`Exited`].
508     #[inline(always)]
509     pub fn exit_code(&self) -> Option<usize> {
510         match self {
511             ProcessState::Exited(code) => Some(*code),
512             _ => None,
513         }
514     }
515 }
516 
517 bitflags! {
518     /// pcb的标志位
519     pub struct ProcessFlags: usize {
520         /// 当前pcb表示一个内核线程
521         const KTHREAD = 1 << 0;
522         /// 当前进程需要被调度
523         const NEED_SCHEDULE = 1 << 1;
524         /// 进程由于vfork而与父进程存在资源共享
525         const VFORK = 1 << 2;
526         /// 进程不可被冻结
527         const NOFREEZE = 1 << 3;
528         /// 进程正在退出
529         const EXITING = 1 << 4;
530         /// 进程由于接收到终止信号唤醒
531         const WAKEKILL = 1 << 5;
532         /// 进程由于接收到信号而退出.(Killed by a signal)
533         const SIGNALED = 1 << 6;
534         /// 进程需要迁移到其他cpu上
535         const NEED_MIGRATE = 1 << 7;
536         /// 随机化的虚拟地址空间,主要用于动态链接器的加载
537         const RANDOMIZE = 1 << 8;
538     }
539 }
540 
541 #[derive(Debug)]
542 pub struct ProcessControlBlock {
543     /// 当前进程的pid
544     pid: Pid,
545     /// 当前进程的线程组id(这个值在同一个线程组内永远不变)
546     tgid: Pid,
547 
548     basic: RwLock<ProcessBasicInfo>,
549     /// 当前进程的自旋锁持有计数
550     preempt_count: AtomicUsize,
551 
552     flags: LockFreeFlags<ProcessFlags>,
553     worker_private: SpinLock<Option<WorkerPrivate>>,
554     /// 进程的内核栈
555     kernel_stack: RwLock<KernelStack>,
556 
557     /// 系统调用栈
558     syscall_stack: RwLock<KernelStack>,
559 
560     /// 与调度相关的信息
561     sched_info: ProcessSchedulerInfo,
562     /// 与处理器架构相关的信息
563     arch_info: SpinLock<ArchPCBInfo>,
564     /// 与信号处理相关的信息(似乎可以是无锁的)
565     sig_info: RwLock<ProcessSignalInfo>,
566     /// 信号处理结构体
567     sig_struct: SpinLock<SignalStruct>,
568     /// 退出信号S
569     exit_signal: AtomicSignal,
570 
571     /// 父进程指针
572     parent_pcb: RwLock<Weak<ProcessControlBlock>>,
573     /// 真实父进程指针
574     real_parent_pcb: RwLock<Weak<ProcessControlBlock>>,
575 
576     /// 子进程链表
577     children: RwLock<Vec<Pid>>,
578 
579     /// 等待队列
580     wait_queue: WaitQueue,
581 
582     /// 线程信息
583     thread: RwLock<ThreadInfo>,
584 }
585 
586 impl ProcessControlBlock {
587     /// Generate a new pcb.
588     ///
589     /// ## 参数
590     ///
591     /// - `name` : 进程的名字
592     /// - `kstack` : 进程的内核栈
593     ///
594     /// ## 返回值
595     ///
596     /// 返回一个新的pcb
597     pub fn new(name: String, kstack: KernelStack) -> Arc<Self> {
598         return Self::do_create_pcb(name, kstack, false);
599     }
600 
601     /// 创建一个新的idle进程
602     ///
603     /// 请注意,这个函数只能在进程管理初始化的时候调用。
604     pub fn new_idle(cpu_id: u32, kstack: KernelStack) -> Arc<Self> {
605         let name = format!("idle-{}", cpu_id);
606         return Self::do_create_pcb(name, kstack, true);
607     }
608 
609     #[inline(never)]
610     fn do_create_pcb(name: String, kstack: KernelStack, is_idle: bool) -> Arc<Self> {
611         let (pid, ppid, cwd) = if is_idle {
612             (Pid(0), Pid(0), "/".to_string())
613         } else {
614             let ppid = ProcessManager::current_pcb().pid();
615             let cwd = ProcessManager::current_pcb().basic().cwd();
616             (Self::generate_pid(), ppid, cwd)
617         };
618 
619         let basic_info = ProcessBasicInfo::new(Pid(0), ppid, name, cwd, None);
620         let preempt_count = AtomicUsize::new(0);
621         let flags = unsafe { LockFreeFlags::new(ProcessFlags::empty()) };
622 
623         let sched_info = ProcessSchedulerInfo::new(None);
624         let arch_info = SpinLock::new(ArchPCBInfo::new(&kstack));
625 
626         let ppcb: Weak<ProcessControlBlock> = ProcessManager::find(ppid)
627             .map(|p| Arc::downgrade(&p))
628             .unwrap_or_default();
629 
630         let pcb = Self {
631             pid,
632             tgid: pid,
633             basic: basic_info,
634             preempt_count,
635             flags,
636             kernel_stack: RwLock::new(kstack),
637             syscall_stack: RwLock::new(KernelStack::new().unwrap()),
638             worker_private: SpinLock::new(None),
639             sched_info,
640             arch_info,
641             sig_info: RwLock::new(ProcessSignalInfo::default()),
642             sig_struct: SpinLock::new(SignalStruct::new()),
643             exit_signal: AtomicSignal::new(Signal::SIGCHLD),
644             parent_pcb: RwLock::new(ppcb.clone()),
645             real_parent_pcb: RwLock::new(ppcb),
646             children: RwLock::new(Vec::new()),
647             wait_queue: WaitQueue::default(),
648             thread: RwLock::new(ThreadInfo::new()),
649         };
650 
651         // 初始化系统调用栈
652         #[cfg(target_arch = "x86_64")]
653         pcb.arch_info
654             .lock()
655             .init_syscall_stack(&pcb.syscall_stack.read());
656 
657         let pcb = Arc::new(pcb);
658 
659         // 设置进程的arc指针到内核栈和系统调用栈的最低地址处
660         unsafe {
661             pcb.kernel_stack
662                 .write()
663                 .set_pcb(Arc::downgrade(&pcb))
664                 .unwrap();
665 
666             pcb.syscall_stack
667                 .write()
668                 .set_pcb(Arc::downgrade(&pcb))
669                 .unwrap()
670         };
671 
672         // 将当前pcb加入父进程的子进程哈希表中
673         if pcb.pid() > Pid(1) {
674             if let Some(ppcb_arc) = pcb.parent_pcb.read_irqsave().upgrade() {
675                 let mut children = ppcb_arc.children.write_irqsave();
676                 children.push(pcb.pid());
677             } else {
678                 panic!("parent pcb is None");
679             }
680         }
681 
682         return pcb;
683     }
684 
685     /// 生成一个新的pid
686     #[inline(always)]
687     fn generate_pid() -> Pid {
688         static NEXT_PID: AtomicPid = AtomicPid::new(Pid(1));
689         return NEXT_PID.fetch_add(Pid(1), Ordering::SeqCst);
690     }
691 
692     /// 返回当前进程的锁持有计数
693     #[inline(always)]
694     pub fn preempt_count(&self) -> usize {
695         return self.preempt_count.load(Ordering::SeqCst);
696     }
697 
698     /// 增加当前进程的锁持有计数
699     #[inline(always)]
700     pub fn preempt_disable(&self) {
701         self.preempt_count.fetch_add(1, Ordering::SeqCst);
702     }
703 
704     /// 减少当前进程的锁持有计数
705     #[inline(always)]
706     pub fn preempt_enable(&self) {
707         self.preempt_count.fetch_sub(1, Ordering::SeqCst);
708     }
709 
710     #[inline(always)]
711     pub unsafe fn set_preempt_count(&self, count: usize) {
712         self.preempt_count.store(count, Ordering::SeqCst);
713     }
714 
715     #[inline(always)]
716     pub fn flags(&self) -> &mut ProcessFlags {
717         return self.flags.get_mut();
718     }
719 
720     /// 请注意,这个值能在中断上下文中读取,但不能被中断上下文修改
721     /// 否则会导致死锁
722     #[inline(always)]
723     pub fn basic(&self) -> RwLockReadGuard<ProcessBasicInfo> {
724         return self.basic.read_irqsave();
725     }
726 
727     #[inline(always)]
728     pub fn set_name(&self, name: String) {
729         self.basic.write().set_name(name);
730     }
731 
732     #[inline(always)]
733     pub fn basic_mut(&self) -> RwLockWriteGuard<ProcessBasicInfo> {
734         return self.basic.write_irqsave();
735     }
736 
737     /// # 获取arch info的锁,同时关闭中断
738     #[inline(always)]
739     pub fn arch_info_irqsave(&self) -> SpinLockGuard<ArchPCBInfo> {
740         return self.arch_info.lock_irqsave();
741     }
742 
743     /// # 获取arch info的锁,但是不关闭中断
744     ///
745     /// 由于arch info在进程切换的时候会使用到,
746     /// 因此在中断上下文外,获取arch info 而不irqsave是不安全的.
747     ///
748     /// 只能在以下情况下使用这个函数:
749     /// - 在中断上下文中(中断已经禁用),获取arch info的锁。
750     /// - 刚刚创建新的pcb
751     #[inline(always)]
752     pub unsafe fn arch_info(&self) -> SpinLockGuard<ArchPCBInfo> {
753         return self.arch_info.lock();
754     }
755 
756     #[inline(always)]
757     pub fn kernel_stack(&self) -> RwLockReadGuard<KernelStack> {
758         return self.kernel_stack.read();
759     }
760 
761     #[inline(always)]
762     #[allow(dead_code)]
763     pub fn kernel_stack_mut(&self) -> RwLockWriteGuard<KernelStack> {
764         return self.kernel_stack.write();
765     }
766 
767     #[inline(always)]
768     pub fn sched_info(&self) -> &ProcessSchedulerInfo {
769         return &self.sched_info;
770     }
771 
772     #[inline(always)]
773     pub fn worker_private(&self) -> SpinLockGuard<Option<WorkerPrivate>> {
774         return self.worker_private.lock();
775     }
776 
777     #[inline(always)]
778     pub fn pid(&self) -> Pid {
779         return self.pid;
780     }
781 
782     #[inline(always)]
783     pub fn tgid(&self) -> Pid {
784         return self.tgid;
785     }
786 
787     /// 获取文件描述符表的Arc指针
788     #[inline(always)]
789     pub fn fd_table(&self) -> Arc<RwLock<FileDescriptorVec>> {
790         return self.basic.read().fd_table().unwrap();
791     }
792 
793     /// 根据文件描述符序号,获取socket对象的Arc指针
794     ///
795     /// ## 参数
796     ///
797     /// - `fd` 文件描述符序号
798     ///
799     /// ## 返回值
800     ///
801     /// Option(&mut Box<dyn Socket>) socket对象的可变引用. 如果文件描述符不是socket,那么返回None
802     pub fn get_socket(&self, fd: i32) -> Option<Arc<SocketInode>> {
803         let binding = ProcessManager::current_pcb().fd_table();
804         let fd_table_guard = binding.read();
805 
806         let f = fd_table_guard.get_file_by_fd(fd)?;
807         drop(fd_table_guard);
808 
809         let guard = f.lock();
810         if guard.file_type() != FileType::Socket {
811             return None;
812         }
813         let socket: Arc<SocketInode> = guard
814             .inode()
815             .downcast_arc::<SocketInode>()
816             .expect("Not a socket inode");
817         return Some(socket);
818     }
819 
820     /// 当前进程退出时,让初始进程收养所有子进程
821     unsafe fn adopt_childen(&self) -> Result<(), SystemError> {
822         match ProcessManager::find(Pid(1)) {
823             Some(init_pcb) => {
824                 let childen_guard = self.children.write();
825                 let mut init_childen_guard = init_pcb.children.write();
826 
827                 childen_guard.iter().for_each(|pid| {
828                     init_childen_guard.push(*pid);
829                 });
830 
831                 return Ok(());
832             }
833             _ => Err(SystemError::ECHILD),
834         }
835     }
836 
837     /// 生成进程的名字
838     pub fn generate_name(program_path: &str, args: &Vec<String>) -> String {
839         let mut name = program_path.to_string();
840         for arg in args {
841             name.push(' ');
842             name.push_str(arg);
843         }
844         return name;
845     }
846 
847     pub fn sig_info_irqsave(&self) -> RwLockReadGuard<ProcessSignalInfo> {
848         self.sig_info.read_irqsave()
849     }
850 
851     pub fn try_siginfo_irqsave(&self, times: u8) -> Option<RwLockReadGuard<ProcessSignalInfo>> {
852         for _ in 0..times {
853             if let Some(r) = self.sig_info.try_read_irqsave() {
854                 return Some(r);
855             }
856         }
857 
858         return None;
859     }
860 
861     pub fn sig_info_mut(&self) -> RwLockWriteGuard<ProcessSignalInfo> {
862         self.sig_info.write_irqsave()
863     }
864 
865     pub fn try_siginfo_mut(&self, times: u8) -> Option<RwLockWriteGuard<ProcessSignalInfo>> {
866         for _ in 0..times {
867             if let Some(r) = self.sig_info.try_write_irqsave() {
868                 return Some(r);
869             }
870         }
871 
872         return None;
873     }
874 
875     pub fn sig_struct(&self) -> SpinLockGuard<SignalStruct> {
876         self.sig_struct.lock_irqsave()
877     }
878 
879     pub fn try_sig_struct_irqsave(&self, times: u8) -> Option<SpinLockGuard<SignalStruct>> {
880         for _ in 0..times {
881             if let Ok(r) = self.sig_struct.try_lock_irqsave() {
882                 return Some(r);
883             }
884         }
885 
886         return None;
887     }
888 
889     pub fn sig_struct_irqsave(&self) -> SpinLockGuard<SignalStruct> {
890         self.sig_struct.lock_irqsave()
891     }
892 }
893 
894 impl Drop for ProcessControlBlock {
895     fn drop(&mut self) {
896         let irq_guard = unsafe { CurrentIrqArch::save_and_disable_irq() };
897         // 在ProcFS中,解除进程的注册
898         procfs_unregister_pid(self.pid())
899             .unwrap_or_else(|e| panic!("procfs_unregister_pid failed: error: {e:?}"));
900 
901         if let Some(ppcb) = self.parent_pcb.read_irqsave().upgrade() {
902             ppcb.children
903                 .write_irqsave()
904                 .retain(|pid| *pid != self.pid());
905         }
906 
907         drop(irq_guard);
908     }
909 }
910 
911 /// 线程信息
912 #[derive(Debug)]
913 pub struct ThreadInfo {
914     // 来自用户空间记录用户线程id的地址,在该线程结束时将该地址置0以通知父进程
915     clear_child_tid: Option<VirtAddr>,
916     set_child_tid: Option<VirtAddr>,
917 
918     vfork_done: Option<Arc<Completion>>,
919     /// 线程组的组长
920     group_leader: Weak<ProcessControlBlock>,
921 }
922 
923 impl ThreadInfo {
924     pub fn new() -> Self {
925         Self {
926             clear_child_tid: None,
927             set_child_tid: None,
928             vfork_done: None,
929             group_leader: Weak::default(),
930         }
931     }
932 
933     pub fn group_leader(&self) -> Option<Arc<ProcessControlBlock>> {
934         return self.group_leader.upgrade();
935     }
936 }
937 
938 /// 进程的基本信息
939 ///
940 /// 这个结构体保存进程的基本信息,主要是那些不会随着进程的运行而经常改变的信息。
941 #[derive(Debug)]
942 pub struct ProcessBasicInfo {
943     /// 当前进程的进程组id
944     pgid: Pid,
945     /// 当前进程的父进程的pid
946     ppid: Pid,
947     /// 进程的名字
948     name: String,
949 
950     /// 当前进程的工作目录
951     cwd: String,
952 
953     /// 用户地址空间
954     user_vm: Option<Arc<AddressSpace>>,
955 
956     /// 文件描述符表
957     fd_table: Option<Arc<RwLock<FileDescriptorVec>>>,
958 }
959 
960 impl ProcessBasicInfo {
961     #[inline(never)]
962     pub fn new(
963         pgid: Pid,
964         ppid: Pid,
965         name: String,
966         cwd: String,
967         user_vm: Option<Arc<AddressSpace>>,
968     ) -> RwLock<Self> {
969         let fd_table = Arc::new(RwLock::new(FileDescriptorVec::new()));
970         return RwLock::new(Self {
971             pgid,
972             ppid,
973             name,
974             cwd,
975             user_vm,
976             fd_table: Some(fd_table),
977         });
978     }
979 
980     pub fn pgid(&self) -> Pid {
981         return self.pgid;
982     }
983 
984     pub fn ppid(&self) -> Pid {
985         return self.ppid;
986     }
987 
988     pub fn name(&self) -> &str {
989         return &self.name;
990     }
991 
992     pub fn set_name(&mut self, name: String) {
993         self.name = name;
994     }
995 
996     pub fn cwd(&self) -> String {
997         return self.cwd.clone();
998     }
999     pub fn set_cwd(&mut self, path: String) {
1000         return self.cwd = path;
1001     }
1002 
1003     pub fn user_vm(&self) -> Option<Arc<AddressSpace>> {
1004         return self.user_vm.clone();
1005     }
1006 
1007     pub unsafe fn set_user_vm(&mut self, user_vm: Option<Arc<AddressSpace>>) {
1008         self.user_vm = user_vm;
1009     }
1010 
1011     pub fn fd_table(&self) -> Option<Arc<RwLock<FileDescriptorVec>>> {
1012         return self.fd_table.clone();
1013     }
1014 
1015     pub fn set_fd_table(&mut self, fd_table: Option<Arc<RwLock<FileDescriptorVec>>>) {
1016         self.fd_table = fd_table;
1017     }
1018 }
1019 
1020 #[derive(Debug)]
1021 pub struct ProcessSchedulerInfo {
1022     /// 当前进程所在的cpu
1023     on_cpu: AtomicProcessorId,
1024     /// 如果当前进程等待被迁移到另一个cpu核心上(也就是flags中的PF_NEED_MIGRATE被置位),
1025     /// 该字段存储要被迁移到的目标处理器核心号
1026     migrate_to: AtomicProcessorId,
1027     inner_locked: RwLock<InnerSchedInfo>,
1028     /// 进程的调度优先级
1029     priority: SchedPriority,
1030     /// 当前进程的虚拟运行时间
1031     virtual_runtime: AtomicIsize,
1032     /// 由实时调度器管理的时间片
1033     rt_time_slice: AtomicIsize,
1034 }
1035 
1036 #[derive(Debug)]
1037 pub struct InnerSchedInfo {
1038     /// 当前进程的状态
1039     state: ProcessState,
1040     /// 进程的调度策略
1041     sched_policy: SchedPolicy,
1042 }
1043 
1044 impl InnerSchedInfo {
1045     pub fn state(&self) -> ProcessState {
1046         return self.state;
1047     }
1048 
1049     pub fn set_state(&mut self, state: ProcessState) {
1050         self.state = state;
1051     }
1052 
1053     pub fn policy(&self) -> SchedPolicy {
1054         return self.sched_policy;
1055     }
1056 }
1057 
1058 impl ProcessSchedulerInfo {
1059     #[inline(never)]
1060     pub fn new(on_cpu: Option<ProcessorId>) -> Self {
1061         let cpu_id = on_cpu.unwrap_or(ProcessorId::INVALID);
1062         return Self {
1063             on_cpu: AtomicProcessorId::new(cpu_id),
1064             migrate_to: AtomicProcessorId::new(ProcessorId::INVALID),
1065             inner_locked: RwLock::new(InnerSchedInfo {
1066                 state: ProcessState::Blocked(false),
1067                 sched_policy: SchedPolicy::CFS,
1068             }),
1069             virtual_runtime: AtomicIsize::new(0),
1070             rt_time_slice: AtomicIsize::new(0),
1071             priority: SchedPriority::new(100).unwrap(),
1072         };
1073     }
1074 
1075     pub fn on_cpu(&self) -> Option<ProcessorId> {
1076         let on_cpu = self.on_cpu.load(Ordering::SeqCst);
1077         if on_cpu == ProcessorId::INVALID {
1078             return None;
1079         } else {
1080             return Some(on_cpu);
1081         }
1082     }
1083 
1084     pub fn set_on_cpu(&self, on_cpu: Option<ProcessorId>) {
1085         if let Some(cpu_id) = on_cpu {
1086             self.on_cpu.store(cpu_id, Ordering::SeqCst);
1087         } else {
1088             self.on_cpu.store(ProcessorId::INVALID, Ordering::SeqCst);
1089         }
1090     }
1091 
1092     pub fn migrate_to(&self) -> Option<ProcessorId> {
1093         let migrate_to = self.migrate_to.load(Ordering::SeqCst);
1094         if migrate_to == ProcessorId::INVALID {
1095             return None;
1096         } else {
1097             return Some(migrate_to);
1098         }
1099     }
1100 
1101     pub fn set_migrate_to(&self, migrate_to: Option<ProcessorId>) {
1102         if let Some(data) = migrate_to {
1103             self.migrate_to.store(data, Ordering::SeqCst);
1104         } else {
1105             self.migrate_to
1106                 .store(ProcessorId::INVALID, Ordering::SeqCst)
1107         }
1108     }
1109 
1110     pub fn inner_lock_write_irqsave(&self) -> RwLockWriteGuard<InnerSchedInfo> {
1111         return self.inner_locked.write_irqsave();
1112     }
1113 
1114     pub fn inner_lock_read_irqsave(&self) -> RwLockReadGuard<InnerSchedInfo> {
1115         return self.inner_locked.read_irqsave();
1116     }
1117 
1118     pub fn inner_lock_try_read_irqsave(
1119         &self,
1120         times: u8,
1121     ) -> Option<RwLockReadGuard<InnerSchedInfo>> {
1122         for _ in 0..times {
1123             if let Some(r) = self.inner_locked.try_read_irqsave() {
1124                 return Some(r);
1125             }
1126         }
1127 
1128         return None;
1129     }
1130 
1131     pub fn inner_lock_try_upgradable_read_irqsave(
1132         &self,
1133         times: u8,
1134     ) -> Option<RwLockUpgradableGuard<InnerSchedInfo>> {
1135         for _ in 0..times {
1136             if let Some(r) = self.inner_locked.try_upgradeable_read_irqsave() {
1137                 return Some(r);
1138             }
1139         }
1140 
1141         return None;
1142     }
1143 
1144     pub fn virtual_runtime(&self) -> isize {
1145         return self.virtual_runtime.load(Ordering::SeqCst);
1146     }
1147 
1148     pub fn set_virtual_runtime(&self, virtual_runtime: isize) {
1149         self.virtual_runtime
1150             .store(virtual_runtime, Ordering::SeqCst);
1151     }
1152     pub fn increase_virtual_runtime(&self, delta: isize) {
1153         self.virtual_runtime.fetch_add(delta, Ordering::SeqCst);
1154     }
1155 
1156     pub fn rt_time_slice(&self) -> isize {
1157         return self.rt_time_slice.load(Ordering::SeqCst);
1158     }
1159 
1160     pub fn set_rt_time_slice(&self, rt_time_slice: isize) {
1161         self.rt_time_slice.store(rt_time_slice, Ordering::SeqCst);
1162     }
1163 
1164     pub fn increase_rt_time_slice(&self, delta: isize) {
1165         self.rt_time_slice.fetch_add(delta, Ordering::SeqCst);
1166     }
1167 
1168     pub fn priority(&self) -> SchedPriority {
1169         return self.priority;
1170     }
1171 }
1172 
1173 #[derive(Debug, Clone)]
1174 pub struct KernelStack {
1175     stack: Option<AlignedBox<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>>,
1176     /// 标记该内核栈是否可以被释放
1177     can_be_freed: bool,
1178 }
1179 
1180 impl KernelStack {
1181     pub const SIZE: usize = 0x4000;
1182     pub const ALIGN: usize = 0x4000;
1183 
1184     pub fn new() -> Result<Self, SystemError> {
1185         return Ok(Self {
1186             stack: Some(
1187                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_zeroed()?,
1188             ),
1189             can_be_freed: true,
1190         });
1191     }
1192 
1193     /// 根据已有的空间,构造一个内核栈结构体
1194     ///
1195     /// 仅仅用于BSP启动时,为idle进程构造内核栈。其他时候使用这个函数,很可能造成错误!
1196     pub unsafe fn from_existed(base: VirtAddr) -> Result<Self, SystemError> {
1197         if base.is_null() || !base.check_aligned(Self::ALIGN) {
1198             return Err(SystemError::EFAULT);
1199         }
1200 
1201         return Ok(Self {
1202             stack: Some(
1203                 AlignedBox::<[u8; KernelStack::SIZE], { KernelStack::ALIGN }>::new_unchecked(
1204                     base.data() as *mut [u8; KernelStack::SIZE],
1205                 ),
1206             ),
1207             can_be_freed: false,
1208         });
1209     }
1210 
1211     /// 返回内核栈的起始虚拟地址(低地址)
1212     pub fn start_address(&self) -> VirtAddr {
1213         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize);
1214     }
1215 
1216     /// 返回内核栈的结束虚拟地址(高地址)(不包含该地址)
1217     pub fn stack_max_address(&self) -> VirtAddr {
1218         return VirtAddr::new(self.stack.as_ref().unwrap().as_ptr() as usize + Self::SIZE);
1219     }
1220 
1221     pub unsafe fn set_pcb(&mut self, pcb: Weak<ProcessControlBlock>) -> Result<(), SystemError> {
1222         // 将一个Weak<ProcessControlBlock>放到内核栈的最低地址处
1223         let p: *const ProcessControlBlock = Weak::into_raw(pcb);
1224         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1225 
1226         // 如果内核栈的最低地址处已经有了一个pcb,那么,这里就不再设置,直接返回错误
1227         if unlikely(unsafe { !(*stack_bottom_ptr).is_null() }) {
1228             kerror!("kernel stack bottom is not null: {:p}", *stack_bottom_ptr);
1229             return Err(SystemError::EPERM);
1230         }
1231         // 将pcb的地址放到内核栈的最低地址处
1232         unsafe {
1233             *stack_bottom_ptr = p;
1234         }
1235 
1236         return Ok(());
1237     }
1238 
1239     /// 清除内核栈的pcb指针
1240     ///
1241     /// ## 参数
1242     ///
1243     /// - `force` : 如果为true,那么,即使该内核栈的pcb指针不为null,也会被强制清除而不处理Weak指针问题
1244     pub unsafe fn clear_pcb(&mut self, force: bool) {
1245         let stack_bottom_ptr = self.start_address().data() as *mut *const ProcessControlBlock;
1246         if unlikely(unsafe { (*stack_bottom_ptr).is_null() }) {
1247             return;
1248         }
1249 
1250         if !force {
1251             let pcb_ptr: Weak<ProcessControlBlock> = Weak::from_raw(*stack_bottom_ptr);
1252             drop(pcb_ptr);
1253         }
1254 
1255         *stack_bottom_ptr = core::ptr::null();
1256     }
1257 
1258     /// 返回指向当前内核栈pcb的Arc指针
1259     #[allow(dead_code)]
1260     pub unsafe fn pcb(&self) -> Option<Arc<ProcessControlBlock>> {
1261         // 从内核栈的最低地址处取出pcb的地址
1262         let p = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
1263         if unlikely(unsafe { (*p).is_null() }) {
1264             return None;
1265         }
1266 
1267         // 为了防止内核栈的pcb指针被释放,这里需要将其包装一下,使得Arc的drop不会被调用
1268         let weak_wrapper: ManuallyDrop<Weak<ProcessControlBlock>> =
1269             ManuallyDrop::new(Weak::from_raw(*p));
1270 
1271         let new_arc: Arc<ProcessControlBlock> = weak_wrapper.upgrade()?;
1272         return Some(new_arc);
1273     }
1274 }
1275 
1276 impl Drop for KernelStack {
1277     fn drop(&mut self) {
1278         if self.stack.is_some() {
1279             let ptr = self.stack.as_ref().unwrap().as_ptr() as *const *const ProcessControlBlock;
1280             if unsafe { !(*ptr).is_null() } {
1281                 let pcb_ptr: Weak<ProcessControlBlock> = unsafe { Weak::from_raw(*ptr) };
1282                 drop(pcb_ptr);
1283             }
1284         }
1285         // 如果该内核栈不可以被释放,那么,这里就forget,不调用AlignedBox的drop函数
1286         if !self.can_be_freed {
1287             let bx = self.stack.take();
1288             core::mem::forget(bx);
1289         }
1290     }
1291 }
1292 
1293 pub fn process_init() {
1294     ProcessManager::init();
1295 }
1296 
1297 #[derive(Debug)]
1298 pub struct ProcessSignalInfo {
1299     // 当前进程
1300     sig_block: SigSet,
1301     // sig_pending 中存储当前线程要处理的信号
1302     sig_pending: SigPending,
1303     // sig_shared_pending 中存储当前线程所属进程要处理的信号
1304     sig_shared_pending: SigPending,
1305     // 当前进程对应的tty
1306     tty: Option<Arc<TtyCore>>,
1307 }
1308 
1309 impl ProcessSignalInfo {
1310     pub fn sig_block(&self) -> &SigSet {
1311         &self.sig_block
1312     }
1313 
1314     pub fn sig_pending(&self) -> &SigPending {
1315         &self.sig_pending
1316     }
1317 
1318     pub fn sig_pending_mut(&mut self) -> &mut SigPending {
1319         &mut self.sig_pending
1320     }
1321 
1322     pub fn sig_block_mut(&mut self) -> &mut SigSet {
1323         &mut self.sig_block
1324     }
1325 
1326     pub fn sig_shared_pending_mut(&mut self) -> &mut SigPending {
1327         &mut self.sig_shared_pending
1328     }
1329 
1330     pub fn sig_shared_pending(&self) -> &SigPending {
1331         &self.sig_shared_pending
1332     }
1333 
1334     pub fn tty(&self) -> Option<Arc<TtyCore>> {
1335         self.tty.clone()
1336     }
1337 
1338     pub fn set_tty(&mut self, tty: Arc<TtyCore>) {
1339         self.tty = Some(tty);
1340     }
1341 
1342     /// 从 pcb 的 siginfo中取出下一个要处理的信号,先处理线程信号,再处理进程信号
1343     ///
1344     /// ## 参数
1345     ///
1346     /// - `sig_mask` 被忽略掉的信号
1347     ///
1348     pub fn dequeue_signal(&mut self, sig_mask: &SigSet) -> (Signal, Option<SigInfo>) {
1349         let res = self.sig_pending.dequeue_signal(sig_mask);
1350         if res.0 != Signal::INVALID {
1351             return res;
1352         } else {
1353             return self.sig_shared_pending.dequeue_signal(sig_mask);
1354         }
1355     }
1356 }
1357 
1358 impl Default for ProcessSignalInfo {
1359     fn default() -> Self {
1360         Self {
1361             sig_block: SigSet::empty(),
1362             sig_pending: SigPending::default(),
1363             sig_shared_pending: SigPending::default(),
1364             tty: None,
1365         }
1366     }
1367 }
1368