xv6 Lab2 System calls - MIT 6.1810 Fall 2025 Operating System
Last updated on July 26, 2026 pm
This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to original Chinese version. I am continuously working to improve the translation.
Reading the xv6 book
An operating system mainly addresses three requirements:
- multiplexing: multiple programs share resources such as the CPU and memory;
- isolation: one program must not break the kernel or other programs;
- interaction: programs still need controlled communication through mechanisms like pipes.
Hence these abstractions emerged:
| Physical resource | Abstraction provided to programs |
|---|---|
| CPU | Processes, threads |
| Physical memory | Address spaces |
| Disk | File systems |
| Inter-process communication | Pipes, file descriptors |
RISC-V privilege levels:
- machine mode: used during the boot phase, with the highest privileges;
- supervisor mode: where the xv6 kernel runs;
- user mode: where ordinary applications run.
When kernel services are needed, ecall is executed in user mode to trap into the kernel.
Monolithic kernel:
- The file system, process management, memory management, drivers, etc. all run in kernel mode.
- Advantages: direct calls, easy cooperation between modules, good performance; disadvantages: the kernel is huge, and any serious bug can crash the entire system.
- xv6 is a monolithic kernel; all core modules in
kernel/call each other directly.
Microkernel:
- The kernel only keeps basic mechanisms such as scheduling, address spaces, and IPC; the file system and others run as user-space servers, communicating via messages.
- Advantages: a smaller kernel that is easier to isolate and verify; disadvantages: cross-process communication adds implementation and performance overhead.
Organization of the xv6 source code:
| Area | Main files |
|---|---|
| Boot | entry.S, start.c, main.c |
| Processes & scheduling | proc.c, swtch.S |
| System calls | syscall.c, sysproc.c, sysfile.c |
| trap | trampoline.S, kernelvec.S, trap.c |
| Virtual memory | vm.c |
| Physical memory | kalloc.c |
| File system | fs.c, file.c, log.c, bio.c |
| Devices | console.c, uart.c, virtio_disk.c |
Processes in xv6:
Each process has a struct proc in the kernel, whose important contents include:
pagetable: the user address space;kstack: the kernel stack used after entering the kernel;trapframe: saves user registers;context: the kernel thread context;state: states such as running, runnable, and sleeping.
A process has two stacks:
- Running in user mode: uses the user stack
- Entering the kernel: uses that process's own kernel stack
Even if the user stack is corrupted, it should not affect the kernel stack. In xv6, a process has only one thread; modern systems usually allow a process to have multiple threads.
An example of the process of making a system call:
Calling write(2, "$", 2);:
User C code calls write()
↓
The write label in user/usys.S (this step is done via linking)
↓
a7 = SYS_write
↓
ecall
↓
uservec → usertrap → syscall()
↓
syscalls[SYS_write]
↓
sys_write()
↓
The return value is written into trapframe->a0
↓
User registers are restored, and execution returns to just after write()In the RISC-V calling convention:
a0,a1,a2, ... hold function arguments;a7holds the system call number;a0is also used to hold the return value.
How the assembly code connects to system calls:
The declaration in user.h + the assembly wrapper functions in usys.S + the linker mapping the two together
Booting xv6
This is the part I felt I didn't understand while doing lab 3, so I came back to fill in the gap.
Reference materials:
- 3.9 XV6 Boot Process | MIT6.S081
- MIT6.s081/6.828 lecture02: OS design and Lab2 takeaways - Article by 逆风的大船 - Zhihu
- Re-reading xv6 (I) | Anri's blog
QEMU
First we need to understand what QEMU is.
You should think of QEMU as a real RISC-V-based computer.
However, intuitively, QEMU is an open-source C program whose core is a while(1) loop that:
- reads a RISC-V instruction
- parses it to find the corresponding op code
- executes the corresponding instruction in software.
The xv6 boot process
RISC-V has three modes in which a CPU executes instructions: machine mode, kernel (supervisor) mode, and user mode.
The boot process:
- The machine boots and loads the kernel into memory
entry.Sruns, setting up a stack for each CPU; at this point we are in machine modestartruns, doing some initial configuration, and switches to kernel modemainruns, initializing each module, creating the first process, and switching to user modeinitruns, setting up standard I/O, starting theshell, and beginning to provide services
start:
- Timer interrupts, used to virtualize the CPU and switch processes
- Page table mapping, used to virtualize memory addresses
main:
- Memory pool, paging, used to allocate user space and virtualize memory
- Trap interrupts, used to respond to exceptions and implement system calls
- Process management, used to allocate resources and manage processes
- File system, used to control file reads and writes
- PLIC, device drivers, disk
In reality it is far more complicated than this; I will write a separate blog post analyzing this process later, TODO.
- I found a really good Bilibili video: 【04(1)-xv6 Operating System - System Boot -1 (bootblock)】 ; I'll review it later.
Using gdb
A series of answer exercises for practicing gdb.
Honestly, this part was a bit boring, because I didn't have much good experience with debugging using gdb before. So for the most part I had an LLM guide me through it.

Answers:
代码
Looking at the backtrace output, which function called syscall?
usertrap() at kernel/trap.c:68
What is the value of p->trapframe->a7 and what does that value represent? (Hint: look at user/init.c, the first user program xv6 starts, and its compiled assembly user/init.asm.)
$4 = 0xf, the value of the user-mode register a7 saved when the current process p entered the kernel. 0xf = 15, and SYS_OPEN = 15, so it represents the open system call.
What was the previous mode that the CPU was in?
User mode
Write down the assembly instruction the kernel is panicing at. Which register corresponds to the variable num?
We get: scause=0xd sepc=0x80001cf8 stval=0x0
panic: kerneltrap
Then we get:
4410: 80001cf8: 00002683 lw a3,0(zero) # 0 <_entry-0x80000000>
a3 corresponds to num
Why does the kernel crash? Hint: look at figure 3-3 in the text; is address 0 mapped in the kernel address space? Is that confirmed by the value in scause above?
The code *(int *)0 asks the CPU to read data from virtual address 0, but the kernel page table does not map address 0, so a page fault occurs.
What is the name of the process that was running when the kernel paniced? What is its process id (pid)?
(gdb)p p->name
$1 "init",\000'<repeats 11 times>
(gdb)p/d p->pid
$2=1One point of confusion:
引用
scause=0xd sepc=0x80001cf8 stval=0x0 panic: kerneltrap — what does each of these represent, and how do we know?
Think of these three items as the "incident report" of an exception:
scause = why it went wrong sepc = which instruction went wrong stval = what address was being accessed when it went wrongIn your case:
scause=0xd sepc=0x80001cf8 stval=0x0 panic: kerneltrap
scause = 0xd
scauseindicates the cause of the trap.0xd = decimal 13 = Load page faultThat is:
A page fault occurred while the CPU was reading memory.
This corresponds exactly to the deliberately added code:
num = *(int *)0;It tries to read an
intfrom memory address0. The RISC-V spec defines exception number 13 as a load page fault. (RISC-V Documentation)
stval = 0x0For a page fault,
stvalusually records the virtual address that caused the fault.Here:
stval = 0x0So we can be sure:
The target of the faulting memory access was virtual address
0.That is, in the code:
*(int *)0 ^The kernel page table does not map address
0, so the read fails. The lab is precisely designed to let you determine, viascause=0xdandstval=0, that this is a page fault caused by reading a null address. (MIT CSAIL)
sepc = 0x80001cf8
sepcholds the address of the instruction that was executing when the exception occurred.Here it means:
The machine instruction located at kernel address
0x80001cf8triggered the exception.Therefore the lab has you take this address and look it up in the compiled assembly:
grep -n -B 4 -A 4 "80001cf8" kernel/kernel.asmYou should find something like:
80001cf8: ... lw a?,0(zero)Where:
lw a?, 0(zero)means reading data from the address:
zero + 0 = 0The lab explicitly requires you to use the printed
sepcto locate the faulting instruction inkernel/kernel.asm. (MIT CSAIL)You can also stop right there directly in GDB:
b *0x80001cf8 c x/i $pc
panic: kerneltrapWhen the exception occurred, the CPU was executing kernel code, so it entered:
kerneltrap()
kerneltrap()tries to determine whether it is a normal device or timer interrupt. This page fault is not a normally-handled device interrupt, so xv6 prints the three registers and executes:panic("kerneltrap");So the whole reasoning process is:
scause = 0xd → it is a page fault caused by reading memory stval = 0 → the address read was virtual address 0 sepc = 0x80001cf8 → go to kernel/kernel.asm to find the instruction at this address Final conclusion → num = *(int *)0 caused the kernel to read unmapped address 0In your answer file you can write:
scause 0xd indicates a load page fault. stval 0x0 shows that the faulting virtual address was zero. sepc 0x80001cf8 is the address of the faulting instruction, which can be located in kernel/kernel.asm. The kernel crashes because it tries to load data from unmapped virtual address 0.
Sandbox a Command
This feels like it's mainly about building intuition and insight, but the documentation's guidance feels insufficient — or maybe I'm just too weak (probably that).
- Second pass: actually the xv6 book explains this very clearly, but I didn't read carefully enough. Oh well — after finishing it, I understood the mechanism anyway.
One question:
引用
- What is struct proc? What is sysproc.c for?
- What are kfork, kexit, and the like? How do they differ from the fork system call? Come to think of it, is this where fork is implemented? How is it pointed to? My head is a mess
Answer:
What is
struct proc?
struct procis defined inkernel/proc.hand represents a process as seen by the kernel.You can think of it as: a kernel-side record corresponding to a process
It stores various information about the process, for example:
struct proc { enum procstate state; // 进程状态 int pid; // 进程号 struct proc *parent; // 父进程 pagetable_t pagetable; // 用户页表 struct trapframe *trapframe; // 用户寄存器 struct context context; // 内核调度所需的寄存器 struct file *ofile[NOFILE]; // 打开的文件 char name[16]; // 进程名称 };Therefore:
struct proc *p = myproc();means: get the struct proc of the currently running process
Afterwards:
p->pid p->trapframe p->statereads the current process's information.
struct procis just a data structure. The code that creates, schedules, and exits processes mainly lives inkernel/proc.c.
What is
sysproc.cfor?
kernel/sysproc.cholds the entry points for process-related system calls, for example:sys_fork() sys_wait() sys_getpid() sys_kill()These
sys_xxx()functions are responsible for receiving system calls and then calling the kernel's internal implementations.For example:
uint64 sys_fork(void) { return kfork(); }Here:
sys_fork(): the system call entry pointkfork(): the kernel function that actually creates the process
sysproc.ccan be understood as the connecting layer between the system call layer and the process management code.
What's the difference between
fork()andkfork()?User programs call:
fork();The kernel's actual implementation of process creation is:
kfork();The full path is:
User program fork() ↓ fork assembly entry in user/usys.S ↓ a7 = SYS_fork ecall ↓ usertrap() ↓ syscall() ↓ syscalls[SYS_fork] ↓ sys_fork() ↓ kfork()
How does
fork()point tosys_fork()?The user-space
fork()assembly entry is roughly:fork: li a7, SYS_fork ecall retIt does not call
sys_fork()directly; instead:it puts the system call number SYS_fork into a7 then executes ecall to enter the kernelThe kernel's
syscall()reads this number:num = p->trapframe->a7;Then it looks up the system call table:
static uint64 (*syscalls[])(void) = { [SYS_fork] sys_fork, [SYS_exit] sys_exit, [SYS_wait] sys_wait, };This entry:
[SYS_fork] sys_forkestablishes the mapping from the number
SYS_fork→ thesys_fork()functionAfterwards:
p->trapframe->a0 = syscalls[num]();For
fork, this is equivalent to:p->trapframe->a0 = sys_fork();
Is
kfork()whereforkis really implemented?Yes.
kfork()is located in:kernel/proc.cIt mainly does:
- Allocate a new struct proc
- Copy the parent's user memory
- Copy the parent's trapframe
- Copy open files
- Set up the parent-child relationship
- Set the child process to RUNNABLE
A simplified structure is:
代码
int kfork(void) { struct proc *p = myproc(); struct proc *np; np = allocproc(); uvmcopy(p->pagetable, np->pagetable, p->sz); *(np->trapframe) = *(p->trapframe); np->trapframe->a0 = 0; np->parent = p; np->state = RUNNABLE; return np->pid; }So the most important thing to remember is:
fork() → ecall → syscall() → sys_fork() → kfork()The relationships among the relevant files:
代码
user/user.h C declaration of fork() user/usys.pl generates the user-space assembly entry for fork kernel/syscall.h defines the SYS_fork number kernel/syscall.c SYS_fork → sys_fork kernel/sysproc.c sys_fork() calls kfork() kernel/proc.c kfork() actually creates the process kernel/proc.h defines struct proc
Following the hints step by step, there is one step that needs attention:
if (p->syscall_mask & (1 << num)) {
p->trapframe->a0 = -1;
} else {
p->trapframe->a0 = syscalls[num]();
}What I initially wrote was:
if (p->syscall_mask & (1 << num)) {
prinf(...) // 一段错误日志
}When a system call returns to user mode, the user program treats a0 as the return value. At that point, what a0 originally held is usually still the first argument of the system call. If you only print a log without modifying a0, then after returning to user mode, open() may treat the address of "README" as its return value instead of getting the failure value -1.
To summarize, following the hints step by step, what exactly did we implement:
Step One
Add
$U/_sandboxto UPROGS in Makefile Add$U/_sandboxto the UPROGS list in Makefile.
Nothing much to say; this is essentially telling the build which user programs need to be compiled and put into xv6's file system.
Step Two
引用
Run make qemu and you will see that the compiler cannot compile
user/sandbox.c, because the user-space stubs for theinterposesystem call don't exist yet: add a prototype forinterposetouser/user.h, a stub touser/usys.pl, and a syscall number tokernel/syscall.h. The Makefile invokes the perl scriptuser/usys.pl, which producesuser/usys.S, the actual system call stubs, which use the RISC-Vecallinstruction to transition to the kernel. Once you fix the compilation issues, run sandbox 32768 - cat README in the xv6 shell; it will fail because you haven't implemented the system call in the kernel yet. Running make qemu cannot compileuser/sandbox.cyet because the user-space stub forinterposeis missing. Declareinterposeinuser/user.h, add its stub touser/usys.pl, and assign a syscall number inkernel/syscall.h. Makefile runsuser/usys.plto generateuser/usys.S. These stubs use the RISC-Vecallinstruction to enter the kernel. After fixing compilation, sandbox 32768 - cat README still fails until the kernel implements the system call.
Provide a user interface in user/user.h; you only need to specify the function prototype signature:
int interpose(int, const char *);Add the system call number in kernel/syscall.h:
# kernel/syscall.h
#define SYS_interpose 22Then, modify user/usys.pl:
The pl suffix here means a Perl script, something like this:
# user/usys.pl
...省略...
entry("getpid");
entry("sbrk");
entry("pause");
entry("uptime");
entry("interpose");What is this actually for? make generates stubs like this:
.global interpose
interpose:
li a7, SYS_interpose
ecall
retA stub here can be understood as: a small piece of "relay code" or a "placeholder entry" that doesn't do the real work itself, only forwards the call somewhere else.
In xv6's system calls, the user-space functions like fork, sbrk, and open are syscall stubs.
For example, the stub for sbrk is roughly:
sbrk:
li a7, SYS_sbrk
ecall
retIt does very little:
put the system call number SYS_sbrk into a7
execute ecall to enter the kernel
return after the kernel finishes handling itIt is not responsible for allocating memory itself. The real work is done by, in the kernel:
sys_sbrk()and further down:
growproc()
uvmalloc()
kalloc()So this path can be written as:
user program calls sbrk()
↓
user-space syscall stub
↓
ecall
↓
kernel syscall()
↓
sys_sbrk()Why is it called a stub and not directly an "implementation"?
Because it is very thin, just an interface shell:
stub: responsible for forwarding the request
implementation: responsible for actually doing the workIn xv6:
the declaration in user/user.h
tells the C compiler how to call the function
the stub generated by user/usys.pl
converts the call into an ecall
kernel/sys_xxx()
actually receives and handles the system callTherefore, the user-space stubs mentioned in the documentation are the small assembly entries in user space responsible for converting ordinary function calls into system calls.
Step Three
Add a
sys_interpose()function inkernel/sysproc.cthat implements the new system call by recording the mask argument in a new field in theprocstructure (seekernel/proc.h). The functions to retrieve system call arguments from user space are inkernel/syscall.c, and you can see examples of their use inkernel/sysproc.c. Add your newsys_interposeto thesyscallsarray inkernel/syscall.c. Inkernel/sysproc.c, implementsys_interpose()by storing the mask argument in a new field of theprocstructure declared inkernel/proc.h. Argument retrieval functions are inkernel/syscall.c, with examples inkernel/sysproc.c. Addsys_interposeto thesyscallsarray inkernel/syscall.c.
Modify struct proc:
It's easy to see that this restriction mask is a per-process variable, so it should be placed in struct proc.
For what this struct is, go back and look at the "Processes in xv6" section of the "Reading the xv6 book" part.
So, go into kernel/proc.h and add an int syscall_mask field.
Modify kernel/syscall.c:
First, near the declarations of the other system calls, add
extern uint64 sys_interpose(void);Then find the system call table and add sys_interpose to it:
// An array mapping syscall numbers from syscall.h
// to the function that handles the system call.
static uint64 (*syscalls[])(void) = {
// ... 省略
[SYS_close] sys_close,
[SYS_interpose] sys_interpose,
};When you later write the sys_call() function, you will understand this point.
Then, implement sys_interpose:
In kernel/sysproc.c:
For what this file is, refer to the xv6 book:

uint64
sys_interpose(void)
{
int mask; // // 在内核栈中准备一个变量
argint(0, &mask); // // 取得用户传入的第 0 个参数,存入 mask
myproc()->syscall_mask = mask; // 把掩码保存到当前进程
return 0;
}You might wonder: this doesn't seem to implement anything at all? My understanding is that this only serves the purpose of passing arguments from user mode.
Step Four
Modify
kfork()(seekernel/proc.c) to copy the mask from the parent to the child process. Updatekfork()inkernel/proc.cso that a child process inherits its parent’s mask.
Because the child process's mask should be inherited from the parent.
It's also very simple: just add this statement in the kfork() function:
np->syscall_mask = p->syscall_mask;and that's it.
Step Five
Modify the
syscall()function inkernel/syscall.cto check if the system call must be rejected. Inkernel/syscall.c, updatesyscall()to determine whether to reject the system call.
if(num > 0 && num < NELEM(syscalls) && syscalls[num]) {
if(p->syscall_mask & (1 << num)) {
p->trapframe->a0 = -1;
} else {
p->trapframe->a0 = syscalls[num]();
}
} else {
printk("%d %s: unknown sys call %d\n",
p->pid, p->name, num);
p->trapframe->a0 = -1;
}This is where the interpose logic is actually implemented.
Honestly, I find this kind of coupling a bit odd. Implementing a mechanism by coupling it into a generic function that dispatches system calls doesn't feel great, but I couldn't think of a better implementation either.
Walking Through the Whole Idea from Start to Finish
Calling interpose from user mode:
- The user calls our implemented system call interface
int interpose(int, const char*) - This interface is implemented by assembly generated by the Perl script, which puts the code of
SYS_interposeinto thea7register; the ecall hardware support transitions from user mode to kernel mode, and the user-mode stack frame is saved intomyproc()->trapframe(explained in detail in section 4.2 of the xv6 book) - Control transfers to xv6's generic interface
void syscall(void), which obtains the syscall to call viaint num; num = p->trapframe->a7;, then jumps to the specific function call through the function pointer arrayuint64 (*syscalls[])(void), and puts the return value into thea0register - Exiting from ecall, ret makes the user side return.
Sandbox with allowed pathnames
Add a feature that checks the pathname for open and exec.
Reading the hints, there are two steps:
Some hints:
- Modify
sys_interpose()to remember the allowed pathname.argstrwill be handy to retrieve the pathname. You can declare a buffer of sizeMAXPATHin theprocstruct.- If
openorexecare masked, check if the pathname matches the allowed pathname. If so, allow the execution of those system calls.
The first one is simple; just follow it. It's basically the same as what was done in the previous exercise.
For the second one, I ran into some difficulties:
I asked the language model:
引用
I'm working on this Sandbox with allowed pathnames,
I'm stuck on this: how to determine whether the paths of open and exec match. I read the source code but couldn't figure it out. For example, I tried reading the implementation of exec:
代码
uint64 sys_exec(void) { char path[MAXPATH], *argv[MAXARG]; int i; uint64 uargv, uarg; argaddr(1, &uargv); if(argstr(0, path, MAXPATH) < 0) { return -1; } memset(argv, 0, sizeof(argv)); for(i=0;; i++){ if(i >= NELEM(argv)){ goto bad; } if(fetchaddr(uargv+sizeof(uint64)*i, (uint64*)&uarg) < 0){ goto bad; } if(uarg == 0){ argv[i] = 0; break; } argv[i] = kalloc(); if(argv[i] == 0) goto bad; if(fetchstr(uarg, argv[i], PGSIZE) < 0) goto bad; } int ret = kexec(path, argv); for(i = 0; i < NELEM(argv) && argv[i] != 0; i++) kfree(argv[i]); return ret; bad: for(i = 0; i < NELEM(argv) && argv[i] != 0; i++) kfree(argv[i]); return -1; }Then I found that I couldn't locate the part about how to obtain the arguments, similar to what existed when implementing interpose. Specifically, when I read this line:
if((n = argstr(0, path, MAXPATH)) < 0)I'm not quite sure what this 0 is; I think it's stdin? I tried reading the code step by step, but it seems like too much and I can't get through it all. In short, I hope you can walk me through it concisely; the answer doesn't need to be long.
The answer I got, summarized:
-
The
0here is not stdin; it means: read the 0th argument of the system call, i.e., the first argument. -
a0, a1, ... correspond to the 0th, 1st, ... arguments of the system call, respectively.
-
And the function signatures of these two system calls (you can tell by looking at the source, in
user.h) are:open(path, mode); exec(path, argv); -
Therefore, inside
syscall(), usingargstr(0, pathm MAXPATH)gets you the argument.

Attack xv6
The background is that in uvmalloc and kalloc, a few memset statements were omitted, so newly allocated memory retains its previously used contents.
Then run a program like this:
代码
#define DATASIZE (8*4096)
char data[DATASIZE];
int
main(int argc, char *argv[])
{
if(argc != 2){
printf("Usage: secret the-secret\n");
exit(1);
}
strcpy(data, "This may help.");
strcpy(data + 16, argv[1]);
exit(0);
}Write attack.c to obtain this secret from secret.c
The specific approach requires a system call, sbrk: it asks the kernel to expand the current process's user memory, and the return value is a pointer to the start of the newly added memory.
In xv6 it is typically declared as:
char *sbrk(int n);So the solution is quite simple:
代码
int
main(int argc, char *argv[])
{
// Your code here.
char *p = sbrk(8*4096);
if (p == (char*)-1) {
exit(1);
}
for (int i = 0; i < 8*4096 - 16; i++) {
if (p[i] =='T') {
char tmp[15];
memcpy(tmp, p + i, 15);
if (!strcmp(tmp, "This may help.")) {
for (char *c = p + i + 16; *c; c++) {
printf("%c", *c);
}
printf("\n");
}
}
}
exit(1);
}Summary and Ramblings

I couldn't find a relatively up-to-date Chinese translation of the xv6 book, so I basically just threw it at an LLM, had it summarize things, skimmed the summary, and jumped straight into writing the labs. It turned out that almost all the problems I ran into while writing the labs were actually answered in the book, but when I started writing I was completely lost, which was a bit rough.
But thinking about it more carefully, I feel that even if I had read it carefully, I wouldn't have been able to absorb it. Instead, going from being completely lost at the start to understanding things as I wrote along the way might actually work better for me. Perhaps now I could go back and re-read that part of the book? But I'm feeling a bit lazy right now, so I'll let it go.