fork.rs 16 KB

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