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