-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathfork.rs
More file actions
3518 lines (3264 loc) · 153 KB
/
Copy pathfork.rs
File metadata and controls
3518 lines (3264 loc) · 153 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Fork系统调用实现
//!
//! 实现完整的进程复制功能,包含写时复制(COW)机制
use crate::process::{
create_process, current_pid, free_address_space, free_kernel_stack, get_process,
FileDescriptor, ProcessArc, ProcessId,
};
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::sync::atomic::{AtomicU32, Ordering};
use mm::memory::FrameAllocator;
use mm::page_table::with_pt_lock;
use mm::{arc_charge_bytes, try_reserve_heap, vec_charge_bytes, AdmittedMap, HeapClass};
use spin::Mutex;
// G.1 Observability: Watchdog handle type for cleanup_partial_child
use trace::watchdog::{unregister_watchdog, WatchdogHandle};
use x86_64::{
registers::control::Cr3,
structures::paging::{
page_table::PageTableEntry, Page, PageTable, PageTableFlags, PhysFrame, Size4KiB,
},
PhysAddr, VirtAddr,
};
/// Fork系统调用的结果
pub enum ForkResult {
/// 父进程返回值:子进程的PID
Parent(ProcessId),
/// 子进程返回值:0
Child,
/// 错误
Error(ForkError),
}
/// Fork错误类型
#[derive(Debug, Clone, Copy)]
pub enum ForkError {
/// 没有当前进程
NoCurrentProcess,
/// 无法获取进程信息
ProcessNotFound,
/// 内存分配失败
MemoryAllocationFailed,
/// 页表复制失败
PageTableCopyFailed,
/// 子进程创建失败(内核栈分配等)
ProcessCreationFailed,
/// F.2: Cgroup pids.max limit exceeded
CgroupPidsLimitExceeded,
/// J2-7: Cgroup files.max limit exceeded — the child's inherited fd count
/// would exceed the cgroup's FD budget. Mapped to EAGAIN (fork(2) must never
/// return EMFILE), matching the pids.max behavior.
CgroupFilesLimitExceeded,
/// R122-1 FIX: mmap_regions contains in-flight PENDING_MAP/PENDING_UNMAP entries;
/// fork must be retried after the concurrent mmap/munmap completes.
MmapTransientState,
/// ST-K3 FIX (F1): the forking task's live user frame carries a
/// non-user-canonical rsp/rip, so the child context it would seed cannot
/// pass `switch_to_user`'s canonicality guard. Building it anyway would let
/// unprivileged code turn `fork()` into a Ring-0 `#UD` kernel panic, so the
/// fork fails closed instead (mapped to EFAULT — the user supplied the bad
/// address). Mirrors the `sys_clone` fail-closed precedent for an
/// unusable parent frame.
InvalidUserFrame,
/// A credential writer has closed reader admission; retry after it commits.
CredentialBusy,
/// R180-19: LSM rejected the prospective child during PREPARE.
SecurityDenied,
/// R180-19: the child's PID namespace membership cannot be represented to
/// the parent; fail before parent PTE commit.
NamespaceTranslationFailed,
/// R180-19: the scheduler could not reserve an exact pre-COW queue slot.
SchedulerAdmissionFailed,
}
/// R180-19: shared-MM transaction reservation spanning metadata snapshot
/// through the parent-PTE COW commit. Mutators observe `fork_in_progress`
/// before arming their own transient state; Drop closes every error path.
struct ForkMmReservation {
mm: Arc<Mutex<crate::process::MmState>>,
}
impl ForkMmReservation {
fn acquire(mm: Arc<Mutex<crate::process::MmState>>) -> Result<Self, ForkError> {
{
let mut state = mm.lock();
if state.fork_in_progress
|| state
.mmap_regions
.values()
.any(|entry: &crate::syscall::MmapEntry| entry.has_transient())
|| state.brk_in_progress
|| state.stack_grow_in_progress
{
return Err(ForkError::MmapTransientState);
}
state.fork_in_progress = true;
}
Ok(Self { mm })
}
}
impl Drop for ForkMmReservation {
fn drop(&mut self) {
self.mm.lock().fork_in_progress = false;
}
}
/// PREPARE-phase cgroup reservations. Until `commit`, dropping the guard
/// returns every acquired charge, including errors from later page-table/KPTI
/// preparation. The type makes it impossible to add a new `?` before COW
/// commit without also inheriting exact rollback.
struct ForkChargeGuard {
cgroup_id: crate::cgroup::CgroupId,
fd_count: u64,
memory_bytes: u64,
committed: bool,
}
impl ForkChargeGuard {
fn new(cgroup_id: crate::cgroup::CgroupId) -> Self {
Self {
cgroup_id,
fd_count: 0,
memory_bytes: 0,
committed: false,
}
}
fn commit(&mut self) {
self.committed = true;
}
}
impl Drop for ForkChargeGuard {
fn drop(&mut self) {
if self.committed {
return;
}
if self.memory_bytes != 0 {
crate::cgroup::uncharge_memory(self.cgroup_id, self.memory_bytes);
}
if self.fd_count != 0 {
crate::cgroup::uncharge_fds(self.cgroup_id, self.fd_count);
}
}
}
/// 执行fork系统调用
///
/// 创建当前进程的完整副本,包括:
/// - 进程控制块(PCB)
/// - CPU上下文
/// - 内存空间(使用写时复制COW)
/// - 文件描述符表
///
/// # 返回值
///
/// - 成功:返回 `(全局子 PID, 父命名空间可见 PID)`
/// - 子进程:返回0
/// - 错误:返回错误码
pub fn sys_fork() -> Result<(ProcessId, ProcessId), ForkError> {
let current = current_pid().ok_or(ForkError::NoCurrentProcess)?;
let parent_process = get_process(current).ok_or(ForkError::ProcessNotFound)?;
// F.2: Check cgroup pids.max limit BEFORE creating any resources
// This prevents fork bombs and ensures cgroup limits are enforced
{
let parent = parent_process.lock();
if !crate::cgroup::check_fork_allowed(parent.cgroup_id) {
return Err(ForkError::CgroupPidsLimitExceeded);
}
}
// 捕获父进程信息后释放锁,避免 create_process 再次获取锁导致潜在问题
let (parent_root, parent_pid, parent_prio, child_name) = {
let parent = parent_process.lock();
let root = if parent.memory_space == 0 {
let (cr3, _) = Cr3::read();
cr3.start_address().as_u64() as usize
} else {
parent.memory_space
};
(
root,
parent.pid,
parent.priority,
crate::process::ProcessNameSnapshot::from_parts(&parent.name, "-child"),
)
};
// 创建子进程(此时未持有父进程锁,避免死锁)
// Z-7: create_process 现在返回 Result,失败时正确传播错误
let child_pid = create_process(child_name, parent_pid, parent_prio)
.map_err(|_| ForkError::ProcessCreationFailed)?;
// R180-19 PREPARE: policy and PID-namespace visibility used to be checked
// by syscall.rs only after fork_inner had COW-committed the parent. Build
// immutable contexts from the prospective child now and reject/clean up
// before any cgroup charge or page-table mutation.
let child_process = match get_process(child_pid) {
Some(process) => process,
None => {
parent_process
.lock()
.children
.retain(|&pid| pid != child_pid);
cleanup_partial_child(child_pid);
return Err(ForkError::ProcessCreationFailed);
}
};
let (parent_ctx, child_ctx, parent_view_pid, child_credentials) =
prepare_fork_identity_or_cleanup(&parent_process, child_pid)?;
let Some(parent_view_pid) = parent_view_pid else {
parent_process
.lock()
.children
.retain(|&pid| pid != child_pid);
cleanup_partial_child(child_pid);
return Err(ForkError::NamespaceTranslationFailed);
};
if lsm::hook_task_fork(&parent_ctx, &child_ctx).is_err() {
parent_process
.lock()
.children
.retain(|&pid| pid != child_pid);
cleanup_partial_child(child_pid);
return Err(ForkError::SecurityDenied);
}
// Scheduler placement consumes affinity + cpuset before taking any queue
// lock. Snapshot them under the parent PCB, release it, then initialize the
// unpublished child. This preserves fork inheritance while keeping the
// canonical READY_QUEUE -> PCB order (never parent PCB -> READY_QUEUE).
let (child_allowed_cpus, child_cpuset_id) = {
let parent = parent_process.lock();
(parent.allowed_cpus, parent.cpuset_id)
};
{
let mut child = child_process.lock();
child.allowed_cpus = child_allowed_cpus;
child.cpuset_id = child_cpuset_id;
}
// R180-19 / review-fix: reserve before taking the parent PCB lock.
// Scheduler operations use READY_QUEUE -> PCB; doing this from inside
// fork_inner while the parent PCB was held inverted that order against a
// scheduler scan of the queued parent. The permit remains non-runnable
// and owns exact rollback across every later PREPARE failure.
let scheduler_permit =
match crate::process::prepare_scheduler_add_process(Arc::clone(&child_process)) {
Ok(permit) => permit,
Err(_) => {
parent_process
.lock()
.children
.retain(|&pid| pid != child_pid);
cleanup_partial_child(child_pid);
return Err(ForkError::SchedulerAdmissionFailed);
}
};
// 重新获取父进程锁执行真正的 fork
let mut parent = parent_process.lock();
// F.2: Get parent's cgroup_id for child attachment
let parent_cgroup_id = parent.cgroup_id;
// R152-5 FIX: Attach child to cgroup BEFORE the expensive fork_inner() PT copy.
// This eliminates the pids.max TOCTOU window where multiple concurrent forks
// all pass check_fork_allowed but waste kernel resources (kernel stack, PID,
// page table copy) before attach_task() serially rejects them.
let mut cgroup_attached = false;
if let Some(cgroup) = crate::cgroup::lookup_cgroup(parent_cgroup_id) {
if let Err(_) = cgroup.attach_task(child_pid as u64) {
parent.children.retain(|&pid| pid != child_pid);
drop(parent);
// READY_QUEUE -> child PCB cancellation must run with no parent
// PCB held (canonical scheduler lock order).
drop(scheduler_permit);
cleanup_partial_child(child_pid);
return Err(ForkError::CgroupPidsLimitExceeded);
}
cgroup_attached = true;
}
match fork_inner(&mut parent, child_pid, parent_root, child_credentials) {
Ok(()) => {}
Err(error) => {
parent.children.retain(|&pid| pid != child_pid);
if cgroup_attached {
if let Some(cg) = crate::cgroup::lookup_cgroup(parent_cgroup_id) {
let _ = cg.detach_task(child_pid as u64);
}
}
drop(parent);
drop(scheduler_permit);
cleanup_partial_child(child_pid);
return Err(error);
}
}
// Publication is infallible and centralized here so syscall wrappers have
// no post-COW lookup/failure window. Drop the parent PCB lock first; the
// scheduler may inspect process state through independent locks.
drop(parent);
scheduler_permit.commit();
Ok((child_pid, parent_view_pid))
}
/// KSA-010: a published child already exists here. Credential contention and
/// admission failure must release the parent guard before unlinking/teardown,
/// just like the later namespace/LSM/scheduler rejection paths.
fn prepare_fork_identity_or_cleanup(
parent_process: &ProcessArc,
child_pid: ProcessId,
) -> Result<
(
lsm::ProcessCtx,
lsm::ProcessCtx,
Option<ProcessId>,
crate::process::Credentials,
),
ForkError,
> {
let result = (|| {
let parent = parent_process.lock();
let visible_pid = crate::pid_namespace::owning_namespace(&parent.pid_ns_chain)
.map(|ns| crate::pid_namespace::pid_in_namespace(&ns, child_pid))
.unwrap_or(Some(child_pid));
let parent_creds = parent
.try_credentials_read()
.ok_or(ForkError::CredentialBusy)?;
let parent_ctx = lsm::ProcessCtx::new(
parent.pid,
parent.tgid,
parent_creds.uid,
parent_creds.gid,
parent_creds.euid,
parent_creds.egid,
);
let supplementary_groups = mm::AdmittedVec::try_copy_from_slice(
HeapClass::CoreProcess,
&parent_creds.supplementary_groups,
)
.map_err(|_| ForkError::MemoryAllocationFailed)?;
let child_credentials = crate::process::Credentials {
uid: parent_creds.uid,
gid: parent_creds.gid,
euid: parent_creds.euid,
egid: parent_creds.egid,
supplementary_groups,
};
let child_ctx = lsm::ProcessCtx::new(
child_pid,
child_pid,
child_credentials.uid,
child_credentials.gid,
child_credentials.euid,
child_credentials.egid,
);
Ok((parent_ctx, child_ctx, visible_pid, child_credentials))
})();
if result.is_err() {
parent_process
.lock()
.children
.retain(|&pid| pid != child_pid);
cleanup_partial_child(child_pid);
}
result
}
#[cfg(all(test, feature = "host_harness", not(target_os = "none")))]
mod credential_preparation_tests {
use super::*;
use crate::process::child_creation_test_support::Fixture;
#[test]
fn credential_lifecycle_fork_contention_cleanup() {
let fixture = Fixture::new();
let (_, child_pid) = fixture.pids();
let credentials = fixture.parent.lock().shared_credentials();
let result = credentials.with_hosted_pending_writer(|| {
prepare_fork_identity_or_cleanup(&fixture.parent, child_pid)
});
assert!(matches!(result, Err(ForkError::CredentialBusy)));
fixture.assert_child_removed();
}
}
/// Fork 的内部实现,便于错误处理和回滚
fn fork_inner(
parent: &mut crate::process::Process,
child_pid: ProcessId,
parent_root: usize,
child_credentials: crate::process::Credentials,
) -> Result<(), ForkError> {
// R122-1 FIX: Reject fork() while any mmap/munmap operation is in-flight.
//
// The three-phase mmap/munmap protocol (R121-4) encodes transient state in
// the low 12 bits of each mmap_regions entry (PENDING_MAP / PENDING_UNMAP).
// Committed entries always store page-aligned lengths (low 12 bits = 0).
//
// If a sibling thread (CLONE_VM) is between Phase 1 (reserve with PENDING
// flag) and Phase 3 (commit by clearing flag), copying the entry into the
// child — even after stripping the flag — produces an inconsistent child
// address space: the region record says "mapped" but the page table may be
// partially populated (PENDING_MAP) or partially torn down (PENDING_UNMAP).
//
// Returning MmapTransientState (mapped to EAGAIN) lets userspace retry.
// This is fail-closed: any non-zero low bits block fork, covering future
// transient flags as well.
//
// D3-ARC-MM-SHARED: mmap_regions now lives inside MmState behind parent.mm.
// Lock ordering: Process (held) → MmState — never reverse.
let _mm_fork_reservation = ForkMmReservation::acquire(Arc::clone(&parent.mm))?;
// ST-K2-P2: snapshot shared-anonymous ranges while the parent MmState is
// already locked below. The admitted temporary vector lives through the
// PT transaction and is dropped only after the child view is prepared.
let mut shared_ranges = mm::AdmittedVec::<(usize, usize)>::new(HeapClass::CoreProcess);
// ST-K3 fork-DF diagnosis: coarse stage tags (debug builds only).
#[cfg(debug_assertions)]
kprintln!("[FORKDIAG] FD1 reservation");
if let Some(child_process) = get_process(child_pid) {
let mut child = child_process.lock();
// 复制 CPU 上下文(RAX 在下方置 0)
child.context = parent.context;
// Lazy FPU: inherit parent's FPU usage flag
// If parent used FPU, the state in context.fx is valid and child inherits it
child.fpu_used = parent.fpu_used;
child.user_stack = parent.user_stack;
// SMP affinity and cpuset were snapshotted before scheduler admission.
// R163-4 FIX: Defer notify_cpuset_task_joined until after all fallible
// operations complete. If fork_inner fails after the notification,
// the counter is incremented but never decremented (cpuset DoS).
// ST-K3 FIX (fork chimera context): entry-state-keyed child resume model.
//
// A Ring-3 parent forks from INSIDE a syscall. The child must resume at
// the SYSCALL RETURN POINT with the parent's CURRENT user frame and
// rax = 0; forcing context.cs/ss to the user selectors below makes the
// scheduler's `next_cs & 3 == 3` check select switch_to_user, whose
// user-canonical rip/rsp validation the frame now satisfies.
//
// The previous code built a CHIMERA for this case: user CS from the
// STALE parent.context, plus — because `used = kernel_top - user_rsp`
// overflowed the copy guard — a KERNEL rsp from the fallback rebase
// below. switch_to_user's canonicality guard then executed its ud2 arm
// on the child's first dispatch (#UD at switch_to_user+0x18e; observed
// on the first Ring-3 fork this kernel ever ran, stress-v2 memory
// profile). The kernel-stack copy/rebase model below is retained for
// KERNEL-context parents only (their context.cs is a kernel selector,
// dispatched via switch_context; with_current_syscall_frame returns
// None outside an active syscall window, which is exactly the
// entry-state discriminator D1-ARC-ENTRY-STATE prescribes).
let ring3_user_frame = crate::syscall::with_current_syscall_frame(|frame| *frame);
if let Some(frame) = ring3_user_frame {
// ST-K3 FIX (F1): validate BEFORE seeding the child. `frame.rsp` and
// `frame.rcx` come straight from the SYSCALL entry stub with no
// validation, and the child's first dispatch runs
// `switch_to_user`'s canonicality guard, whose failure arm is a
// Ring-0 `ud2` -> kernel panic. Unprivileged code could therefore
// weaponize `mov rsp, <non-canonical>; syscall` into a kernel kill.
// `< USER_SPACE_TOP` (0x0000_8000_0000_0000) is exactly the guard's
// condition: below 2^47 implies both canonical and bit47 == 0. A
// merely-unmapped (but canonical) user rsp/rip stays allowed — that
// faults in Ring 3 and terminates the child with SIGSEGV, which is
// correct Linux behavior, not a kernel bug.
const USER_ADDR_LIMIT: u64 = crate::usercopy::USER_SPACE_TOP as u64;
if frame.rsp >= USER_ADDR_LIMIT || frame.rcx >= USER_ADDR_LIMIT {
return Err(ForkError::InvalidUserFrame);
}
// SYSCALL entry saved: rcx = user RIP, r11 = user RFLAGS. Mirror
// the exact ABI the parent's own return path exposes (rcx/r11 are
// architecturally clobbered by SYSCALL, so userspace already
// treats them as such). switch_to_user sanitizes RFLAGS again
// (mask + force IF) before the IRETQ — defense in depth.
child.context.rax = 0; // fork() returns 0 in the child
child.context.rbx = frame.rbx;
child.context.rcx = frame.rcx;
child.context.rdx = frame.rdx;
child.context.rsi = frame.rsi;
child.context.rdi = frame.rdi;
child.context.rbp = frame.rbp;
child.context.rsp = frame.rsp; // user RSP
child.context.r8 = frame.r8;
child.context.r9 = frame.r9;
child.context.r10 = frame.r10;
child.context.r11 = frame.r11;
child.context.r12 = frame.r12;
child.context.r13 = frame.r13;
child.context.r14 = frame.r14;
child.context.r15 = frame.r15;
child.context.rip = frame.rcx; // user return RIP
child.context.rflags = frame.r11; // user RFLAGS
// cs/ss MUST be forced: the parent's saved context.cs is a KERNEL
// selector (both switch_context and switch_to_user save-halves
// store the live `mov ax, cs` — i.e. the kernel CS active at
// save time), so inheriting it routes the child through the
// scheduler's `next_cs & 3 == 3` check into switch_context, which
// `ret`s into the USER rsp set above (#PF at RIP=user-stack
// garbage; observed addr=0x1). Same idiom as the CLONE_VM child
// path (syscall.rs).
child.context.cs = 0x23; // USER_CODE_SELECTOR
child.context.ss = 0x1b; // USER_DATA_SELECTOR
} else {
// 子进程使用自己的内核栈(由 create_process -> allocate_kernel_stack 分配)
// 复制父进程内核栈内容以保持返回路径一致
let parent_top = parent.kernel_stack_top.as_u64();
let parent_rsp = parent.context.rsp;
let child_top = child.kernel_stack_top.as_u64();
// 计算父进程已使用的栈空间
let used = parent_top.saturating_sub(parent_rsp);
let parent_stack_size = parent_top.saturating_sub(parent.kernel_stack.as_u64());
if child_top != 0 && used > 0 && used <= parent_stack_size {
// 子进程栈顶减去相同使用量 = 子进程 RSP
let child_rsp = child_top - used;
// 复制父栈内容到子栈
unsafe {
core::ptr::copy_nonoverlapping(
parent_rsp as *const u8,
child_rsp as *mut u8,
used as usize,
);
}
child.context.rsp = child_rsp;
// 调整 RBP(如果它指向父栈范围内)
if parent.context.rbp >= parent_rsp && parent.context.rbp <= parent_top {
// RBP 相对偏移保持不变
let rbp_offset = parent.context.rbp - parent_rsp;
child.context.rbp = child_rsp + rbp_offset;
} else {
// RBP 不在栈范围内,直接使用子栈顶
child.context.rbp = child_rsp;
}
} else if child_top != 0 {
// 无法复制栈,使用子栈顶作为起点
child.context.rsp = child_top;
child.context.rbp = child_top;
}
// 如果 child_top == 0,保持父进程的 rsp/rbp(回退到共享栈)
}
// R162-7 FIX: Clone fd_table with bounded fallibility.
// clone_box() is still infallible (Box::new), but we pre-validate
// the fd count fits in memory. With MAX_FD=256, total alloc is ~128KB.
// If fd_table is excessively large, fail early.
if parent.fd_table.len() > crate::process::MAX_FD as usize {
return Err(ForkError::MemoryAllocationFailed);
}
child
.fd_table
.ensure_capacity_for(parent.fd_table.len())
.map_err(|_| ForkError::MemoryAllocationFailed)?;
child
.cloexec_fds
.ensure_capacity_for(parent.cloexec_fds.len())
.map_err(|_| ForkError::MemoryAllocationFailed)?;
for (&fd, desc) in parent.fd_table.iter() {
let cloned = desc
.try_clone_box()
.map_err(|_| ForkError::MemoryAllocationFailed)?;
if child.fd_table.insert_unique_reserved(fd, cloned).is_err() {
panic!("fork FD snapshot violated unique reserved publication");
}
}
// R39-4 FIX: 克隆 close-on-exec 标记集合
// R162-14 FIX: BTreeSet::clone() is infallible but bounded by MAX_FD=256
// (~12KB worst case). Accepted risk documented.
for &fd in parent.cloexec_fds.iter() {
if child.cloexec_fds.insert_reserved(fd).is_err() {
panic!("fork CLOEXEC snapshot exceeded prepared capacity");
}
}
// M0-6: inherit POSIX resource limits across fork (POSIX: child inherits
// the parent's rlimits). `[RLimit; N]` is Copy — a trivial value copy.
child.rlimits = parent.rlimits;
// M0 item 5: inherit signal dispositions + blocked mask across fork (POSIX).
// `[SigAction; NSIG]` and `u64` are Copy. `saved_blocked`/`in_signal_handler`
// are handler scratch state and intentionally stay born-clean in the child
// (a fork inside a handler does NOT carry the parent's live frame state). The
// "any handler installed" fast-path hint is a monotonic global, so the child
// inheriting a parent's handler needs no per-task bookkeeping here.
child.sigactions = parent.sigactions;
child.blocked = parent.blocked;
// 克隆能力表(尊重 CLOFORK 标志)
//
// clone_for_fork() 会过滤掉带有 CLOFORK 标志的能力条目,
// 并保持生成计数器的单调性以防止 wrap 攻击。
// R161-4 FIX: Use fallible try_clone_for_fork to avoid OOM panic
//
// U.S3-SLICE-2 FIX: reconcile the child cap_table refcounts to match the
// child's ACTUAL fd count when the parent is a CLONE_THREAD thread sharing
// its cap_table Arc with siblings. CapSlot::clone copies refcounts VERBATIM
// (U.S3-A1), but fork's fd_table copy (loop above) copies ONLY the forking
// thread's fds, not sibling fds. So the child's cap refcounts include
// sibling-held references → over-count → child-local slot leak (TableFull
// DoS class, fail-safe: revoke-too-late, never premature). Reconciliation:
// COUNT the child's actual per-cap fd references and OVERWRITE each
// CapEntry.refcount to match. Safe under parent lock; child not visible yet.
// Reconcile only if parent's cap_table Arc::strong_count > 1 (shared).
// A non-shared parent (standalone process or the last survivor of a thread
// group) has cap refcounts that already equal its own fd count, so the
// verbatim copy is correct. Checking `> 1` avoids the O(fds × caps) scan
// on the common non-threaded fork path.
let cap_table = if parent.capability_table_is_shared() {
// Build a histogram: CapId → count of child fds carrying it.
let mut child_cap_counts =
[(cap::CapId::INVALID, 0usize); crate::process::MAX_FD as usize];
let mut child_cap_count_len = 0usize;
for desc in child.fd_table.values() {
if let Some(cid) = desc.cap_id() {
let Some(slot) = child_cap_counts.get_mut(child_cap_count_len) else {
return Err(ForkError::MemoryAllocationFailed);
};
*slot = (cid, 1);
child_cap_count_len += 1;
}
}
child_cap_counts[..child_cap_count_len].sort_unstable_by_key(|entry| entry.0);
let mut unique_len = 0usize;
for index in 0..child_cap_count_len {
let (cid, count) = child_cap_counts[index];
if unique_len != 0 && child_cap_counts[unique_len - 1].0 == cid {
child_cap_counts[unique_len - 1].1 = child_cap_counts[unique_len - 1]
.1
.checked_add(count)
.ok_or(ForkError::MemoryAllocationFailed)?;
} else {
child_cap_counts[unique_len] = (cid, count);
unique_len += 1;
}
}
parent
.try_clone_capability_table_for_fork(Some(&child_cap_counts[..unique_len]))
.map_err(|_| ForkError::MemoryAllocationFailed)?
} else {
parent
.try_clone_capability_table_for_fork(None)
.map_err(|_| ForkError::MemoryAllocationFailed)?
};
child.install_capability_table(cap_table);
child.time_slice = parent.time_slice;
child.cpu_time = 0;
// E.4 Priority Inheritance: 继承基础动态优先级
//
// 子进程继承父进程的 base_dynamic_priority(未应用 PI 的优先级基线)。
// 但不继承 pi_boosts(父进程持有的 futex 相关),子进程从空开始。
// waiting_on_futex 也不继承(子进程未阻塞在任何 futex 上)。
child.base_dynamic_priority = parent.base_dynamic_priority;
// pi_boosts 和 waiting_on_futex 在 Process::new() 中已初始化为空
// R39-3 FIX: 继承父进程的凭证(fork 创建独立副本)
//
// fork() 创建的子进程获得父进程凭证的克隆副本(独立 Arc)。
// 这意味着子进程后续的 setuid/setgid 不会影响父进程。
// 对于 CLONE_THREAD,sys_clone 中会处理共享凭证。
let credential_arc_reservation = try_reserve_heap(
HeapClass::CoreProcess,
arc_charge_bytes::<crate::process::SharedCredentials>()
.map_err(|_| ForkError::MemoryAllocationFailed)?,
)
.map_err(|_| ForkError::MemoryAllocationFailed)?;
let credentials = Arc::try_new(crate::process::SharedCredentials::new(child_credentials))
.map_err(|_| ForkError::MemoryAllocationFailed)?;
child.install_shared_credentials_for_clone(credentials);
drop(credential_arc_reservation);
child.umask = parent.umask;
child.fs_context = parent.fs_context.clone();
// D3-ARC-MM-SHARED: Build the child's independent MmState from the
// parent's shared mm. This replaces the old per-field copies of
// brk_start, brk, elf_charged_bytes, mmap_regions, and next_mmap_addr.
//
// R138-1 FIX: Inherit parent's ELF loader charges so the child's cgroup
// accounting is complete under worst-case COW semantics. The exact
// charge is derived from this same locked snapshot and reserved below,
// before the parent-PTE commit.
//
// R122-1 FIX: Strip transient PENDING_* flags when cloning committed
// regions into the child, preserving persistent per-region flags (e.g.
// PROT_NONE) so the child inherits correct region metadata.
//
// R157-3 FIX: Fallible pre-allocation — BTreeMap::collect() uses
// infallible allocation; 65536 entries can exhaust the 1 MiB kernel heap.
// We pre-allocate into a Vec first to detect OOM early.
//
// Lock ordering: Process (held) → MmState — never reverse.
let fork_charge_bytes = {
let parent_mm = parent.mm.lock();
// Re-check every transient at the actual snapshot point. The early
// check rejects quickly; this one prevents a CLONE_VM sibling from
// opening a prepare window before the metadata/charge snapshot.
if parent_mm
.mmap_regions
.values()
.any(|entry: &crate::syscall::MmapEntry| entry.has_transient())
|| parent_mm.brk_in_progress
|| parent_mm.stack_grow_in_progress
{
return Err(ForkError::MmapTransientState);
}
debug_assert!(
parent_mm.fork_in_progress,
"fork snapshot must own the shared-MM reservation"
);
for (&base, entry) in parent_mm.mmap_regions.iter() {
let entry: &crate::syscall::MmapEntry = entry;
if entry.is_shared() {
let end = base
.checked_add(crate::syscall::mmap_region_len(*entry))
.ok_or(ForkError::MemoryAllocationFailed)?;
shared_ranges
.try_push((base, end))
.map_err(|_| ForkError::MemoryAllocationFailed)?;
}
}
let mut charge_bytes = 0u64;
for (_base, entry) in parent_mm.mmap_regions.iter() {
let entry: &crate::syscall::MmapEntry = entry;
if !entry.is_prot_none() && !entry.is_shared() {
charge_bytes =
charge_bytes.saturating_add(crate::syscall::mmap_region_len(*entry) as u64);
}
}
const PAGE_SIZE: usize = 0x1000;
let brk_aligned = parent_mm.brk.saturating_add(PAGE_SIZE - 1) & !(PAGE_SIZE - 1);
let brk_start_aligned =
parent_mm.brk_start.saturating_add(PAGE_SIZE - 1) & !(PAGE_SIZE - 1);
charge_bytes = charge_bytes
.saturating_add(brk_aligned.saturating_sub(brk_start_aligned) as u64)
.saturating_add(parent_mm.elf_charged_bytes)
.saturating_add(parent_mm.pt_charged_bytes);
let region_count = parent_mm.mmap_regions.len();
// R165-14: Re-assert the MAX_MAP_COUNT bound before cloning. mmap()
// already enforces it on insert, but checking here keeps the child's
// infallible BTreeMap build (below) bounded even if a future path
// grows mmap_regions past the limit.
if region_count > crate::syscall::MAX_MAP_COUNT {
return Err(ForkError::MemoryAllocationFailed);
}
// R186-4 FIX: reserve the exact snapshot backing before asking the
// allocator for it. The reservation is handed to the map constructor
// after population, so this path cannot double-reserve or allocate
// outside the CoreProcess admission ledger.
let child_mmap_regions = if region_count == 0 {
// Avoid the published-ledger precondition for a zero-sized map.
mm::AdmittedMap::new(mm::HeapClass::CoreProcess)
} else {
let snapshot_bytes =
vec_charge_bytes::<(usize, crate::syscall::MmapEntry)>(region_count)
.map_err(|_| ForkError::MemoryAllocationFailed)?;
let reservation = try_reserve_heap(HeapClass::CoreProcess, snapshot_bytes)
.map_err(|_| ForkError::MemoryAllocationFailed)?;
let mut snap: Vec<(usize, crate::syscall::MmapEntry)> = Vec::new();
if snap.try_reserve_exact(region_count).is_err() {
// Dropping the armed reservation rolls back both ledger lanes.
return Err(ForkError::MemoryAllocationFailed);
}
// D2 Phase 2: strip transient flags via the typed accessor (clears
// PENDING_*, preserves PROT_NONE + prot bits, which are load-bearing
// for the child's cgroup-charge skip).
snap.extend(parent_mm.mmap_regions.iter().map(
|(&base, len_with_flags): (&usize, &crate::syscall::MmapEntry)| {
(base, len_with_flags.fork_stripped())
},
));
match mm::AdmittedMap::from_sorted_vec_with_reservation(snap, reservation) {
Ok(map) => map,
Err(error) => {
let (snap, reservation, _error) = error.into_parts();
// Release the backing reservation only after the
// returned Vec has been destroyed.
drop(snap);
drop(reservation);
return Err(ForkError::MemoryAllocationFailed);
}
}
};
// ST-K2-P2: shared-anonymous region metadata is a second admitted
// map. Its values are Arc handles to the parent's page slots, so
// regular fork inherits the same demand-paged frames and region
// pin; CLONE_VM already shares this MmState directly.
let mut child_shared_regions = mm::AdmittedMap::new(mm::HeapClass::CoreProcess);
if parent_mm.shared_regions.len() > crate::syscall::MAX_MAP_COUNT {
return Err(ForkError::MemoryAllocationFailed);
}
if child_shared_regions
.try_reserve(parent_mm.shared_regions.len())
.is_err()
{
return Err(ForkError::MemoryAllocationFailed);
}
for (&base, region) in parent_mm.shared_regions.iter() {
if child_shared_regions
.try_insert(base, Arc::clone(region))
.is_err()
{
return Err(ForkError::MemoryAllocationFailed);
}
}
let child_mm = crate::process::MmState {
// next-phase #11 / R165-14 (CLOSED, was AD-02 tech-debt): the
// child's region map is now a `FallibleOrderedMap`, adopted in
// O(1) with NO allocation from the already-sorted, admission-
// reserved `snap` Vec. The prior infallible
// `BTreeMap::collect()` (which could abort under OOM with up to
// MAX_MAP_COUNT entries) is eliminated: every allocation on this
// path is now the fallible `try_reserve_exact` on `snap` above,
// and `from_sorted_vec` consumes that Vec verbatim. `snap` is
// strictly key-sorted because it is built from the parent's
// ordered `mmap_regions.iter()` (debug-asserted by from_sorted_vec).
//
// R186-4 FIX: Migrated to AdmittedMap with the reservation handoff,
// which charges the Vec capacity to CoreProcess before adoption.
mmap_regions: child_mmap_regions,
shared_regions: child_shared_regions,
brk_start: parent_mm.brk_start,
brk: parent_mm.brk,
next_mmap_addr: parent_mm.next_mmap_addr,
vm_charged_bytes: parent_mm.vm_charged_bytes,
elf_charged_bytes: parent_mm.elf_charged_bytes,
// J2-9 FIX: inherit the page-table-frame kmem charge. The child
// builds its OWN page tables (so the value, like elf, is a copy of
// the parent's) and its last-exit uncharges this; the matching
// charge to the parent cgroup is folded into fork_charge_bytes.
pt_charged_bytes: parent_mm.pt_charged_bytes,
// R171-CG1x0 FIX (M2-1 SLICE-0): the child's whole inherited PT
// basis lives in `pt_inherited_bytes` with an EMPTY frame ledger —
// the child's page tables are freshly built at DIFFERENT physical
// addresses, so cloning the parent's frame keys would risk a
// cross-AS uncharge. Non-authoritative until the child's first own
// mmap. INVARIANT I' holds at birth: pt_charged_bytes(=P) ==
// pt_inherited_bytes(=P) + 0. The child's munmap of an inherited
// region therefore uncharges 0 (the basis rides to last-exit,
// over-count-safe), preserving today's +P(parent)/-P(child exit)
// fork balance with zero new fork PT-recording surface.
//
// R186-4 FIX: Migrated to AdmittedMap; child starts with empty ledger
// (AdmittedMap::new charges nothing for zero capacity).
pt_charged_frames: mm::AdmittedMap::new(mm::HeapClass::CoreProcess),
pt_inherited_bytes: parent_mm.pt_charged_bytes,
pt_ledger_authoritative: false,
// Transient pending counters reset for child — no in-flight
// operations can be inherited across fork.
brk_pending_growth: 0,
mprotect_pending_bytes: 0,
exec_pending_bytes: 0,
// R165-1 FIX: child starts with no brk reservation (fork is
// rejected above while a brk is in flight).
brk_in_progress: false,
// R172-16: child inherits no brk-grow VA reservation — fork EAGAINs while
// brk_in_progress, so this path is never reached mid-grow; zero defensively.
brk_grow_resv_lo: 0,
brk_grow_resv_hi: 0,
// M0-7 item7 SLICE 4: the child inherits no in-flight stack grow nor its
// reservation — fork EAGAINs while stack_grow_in_progress, so this path is
// never reached mid-grow; zero defensively. The COMMITTED watermark IS
// copied: the grown stack region is COW-inherited (this is an independent
// address space built by copying the parent's page tables), so the child's
// committed floor matches the parent's, and the inherited grow DATA already
// rides in elf_charged_bytes (copied above + charged to the parent cgroup
// via fork_charge_bytes), so the child's last-exit uncharges it symmetrically.
stack_grow_pending_bytes: 0,
stack_floor_committed: parent_mm.stack_floor_committed,
stack_grow_in_progress: false,
fork_in_progress: false,
};
child.mm = Arc::try_new(Mutex::new(child_mm))
.map_err(|_| ForkError::MemoryAllocationFailed)?;
charge_bytes
};
// 复制 TLS 状态(FS/GS base)
child.fs_base = parent.fs_base;
child.gs_base = parent.gs_base;
// F.2: 继承 Cgroup 成员关系
// 子进程继承父进程的 cgroup,并注册到 cgroup 的任务列表
child.cgroup_id = parent.cgroup_id;
// Note: cgroup task tracking is done after process is fully created
// R93-1 FIX: 继承 IPC/Network/User 命名空间(以及 for_children 默认值)
// 防止 fork() 产生的子进程意外回落到 root namespace 造成隔离逃逸
// 注:PID namespace 和 Mount namespace 已在 create_process() 中继承
child.ipc_ns = parent.ipc_ns.clone();
child.ipc_ns_for_children = parent.ipc_ns_for_children.clone();
child.net_ns = parent.net_ns.clone();
child.net_ns_for_children = parent.net_ns_for_children.clone();
child.user_ns = parent.user_ns.clone();
child.user_ns_for_children = parent.user_ns_for_children.clone();
// 继承 Seccomp/Pledge 沙箱状态
// - SeccompState.filters: Vec<Arc<SeccompFilter>> 通过 Arc 共享,避免深拷贝
// - no_new_privs: 粘滞标志,一旦设置不可清除,必须继承
// - pledge_state: 包含 promises 和 exec_promises(exec 后生效)
// R162-6 FIX: Use fallible try_clone to avoid OOM panic (R161-3 regression)
child.seccomp_state = parent
.seccomp_state
.try_clone()
.map_err(|_| ForkError::MemoryAllocationFailed)?;
child.pledge_state = parent.pledge_state.clone();
// Finish every infallible PCB field before scheduler admission. The
// reserved queue entry is non-runnable until its permit is committed.
child.clear_child_tid = 0;
child.set_child_tid = 0;
child.robust_list_head = 0;
child.robust_list_len = 0;
child.socket_timeout_marker.store(0, Ordering::Relaxed);
child.wq_timeout_marker.store(0, Ordering::Relaxed);
child.active_wait_seq.store(0, Ordering::Relaxed);
child.context.rax = 0;
// R180-19 PREPARE: reserve the exact resources represented by the
// already-built child state. The RAII guard rolls both controllers back
// on root-frame, KPTI, or COW-plan failure; after this point there is no
// unguarded charge and no mismatch between the cloned MmState and its
// memory.max amount.
let child_fd_count = child.fd_table.len() as u64;
let mut charge_guard = ForkChargeGuard::new(parent.cgroup_id);
if child_fd_count != 0 {
crate::cgroup::try_charge_fds(parent.cgroup_id, child_fd_count)
.map_err(|_| ForkError::CgroupFilesLimitExceeded)?;
charge_guard.fd_count = child_fd_count;
}
if fork_charge_bytes != 0 {
crate::cgroup::try_charge_memory(parent.cgroup_id, fork_charge_bytes)
.map_err(|_| ForkError::MemoryAllocationFailed)?;
charge_guard.memory_bytes = fork_charge_bytes;
}
let child_cpuset_id = child.cpuset_id;
drop(child);
#[cfg(debug_assertions)]
kprintln!("[FORKDIAG] FD3 charged");
// R180-19 FIX: the parent-PTE COW transition is the COMMIT point.
// Every heap allocation, namespace/capability/credential clone, cgroup
// charge, and child metadata build above has already succeeded. The
// page-table transaction also prepares KPTI before touching the parent,
// so nothing below this call can return an error after parent PTEs have
// become read-only.
let mut frame_alloc = FrameAllocator::new();
let child_root_frame = frame_alloc
.allocate_frame()
.ok_or(ForkError::MemoryAllocationFailed)?;
unsafe {
zero_table(child_root_frame);
}
let child_memory_space = child_root_frame.start_address().as_u64() as usize;
let child_user_memory_space = unsafe {
match copy_page_table_cow_with_shared(
parent_root,
child_memory_space,
shared_ranges.as_slice(),
) {
Ok(user_memory_space) => user_memory_space,
Err(error) => {
// copy_page_table_cow guarantees the root's user half is
// empty on failure, so the generic teardown releases only
// the private root and never touches parent-owned leaves.
free_address_space(child_memory_space);
return Err(error);
}
}
};
let mut child = child_process.lock();
child.memory_space = child_memory_space;
child.user_memory_space = child_user_memory_space;
// The admission charge becomes owned by the child at the same commit.
// No error path exists below this assignment; normal exit now performs
// the exact matching uncharge.
child.fds_charged_count = child_fd_count;
charge_guard.commit();
// R163-4 FIX: All fallible operations above have succeeded. Safe to