xref: /DragonOS/kernel/src/process/fork.rs (revision 11f78b73e7b18ef04e05e63612f8027eda0740e7)
1 use core::{intrinsics::unlikely, sync::atomic::Ordering};
2 
3 use alloc::{string::ToString, sync::Arc};
4 
5 use crate::{
6     arch::{interrupt::TrapFrame, ipc::signal::Signal},
7     filesystem::procfs::procfs_register_pid,
8     ipc::signal::flush_signal_handlers,
9     libs::rwlock::RwLock,
10     mm::VirtAddr,
11     process::ProcessFlags,
12     syscall::{user_access::UserBufferWriter, SystemError},
13 };
14 
15 use super::{
16     kthread::{KernelThreadPcbPrivate, WorkerPrivate},
17     KernelStack, Pid, ProcessControlBlock, ProcessManager,
18 };
19 
20 bitflags! {
21     /// 进程克隆标志
22     pub struct CloneFlags: u64 {
23         /// 在进程间共享虚拟内存空间
24         const CLONE_VM = 0x00000100;
25         /// 在进程间共享文件系统信息
26         const CLONE_FS = 0x00000200;
27         /// 共享打开的文件
28         const CLONE_FILES = 0x00000400;
29         /// 克隆时,与父进程共享信号处理结构体
30         const CLONE_SIGHAND = 0x00000800;
31         /// 返回进程的文件描述符
32         const CLONE_PIDFD = 0x00001000;
33         /// 使克隆对象成为父进程的跟踪对象
34         const CLONE_PTRACE = 0x00002000;
35         /// 在执行 exec() 或 _exit() 之前挂起父进程的执行
36         const CLONE_VFORK = 0x00004000;
37         /// 使克隆对象的父进程为调用进程的父进程
38         const CLONE_PARENT = 0x00008000;
39         /// 拷贝线程
40         const CLONE_THREAD = 0x00010000;
41         /// 创建一个新的命名空间,其中包含独立的文件系统挂载点层次结构。
42         const CLONE_NEWNS =	0x00020000;
43         /// 与父进程共享 System V 信号量。
44         const CLONE_SYSVSEM = 0x00040000;
45         /// 设置其线程本地存储
46         const CLONE_SETTLS = 0x00080000;
47         /// 设置partent_tid地址为子进程线程 ID
48         const CLONE_PARENT_SETTID = 0x00100000;
49         /// 在子进程中设置一个清除线程 ID 的用户空间地址
50         const CLONE_CHILD_CLEARTID = 0x00200000;
51         /// 创建一个新线程,将其设置为分离状态
52         const CLONE_DETACHED = 0x00400000;
53         /// 使其在创建者进程或线程视角下成为无法跟踪的。
54         const CLONE_UNTRACED = 0x00800000;
55         /// 设置其子进程线程 ID
56         const CLONE_CHILD_SETTID = 0x01000000;
57         /// 将其放置在一个新的 cgroup 命名空间中
58         const CLONE_NEWCGROUP = 0x02000000;
59         /// 将其放置在一个新的 UTS 命名空间中
60         const CLONE_NEWUTS = 0x04000000;
61         /// 将其放置在一个新的 IPC 命名空间中
62         const CLONE_NEWIPC = 0x08000000;
63         /// 将其放置在一个新的用户命名空间中
64         const CLONE_NEWUSER = 0x10000000;
65         /// 将其放置在一个新的 PID 命名空间中
66         const CLONE_NEWPID = 0x20000000;
67         /// 将其放置在一个新的网络命名空间中
68         const CLONE_NEWNET = 0x40000000;
69         /// 在新的 I/O 上下文中运行它
70         const CLONE_IO = 0x80000000;
71         /// 克隆时,与父进程共享信号结构体
72         const CLONE_SIGNAL = 0x00010000 | 0x00000800;
73         /// 克隆时,将原本被设置为SIG_IGNORE的信号,设置回SIG_DEFAULT
74         const CLONE_CLEAR_SIGHAND = 0x100000000;
75     }
76 }
77 
78 /// ## clone与clone3系统调用的参数载体
79 ///
80 /// 因为这两个系统调用的参数很多,所以有这样一个载体更灵活
81 ///
82 /// 仅仅作为参数传递
83 #[derive(Debug, Clone, Copy)]
84 pub struct KernelCloneArgs {
85     pub flags: CloneFlags,
86 
87     // 下列属性均来自用户空间
88     pub pidfd: VirtAddr,
89     pub child_tid: VirtAddr,
90     pub parent_tid: VirtAddr,
91     pub set_tid: VirtAddr,
92 
93     /// 进程退出时发送的信号
94     pub exit_signal: Signal,
95 
96     pub stack: usize,
97     // clone3用到
98     pub stack_size: usize,
99     pub tls: usize,
100 
101     pub set_tid_size: usize,
102     pub cgroup: i32,
103 
104     pub io_thread: bool,
105     pub kthread: bool,
106     pub idle: bool,
107     pub func: VirtAddr,
108     pub fn_arg: VirtAddr,
109     // cgrp 和 cset?
110 }
111 
112 impl KernelCloneArgs {
113     pub fn new() -> Self {
114         let null_addr = VirtAddr::new(0);
115         Self {
116             flags: unsafe { CloneFlags::from_bits_unchecked(0) },
117             pidfd: null_addr,
118             child_tid: null_addr,
119             parent_tid: null_addr,
120             set_tid: null_addr,
121             exit_signal: Signal::SIGCHLD,
122             stack: 0,
123             stack_size: 0,
124             tls: 0,
125             set_tid_size: 0,
126             cgroup: 0,
127             io_thread: false,
128             kthread: false,
129             idle: false,
130             func: null_addr,
131             fn_arg: null_addr,
132         }
133     }
134 }
135 
136 impl ProcessManager {
137     /// 创建一个新进程
138     ///
139     /// ## 参数
140     ///
141     /// - `current_trapframe`: 当前进程的trapframe
142     /// - `clone_flags`: 进程克隆标志
143     ///
144     /// ## 返回值
145     ///
146     /// - 成功:返回新进程的pid
147     /// - 失败:返回Err(SystemError),fork失败的话,子线程不会执行。
148     ///
149     /// ## Safety
150     ///
151     /// - fork失败的话,子线程不会执行。
152     pub fn fork(
153         current_trapframe: &mut TrapFrame,
154         clone_flags: CloneFlags,
155     ) -> Result<Pid, SystemError> {
156         let current_pcb = ProcessManager::current_pcb();
157         let new_kstack = KernelStack::new()?;
158         let name = current_pcb.basic().name().to_string();
159         let pcb = ProcessControlBlock::new(name, new_kstack);
160 
161         let mut args = KernelCloneArgs::new();
162         args.flags = clone_flags;
163         args.exit_signal = Signal::SIGCHLD;
164 
165         Self::copy_process(&current_pcb, &pcb, args, current_trapframe)?;
166 
167         ProcessManager::add_pcb(pcb.clone());
168 
169         // 向procfs注册进程
170         procfs_register_pid(pcb.pid()).unwrap_or_else(|e| {
171             panic!(
172                 "fork: Failed to register pid to procfs, pid: [{:?}]. Error: {:?}",
173                 pcb.pid(),
174                 e
175             )
176         });
177 
178         ProcessManager::wakeup(&pcb).unwrap_or_else(|e| {
179             panic!(
180                 "fork: Failed to wakeup new process, pid: [{:?}]. Error: {:?}",
181                 pcb.pid(),
182                 e
183             )
184         });
185 
186         return Ok(pcb.pid());
187     }
188 
189     fn copy_flags(
190         clone_flags: &CloneFlags,
191         new_pcb: &Arc<ProcessControlBlock>,
192     ) -> Result<(), SystemError> {
193         if clone_flags.contains(CloneFlags::CLONE_VM) {
194             new_pcb.flags().insert(ProcessFlags::VFORK);
195         }
196         *new_pcb.flags.get_mut() = ProcessManager::current_pcb().flags().clone();
197         return Ok(());
198     }
199 
200     /// 拷贝进程的地址空间
201     ///
202     /// ## 参数
203     ///
204     /// - `clone_vm`: 是否与父进程共享地址空间。true表示共享
205     /// - `new_pcb`: 新进程的pcb
206     ///
207     /// ## 返回值
208     ///
209     /// - 成功:返回Ok(())
210     /// - 失败:返回Err(SystemError)
211     ///
212     /// ## Panic
213     ///
214     /// - 如果当前进程没有用户地址空间,则panic
215     fn copy_mm(
216         clone_flags: &CloneFlags,
217         current_pcb: &Arc<ProcessControlBlock>,
218         new_pcb: &Arc<ProcessControlBlock>,
219     ) -> Result<(), SystemError> {
220         let old_address_space = current_pcb.basic().user_vm().unwrap_or_else(|| {
221             panic!(
222                 "copy_mm: Failed to get address space of current process, current pid: [{:?}]",
223                 current_pcb.pid()
224             )
225         });
226 
227         if clone_flags.contains(CloneFlags::CLONE_VM) {
228             unsafe { new_pcb.basic_mut().set_user_vm(Some(old_address_space)) };
229             return Ok(());
230         }
231         let new_address_space = old_address_space.write().try_clone().unwrap_or_else(|e| {
232             panic!(
233                 "copy_mm: Failed to clone address space of current process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}",
234                 current_pcb.pid(), new_pcb.pid(), e
235             )
236         });
237         unsafe { new_pcb.basic_mut().set_user_vm(Some(new_address_space)) };
238         return Ok(());
239     }
240 
241     fn copy_files(
242         clone_flags: &CloneFlags,
243         current_pcb: &Arc<ProcessControlBlock>,
244         new_pcb: &Arc<ProcessControlBlock>,
245     ) -> Result<(), SystemError> {
246         // 如果不共享文件描述符表,则拷贝文件描述符表
247         if !clone_flags.contains(CloneFlags::CLONE_FILES) {
248             let new_fd_table = current_pcb.basic().fd_table().unwrap().read().clone();
249             let new_fd_table = Arc::new(RwLock::new(new_fd_table));
250             new_pcb.basic_mut().set_fd_table(Some(new_fd_table));
251         } else {
252             // 如果共享文件描述符表,则直接拷贝指针
253             new_pcb
254                 .basic_mut()
255                 .set_fd_table(current_pcb.basic().fd_table().clone());
256         }
257 
258         return Ok(());
259     }
260 
261     #[allow(dead_code)]
262     fn copy_sighand(
263         clone_flags: &CloneFlags,
264         current_pcb: &Arc<ProcessControlBlock>,
265         new_pcb: &Arc<ProcessControlBlock>,
266     ) -> Result<(), SystemError> {
267         // // 将信号的处理函数设置为default(除了那些被手动屏蔽的)
268         if clone_flags.contains(CloneFlags::CLONE_CLEAR_SIGHAND) {
269             flush_signal_handlers(new_pcb.clone(), false);
270         }
271 
272         if clone_flags.contains(CloneFlags::CLONE_SIGHAND) {
273             (*new_pcb.sig_struct()).handlers = current_pcb.sig_struct().handlers.clone();
274         }
275         return Ok(());
276     }
277 
278     /// 拷贝进程信息
279     ///
280     /// ## panic:
281     /// 某一步拷贝失败时会引发panic
282     /// 例如:copy_mm等失败时会触发panic
283     ///
284     /// ## 参数
285     ///
286     /// - clone_flags 标志位
287     /// - des_pcb 目标pcb
288     /// - src_pcb 拷贝源pcb
289     ///
290     /// ## return
291     /// - 发生错误时返回Err(SystemError)
292     pub fn copy_process(
293         current_pcb: &Arc<ProcessControlBlock>,
294         pcb: &Arc<ProcessControlBlock>,
295         clone_args: KernelCloneArgs,
296         current_trapframe: &mut TrapFrame,
297     ) -> Result<(), SystemError> {
298         let clone_flags = clone_args.flags;
299         // 不允许与不同namespace的进程共享根目录
300         if (clone_flags == (CloneFlags::CLONE_NEWNS | CloneFlags::CLONE_FS))
301             || clone_flags == (CloneFlags::CLONE_NEWUSER | CloneFlags::CLONE_FS)
302         {
303             return Err(SystemError::EINVAL);
304         }
305 
306         // 线程组必须共享信号,分离线程只能在线程组内启动。
307         if clone_flags.contains(CloneFlags::CLONE_THREAD)
308             && !clone_flags.contains(CloneFlags::CLONE_SIGHAND)
309         {
310             return Err(SystemError::EINVAL);
311         }
312 
313         // 共享信号处理器意味着共享vm。
314         // 线程组也意味着共享vm。阻止这种情况可以简化其他代码。
315         if clone_flags.contains(CloneFlags::CLONE_SIGHAND)
316             && !clone_flags.contains(CloneFlags::CLONE_VM)
317         {
318             return Err(SystemError::EINVAL);
319         }
320 
321         // TODO: 处理CLONE_PARENT 与 SIGNAL_UNKILLABLE的情况
322 
323         // 如果新进程使用不同的 pid 或 namespace,
324         // 则不允许它与分叉任务共享线程组。
325         if clone_flags.contains(CloneFlags::CLONE_THREAD) {
326             if clone_flags.contains(CloneFlags::CLONE_NEWUSER | CloneFlags::CLONE_NEWPID) {
327                 return Err(SystemError::EINVAL);
328             }
329             // TODO: 判断新进程与当前进程namespace是否相同,不同则返回错误
330         }
331 
332         // 如果新进程将处于不同的time namespace,
333         // 则不能让它共享vm或线程组。
334         if clone_flags.contains(CloneFlags::CLONE_THREAD | CloneFlags::CLONE_VM) {
335             // TODO: 判断time namespace,不同则返回错误
336         }
337 
338         if clone_flags.contains(CloneFlags::CLONE_PIDFD)
339             && clone_flags.contains(CloneFlags::CLONE_DETACHED | CloneFlags::CLONE_THREAD)
340         {
341             return Err(SystemError::EINVAL);
342         }
343 
344         // TODO: 克隆前应该锁信号处理,等待克隆完成后再处理
345 
346         // 克隆架构相关
347         let guard = current_pcb.arch_info_irqsave();
348         pcb.arch_info().clone_from(&guard);
349         drop(guard);
350 
351         // 为内核线程设置WorkerPrivate
352         if current_pcb.flags().contains(ProcessFlags::KTHREAD) {
353             *pcb.worker_private() =
354                 Some(WorkerPrivate::KernelThread(KernelThreadPcbPrivate::new()));
355         }
356 
357         // 设置clear_child_tid,在线程结束时将其置0以通知父进程
358         if clone_flags.contains(CloneFlags::CLONE_CHILD_CLEARTID) {
359             pcb.thread.write().clear_child_tid = Some(clone_args.child_tid);
360         }
361 
362         // 设置child_tid,意味着子线程能够知道自己的id
363         if clone_flags.contains(CloneFlags::CLONE_CHILD_SETTID) {
364             pcb.thread.write().set_child_tid = Some(clone_args.child_tid);
365         }
366 
367         // 将子进程/线程的id存储在用户态传进的地址中
368         if clone_flags.contains(CloneFlags::CLONE_PARENT_SETTID) {
369             let mut writer = UserBufferWriter::new(
370                 clone_args.parent_tid.data() as *mut i32,
371                 core::mem::size_of::<i32>(),
372                 true,
373             )?;
374 
375             writer.copy_one_to_user(&(pcb.pid().0 as i32), 0)?;
376         }
377 
378         // 拷贝标志位
379         Self::copy_flags(&clone_flags, &pcb).unwrap_or_else(|e| {
380             panic!(
381                 "fork: Failed to copy flags from current process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}",
382                 current_pcb.pid(), pcb.pid(), e
383             )
384         });
385 
386         // 拷贝用户地址空间
387         Self::copy_mm(&clone_flags, &current_pcb, &pcb).unwrap_or_else(|e| {
388             panic!(
389                 "fork: Failed to copy mm from current process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}",
390                 current_pcb.pid(), pcb.pid(), e
391             )
392         });
393 
394         // 拷贝文件描述符表
395         Self::copy_files(&clone_flags, &current_pcb, &pcb).unwrap_or_else(|e| {
396             panic!(
397                 "fork: Failed to copy files from current process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}",
398                 current_pcb.pid(), pcb.pid(), e
399             )
400         });
401 
402         // 拷贝信号相关数据
403         Self::copy_sighand(&clone_flags, &current_pcb, &pcb).map_err(|e| {
404             panic!(
405                 "fork: Failed to copy sighand from current process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}",
406                 current_pcb.pid(), pcb.pid(), e
407             )
408         })?;
409 
410         // 拷贝线程
411         Self::copy_thread(&current_pcb, &pcb, clone_args,&current_trapframe).unwrap_or_else(|e| {
412             panic!(
413                 "fork: Failed to copy thread from current process, current pid: [{:?}], new pid: [{:?}]. Error: {:?}",
414                 current_pcb.pid(), pcb.pid(), e
415             )
416         });
417 
418         // 设置线程组id、组长
419         if clone_flags.contains(CloneFlags::CLONE_THREAD) {
420             pcb.thread.write().group_leader = current_pcb.thread.read().group_leader.clone();
421             unsafe {
422                 let ptr = pcb.as_ref() as *const ProcessControlBlock as *mut ProcessControlBlock;
423                 (*ptr).tgid = current_pcb.tgid;
424             }
425         } else {
426             pcb.thread.write().group_leader = Arc::downgrade(&pcb);
427             unsafe {
428                 let ptr = pcb.as_ref() as *const ProcessControlBlock as *mut ProcessControlBlock;
429                 (*ptr).tgid = pcb.tgid;
430             }
431         }
432 
433         // CLONE_PARENT re-uses the old parent
434         if clone_flags.contains(CloneFlags::CLONE_PARENT | CloneFlags::CLONE_THREAD) {
435             *pcb.real_parent_pcb.write() = current_pcb.real_parent_pcb.read().clone();
436 
437             if clone_flags.contains(CloneFlags::CLONE_THREAD) {
438                 pcb.exit_signal.store(Signal::INVALID, Ordering::SeqCst);
439             } else {
440                 let leader = current_pcb.thread.read().group_leader();
441                 if unlikely(leader.is_none()) {
442                     panic!(
443                         "fork: Failed to get leader of current process, current pid: [{:?}]",
444                         current_pcb.pid()
445                     );
446                 }
447 
448                 pcb.exit_signal.store(
449                     leader.unwrap().exit_signal.load(Ordering::SeqCst),
450                     Ordering::SeqCst,
451                 );
452             }
453         } else {
454             // 新创建的进程,设置其父进程为当前进程
455             *pcb.real_parent_pcb.write() = Arc::downgrade(&current_pcb);
456             pcb.exit_signal
457                 .store(clone_args.exit_signal, Ordering::SeqCst);
458         }
459 
460         // todo: 增加线程组相关的逻辑。 参考 https://opengrok.ringotek.cn/xref/linux-6.1.9/kernel/fork.c#2437
461 
462         Ok(())
463     }
464 }
465