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
use core::fmt::{self, Debug, Formatter};
use super::signal::*;
use super::AuxvEntry;
use super::AuxvType;
use super::TaskContext;
use super::{pid_alloc, KernelStack, PidHandle};
use crate::fs::{open, DiskInodeType, File, FileDescriptor, FileLike, OSInode, OpenFlags, TTY, open_root_inode};
use crate::mm::PageTable;
use crate::mm::{MemorySet, PhysPageNum, VirtAddr, KERNEL_SPACE};
use crate::syscall::errno::*;
use crate::task::current_task;
use crate::timer::TICKS_PER_SEC;
use crate::timer::{ITimerVal, TimeVal};
use crate::trap::{trap_handler, TrapContext};
use crate::{config::*, show_frame_consumption};
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::string::ToString;
use alloc::sync::{Arc, Weak};
use alloc::vec;
use alloc::vec::Vec;
use log::{debug, error, info, trace, warn};
use riscv::register::scause::{Interrupt, Trap};
use spin::{Mutex, MutexGuard};
pub struct TaskControlBlock {
pub pid: PidHandle,
pub kernel_stack: KernelStack,
inner: Mutex<TaskControlBlockInner>,
}
pub type FdTable = Vec<Option<FileDescriptor>>;
pub struct TaskControlBlockInner {
pub working_inode: Arc<OSInode>,
pub working_dir: String,
pub sigmask: Signals,
pub trap_cx_ppn: PhysPageNum,
pub base_size: usize,
pub task_cx_ptr: usize,
pub task_status: TaskStatus,
pub memory_set: MemorySet,
pub parent: Option<Weak<TaskControlBlock>>,
pub children: Vec<Arc<TaskControlBlock>>,
pub exit_code: u32,
pub fd_table: FdTable,
pub address: ProcAddress,
pub heap_bottom: usize,
pub heap_pt: usize,
pub siginfo: SigInfo,
pub pgid: usize,
pub rusage: Rusage,
pub clock: ProcClock,
pub timer: [ITimerVal; 3],
}
pub struct ProcClock {
last_enter_u_mode: TimeVal,
last_enter_s_mode: TimeVal,
}
impl ProcClock {
pub fn new() -> Self {
let now = TimeVal::now();
Self {
last_enter_u_mode: now,
last_enter_s_mode: now,
}
}
}
#[allow(unused)]
#[derive(Clone, Copy)]
pub struct Rusage {
pub ru_utime: TimeVal,
pub ru_stime: TimeVal,
ru_maxrss: isize,
ru_ixrss: isize,
ru_idrss: isize,
ru_isrss: isize,
ru_minflt: isize,
ru_majflt: isize,
ru_nswap: isize,
ru_inblock: isize,
ru_oublock: isize,
ru_msgsnd: isize,
ru_msgrcv: isize,
ru_nsignals: isize,
ru_nvcsw: isize,
ru_nivcsw: isize,
}
impl Rusage {
pub fn new() -> Self {
Self {
ru_utime: TimeVal::new(),
ru_stime: TimeVal::new(),
ru_maxrss: 0,
ru_ixrss: 0,
ru_idrss: 0,
ru_isrss: 0,
ru_minflt: 0,
ru_majflt: 0,
ru_nswap: 0,
ru_inblock: 0,
ru_oublock: 0,
ru_msgsnd: 0,
ru_msgrcv: 0,
ru_nsignals: 0,
ru_nvcsw: 0,
ru_nivcsw: 0,
}
}
}
impl Debug for Rusage {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.write_fmt(format_args!(
"(ru_utime:{:?}, ru_stime:{:?})",
self.ru_utime, self.ru_stime
))
}
}
impl TaskControlBlockInner {
pub fn get_task_cx_ptr2(&self) -> *const usize {
&self.task_cx_ptr as *const usize
}
pub fn get_trap_cx(&self) -> &'static mut TrapContext {
self.trap_cx_ppn.get_mut()
}
pub fn get_user_token(&self) -> usize {
self.memory_set.token()
}
fn get_status(&self) -> TaskStatus {
self.task_status
}
pub fn is_zombie(&self) -> bool {
self.get_status() == TaskStatus::Zombie
}
pub fn alloc_fd(&mut self) -> Option<usize> {
self.alloc_fd_at(0)
}
pub fn alloc_fd_at(&mut self, hint: usize) -> Option<usize> {
const FD_LIMIT: usize = 128;
if hint < self.fd_table.len() {
if let Some(fd) = (hint..self.fd_table.len()).find(|fd| self.fd_table[*fd].is_none()) {
Some(fd)
} else {
if self.fd_table.len() < FD_LIMIT {
self.fd_table.push(None);
Some(self.fd_table.len() - 1)
} else {
None
}
}
} else {
if hint < FD_LIMIT {
self.fd_table.resize(hint + 1, None);
Some(hint)
} else {
None
}
}
}
pub fn add_signal(&mut self, signal: Signals) {
self.siginfo.signal_pending.insert(signal);
}
pub fn update_process_times_enter_trap(&mut self) {
let now = TimeVal::now();
self.clock.last_enter_s_mode = now;
let diff = now - self.clock.last_enter_u_mode;
self.rusage.ru_utime = self.rusage.ru_utime + diff;
self.update_itimer_virtual_if_exists(diff);
self.update_itimer_prof_if_exists(diff);
}
pub fn update_process_times_leave_trap(&mut self, scause: Trap) {
let now = TimeVal::now();
self.update_itimer_real_if_exists(now - self.clock.last_enter_u_mode);
if scause != Trap::Interrupt(Interrupt::SupervisorTimer) {
let diff = now - self.clock.last_enter_s_mode;
self.rusage.ru_stime = self.rusage.ru_stime + diff;
self.update_itimer_prof_if_exists(diff);
}
self.clock.last_enter_u_mode = now;
}
pub fn update_itimer_real_if_exists(&mut self, diff: TimeVal) {
if !self.timer[0].it_value.is_zero() {
self.timer[0].it_value = self.timer[0].it_value - diff;
if self.timer[0].it_value.is_zero() {
self.add_signal(Signals::SIGALRM);
self.timer[0].it_value = self.timer[0].it_interval;
}
}
}
pub fn update_itimer_virtual_if_exists(&mut self, diff: TimeVal) {
if !self.timer[1].it_value.is_zero() {
self.timer[1].it_value = self.timer[1].it_value - diff;
if self.timer[1].it_value.is_zero() {
self.add_signal(Signals::SIGVTALRM);
self.timer[1].it_value = self.timer[1].it_interval;
}
}
}
pub fn update_itimer_prof_if_exists(&mut self, diff: TimeVal) {
if !self.timer[2].it_value.is_zero() {
self.timer[2].it_value = self.timer[2].it_value - diff;
if self.timer[2].it_value.is_zero() {
self.add_signal(Signals::SIGPROF);
self.timer[2].it_value = self.timer[2].it_interval;
}
}
}
}
impl TaskControlBlock {
pub fn acquire_inner_lock(&self) -> MutexGuard<TaskControlBlockInner> {
self.inner.lock()
}
pub fn new(elf_data: &[u8]) -> Self {
let (memory_set, user_sp, user_heap, elf_info) = MemorySet::from_elf(elf_data);
crate::mm::KERNEL_SPACE
.lock()
.remove_area_with_start_vpn(VirtAddr::from(elf_data.as_ptr() as usize).floor())
.unwrap();
let trap_cx_ppn = memory_set
.translate(VirtAddr::from(TRAP_CONTEXT).into())
.unwrap()
.ppn();
let pid_handle = pid_alloc();
let pgid = pid_handle.0;
let kernel_stack = KernelStack::new(&pid_handle);
let kernel_stack_top = kernel_stack.get_top();
let task_cx_ptr = kernel_stack.push_on_top(TaskContext::goto_trap_return());
let task_control_block = Self {
pid: pid_handle,
kernel_stack,
inner: Mutex::new(TaskControlBlockInner {
working_inode: open_root_inode(),
working_dir: "/".to_string(),
trap_cx_ppn,
pgid,
sigmask: Signals::empty(),
base_size: user_sp,
task_cx_ptr: task_cx_ptr as usize,
task_status: TaskStatus::Ready,
memory_set,
parent: None,
children: Vec::new(),
exit_code: 0,
fd_table: vec![
Some(FileDescriptor::new(false, FileLike::Abstract(TTY.clone()))),
Some(FileDescriptor::new(false, FileLike::Abstract(TTY.clone()))),
Some(FileDescriptor::new(false, FileLike::Abstract(TTY.clone()))),
],
address: ProcAddress::new(),
heap_bottom: user_heap,
heap_pt: user_heap,
siginfo: SigInfo::new(),
rusage: Rusage::new(),
clock: ProcClock::new(),
timer: [ITimerVal::new(); 3],
}),
};
let trap_cx = task_control_block.acquire_inner_lock().get_trap_cx();
*trap_cx = TrapContext::app_init_context(
elf_info.entry,
user_sp,
KERNEL_SPACE.lock().token(),
kernel_stack_top,
trap_handler as usize,
);
task_control_block
}
pub fn load_elf(&self, elf_data: &[u8], argv_vec: &Vec<String>, envp_vec: &Vec<String>) {
let (memory_set, mut user_sp, program_break, elf_info) = MemorySet::from_elf(elf_data);
let token = (&memory_set).token();
user_sp -= 2 * core::mem::size_of::<usize>();
let mut phys_user_sp = PageTable::from_token(token)
.translate_va(VirtAddr::from(user_sp))
.unwrap()
.0;
let virt_phys_offset = user_sp - phys_user_sp;
let phys_start = phys_user_sp;
fn copy_to_user_string_unchecked(src: &str, dst: *mut u8) {
let size = src.len();
unsafe {
core::slice::from_raw_parts_mut(dst, size)
.copy_from_slice(core::slice::from_raw_parts(src.as_ptr(), size));
*dst.add(size) = b'\0';
}
}
let mut envp_user = Vec::<*const u8>::new();
for env in envp_vec.iter() {
phys_user_sp -= env.len() + 1;
envp_user.push((phys_user_sp + virt_phys_offset) as *const u8);
copy_to_user_string_unchecked(env, phys_user_sp as *mut u8);
}
envp_user.push(core::ptr::null());
let mut argv_user = Vec::<*const u8>::new();
for arg in argv_vec.iter() {
phys_user_sp -= arg.len() + 1;
argv_user.push((phys_user_sp + virt_phys_offset) as *const u8);
copy_to_user_string_unchecked(arg, phys_user_sp as *mut u8);
}
argv_user.push(core::ptr::null());
phys_user_sp &= !0x7;
phys_user_sp -= 2 * core::mem::size_of::<usize>();
let random_bits_ptr = phys_user_sp + virt_phys_offset;
unsafe {
*(phys_user_sp as *mut usize) = 0xdeadbeefcafebabe;
*(phys_user_sp as *mut usize).add(1) = 0xdeadbeefcafebabe;
}
phys_user_sp -= core::mem::size_of::<usize>();
unsafe {
*(phys_user_sp as *mut usize) = 0x0000000000000000;
}
let auxv = [
AuxvEntry::new(AuxvType::HWCAP, 0x112d),
AuxvEntry::new(AuxvType::PAGESZ, PAGE_SIZE),
AuxvEntry::new(AuxvType::CLKTCK, TICKS_PER_SEC),
AuxvEntry::new(AuxvType::PHDR, elf_info.phdr),
AuxvEntry::new(AuxvType::PHENT, elf_info.phent),
AuxvEntry::new(AuxvType::PHNUM, elf_info.phnum),
AuxvEntry::new(AuxvType::BASE, 0),
AuxvEntry::new(AuxvType::FLAGS, 0),
AuxvEntry::new(AuxvType::ENTRY, elf_info.entry),
AuxvEntry::new(AuxvType::UID, 0),
AuxvEntry::new(AuxvType::EUID, 0),
AuxvEntry::new(AuxvType::GID, 0),
AuxvEntry::new(AuxvType::EGID, 0),
AuxvEntry::new(AuxvType::SECURE, 0),
AuxvEntry::new(AuxvType::RANDOM, random_bits_ptr as usize),
AuxvEntry::new(
AuxvType::EXECFN,
argv_user.first().copied().unwrap() as usize,
),
AuxvEntry::new(AuxvType::NULL, 0),
];
phys_user_sp -= auxv.len() * core::mem::size_of::<AuxvEntry>();
unsafe {
core::slice::from_raw_parts_mut(phys_user_sp as *mut AuxvEntry, auxv.len())
.copy_from_slice(auxv.as_slice());
}
phys_user_sp -= envp_user.len() * core::mem::size_of::<usize>();
unsafe {
core::slice::from_raw_parts_mut(phys_user_sp as *mut *const u8, envp_user.len())
.copy_from_slice(envp_user.as_slice());
}
phys_user_sp -= argv_user.len() * core::mem::size_of::<usize>();
unsafe {
core::slice::from_raw_parts_mut(phys_user_sp as *mut *const u8, argv_user.len())
.copy_from_slice(argv_user.as_slice());
}
phys_user_sp -= core::mem::size_of::<usize>();
unsafe {
*(phys_user_sp as *mut usize) = argv_vec.len();
}
user_sp = phys_user_sp + virt_phys_offset;
assert_eq!(phys_start & !0xfff, phys_user_sp & !0xfff);
let mut phys_addr = phys_user_sp & !0xf;
while phys_start >= phys_addr {
info!(
"0x{:0>16X}: {:0>16X} {:0>16X}",
phys_addr + virt_phys_offset,
unsafe { *(phys_addr as *mut usize) },
unsafe { *((phys_addr + core::mem::size_of::<usize>()) as *mut usize) }
);
phys_addr += 2 * core::mem::size_of::<usize>();
}
let trap_cx = TrapContext::app_init_context(
elf_info.entry,
user_sp,
KERNEL_SPACE.lock().token(),
self.kernel_stack.get_top(),
trap_handler as usize,
);
let mut inner = self.acquire_inner_lock();
inner.trap_cx_ppn = (&memory_set)
.translate(VirtAddr::from(TRAP_CONTEXT).into())
.unwrap()
.ppn();
*inner.get_trap_cx() = trap_cx;
inner.memory_set = memory_set;
inner.heap_bottom = program_break;
inner.heap_pt = program_break;
inner.siginfo.signal_handler = BTreeMap::new();
inner.fd_table.iter_mut().for_each(|fd| match fd {
Some(file) => {
if file.get_cloexec() {
*fd = None;
}
}
None => (),
});
}
pub fn fork(self: &Arc<TaskControlBlock>) -> Arc<TaskControlBlock> {
let mut parent_inner = self.acquire_inner_lock();
let memory_set = MemorySet::from_existed_user(&mut parent_inner.memory_set);
let trap_cx_ppn = memory_set
.translate(VirtAddr::from(TRAP_CONTEXT).into())
.unwrap()
.ppn();
let pid_handle = pid_alloc();
let kernel_stack = KernelStack::new(&pid_handle);
let kernel_stack_top = kernel_stack.get_top();
let task_cx_ptr = kernel_stack.push_on_top(TaskContext::goto_trap_return());
let mut new_fd_table: FdTable = Vec::new();
for fd in parent_inner.fd_table.iter() {
if let Some(file) = fd {
new_fd_table.push(Some(file.clone()));
} else {
new_fd_table.push(None);
}
}
let task_control_block = Arc::new(TaskControlBlock {
pid: pid_handle,
kernel_stack,
inner: Mutex::new(TaskControlBlockInner {
pgid: parent_inner.pgid,
base_size: parent_inner.base_size,
heap_bottom: parent_inner.heap_bottom,
heap_pt: parent_inner.heap_pt,
working_inode: parent_inner.working_inode.clone(),
working_dir: parent_inner.working_dir.clone(),
siginfo: parent_inner.siginfo.clone(),
parent: Some(Arc::downgrade(self)),
children: Vec::new(),
rusage: Rusage::new(),
clock: ProcClock::new(),
address: ProcAddress::new(),
timer: [ITimerVal::new(); 3],
sigmask: Signals::empty(),
fd_table: new_fd_table,
task_cx_ptr: task_cx_ptr as usize,
task_status: TaskStatus::Ready,
trap_cx_ppn,
memory_set,
exit_code: 0,
}),
});
parent_inner.children.push(task_control_block.clone());
let trap_cx = task_control_block.acquire_inner_lock().get_trap_cx();
trap_cx.kernel_sp = kernel_stack_top;
task_control_block
}
pub fn getpid(&self) -> usize {
self.pid.0
}
pub fn setpgid(&self, pgid: usize) -> isize {
if (pgid as isize) < 0 {
return -1;
}
let mut inner = self.acquire_inner_lock();
inner.pgid = pgid;
0
}
pub fn getpgid(&self) -> usize {
let inner = self.acquire_inner_lock();
inner.pgid
}
}
fn elf_exec(file: Arc<OSInode>, argv_vec: &Vec<String>, envp_vec: &Vec<String>) -> isize {
let size = file.size();
let start: usize = MMAP_BASE;
let buffer = unsafe { core::slice::from_raw_parts_mut(start as *mut u8, size) };
show_frame_consumption! {
"push_elf_area";
if crate::mm::push_elf_area(file.clone()).is_err() {
file.kread(None, buffer);
} else {
info!("[elf_exec] Hit ELF cache, no alloc");
};
}
let task = current_task().unwrap();
show_frame_consumption! {
"task_exec";
task.load_elf(buffer, argv_vec, envp_vec);
}
crate::mm::KERNEL_SPACE
.lock()
.remove_area_with_start_vpn(VirtAddr::from(MMAP_BASE).floor())
.unwrap();
SUCCESS
}
pub fn execve(path: String, mut argv_vec: Vec<String>, envp_vec: Vec<String>) -> isize {
const DEFAULT_SHELL: &str = "/bin/bash";
debug!(
"[exec] argv: {:?} /* {} vars */, envp: {:?} /* {} vars */",
argv_vec,
argv_vec.len(),
envp_vec,
envp_vec.len()
);
let task = current_task().unwrap();
let inner = task.acquire_inner_lock();
let working_inode = inner.working_inode.clone();
drop(inner);
match open(
&working_inode,
path.as_str(),
OpenFlags::O_RDONLY,
DiskInodeType::File,
) {
Ok(file) => {
if file.size() < 4 {
return ENOEXEC;
}
let mut magic_number = Box::<[u8; 4]>::new([0; 4]);
file.kread(Some(&mut 0usize), magic_number.as_mut_slice());
match magic_number.as_slice() {
b"\x7fELF" => elf_exec(file, &argv_vec, &envp_vec),
b"#!" => {
let shell_file = open(
&working_inode,
DEFAULT_SHELL,
OpenFlags::O_RDONLY,
DiskInodeType::File,
)
.unwrap();
argv_vec.insert(0, DEFAULT_SHELL.to_string());
elf_exec(shell_file, &argv_vec, &envp_vec)
}
_ => ENOEXEC,
}
}
Err(_) => ENOENT,
}
}
#[derive(Copy, Clone, PartialEq, Debug)]
pub enum TaskStatus {
Ready,
Running,
Zombie,
Interruptible,
}
pub struct ProcAddress {
pub set_child_tid: usize,
pub clear_child_tid: usize,
}
impl ProcAddress {
pub fn new() -> Self {
Self {
set_child_tid: 0,
clear_child_tid: 0,
}
}
}