HW3-system-calls

为 xv6 添加一个系统调用。

Part One: System call tracing

第一个任务是修改 xv6 内核,为每个系统调用打印出一行。打印系统调用的名称和返回值就足够,不需要打印系统调用参数。

完成过后,会看到类似于以下的输出:

1
2
3
4
5
6
fork -> 2
exec -> 0
open -> 3
close -> 0
$write -> 1
write -> 1

提示:修改 syscall.c 文件中的 syscall() 函数。

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
static char *syscalls_name[] = {
[SYS_fork] "fork",
[SYS_exit] "exit",
[SYS_wait] "wait",
[SYS_pipe] "pipe",
[SYS_read] "read",
[SYS_kill] "kill",
[SYS_exec] "exec",
[SYS_fstat] "fstat",
[SYS_chdir] "chdir",
[SYS_dup] "dup",
[SYS_getpid] "getpid",
[SYS_sbrk] "sbrk",
[SYS_sleep] "sleep",
[SYS_uptime] "uptime",
[SYS_open] "open",
[SYS_write] "write",
[SYS_mknod] "mknod",
[SYS_unlink] "unlink",
[SYS_link] "link",
[SYS_mkdir] "mkdir",
[SYS_close] "close",
};

void
syscall(void)
{
int num;
struct proc *curproc = myproc();

num = curproc->tf->eax;
if(num > 0 && num < NELEM(syscalls) && syscalls[num]) {
curproc->tf->eax = syscalls[num]();
// solution
cprintf("%s -> %d\n", syscalls_name[num], curproc->tf->eax);
} else {
cprintf("%d %s: unknown sys call %d\n",
curproc->pid, curproc->name, num);
curproc->tf->eax = -1;
}
}

result

Part Two: Date system call

添加一个系统调用,这个系统调用可以获取当前的 UTC 时间,并且返回给用户程序。cmostime() 等接口 在 lapic.c 文件中定义好了。

查看 uptime 系统调用

参照 uptime 系统调用,然后挨着在每个地方添加相应的内容。

  • syscall.c
1
2
3
4
5
extern int sys_date(void);
...
[SYS_date] sys_date,
...
[SYS_date] "date",
  • syscall.h
1
#define SYS_date   22
  • sysproc.c
1
2
3
4
5
6
7
8
9
10
11
12
int 
sys_date(void)
{
struct rtcdate *r;

if(argptr(0,r,sizeof(struct rtcdate)) < 0){
return -1;
}

cmostime(r);
return 0;
}
  • user.h
1
int date(struct rtcdate *r);
  • usys.S
1
SYSCALL(date)

然后再添加一个用户程序 date.c,来调用该系统调用。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include "types.h"
#include "user.h"
#include "date.h"

int
main(int argc, char *argv[])
{
struct rtcdate r;

if (date(&r)) {
printf(2, "date failed\n");
exit();
}

// your code to print the time in any format you like...
printf(1, "%d-%d-%d %d:%d:%d UTC\n", r.year, r.month, r.day, r.hour, r.minute, r.second);
exit();
}

Makefile 里添加具体的应用程序。

运行结果


HW3-system-calls
https://www.bencorn.com/2023/07/20/HW3-system-calls/
作者
Bencorn
发布于
2023年7月20日
许可协议