-
Notifications
You must be signed in to change notification settings - Fork 111
Expand file tree
/
Copy pathprocess.rs
More file actions
1611 lines (1465 loc) · 55.9 KB
/
process.rs
File metadata and controls
1611 lines (1465 loc) · 55.9 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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//! Process/thread related syscalls.
use crate::{ConstPtr, MutPtr, ShimFS, Task};
use alloc::boxed::Box;
use alloc::collections::btree_map::BTreeMap;
use alloc::sync::Arc;
use alloc::vec::Vec;
use core::cell::Cell;
use core::mem::offset_of;
use core::ops::Range;
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
use litebox::event::wait::WaitError;
use litebox::mm::linux::VmFlags;
use litebox::platform::RawMutPointer as _;
use litebox::platform::ThreadProvider;
use litebox::platform::{Instant as _, SystemTime as _, TimeProvider};
use litebox::platform::{
PunchthroughProvider as _, PunchthroughToken as _, RawConstPointer as _, RawMutex as _,
ThreadLocalStorageProvider as _,
};
use litebox::sync::Mutex;
use litebox::utils::TruncateExt as _;
use litebox_common_linux::{
ArchPrctlArg, CloneFlags, FutexArgs, PrctlArg, TimeParam, errno::Errno,
};
use litebox_platform_multiplex::Platform;
/// Process-management-related state on [`Task`].
pub(crate) struct ThreadState {
init_state: Cell<ThreadInitState>,
process: Arc<Process>,
/// Thread state that can be accessed from a remote thread.
remote: Arc<ThreadRemote>,
attached_tid: Cell<Option<i32>>,
/// When a thread whose `clear_child_tid` is not `None` terminates, and it shares memory with other threads,
/// the kernel writes 0 to the address specified by `clear_child_tid` and then executes:
///
/// futex(clear_child_tid, FUTEX_WAKE, 1, NULL, NULL, 0);
///
/// This operation wakes a single thread waiting on the specified memory location via futex.
/// Any errors from the futex wake operation are ignored.
clear_child_tid: Cell<Option<MutPtr<i32>>>,
/// The purpose of the robust futex list is to ensure that if a thread accidentally fails to unlock a futex before
/// terminating or calling execve(2), another thread that is waiting on that futex is notified that the former owner
/// of the futex has died. This notification consists of two pieces: the FUTEX_OWNER_DIED bit is set in the futex word,
/// and the kernel performs a futex(2) FUTEX_WAKE operation on one of the threads waiting on the futex.
robust_list: Cell<Option<ConstPtr<litebox_common_linux::RobustListHead>>>,
}
// TODO: remove once we figure out how to handle Send/Sync for raw pointers.
unsafe impl Send for ThreadState {}
impl ThreadState {
pub fn new_process(pid: i32) -> Self {
let remote = Arc::new(ThreadRemote::new());
Self {
init_state: Cell::new(ThreadInitState::None),
process: Arc::new(Process::new(pid, remote.clone())),
remote,
attached_tid: Cell::new(Some(pid)),
clear_child_tid: Cell::new(None),
robust_list: Cell::new(None),
}
}
pub(crate) fn new_thread(&self, tid: i32) -> Option<Self> {
let remote = self.process.attach_thread(tid)?;
Some(Self {
init_state: Cell::new(ThreadInitState::None),
process: self.process.clone(),
remote,
attached_tid: Cell::new(Some(tid)),
clear_child_tid: Cell::new(None),
robust_list: Cell::new(None),
})
}
fn detach_from_process(&self) {
if let Some(tid) = self.attached_tid.take() {
self.process.detach_thread(tid);
}
}
}
impl Drop for ThreadState {
fn drop(&mut self) {
self.detach_from_process();
}
}
/// Thread state that can be accessed from a remote thread.
struct ThreadRemote {
/// Always set under the process `inner` lock, but can be read without
/// locking.
is_exiting: AtomicBool,
/// Handle to interrupt waits on this thread.
handle: once_cell::race::OnceBox<litebox::event::wait::ThreadHandle<Platform>>,
}
impl ThreadRemote {
fn new() -> Self {
Self {
is_exiting: AtomicBool::new(false),
handle: once_cell::race::OnceBox::new(),
}
}
fn interrupt(&self) {
if let Some(handle) = self.handle.get() {
handle.interrupt();
}
}
}
/// A Linux process, which may have multiple threads.
pub(crate) struct Process {
/// Number of threads in this process. Always updated under the `inner`
/// mutex lock.
nr_threads:
<litebox_platform_multiplex::Platform as litebox::platform::RawMutexProvider>::RawMutex,
inner: Mutex<Platform, ProcessInner>,
/// Resource limits for this process.
pub(crate) limits: ResourceLimits,
}
/// The locked portion of the process state.
struct ProcessInner {
/// If true, the whole process is exiting.
group_exit: bool,
/// If true, one thread is waiting for other threads to exit.
is_killing_other_threads: bool,
/// The exit code of the last exited thread in the process. Not updated once
/// `group_exit` is set.
exit_status: ExitStatus,
/// The thread list for the process, mapped by thread ID.
threads: BTreeMap<i32, Arc<ThreadRemote>>,
}
#[derive(Clone, Copy, Debug)]
pub(crate) enum ExitStatus {
Exit(i8),
Signal(litebox_common_linux::signal::Signal),
}
impl Process {
/// Creates a new process with the given initial thread.
fn new(pid: i32, remote: Arc<ThreadRemote>) -> Self {
let nr_threads = <Platform as litebox::platform::RawMutexProvider>::RawMutex::INIT;
nr_threads.underlying_atomic().store(1, Ordering::Relaxed);
Self {
nr_threads,
inner: Mutex::new(ProcessInner {
exit_status: ExitStatus::Exit(0),
group_exit: false,
is_killing_other_threads: false,
threads: BTreeMap::from_iter([(pid, remote)]),
}),
limits: ResourceLimits::default(),
}
}
/// Returns the current number of threads in this process.
pub fn nr_threads(&self) -> u32 {
self.nr_threads.underlying_atomic().load(Ordering::Relaxed)
}
/// Waits for all threads in this process to exit, returning the exit code.
pub fn wait_for_exit(&self) -> ExitStatus {
loop {
let n = self.nr_threads.underlying_atomic().load(Ordering::Acquire);
if n == 0 {
break;
}
let _ = self.nr_threads.block(n);
}
self.inner.lock().exit_status
}
/// Attaches a new thread to this process, returning a new remote state for
/// the thread.
fn attach_thread(&self, tid: i32) -> Option<Arc<ThreadRemote>> {
// Allocate outside the lock.
let remote = Arc::new(ThreadRemote::new());
let mut inner = self.inner.lock();
if inner.group_exit || inner.is_killing_other_threads {
return None;
}
let old_thread = inner.threads.insert(tid, remote.clone());
assert!(old_thread.is_none(), "thread ID {tid} already exists");
let nr_threads = self.nr_threads.underlying_atomic();
nr_threads.store(nr_threads.load(Ordering::Relaxed) + 1, Ordering::Release);
Some(remote)
}
/// Detaches a thread from this process.
///
/// # Panics
/// Panics if the thread ID does not exist in this process.
fn detach_thread(&self, tid: i32) {
let data;
let notify = {
let mut inner = self.inner.lock();
data = inner.threads.remove(&tid);
assert!(data.is_some());
let nr_threads = self.nr_threads.underlying_atomic();
let n = nr_threads.load(Ordering::Relaxed);
let new_count = n.checked_sub(1).expect("decrementing from zero threads");
nr_threads.store(new_count, Ordering::Release);
if new_count == 0 {
assert!(inner.threads.is_empty());
// The last thread exited. Prevent new threads.
inner.group_exit = true;
}
// Notify waiters if this is the last thread of the process
// (`wait_for_exit`) or if this is the last thread being killed
// during an exec (`kill_other_threads`).
new_count == 0 || (new_count == 1 && inner.is_killing_other_threads)
};
if notify {
self.nr_threads.wake_all();
}
}
}
impl<FS: ShimFS> Task<FS> {
/// Updates the process exit status for a thread exit.
fn exit_thread(&self, code: i8) {
let mut inner = self.thread.process.inner.lock();
if self.is_exiting() {
return;
}
inner.exit_status = ExitStatus::Exit(code);
self.thread.remote.is_exiting.store(true, Ordering::Relaxed);
}
/// Updates the process exit status for a group exit and signals all threads
/// to exit.
pub(crate) fn exit_group(&self, status: ExitStatus) {
let mut inner = self.thread.process.inner.lock();
if self.is_exiting() {
return;
}
assert!(!inner.group_exit);
inner.exit_status = status;
inner.group_exit = true;
for thread in inner.threads.values() {
thread.is_exiting.store(true, Ordering::Relaxed);
thread.interrupt();
}
}
/// Kills all other threads in the process, waiting for them to exit.
///
/// Returns false if this thread is already exiting.
#[must_use]
fn kill_other_threads(&self) -> bool {
{
let mut inner = self.thread.process.inner.lock();
if self.is_exiting() {
return false;
}
for (&tid, thread) in &inner.threads {
if tid == self.tid {
continue;
}
thread.is_exiting.store(true, Ordering::Relaxed);
thread.interrupt();
}
assert!(!inner.is_killing_other_threads);
inner.is_killing_other_threads = true;
}
// Wait for other threads to exit.
loop {
let n = self
.thread
.process
.nr_threads
.underlying_atomic()
.load(Ordering::Acquire);
if n == 1 {
break;
}
let _ = self.thread.process.nr_threads.block(n);
}
self.thread.process.inner.lock().is_killing_other_threads = false;
true
}
/// Returns true if the task is exiting and should not continue running
/// guest code.
pub fn is_exiting(&self) -> bool {
self.thread.remote.is_exiting.load(Ordering::Relaxed)
}
}
#[derive(Default)]
enum ThreadInitState {
#[default]
None,
NewProcess(crate::loader::elf::ElfLoadInfo),
NewThread {
stack: Option<usize>,
tls: Option<ThreadLocalDescriptor>,
set_child_tid: Option<MutPtr<i32>>,
},
}
/// Credentials of a process
#[derive(Clone)]
pub(crate) struct Credentials {
pub uid: u32,
pub euid: u32,
pub gid: u32,
pub egid: u32,
}
impl<FS: ShimFS> Task<FS> {
pub(crate) fn process(&self) -> &Arc<Process> {
&self.thread.process
}
/// Set the current task's command name.
pub(crate) fn set_task_comm(&self, comm: &[u8]) {
let mut new_comm = [0u8; litebox_common_linux::TASK_COMM_LEN];
let comm = &comm[..comm.len().min(litebox_common_linux::TASK_COMM_LEN - 1)];
new_comm[..comm.len()].copy_from_slice(comm);
self.comm.set(new_comm);
}
/// Handle syscall `prctl`.
pub(crate) fn sys_prctl(
&self,
arg: PrctlArg<litebox_platform_multiplex::Platform>,
) -> Result<usize, Errno> {
match arg {
PrctlArg::GetName(name) => name
.write_slice_at_offset(0, &self.comm.get())
.ok_or(Errno::EFAULT)
.map(|()| 0),
PrctlArg::SetName(name) => {
let mut name_buf = [0u8; litebox_common_linux::TASK_COMM_LEN - 1];
// strncpy
for (i, byte) in name_buf.iter_mut().enumerate() {
let b = name
.read_at_offset(isize::try_from(i).unwrap())
.ok_or(Errno::EFAULT)?;
if b == 0 {
break;
}
*byte = b;
}
self.set_task_comm(&name_buf);
Ok(0)
}
PrctlArg::CapBSetRead(cap) => {
// Return 1 if the capability specified in cap is in the calling
// thread's capability bounding set, or 0 if it is not.
if cap
> litebox_common_linux::CapSet::LAST_CAP
.bits()
.trailing_zeros() as usize
{
return Err(Errno::EINVAL);
}
// Note we don't support capabilities in LiteBox, so we always return 0.
Ok(0)
}
_ => unimplemented!(),
}
}
/// Handle syscall `arch_prctl`.
pub(crate) fn sys_arch_prctl(
&self,
arg: ArchPrctlArg<litebox_platform_multiplex::Platform>,
) -> Result<(), Errno> {
match arg {
#[cfg(target_arch = "x86_64")]
ArchPrctlArg::SetFs(addr) => {
let punchthrough = litebox_common_linux::PunchthroughSyscall::SetFsBase { addr };
let token = self
.global
.platform
.get_punchthrough_token_for(punchthrough)
.expect("Failed to get punchthrough token for SET_FS");
token.execute().map(|_| ()).map_err(|e| match e {
litebox::platform::PunchthroughError::Failure(errno) => errno,
_ => unimplemented!("Unsupported punchthrough error {:?}", e),
})
}
#[cfg(target_arch = "x86_64")]
ArchPrctlArg::GetFs(addr) => {
let punchthrough = litebox_common_linux::PunchthroughSyscall::GetFsBase;
let token = self
.global
.platform
.get_punchthrough_token_for(punchthrough)
.expect("Failed to get punchthrough token for GET_FS");
let fsbase = token.execute().map_err(|e| match e {
litebox::platform::PunchthroughError::Failure(errno) => errno,
_ => unimplemented!("Unsupported punchthrough error {:?}", e),
})?;
addr.write_at_offset(0, fsbase).ok_or(Errno::EFAULT)?;
Ok(())
}
ArchPrctlArg::CETStatus | ArchPrctlArg::CETDisable | ArchPrctlArg::CETLock => {
Err(Errno::EINVAL)
}
_ => unimplemented!(),
}
}
#[cfg(target_arch = "x86")]
pub(crate) fn set_thread_area(
&self,
user_desc: &mut litebox_common_linux::UserDesc,
) -> Result<(), Errno> {
let punchthrough = litebox_common_linux::PunchthroughSyscall::SetThreadArea { user_desc };
let token = self
.global
.platform
.get_punchthrough_token_for(punchthrough)
.expect("Failed to get punchthrough token for SET_THREAD_AREA");
token.execute().map(|_| ()).map_err(|e| match e {
litebox::platform::PunchthroughError::Failure(errno) => errno,
_ => unimplemented!("Unsupported punchthrough error {:?}", e),
})
}
}
const ROBUST_LIST_LIMIT: isize = 2048;
/*
* Process a futex-list entry, check whether it's owned by the
* dying task, and do notification if so:
*/
fn handle_futex_death(
futex_addr: crate::ConstPtr<u32>,
_pi: bool,
_pending_op: bool,
) -> Result<(), Errno> {
if futex_addr.as_usize() % 4 != 0 {
return Err(Errno::EINVAL);
}
todo!("handle_futex_death is not implemented yet");
}
fn fetch_robust_entry(
head: crate::ConstPtr<litebox_common_linux::RobustList>,
) -> (crate::ConstPtr<litebox_common_linux::RobustList>, bool) {
let next = head.as_usize();
(crate::ConstPtr::from_usize(next & !1), next & 1 != 0)
}
fn wake_robust_list(
head: crate::ConstPtr<litebox_common_linux::RobustListHead>,
) -> Result<(), Errno> {
let mut limit = ROBUST_LIST_LIMIT;
let head_ptr = head.as_usize();
let head = head.read_at_offset(0).ok_or(Errno::EFAULT)?;
let (mut entry, mut pi) = fetch_robust_entry(crate::ConstPtr::from_usize(head.list.next));
let (pending, ppi) = fetch_robust_entry(crate::ConstPtr::from_usize(head.list_op_pending));
let futex_offset = head.futex_offset;
let entry_head = head_ptr.wrapping_add(offset_of!(litebox_common_linux::RobustListHead, list));
while entry.as_usize() != entry_head && limit > 0 {
let nxt = entry
.read_at_offset(0)
.map(|e| fetch_robust_entry(crate::ConstPtr::from_usize(e.next)));
if entry.as_usize() != pending.as_usize() {
handle_futex_death(
crate::ConstPtr::from_usize(entry.as_usize().wrapping_add(futex_offset)),
pi,
false,
)?;
}
let Some((next_entry, next_pi)) = nxt else {
return Err(Errno::EFAULT);
};
entry = next_entry;
pi = next_pi;
limit -= 1;
}
if pending.as_usize() != 0 {
let _ = handle_futex_death(
crate::ConstPtr::from_usize(pending.as_usize().wrapping_add(futex_offset)),
ppi,
true,
);
}
Ok(())
}
impl<FS: ShimFS> Task<FS> {
/// Called when the task is exiting.
pub(crate) fn prepare_for_exit(&mut self) {
self.thread.detach_from_process();
if let Some(clear_child_tid) = self.thread.clear_child_tid.take() {
// Clear the child TID if requested
// TODO: if we are the last thread, we don't need to clear it
let _ = clear_child_tid.write_at_offset(0, 0);
// Cast from *i32 to *u32
let clear_child_tid = crate::MutPtr::from_usize(clear_child_tid.as_usize());
let _ = self.sys_futex(litebox_common_linux::FutexArgs::Wake {
addr: clear_child_tid,
flags: litebox_common_linux::FutexFlags::PRIVATE,
count: 1,
});
}
if let Some(robust_list) = self.thread.robust_list.take() {
let _ = wake_robust_list(robust_list);
}
}
pub(crate) fn sys_exit(&self, status: i32) {
// The `Task` will be dropped on the way out of the shim, which will
// call `self.prepare_for_exit()`.
self.exit_thread(status.truncate());
}
pub(crate) fn sys_exit_group(&self, status: i32) {
// Tear down occurs similarly to `sys_exit`.
self.exit_group(ExitStatus::Exit(status.truncate()));
}
}
/// A descriptor for thread-local storage (TLS).
///
/// On `x86_64`, this is represented as a `*mut u8`. The TLS pointer can point to
/// an arbitrary-sized memory region.
#[cfg(target_arch = "x86_64")]
type ThreadLocalDescriptor = MutPtr<u8>;
/// A descriptor for thread-local storage (TLS).
///
/// On `x86`, this is represented as a `UserDesc`, which provides a more
/// structured descriptor (e.g., base address, limit, flags).
#[cfg(target_arch = "x86")]
type ThreadLocalDescriptor = litebox_common_linux::UserDesc;
struct NewThreadArgs<FS: ShimFS> {
/// Task struct that maintains all per-thread data
task: Task<FS>,
}
impl<FS: ShimFS> litebox::shim::InitThread for NewThreadArgs<FS> {
type ExecutionContext = litebox_common_linux::PtRegs;
fn init(
self: alloc::boxed::Box<Self>,
) -> alloc::boxed::Box<dyn litebox::shim::EnterShim<ExecutionContext = Self::ExecutionContext>>
{
let Self { task } = *self;
Box::new(crate::LinuxShimEntrypoints {
task,
_not_send: core::marker::PhantomData,
})
}
}
impl<FS: ShimFS> Task<FS> {
pub(crate) fn sys_clone(
&self,
ctx: &litebox_common_linux::PtRegs,
args: &litebox_common_linux::CloneArgs,
) -> Result<usize, Errno> {
self.do_clone(ctx, args, false)
}
pub(crate) fn sys_clone3(
&self,
ctx: &litebox_common_linux::PtRegs,
args: ConstPtr<litebox_common_linux::CloneArgs>,
) -> Result<usize, Errno> {
let args = args.read_at_offset(0).ok_or(Errno::EFAULT)?;
self.do_clone(ctx, &args, true)
}
/// Creates a new thread or process.
///
/// Note we currently only support creating threads with the VM, FS, and FILES flags set.
fn do_clone(
&self,
ctx: &litebox_common_linux::PtRegs,
args: &litebox_common_linux::CloneArgs,
clone3: bool,
) -> Result<usize, Errno> {
const MAX_SIGNAL_NUMBER: u64 = 64;
let litebox_common_linux::CloneArgs {
mut flags,
pidfd: _,
child_tid,
parent_tid,
exit_signal,
stack,
stack_size,
tls,
set_tid,
set_tid_size,
cgroup,
} = *args;
// `CLONE_DETACHED` is ignored but has been reserved for reuse with
// `clone3` or in combination with `CLONE_PIDFD`.
if !clone3 && !flags.contains(CloneFlags::PIDFD) {
flags.remove(CloneFlags::DETACHED);
}
let required_clone_flags =
CloneFlags::VM | CloneFlags::THREAD | CloneFlags::SIGHAND | CloneFlags::FILES;
let supported_clone_flags = CloneFlags::VM
| CloneFlags::FS
| CloneFlags::FILES
| CloneFlags::SIGHAND
| CloneFlags::PARENT
| CloneFlags::THREAD
| CloneFlags::SETTLS
| CloneFlags::PARENT_SETTID
| CloneFlags::CHILD_CLEARTID
| CloneFlags::CHILD_SETTID
// Ignored since we don't support sysv semaphores anyway.
| CloneFlags::SYSVSEM;
if flags.intersects(!supported_clone_flags) {
log_unsupported!(
"clone with unsupported flags: {:?}",
flags & !supported_clone_flags
);
return Err(Errno::EINVAL);
}
if !flags.contains(required_clone_flags) {
log_unsupported!(
"clone with missing required flags: {:?}",
required_clone_flags & !flags
);
return Err(Errno::EINVAL);
}
if cgroup != 0 {
log_unsupported!("clone with cgroup");
return Err(Errno::EINVAL);
}
if set_tid != 0 || set_tid_size != 0 {
log_unsupported!("clone with set_tid");
return Err(Errno::EINVAL);
}
// Note `exit_signal` is ignored because we don't support `fork` yet; we just validate it.
if exit_signal > MAX_SIGNAL_NUMBER {
return Err(Errno::EINVAL);
}
let tls = if flags.contains(CloneFlags::SETTLS) {
let addr = tls.truncate();
#[cfg(target_arch = "x86_64")]
let desc = MutPtr::from_usize(addr);
#[cfg(target_arch = "x86")]
let desc = {
let desc = MutPtr::<litebox_common_linux::UserDesc>::from_usize(addr)
.read_at_offset(0)
.ok_or(Errno::EFAULT)?;
// Note that different from `set_thread_area` syscall that returns the allocated entry number
// when requested (i.e., `desc.entry_number` is -1), here we just read the descriptor to LiteBox and
// assume the entry number is properly set so that we don't need to write it back. This is because
// we set up the TLS descriptor in the new thread's context, at which point the original descriptor
// pointer might no longer be valid. Linux does not have this problem because it sets up the TLS for
// the child thread in the parent thread before `clone` returns.
// In practice, glibc always sets the entry number to a valid value when calling `clone` with TLS as
// all threads can share the same TLS entry as the main thread.
let idx = desc.entry_number;
if idx == u32::MAX {
return Err(Errno::EINVAL);
}
desc
};
Some(desc)
} else {
None
};
let child_tid = if child_tid == 0 {
None
} else {
Some(MutPtr::from_usize(child_tid.truncate()))
};
let set_child_tid = if flags.contains(CloneFlags::CHILD_SETTID) {
child_tid
} else {
None
};
let clear_child_tid = if flags.contains(CloneFlags::CHILD_CLEARTID) {
child_tid
} else {
None
};
let set_parent_tid = if flags.contains(CloneFlags::PARENT_SETTID) && parent_tid != 0 {
Some(MutPtr::from_usize(parent_tid.truncate()))
} else {
None
};
let fs = if flags.contains(CloneFlags::FS) {
self.fs.borrow().clone()
} else {
alloc::sync::Arc::new((**self.fs.borrow()).clone())
};
let child_tid = self.global.next_thread_id.fetch_add(1, Ordering::Relaxed);
if let Some(parent_tid_ptr) = set_parent_tid {
let _ = parent_tid_ptr.write_at_offset(0, child_tid);
}
if (stack == 0 && stack_size != 0) || (stack != 0 && clone3 && stack_size == 0) {
return Err(Errno::EINVAL);
}
let sp = if stack != 0 {
let stack: usize = stack.truncate();
Some(stack.wrapping_add(stack_size.truncate()))
} else {
None
};
let thread = self.thread.new_thread(child_tid).ok_or(Errno::EBUSY)?;
thread.init_state.set(ThreadInitState::NewThread {
stack: sp,
tls,
set_child_tid,
});
thread.clear_child_tid.set(clear_child_tid);
let r = unsafe {
self.global.platform.spawn_thread(
ctx,
Box::new(NewThreadArgs {
task: Task {
global: self.global.clone(),
wait_state: crate::wait::WaitState::new(self.global.platform),
thread,
pid: self.pid,
tid: child_tid,
ppid: self.ppid,
credentials: self.credentials.clone(),
comm: self.comm.clone(),
fs: fs.into(),
files: self.files.clone(), // TODO: !CLONE_FILES support
signals: self.signals.clone_for_new_task(),
},
}),
)
};
if let Err(err) = r {
litebox::log_println!(self.global.platform, "failed to spawn thread: {}", err);
// Treat all spawn errors as `ENOMEM`. `EAGAIN` and other errors are
// for conditions the user can control (such as "in-shim" rlimit
// violations).
return Err(Errno::ENOMEM);
}
Ok(usize::try_from(child_tid).unwrap())
}
/// Handle syscall `set_tid_address`.
pub(crate) fn sys_set_tid_address(&self, tidptr: crate::MutPtr<i32>) -> i32 {
self.thread.clear_child_tid.set(Some(tidptr));
self.tid
}
/// Handle syscall `gettid`.
pub(crate) fn sys_gettid(&self) -> i32 {
self.tid
}
}
// TODO: enforce the following limits:
const RLIMIT_NOFILE_CUR: usize = 1024 * 1024;
const RLIMIT_NOFILE_MAX: usize = 1024 * 1024;
struct AtomicRlimit {
cur: core::sync::atomic::AtomicUsize,
max: core::sync::atomic::AtomicUsize,
}
impl AtomicRlimit {
const fn new(cur: usize, max: usize) -> Self {
Self {
cur: core::sync::atomic::AtomicUsize::new(cur),
max: core::sync::atomic::AtomicUsize::new(max),
}
}
}
pub(crate) struct ResourceLimits {
limits: [AtomicRlimit; litebox_common_linux::RlimitResource::RLIM_NLIMITS],
}
impl ResourceLimits {
const fn default() -> Self {
seq_macro::seq!(N in 0..16 {
let mut limits = [
#(
AtomicRlimit::new(0, 0),
)*
];
});
limits[litebox_common_linux::RlimitResource::NOFILE as usize] = AtomicRlimit {
cur: core::sync::atomic::AtomicUsize::new(RLIMIT_NOFILE_CUR),
max: core::sync::atomic::AtomicUsize::new(RLIMIT_NOFILE_MAX),
};
limits[litebox_common_linux::RlimitResource::STACK as usize] = AtomicRlimit {
cur: core::sync::atomic::AtomicUsize::new(crate::loader::DEFAULT_STACK_SIZE),
max: core::sync::atomic::AtomicUsize::new(litebox_common_linux::rlim_t::MAX),
};
Self { limits }
}
pub(crate) fn get_rlimit(
&self,
resource: litebox_common_linux::RlimitResource,
) -> litebox_common_linux::Rlimit {
let r = &self.limits[resource as usize];
litebox_common_linux::Rlimit {
rlim_cur: r.cur.load(Ordering::Relaxed),
rlim_max: r.max.load(Ordering::Relaxed),
}
}
pub(crate) fn get_rlimit_cur(&self, resource: litebox_common_linux::RlimitResource) -> usize {
let r = &self.limits[resource as usize];
r.cur.load(Ordering::Relaxed)
}
fn set_rlimit(
&self,
resource: litebox_common_linux::RlimitResource,
new_limit: litebox_common_linux::Rlimit,
) {
let r = &self.limits[resource as usize];
r.cur.store(new_limit.rlim_cur, Ordering::Relaxed);
r.max.store(new_limit.rlim_max, Ordering::Relaxed);
}
}
impl<FS: ShimFS> Task<FS> {
/// Get resource limits, and optionally set new limits.
pub(crate) fn do_prlimit(
&self,
resource: litebox_common_linux::RlimitResource,
new_limit: Option<litebox_common_linux::Rlimit>,
) -> Result<litebox_common_linux::Rlimit, Errno> {
let old_rlimit = match resource {
litebox_common_linux::RlimitResource::NOFILE
| litebox_common_linux::RlimitResource::STACK => {
self.thread.process.limits.get_rlimit(resource)
}
_ => unimplemented!("Unsupported resource for get_rlimit: {:?}", resource),
};
if let Some(new_limit) = new_limit {
if new_limit.rlim_cur > new_limit.rlim_max {
return Err(Errno::EINVAL);
}
if let litebox_common_linux::RlimitResource::NOFILE = resource
&& new_limit.rlim_max > RLIMIT_NOFILE_MAX
{
return Err(Errno::EPERM);
}
// Note process with `CAP_SYS_RESOURCE` can increase the hard limit, but we don't
// support capabilities in LiteBox, so we don't check for that here.
if new_limit.rlim_max > old_rlimit.rlim_max {
return Err(Errno::EPERM);
}
match resource {
litebox_common_linux::RlimitResource::NOFILE => {
self.thread.process.limits.set_rlimit(resource, new_limit);
}
_ => unimplemented!("Unsupported resource for set_rlimit: {:?}", resource),
}
}
Ok(old_rlimit)
}
/// Handle syscall `prlimit64`.
///
/// Note for now setting new limits is not supported yet, and thus returning constant values
/// for the requested resource. Getting resources for a specific PID is also not supported yet.
pub(crate) fn sys_prlimit(
&self,
pid: i32,
resource: litebox_common_linux::RlimitResource,
new_rlim: Option<crate::ConstPtr<litebox_common_linux::Rlimit64>>,
old_rlim: Option<crate::MutPtr<litebox_common_linux::Rlimit64>>,
) -> Result<(), Errno> {
if pid != 0 {
unimplemented!("prlimit for a specific PID is not supported yet");
}
let new_limit = match new_rlim {
Some(rlim) => {
let rlim = rlim.read_at_offset(0).ok_or(Errno::EINVAL)?;
Some(litebox_common_linux::rlimit64_to_rlimit(rlim))
}
None => None,
};
let old_limit =
litebox_common_linux::rlimit_to_rlimit64(self.do_prlimit(resource, new_limit)?);
if let Some(old_rlim) = old_rlim {
old_rlim
.write_at_offset(0, old_limit)
.ok_or(Errno::EINVAL)?;
}
Ok(())
}
/// Handle syscall `setrlimit`.
pub(crate) fn sys_getrlimit(
&self,
resource: litebox_common_linux::RlimitResource,
rlim: crate::MutPtr<litebox_common_linux::Rlimit>,
) -> Result<(), Errno> {
let old_limit = self.do_prlimit(resource, None)?;
rlim.write_at_offset(0, old_limit).ok_or(Errno::EINVAL)
}
/// Handle syscall `setrlimit`.
pub(crate) fn sys_setrlimit(
&self,
resource: litebox_common_linux::RlimitResource,
rlim: crate::ConstPtr<litebox_common_linux::Rlimit>,
) -> Result<(), Errno> {
let new_limit = rlim.read_at_offset(0).ok_or(Errno::EFAULT)?;
let _ = self.do_prlimit(resource, Some(new_limit))?;
Ok(())
}
/// Handle syscall `set_robust_list`.
pub(crate) fn sys_set_robust_list(&self, head: usize) {
let head = crate::ConstPtr::from_usize(head);
self.thread.robust_list.set(Some(head));
}
/// Handle syscall `get_robust_list`.
pub(crate) fn sys_get_robust_list(
&self,
pid: Option<i32>,
head_ptr: crate::MutPtr<usize>,
) -> Result<(), Errno> {
if pid.is_some() {
unimplemented!("Getting robust list for a specific PID is not supported yet");
}
let head = self
.thread
.robust_list
.get()
.map_or(0, |ptr| ptr.as_usize());
head_ptr.write_at_offset(0, head).ok_or(Errno::EFAULT)
}
fn real_time_as_duration_since_epoch(&self) -> core::time::Duration {
let now = self.global.platform.current_time();
let unix_epoch =
<litebox_platform_multiplex::Platform as TimeProvider>::SystemTime::UNIX_EPOCH;
now.duration_since(&unix_epoch)
.expect("must be after unix epoch")
}
/// Handle syscall `clock_gettime`.
pub(crate) fn sys_clock_gettime(
&self,
clockid: litebox_common_linux::ClockId,
tp: TimeParam<Platform>,
) -> Result<(), Errno> {
let duration = self.gettime_as_duration(clockid)?;
tp.write(duration)
}
fn gettime_as_duration(
&self,
clockid: litebox_common_linux::ClockId,
) -> Result<core::time::Duration, Errno> {
let duration = match clockid {
litebox_common_linux::ClockId::RealTime => {
// CLOCK_REALTIME
self.real_time_as_duration_since_epoch()
}
litebox_common_linux::ClockId::Monotonic => {
// CLOCK_MONOTONIC
self.global
.platform
.now()