10 Commits

Author SHA1 Message Date
0e751d690f optinal finished 2025-03-26 20:17:38 +08:00
2001e8e478 optinal load_avg to fix 2025-03-26 09:32:27 +08:00
e66ab82e63 syscall optional to finish 2025-03-25 19:18:29 +08:00
992f76ca30 syscall lab finished 2025-03-25 11:36:21 +08:00
a087b429df syscall trace finished 2025-03-25 10:35:06 +08:00
d92eea9e49 syscall lab need to finish 2025-03-25 01:13:50 +08:00
e33ff43dd6 syscall lab start 2025-03-08 11:25:52 +08:00
07fc8a52bd syscall branch 2025-03-04 11:23:18 +08:00
962a7083da optional added 2025-03-03 18:33:08 +08:00
a226786836 util branch case closed 2025-03-03 17:47:43 +08:00
24 changed files with 650 additions and 242 deletions

5
.lldbinit Normal file
View File

@ -0,0 +1,5 @@
settings set target.default-arch riscv64
platform select remote-gdb-server
process connect connect://127.0.0.1:26000
target create kernel/kernel
settings set stop-disassembly-display always

View File

@ -189,10 +189,14 @@ UPROGS=\
$U/_wc\ $U/_wc\
$U/_zombie\ $U/_zombie\
$U/_sleep\ $U/_sleep\
$U/_uptime\
$U/_pingpong\ $U/_pingpong\
$U/_primes\ $U/_primes\
$U/_find\ $U/_find\
$U/_xargs\ $U/_xargs\
$U/_trace\
$U/_sysinfo\
$U/_sysinfotest\

18
answers-syscall.txt Normal file
View File

@ -0,0 +1,18 @@
在xv6中当执行到地址 0x3ffffff11c 处的 sret 指令时,特权级和执行流程的变化如下:
1. 特权级变化
- 执行前核心态S模式特权级 1
- 执行后用户态U模式特权级 0
sret 指令会从 sstatus 寄存器中恢复之前的特权级(由 SPP 位决定。在进入陷阱处理时处理器已自动将用户态的特权级0保存到 sstatus.SPP因此 sret 会将特权级切换回用户态。
2. 恢复点地址
恢复点地址由 sepc 寄存器指定。在进入陷阱处理时sepc 被设置为触发 ecall 的下一条指令地址(即 0x14。因此sret 执行后,程序会跳转到 0x14 处继续执行用户代码。
3. 执行的函数
sret 返回后,用户程序会从 0x14 处继续执行。根据 initcode.S 的代码0x14 是 ecall 指令的下一条地址。若 exec 系统调用成功,用户地址空间会被替换为新程序(如 init此时 sret 返回后直接进入新程序的入口点。若 exec 失败(理论上不会发生),则会继续执行 initcode.S 中 ecall 后的代码(但实际代码中 ecall 后无其他指令)。
综上所述
- 特权级核心态1→ 用户态0
- 恢复点地址0x14用户代码中 ecall 的下一条指令)
- 执行函数:若 exec 成功,执行新程序(如 init否则继续 initcode.S 的后续代码(实际无后续指令)。

View File

@ -1 +1 @@
LAB=util LAB=syscall

136
grade-lab-syscall Executable file
View File

@ -0,0 +1,136 @@
#!/usr/bin/env python3
import re
from gradelib import *
r = Runner(save("xv6.out"))
@test(5, "answers-syscall.txt")
def test_answers():
# just a simple sanity check, will be graded manually
check_answers("answers-syscall.txt")
@test(5, "trace 32 grep")
def test_trace_32_grep():
r.run_qemu(shell_script([
'trace 32 grep hello README'
]))
sys_cnt = {
'read' : 0
}
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 1023'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 961'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 321'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 0'
r.match(s)
@test(5, "trace all grep")
def test_trace_all_grep():
r.run_qemu(shell_script([
'trace 2147483647 grep hello README'
]))
sys_cnt = {
'read' : 0,
'trace' : 0,
'exec' : 0,
'open' : 0,
'close' : 0,
'fork' : 0,
}
sys_cnt['trace'] += 1
s = r'^\d+: syscall trace\(trace counts: ' + str(sys_cnt['trace']) + r'\) -> 0'
r.match(s)
sys_cnt['exec'] += 1
s = r'^\d+: syscall exec\(trace counts: ' + str(sys_cnt['exec']) + r'\) -> 3'
r.match(s)
sys_cnt['open'] += 1
s = r'^\d+: syscall open\(trace counts: ' + str(sys_cnt['open']) + r'\) -> 3'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 1023'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 961'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 321'
r.match(s)
sys_cnt['read'] += 1
s = r'^\d+: syscall read\(trace counts: ' + str(sys_cnt['read']) + r'\) -> 0'
r.match(s)
sys_cnt['close'] += 1
s = r'^\d+: syscall close\(trace counts: ' + str(sys_cnt['close']) + r'\) -> 0'
r.match(s)
@test(5, "trace nothing")
def test_trace_nothing():
r.run_qemu(shell_script([
'grep hello README'
]))
r.match(no=[".* syscall .*"])
@test(5, "trace children")
def test_trace_children():
r.run_qemu(shell_script([
'trace 2 usertests forkforkfork'
]))
sys_cnt = {
'read' : 0,
'trace' : 0,
'exec' : 0,
'open' : 0,
'close' : 0,
'fork' : 0,
}
sys_cnt['fork'] += 1
s = r'3: syscall fork\(trace counts: ' + str(sys_cnt['fork']) + r'\) -> 4'
r.match(s)
s = r'^5: syscall fork\(trace counts: \d+\) -> \d+'
r.match(s)
s = r'^6: syscall fork\(trace counts: \d+\) -> \d+'
r.match(s)
s = r'^\d+: syscall fork\(trace counts: \d+\) -> -1'
r.match(s)
r.match('^ALL TESTS PASSED')
@test(14, "sysinfotest")
def test_sysinfotest():
r.run_qemu(shell_script([
'sysinfotest'
]))
r.match('^sysinfotest: OK', no=[".* FAIL .*"])
@test(1, "time")
def test_time():
check_time()
run_tests()

View File

@ -1,86 +0,0 @@
#!/usr/bin/env python3
import re
from gradelib import *
r = Runner(save("xv6.out"))
@test(5, "sleep, no arguments")
def test_sleep_no_args():
r.run_qemu(shell_script([
'sleep'
]))
r.match(no=["exec .* failed", "$ sleep\n$"])
@test(5, "sleep, returns")
def test_sleep_no_args():
r.run_qemu(shell_script([
'sleep',
'echo OK'
]))
r.match('^OK$', no=["exec .* failed", "$ sleep\n$"])
@test(10, "sleep, makes syscall")
def test_sleep():
r.run_qemu(shell_script([
'sleep 10',
'echo FAIL'
]), stop_breakpoint('sys_sleep'))
r.match('\\$ sleep 10', no=['FAIL'])
@test(20, "pingpong")
def test_pingpong():
r.run_qemu(shell_script([
'pingpong', 'echo OK'
]))
r.match('^\\d+: received ping$', '^\\d+: received pong$', '^OK$')
@test(20, "primes")
def test_primes():
r.run_qemu(shell_script([
'primes', 'echo OK'
]))
args = ['prime %d' % i for i in [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31]]
args.append('^OK$')
r.match(*args)
@test(10, "find, in current directory")
def test_find_curdir():
fn = random_str()
r.run_qemu(shell_script([
'echo > %s' % fn,
'find . %s' % fn
]))
r.match('./%s' % fn)
@test(10, "find, recursive")
def test_find_recursive():
needle = random_str()
dirs = [random_str() for _ in range(3)]
r.run_qemu(shell_script([
'mkdir %s' % dirs[0],
'echo > %s/%s' % (dirs[0], needle),
'mkdir %s/%s' % (dirs[0], dirs[1]),
'echo > %s/%s/%s' % (dirs[0], dirs[1], needle),
'mkdir %s' % dirs[2],
'echo > %s/%s' % (dirs[2], needle),
'find . %s' % needle
]))
r.match('./%s/%s' % (dirs[0], needle),
'./%s/%s/%s' % (dirs[0], dirs[1], needle),
'./%s/%s' % (dirs[2], needle))
@test(19, "xargs")
def test_xargs():
r.run_qemu(shell_script([
'sh < xargstest.sh',
'echo DONE',
], 'DONE'))
matches = re.findall("hello", r.qemu.output)
assert_equal(len(matches), 3, "Number of appearances of 'hello'")
@test(1, "time")
def test_time():
check_time()
run_tests()

View File

@ -63,6 +63,7 @@ void ramdiskrw(struct buf *);
void *kalloc(void); void *kalloc(void);
void kfree(void *); void kfree(void *);
void kinit(void); void kinit(void);
int freemem(void);
// log.c // log.c
void initlog(int, struct superblock *); void initlog(int, struct superblock *);
@ -106,6 +107,8 @@ void yield(void);
int either_copyout(int user_dst, uint64 dst, void *src, uint64 len); int either_copyout(int user_dst, uint64 dst, void *src, uint64 len);
int either_copyin(void *dst, int user_src, uint64 src, uint64 len); int either_copyin(void *dst, int user_src, uint64 src, uint64 len);
void procdump(void); void procdump(void);
int proc_size(void);
int update_load(void);
// swtch.S // swtch.S
void swtch(struct context *, struct context *); void swtch(struct context *, struct context *);

View File

@ -7,6 +7,7 @@
#include "memlayout.h" #include "memlayout.h"
#include "spinlock.h" #include "spinlock.h"
#include "riscv.h" #include "riscv.h"
#include "proc.h"
#include "defs.h" #include "defs.h"
void freerange(void *pa_start, void *pa_end); void freerange(void *pa_start, void *pa_end);
@ -80,3 +81,17 @@ kalloc(void)
memset((char*)r, 5, PGSIZE); // fill with junk memset((char*)r, 5, PGSIZE); // fill with junk
return (void*)r; return (void*)r;
} }
int
freemem(void)
{
struct run* p = kmem.freelist;
uint64 num = 0;
while (p) {
num += 1;
p = p->next;
}
return num * PGSIZE;
}

View File

@ -5,6 +5,9 @@
#include "spinlock.h" #include "spinlock.h"
#include "proc.h" #include "proc.h"
#include "defs.h" #include "defs.h"
#include "sysinfo.h"
uint64 current_load = 0;
struct cpu cpus[NCPU]; struct cpu cpus[NCPU];
@ -146,6 +149,9 @@ found:
p->context.ra = (uint64)forkret; p->context.ra = (uint64)forkret;
p->context.sp = p->kstack + PGSIZE; p->context.sp = p->kstack + PGSIZE;
// 初始化计数器
memset(p->syscall_counts, 0, sizeof(p->syscall_counts));
return p; return p;
} }
@ -310,6 +316,8 @@ fork(void)
safestrcpy(np->name, p->name, sizeof(p->name)); safestrcpy(np->name, p->name, sizeof(p->name));
// 复制掩码
np->tracemask = p->tracemask;
pid = np->pid; pid = np->pid;
release(&np->lock); release(&np->lock);
@ -446,6 +454,7 @@ scheduler(void)
{ {
struct proc *p; struct proc *p;
struct cpu *c = mycpu(); struct cpu *c = mycpu();
/*update_load_avg();*/
c->proc = 0; c->proc = 0;
for(;;){ for(;;){
@ -462,6 +471,7 @@ scheduler(void)
// before jumping back to us. // before jumping back to us.
p->state = RUNNING; p->state = RUNNING;
c->proc = p; c->proc = p;
current_load += 1;
swtch(&c->context, &p->context); swtch(&c->context, &p->context);
// Process is done running for now. // Process is done running for now.
@ -686,3 +696,18 @@ procdump(void)
printf("\n"); printf("\n");
} }
} }
int
proc_size()
{
int i =0, n = 0;
for (; i < NPROC; ++i) {
if (proc[i].state != UNUSED) n += 1;
}
return n;
}
int
update_load() {
return current_load;
}

View File

@ -1,3 +1,5 @@
#include "defs.h"
// Saved registers for kernel context switches. // Saved registers for kernel context switches.
struct context { struct context {
uint64 ra; uint64 ra;
@ -91,6 +93,7 @@ struct proc {
int killed; // If non-zero, have been killed int killed; // If non-zero, have been killed
int xstate; // Exit status to be returned to parent's wait int xstate; // Exit status to be returned to parent's wait
int pid; // Process ID int pid; // Process ID
int tracemask; // Trace Mask
// wait_lock must be held when using this: // wait_lock must be held when using this:
struct proc *parent; // Parent process struct proc *parent; // Parent process
@ -104,4 +107,5 @@ struct proc {
struct file *ofile[NOFILE]; // Open files struct file *ofile[NOFILE]; // Open files
struct inode *cwd; // Current directory struct inode *cwd; // Current directory
char name[16]; // Process name (debugging) char name[16]; // Process name (debugging)
int syscall_counts[24]; // 每个系统调用的调用次数
}; };

View File

@ -7,6 +7,11 @@
#include "syscall.h" #include "syscall.h"
#include "defs.h" #include "defs.h"
// 保留系统调用别名
char* syscalls_name[25] = {"", "fork", "exit", "wait", "pipe", "read", "kill", "exec",
"fstat", "chdir", "dup", "getpid", "sbrk", "sleep", "uptime",
"open", "write", "mknod", "unlink", "link", "mkdir", "close", "trace", "sysinfo"};
// Fetch the uint64 at addr from the current process. // Fetch the uint64 at addr from the current process.
int int
fetchaddr(uint64 addr, uint64 *ip) fetchaddr(uint64 addr, uint64 *ip)
@ -101,6 +106,8 @@ extern uint64 sys_unlink(void);
extern uint64 sys_link(void); extern uint64 sys_link(void);
extern uint64 sys_mkdir(void); extern uint64 sys_mkdir(void);
extern uint64 sys_close(void); extern uint64 sys_close(void);
extern uint64 sys_trace(void);
extern uint64 sys_sysinfo(void);
// An array mapping syscall numbers from syscall.h // An array mapping syscall numbers from syscall.h
// to the function that handles the system call. // to the function that handles the system call.
@ -126,6 +133,8 @@ static uint64 (*syscalls[])(void) = {
[SYS_link] sys_link, [SYS_link] sys_link,
[SYS_mkdir] sys_mkdir, [SYS_mkdir] sys_mkdir,
[SYS_close] sys_close, [SYS_close] sys_close,
[SYS_trace] sys_trace,
[SYS_sysinfo] sys_sysinfo,
}; };
void void
@ -139,6 +148,12 @@ syscall(void)
// Use num to lookup the system call function for num, call it, // Use num to lookup the system call function for num, call it,
// and store its return value in p->trapframe->a0 // and store its return value in p->trapframe->a0
p->trapframe->a0 = syscalls[num](); p->trapframe->a0 = syscalls[num]();
if (p->tracemask & (1 << num)) {
p->syscall_counts[num]++;
printf("%d: syscall %s(trace counts: %d) -> %d\n",
p->pid, syscalls_name[num], p->syscall_counts[num], p->trapframe->a0);
printf("a1:%d a2:%d a3:%d a4:%d a5:%d a6:%d a7:%d\n",p->trapframe->a1,p->trapframe->a2,p->trapframe->a3,p->trapframe->a4,p->trapframe->a5,p->trapframe->a6,p->trapframe->a7);
}
} else { } else {
printf("%d %s: unknown sys call %d\n", printf("%d %s: unknown sys call %d\n",
p->pid, p->name, num); p->pid, p->name, num);

View File

@ -20,3 +20,5 @@
#define SYS_link 19 #define SYS_link 19
#define SYS_mkdir 20 #define SYS_mkdir 20
#define SYS_close 21 #define SYS_close 21
#define SYS_trace 22
#define SYS_sysinfo 23

7
kernel/sysinfo.h Normal file
View File

@ -0,0 +1,7 @@
#include "kernel/types.h"
struct sysinfo {
uint64 freemem;
uint64 nproc;
uint64 unused_proc_num;
uint64 load_avg;
};

View File

@ -5,6 +5,7 @@
#include "memlayout.h" #include "memlayout.h"
#include "spinlock.h" #include "spinlock.h"
#include "proc.h" #include "proc.h"
#include "sysinfo.h"
uint64 uint64
sys_exit(void) sys_exit(void)
@ -91,3 +92,30 @@ sys_uptime(void)
release(&tickslock); release(&tickslock);
return xticks; return xticks;
} }
uint64
sys_trace(void)
{
int n;
argint(0, &n);
if(n<0) return -1;
myproc()->tracemask = n;
return 0;
}
uint64
sys_sysinfo(void)
{
struct sysinfo info;
uint64 addr;
argaddr(0, &addr);
if (addr < 0) return -1;
struct proc* p = myproc();
info.nproc = proc_size();
info.freemem = freemem();
info.unused_proc_num = NPROC - info.nproc;
info.load_avg = update_load() * 100 / sys_uptime();
if (copyout(p->pagetable, addr, (char*)&info, sizeof(info)) < 0)
return -1;
return 0;
}

BIN
mkfs/mkfs

Binary file not shown.

View File

@ -1 +1 @@
3 4

View File

@ -3,20 +3,48 @@
#include "kernel/types.h" #include "kernel/types.h"
#include "user/user.h" #include "user/user.h"
void find(char *path, char *filename) { int match_pattern(const char *name, const char *pattern) {
int fd = open(path, 0); const char *star = 0;
const char *name_ptr = name;
const char *pattern_ptr = pattern;
while (1) {
if (*pattern_ptr == '*') {
star = pattern_ptr++;
name_ptr = name;
continue;
}
if (!*name)
return (!*pattern_ptr || (star && !*++pattern_ptr));
if (*pattern_ptr == '?' || *pattern_ptr == *name) {
pattern_ptr++;
name++;
continue;
}
if (star) {
pattern_ptr = star + 1;
name = ++name_ptr;
continue;
}
return 0;
}
}
void find(char *path, char *pattern) {
char buf[512], *p; char buf[512], *p;
int fd;
struct dirent de; struct dirent de;
struct stat st; struct stat st;
if (fd < 0 || strlen(path) + 1 + DIRSIZ + 1 >= sizeof(buf)) { if ((fd = open(path, 0)) < 0) {
fprintf(2, "find: Invalid path: %s\n", path); fprintf(2, "find: cannot open %s\n", path);
// close(fd);
return; return;
} }
if (fstat(fd, &st) < 0) { if (fstat(fd, &st) < 0) {
fprintf(2, "find: Failed to stat %s\n", path); fprintf(2, "find: cannot stat %s\n", path);
close(fd); close(fd);
return; return;
} }
@ -27,38 +55,44 @@ void find(char *path, char *filename) {
return; return;
} }
strncpy(buf, path, strlen(path) + 1); if (strlen(path) + 1 + DIRSIZ + 1 > sizeof buf) {
p = buf + strlen(path); fprintf(2, "find: path too long\n");
close(fd);
return;
}
strcpy(buf, path);
p = buf + strlen(buf);
*p++ = '/'; *p++ = '/';
while (read(fd, &de, sizeof(de)) == sizeof(de)) { while (read(fd, &de, sizeof(de)) == sizeof(de)) {
if (de.inum == 0) if (de.inum == 0 || !strcmp(de.name, ".") || !strcmp(de.name, ".."))
continue;
if (!strcmp(de.name, ".") || !strcmp(de.name, ".."))
continue; continue;
memmove(p, de.name, DIRSIZ); memmove(p, de.name, DIRSIZ);
p[DIRSIZ] = 0; p[DIRSIZ] = 0;
if (stat(buf, &st) < 0) { if (stat(buf, &st) < 0) {
fprintf(2, "find: Failed to stat %s\n", buf); fprintf(2, "find: cannot stat %s\n", buf);
continue; continue;
} }
if (st.type == T_DIR) { if (st.type == T_DIR) {
find(buf, filename); find(buf, pattern);
} else if (st.type == T_FILE) { } else if (st.type == T_FILE) {
if (!strcmp(filename, "*") || !strcmp(filename, de.name)) { if (match_pattern(de.name, pattern)) {
printf("%s\n", buf); fprintf(1, "%s\n", buf);
} }
} }
} }
close(fd);
} }
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
if (argc != 3) { if (argc != 3) {
printf("Usage: find path filename\n"); fprintf(2, "Usage: find <path> <pattern>\n");
exit(1); exit(1);
} }
find(argv[1], argv[2]); find(argv[1], argv[2]);
exit(0); exit(0);
} }

243
user/sh.c
View File

@ -1,15 +1,16 @@
// Shell. // Shell.
#include "kernel/fcntl.h"
#include "kernel/fs.h"
#include "kernel/types.h" #include "kernel/types.h"
#include "user/user.h" #include "user/user.h"
#include "kernel/fcntl.h"
// Parsed command representation // Parsed command representation
#define EXEC 1 #define EXEC 1
#define REDIR 2 #define REDIR 2
#define PIPE 3 #define PIPE 3
#define LIST 4 #define LIST 4
#define BACK 5 #define BACK 5
#define MAXARGS 10 #define MAXARGS 10
@ -49,15 +50,15 @@ struct backcmd {
struct cmd *cmd; struct cmd *cmd;
}; };
int fork1(void); // Fork but panics on failure. int fork1(void); // Fork but panics on failure.
void panic(char*); void panic(char *);
struct cmd *parsecmd(char*); struct cmd *parsecmd(char *);
void runcmd(struct cmd*) __attribute__((noreturn)); void runcmd(struct cmd *) __attribute__((noreturn));
// void handle_tab_completion(char *buf, int *i, int nbuf);
// 尝试添加tab补全功能
// Execute cmd. Never returns. // Execute cmd. Never returns.
void void runcmd(struct cmd *cmd) {
runcmd(struct cmd *cmd)
{
int p[2]; int p[2];
struct backcmd *bcmd; struct backcmd *bcmd;
struct execcmd *ecmd; struct execcmd *ecmd;
@ -65,25 +66,25 @@ runcmd(struct cmd *cmd)
struct pipecmd *pcmd; struct pipecmd *pcmd;
struct redircmd *rcmd; struct redircmd *rcmd;
if(cmd == 0) if (cmd == 0)
exit(1); exit(1);
switch(cmd->type){ switch (cmd->type) {
default: default:
panic("runcmd"); panic("runcmd");
case EXEC: case EXEC:
ecmd = (struct execcmd*)cmd; ecmd = (struct execcmd *)cmd;
if(ecmd->argv[0] == 0) if (ecmd->argv[0] == 0)
exit(1); exit(1);
exec(ecmd->argv[0], ecmd->argv); exec(ecmd->argv[0], ecmd->argv);
fprintf(2, "exec %s failed\n", ecmd->argv[0]); fprintf(2, "exec %s failed\n", ecmd->argv[0]);
break; break;
case REDIR: case REDIR:
rcmd = (struct redircmd*)cmd; rcmd = (struct redircmd *)cmd;
close(rcmd->fd); close(rcmd->fd);
if(open(rcmd->file, rcmd->mode) < 0){ if (open(rcmd->file, rcmd->mode) < 0) {
fprintf(2, "open %s failed\n", rcmd->file); fprintf(2, "open %s failed\n", rcmd->file);
exit(1); exit(1);
} }
@ -91,25 +92,25 @@ runcmd(struct cmd *cmd)
break; break;
case LIST: case LIST:
lcmd = (struct listcmd*)cmd; lcmd = (struct listcmd *)cmd;
if(fork1() == 0) if (fork1() == 0)
runcmd(lcmd->left); runcmd(lcmd->left);
wait(0); wait(0);
runcmd(lcmd->right); runcmd(lcmd->right);
break; break;
case PIPE: case PIPE:
pcmd = (struct pipecmd*)cmd; pcmd = (struct pipecmd *)cmd;
if(pipe(p) < 0) if (pipe(p) < 0)
panic("pipe"); panic("pipe");
if(fork1() == 0){ if (fork1() == 0) {
close(1); close(1);
dup(p[1]); dup(p[1]);
close(p[0]); close(p[0]);
close(p[1]); close(p[1]);
runcmd(pcmd->left); runcmd(pcmd->left);
} }
if(fork1() == 0){ if (fork1() == 0) {
close(0); close(0);
dup(p[0]); dup(p[0]);
close(p[0]); close(p[0]);
@ -123,90 +124,82 @@ runcmd(struct cmd *cmd)
break; break;
case BACK: case BACK:
bcmd = (struct backcmd*)cmd; bcmd = (struct backcmd *)cmd;
if(fork1() == 0) if (fork1() == 0)
runcmd(bcmd->cmd); runcmd(bcmd->cmd);
break; break;
} }
exit(0); exit(0);
} }
int int getcmd(char *buf, int nbuf) {
getcmd(char *buf, int nbuf)
{
write(2, "$ ", 2); write(2, "$ ", 2);
memset(buf, 0, nbuf); memset(buf, 0, nbuf);
gets(buf, nbuf); gets(buf, nbuf);
if(buf[0] == 0) // EOF if (buf[0] == 0) // EOF
return -1; return -1;
return 0; return 0;
} }
int int main(void) {
main(void)
{
static char buf[100]; static char buf[100];
int fd; int fd;
// Ensure that three file descriptors are open. // Ensure that three file descriptors are open.
while((fd = open("console", O_RDWR)) >= 0){ while ((fd = open("console", O_RDWR)) >= 0) {
if(fd >= 3){ if (fd >= 3) {
close(fd); close(fd);
break; break;
} }
} }
// Read and run input commands. // Read and run input commands.
while(getcmd(buf, sizeof(buf)) >= 0){ while (getcmd(buf, sizeof(buf)) >= 0) {
if(buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' '){ if (strcmp(buf, "exit\n") == 0) {
exit(0);
}
if (buf[0] == 'c' && buf[1] == 'd' && buf[2] == ' ') {
// Chdir must be called by the parent, not the child. // Chdir must be called by the parent, not the child.
buf[strlen(buf)-1] = 0; // chop \n buf[strlen(buf) - 1] = 0; // chop \n
if(chdir(buf+3) < 0) if (chdir(buf + 3) < 0)
fprintf(2, "cannot cd %s\n", buf+3); fprintf(2, "cannot cd %s\n", buf + 3);
continue; continue;
} }
if(fork1() == 0) if (fork1() == 0)
runcmd(parsecmd(buf)); runcmd(parsecmd(buf));
wait(0); wait(0);
} }
exit(0); exit(0);
} }
void void panic(char *s) {
panic(char *s)
{
fprintf(2, "%s\n", s); fprintf(2, "%s\n", s);
exit(1); exit(1);
} }
int int fork1(void) {
fork1(void)
{
int pid; int pid;
pid = fork(); pid = fork();
if(pid == -1) if (pid == -1)
panic("fork"); panic("fork");
return pid; return pid;
} }
//PAGEBREAK! // PAGEBREAK!
// Constructors // Constructors
struct cmd* struct cmd *execcmd(void) {
execcmd(void)
{
struct execcmd *cmd; struct execcmd *cmd;
cmd = malloc(sizeof(*cmd)); cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd)); memset(cmd, 0, sizeof(*cmd));
cmd->type = EXEC; cmd->type = EXEC;
return (struct cmd*)cmd; return (struct cmd *)cmd;
} }
struct cmd* struct cmd *redircmd(struct cmd *subcmd, char *file, char *efile, int mode,
redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd) int fd) {
{
struct redircmd *cmd; struct redircmd *cmd;
cmd = malloc(sizeof(*cmd)); cmd = malloc(sizeof(*cmd));
@ -217,12 +210,10 @@ redircmd(struct cmd *subcmd, char *file, char *efile, int mode, int fd)
cmd->efile = efile; cmd->efile = efile;
cmd->mode = mode; cmd->mode = mode;
cmd->fd = fd; cmd->fd = fd;
return (struct cmd*)cmd; return (struct cmd *)cmd;
} }
struct cmd* struct cmd *pipecmd(struct cmd *left, struct cmd *right) {
pipecmd(struct cmd *left, struct cmd *right)
{
struct pipecmd *cmd; struct pipecmd *cmd;
cmd = malloc(sizeof(*cmd)); cmd = malloc(sizeof(*cmd));
@ -230,12 +221,10 @@ pipecmd(struct cmd *left, struct cmd *right)
cmd->type = PIPE; cmd->type = PIPE;
cmd->left = left; cmd->left = left;
cmd->right = right; cmd->right = right;
return (struct cmd*)cmd; return (struct cmd *)cmd;
} }
struct cmd* struct cmd *listcmd(struct cmd *left, struct cmd *right) {
listcmd(struct cmd *left, struct cmd *right)
{
struct listcmd *cmd; struct listcmd *cmd;
cmd = malloc(sizeof(*cmd)); cmd = malloc(sizeof(*cmd));
@ -243,39 +232,35 @@ listcmd(struct cmd *left, struct cmd *right)
cmd->type = LIST; cmd->type = LIST;
cmd->left = left; cmd->left = left;
cmd->right = right; cmd->right = right;
return (struct cmd*)cmd; return (struct cmd *)cmd;
} }
struct cmd* struct cmd *backcmd(struct cmd *subcmd) {
backcmd(struct cmd *subcmd)
{
struct backcmd *cmd; struct backcmd *cmd;
cmd = malloc(sizeof(*cmd)); cmd = malloc(sizeof(*cmd));
memset(cmd, 0, sizeof(*cmd)); memset(cmd, 0, sizeof(*cmd));
cmd->type = BACK; cmd->type = BACK;
cmd->cmd = subcmd; cmd->cmd = subcmd;
return (struct cmd*)cmd; return (struct cmd *)cmd;
} }
//PAGEBREAK! // PAGEBREAK!
// Parsing // Parsing
char whitespace[] = " \t\r\n\v"; char whitespace[] = " \t\r\n\v";
char symbols[] = "<|>&;()"; char symbols[] = "<|>&;()";
int int gettoken(char **ps, char *es, char **q, char **eq) {
gettoken(char **ps, char *es, char **q, char **eq)
{
char *s; char *s;
int ret; int ret;
s = *ps; s = *ps;
while(s < es && strchr(whitespace, *s)) while (s < es && strchr(whitespace, *s))
s++; s++;
if(q) if (q)
*q = s; *q = s;
ret = *s; ret = *s;
switch(*s){ switch (*s) {
case 0: case 0:
break; break;
case '|': case '|':
@ -288,53 +273,49 @@ gettoken(char **ps, char *es, char **q, char **eq)
break; break;
case '>': case '>':
s++; s++;
if(*s == '>'){ if (*s == '>') {
ret = '+'; ret = '+';
s++; s++;
} }
break; break;
default: default:
ret = 'a'; ret = 'a';
while(s < es && !strchr(whitespace, *s) && !strchr(symbols, *s)) while (s < es && !strchr(whitespace, *s) && !strchr(symbols, *s))
s++; s++;
break; break;
} }
if(eq) if (eq)
*eq = s; *eq = s;
while(s < es && strchr(whitespace, *s)) while (s < es && strchr(whitespace, *s))
s++; s++;
*ps = s; *ps = s;
return ret; return ret;
} }
int int peek(char **ps, char *es, char *toks) {
peek(char **ps, char *es, char *toks)
{
char *s; char *s;
s = *ps; s = *ps;
while(s < es && strchr(whitespace, *s)) while (s < es && strchr(whitespace, *s))
s++; s++;
*ps = s; *ps = s;
return *s && strchr(toks, *s); return *s && strchr(toks, *s);
} }
struct cmd *parseline(char**, char*); struct cmd *parseline(char **, char *);
struct cmd *parsepipe(char**, char*); struct cmd *parsepipe(char **, char *);
struct cmd *parseexec(char**, char*); struct cmd *parseexec(char **, char *);
struct cmd *nulterminate(struct cmd*); struct cmd *nulterminate(struct cmd *);
struct cmd* struct cmd *parsecmd(char *s) {
parsecmd(char *s)
{
char *es; char *es;
struct cmd *cmd; struct cmd *cmd;
es = s + strlen(s); es = s + strlen(s);
cmd = parseline(&s, es); cmd = parseline(&s, es);
peek(&s, es, ""); peek(&s, es, "");
if(s != es){ if (s != es) {
fprintf(2, "leftovers: %s\n", s); fprintf(2, "leftovers: %s\n", s);
panic("syntax"); panic("syntax");
} }
@ -342,102 +323,92 @@ parsecmd(char *s)
return cmd; return cmd;
} }
struct cmd* struct cmd *parseline(char **ps, char *es) {
parseline(char **ps, char *es)
{
struct cmd *cmd; struct cmd *cmd;
cmd = parsepipe(ps, es); cmd = parsepipe(ps, es);
while(peek(ps, es, "&")){ while (peek(ps, es, "&")) {
gettoken(ps, es, 0, 0); gettoken(ps, es, 0, 0);
cmd = backcmd(cmd); cmd = backcmd(cmd);
} }
if(peek(ps, es, ";")){ if (peek(ps, es, ";")) {
gettoken(ps, es, 0, 0); gettoken(ps, es, 0, 0);
cmd = listcmd(cmd, parseline(ps, es)); cmd = listcmd(cmd, parseline(ps, es));
} }
return cmd; return cmd;
} }
struct cmd* struct cmd *parsepipe(char **ps, char *es) {
parsepipe(char **ps, char *es)
{
struct cmd *cmd; struct cmd *cmd;
cmd = parseexec(ps, es); cmd = parseexec(ps, es);
if(peek(ps, es, "|")){ if (peek(ps, es, "|")) {
gettoken(ps, es, 0, 0); gettoken(ps, es, 0, 0);
cmd = pipecmd(cmd, parsepipe(ps, es)); cmd = pipecmd(cmd, parsepipe(ps, es));
} }
return cmd; return cmd;
} }
struct cmd* struct cmd *parseredirs(struct cmd *cmd, char **ps, char *es) {
parseredirs(struct cmd *cmd, char **ps, char *es)
{
int tok; int tok;
char *q, *eq; char *q, *eq;
while(peek(ps, es, "<>")){ while (peek(ps, es, "<>")) {
tok = gettoken(ps, es, 0, 0); tok = gettoken(ps, es, 0, 0);
if(gettoken(ps, es, &q, &eq) != 'a') if (gettoken(ps, es, &q, &eq) != 'a')
panic("missing file for redirection"); panic("missing file for redirection");
switch(tok){ switch (tok) {
case '<': case '<':
cmd = redircmd(cmd, q, eq, O_RDONLY, 0); cmd = redircmd(cmd, q, eq, O_RDONLY, 0);
break; break;
case '>': case '>':
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE|O_TRUNC, 1); cmd = redircmd(cmd, q, eq, O_WRONLY | O_CREATE | O_TRUNC, 1);
break; break;
case '+': // >> case '+': // >>
cmd = redircmd(cmd, q, eq, O_WRONLY|O_CREATE, 1); cmd = redircmd(cmd, q, eq, O_WRONLY | O_CREATE, 1);
break; break;
} }
} }
return cmd; return cmd;
} }
struct cmd* struct cmd *parseblock(char **ps, char *es) {
parseblock(char **ps, char *es)
{
struct cmd *cmd; struct cmd *cmd;
if(!peek(ps, es, "(")) if (!peek(ps, es, "("))
panic("parseblock"); panic("parseblock");
gettoken(ps, es, 0, 0); gettoken(ps, es, 0, 0);
cmd = parseline(ps, es); cmd = parseline(ps, es);
if(!peek(ps, es, ")")) if (!peek(ps, es, ")"))
panic("syntax - missing )"); panic("syntax - missing )");
gettoken(ps, es, 0, 0); gettoken(ps, es, 0, 0);
cmd = parseredirs(cmd, ps, es); cmd = parseredirs(cmd, ps, es);
return cmd; return cmd;
} }
struct cmd* struct cmd *parseexec(char **ps, char *es) {
parseexec(char **ps, char *es)
{
char *q, *eq; char *q, *eq;
int tok, argc; int tok, argc;
struct execcmd *cmd; struct execcmd *cmd;
struct cmd *ret; struct cmd *ret;
if(peek(ps, es, "(")) if (peek(ps, es, "("))
return parseblock(ps, es); return parseblock(ps, es);
ret = execcmd(); ret = execcmd();
cmd = (struct execcmd*)ret; cmd = (struct execcmd *)ret;
argc = 0; argc = 0;
ret = parseredirs(ret, ps, es); ret = parseredirs(ret, ps, es);
while(!peek(ps, es, "|)&;")){ while (!peek(ps, es, "|)&;")) {
if((tok=gettoken(ps, es, &q, &eq)) == 0) if ((tok = gettoken(ps, es, &q, &eq)) == 0)
break; break;
if(tok != 'a') if (tok != 'a')
panic("syntax"); panic("syntax");
cmd->argv[argc] = q; cmd->argv[argc] = q;
cmd->eargv[argc] = eq; cmd->eargv[argc] = eq;
argc++; argc++;
if(argc >= MAXARGS) if (argc >= MAXARGS)
panic("too many args"); panic("too many args");
ret = parseredirs(ret, ps, es); ret = parseredirs(ret, ps, es);
} }
@ -447,9 +418,7 @@ parseexec(char **ps, char *es)
} }
// NUL-terminate all the counted strings. // NUL-terminate all the counted strings.
struct cmd* struct cmd *nulterminate(struct cmd *cmd) {
nulterminate(struct cmd *cmd)
{
int i; int i;
struct backcmd *bcmd; struct backcmd *bcmd;
struct execcmd *ecmd; struct execcmd *ecmd;
@ -457,36 +426,36 @@ nulterminate(struct cmd *cmd)
struct pipecmd *pcmd; struct pipecmd *pcmd;
struct redircmd *rcmd; struct redircmd *rcmd;
if(cmd == 0) if (cmd == 0)
return 0; return 0;
switch(cmd->type){ switch (cmd->type) {
case EXEC: case EXEC:
ecmd = (struct execcmd*)cmd; ecmd = (struct execcmd *)cmd;
for(i=0; ecmd->argv[i]; i++) for (i = 0; ecmd->argv[i]; i++)
*ecmd->eargv[i] = 0; *ecmd->eargv[i] = 0;
break; break;
case REDIR: case REDIR:
rcmd = (struct redircmd*)cmd; rcmd = (struct redircmd *)cmd;
nulterminate(rcmd->cmd); nulterminate(rcmd->cmd);
*rcmd->efile = 0; *rcmd->efile = 0;
break; break;
case PIPE: case PIPE:
pcmd = (struct pipecmd*)cmd; pcmd = (struct pipecmd *)cmd;
nulterminate(pcmd->left); nulterminate(pcmd->left);
nulterminate(pcmd->right); nulterminate(pcmd->right);
break; break;
case LIST: case LIST:
lcmd = (struct listcmd*)cmd; lcmd = (struct listcmd *)cmd;
nulterminate(lcmd->left); nulterminate(lcmd->left);
nulterminate(lcmd->right); nulterminate(lcmd->right);
break; break;
case BACK: case BACK:
bcmd = (struct backcmd*)cmd; bcmd = (struct backcmd *)cmd;
nulterminate(bcmd->cmd); nulterminate(bcmd->cmd);
break; break;
} }

21
user/sysinfo.c Normal file
View File

@ -0,0 +1,21 @@
#include "kernel/param.h"
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int main() {
struct sysinfo info;
if (sysinfo(&info) < 0) {
printf("sysinfo: failed to retrieve system information\n");
exit(1);
}
printf("System Information:\n");
printf(" Free Memory: %d bytes\n", info.freemem);
printf(" Number of Processes: %d\n", info.nproc);
printf(" Unused Process Slots: %d\n", info.unused_proc_num);
printf(" Load Average: %d / 100 \n", info.load_avg);
exit(0);
}

164
user/sysinfotest.c Normal file
View File

@ -0,0 +1,164 @@
#include "kernel/types.h"
#include "kernel/riscv.h"
/*#include "kernel/sysinfo.h"*/
#include "user/user.h"
void
sinfo(struct sysinfo *info) {
if (sysinfo(info) < 0) {
printf("FAIL: sysinfo failed");
exit(1);
}
}
//
// use sbrk() to count how many free physical memory pages there are.
//
int
countfree()
{
uint64 sz0 = (uint64)sbrk(0);
struct sysinfo info;
int n = 0;
while(1){
if((uint64)sbrk(PGSIZE) == 0xffffffffffffffff){
break;
}
n += PGSIZE;
}
sinfo(&info);
if (info.freemem != 0) {
printf("FAIL: there is no free mem, but sysinfo.freemem=%d\n",
info.freemem);
exit(1);
}
sbrk(-((uint64)sbrk(0) - sz0));
return n;
}
void
testmem() {
struct sysinfo info;
uint64 n = countfree();
sinfo(&info);
if (info.freemem!= n) {
printf("FAIL: free mem %d (bytes) instead of %d\n", info.freemem, n);
exit(1);
}
if((uint64)sbrk(PGSIZE) == 0xffffffffffffffff){
printf("sbrk failed");
exit(1);
}
sinfo(&info);
if (info.freemem != n-PGSIZE) {
printf("FAIL: free mem %d (bytes) instead of %d\n", n-PGSIZE, info.freemem);
exit(1);
}
if((uint64)sbrk(-PGSIZE) == 0xffffffffffffffff){
printf("sbrk failed");
exit(1);
}
sinfo(&info);
if (info.freemem != n) {
printf("FAIL: free mem %d (bytes) instead of %d\n", n, info.freemem);
exit(1);
}
}
void
testcall() {
struct sysinfo info;
if (sysinfo(&info) < 0) {
printf("FAIL: sysinfo failed\n");
exit(1);
}
if (sysinfo((struct sysinfo *) 0xeaeb0b5b00002f5e) != 0xffffffffffffffff) {
printf("FAIL: sysinfo succeeded with bad argument\n");
exit(1);
}
}
void testproc() {
struct sysinfo info;
uint64 nproc, unused_proc_num;
int status;
int pid;
sinfo(&info);
nproc = info.nproc;
unused_proc_num = info.unused_proc_num;
pid = fork();
if(pid < 0){
printf("sysinfotest: fork failed\n");
exit(1);
}
if(pid == 0){
sinfo(&info);
if(info.nproc != nproc+1) {
printf("sysinfotest: FAIL nproc is %d instead of %d\n", info.nproc, nproc+1);
exit(1);
}
if(info.unused_proc_num != unused_proc_num-1) {
printf("sysinfotest: FAIL unused_proc_num is %d instead of %d\n", info.unused_proc_num, unused_proc_num-1);
exit(1);
}
exit(0);
}
wait(&status);
sinfo(&info);
if(info.nproc != nproc) {
printf("sysinfotest: FAIL nproc is %d instead of %d\n", info.nproc, nproc);
exit(1);
}
if(info.unused_proc_num != unused_proc_num) {
printf("sysinfotest: FAIL unused_proc_num is %d instead of %d\n", info.unused_proc_num, unused_proc_num);
exit(1);
}
}
void testbad() {
int pid = fork();
int xstatus;
if(pid < 0){
printf("sysinfotest: fork failed\n");
exit(1);
}
if(pid == 0){
sinfo(0x0);
exit(0);
}
wait(&xstatus);
if(xstatus == -1) // kernel killed child?
exit(0);
else {
printf("sysinfotest: testbad succeeded %d\n", xstatus);
exit(xstatus);
}
}
int
main(int argc, char *argv[])
{
printf("sysinfotest: start\n");
testcall();
testmem();
testproc();
printf("sysinfotest: OK\n");
exit(0);
}

24
user/trace.c Normal file
View File

@ -0,0 +1,24 @@
#include "kernel/param.h"
#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"
int
main(int argc, char *argv[])
{
int i;
char *nargv[MAXARG];
if(argc < 3 || (argv[1][0] < '0' || argv[1][0] > '9')){
fprintf(2, "Usage: %s mask command\n", argv[0]);
exit(1);
}
if (trace(atoi(argv[1])) < 0) {
fprintf(2, "%s: trace failed\n", argv[0]);
exit(1);
}
for(i = 2; i < argc && i < MAXARG; i++){
nargv[i-2] = argv[i];
}
exec(nargv[0], nargv);
exit(0);
}

15
user/uptime.c Normal file
View File

@ -0,0 +1,15 @@
#include "kernel/types.h"
#include "user/user.h"
int main(int argc, char *argv[]) {
if (argc != 1) {
// 错误输出到stderr文件描述符2
fprintf(2, "Usage: uptime\n");
exit(1);
}
fprintf(1,"up: %d\n",uptime());
exit(0);
}

View File

@ -1,4 +1,5 @@
#include "kernel/types.h" #include "kernel/types.h"
#include "kernel/sysinfo.h"
struct stat; struct stat;
// system calls // system calls
@ -23,6 +24,8 @@ int getpid(void);
char *sbrk(int); char *sbrk(int);
int sleep(int); int sleep(int);
int uptime(void); int uptime(void);
int trace(int);
int sysinfo(struct sysinfo*);
// ulib.c // ulib.c
int stat(const char *, struct stat *); int stat(const char *, struct stat *);

View File

@ -36,3 +36,5 @@ entry("getpid");
entry("sbrk"); entry("sbrk");
entry("sleep"); entry("sleep");
entry("uptime"); entry("uptime");
entry("trace");
entry("sysinfo");