# xv6 Lab2 System calls - MIT 6.1810 Fall 2025 Operating System

> This article is currently an experimental machine translation and may contain errors. If anything is unclear, please refer to [original Chinese version](<https://blog.wendain.ing/posts/xv6-lab2-system-calls/>). 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);`:

```text
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;
- `a7` holds the system call number;
- `a0` is 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](https://mit-public-courses-cn-translatio.gitbook.io/mit6-s081/lec03-os-organization-and-system-calls/3.9-xv6-qi-dong-guo-cheng)
- [MIT6.s081/6.828 lecture02: OS design and Lab2 takeaways - Article by 逆风的大船 - Zhihu](https://zhuanlan.zhihu.com/p/651170875)
- [Re-reading xv6 (I) | Anri's blog](https://copicomi.github.io/posts/重读-xv6/i/)

#### 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:

1. The machine boots and loads the kernel into memory
2. `entry.S` runs, setting up a stack for each CPU; at this point we are in ***machine mode***
3. `start` runs, doing some initial configuration, and switches to ***kernel mode***
4. `main` runs, initializing each module, creating the first process, and switching to ***user mode***
5. `init` runs, setting up standard I/O, starting the `shell`, 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)】 ](https://www.bilibili.com/video/BV1PL411N7u9/?share_source=copy_web&vd_source=60b44c8f21723cac51d65c96f7acfb00); 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.

<img src="https://image.wendaining.top/image-20260726163250240.png" alt="belike" style="zoom:33%;" />

Answers:

```txt
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=1
```

One 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:
>
> ```text
> scause = why it went wrong
> sepc   = which instruction went wrong
> stval  = what address was being accessed when it went wrong
> ```
>
> In your case:
>
> ```text
> scause=0xd sepc=0x80001cf8 stval=0x0
> panic: kerneltrap
> ```
>
> `scause = 0xd`
>
> `scause` indicates the cause of the trap.
>
> ```text
> 0xd = decimal 13 = Load page fault
> ```
>
> That is:
>
> > A page fault occurred while the CPU was **reading memory**.
>
> This corresponds exactly to the deliberately added code:
>
> ```c
> num = *(int *)0;
> ```
>
> It tries to read an `int` from memory address `0`. The RISC-V spec defines exception number 13 as a load page fault. ([RISC-V Documentation](https://docs.riscv.org/reference/isa/_attachments/riscv-privileged.pdf?utm_source=chatgpt.com))
>
> `stval = 0x0`
>
> For a page fault, `stval` usually records the virtual address that caused the fault.
>
> Here:
>
> ```text
> stval = 0x0
> ```
>
> So we can be sure:
>
> > The target of the faulting memory access was virtual address `0`.
>
> That is, in the code:
>
> ```c
> *(int *)0
>         ^
> ```
>
> The kernel page table does not map address `0`, so the read fails. The lab is precisely designed to let you determine, via `scause=0xd` and `stval=0`, that this is a page fault caused by reading a null address. ([MIT CSAIL](https://pdos.csail.mit.edu/6.828/2024/labs/syscall.html))
>
> `sepc = 0x80001cf8`
>
> `sepc` holds the address of the instruction that was executing when the exception occurred.
>
> Here it means:
>
> > The machine instruction located at kernel address `0x80001cf8` triggered the exception.
>
> Therefore the lab has you take this address and look it up in the compiled assembly:
>
> ```bash
> grep -n -B 4 -A 4 "80001cf8" kernel/kernel.asm
> ```
>
> You should find something like:
>
> ```asm
> 80001cf8:  ...    lw a?,0(zero)
> ```
>
> Where:
>
> ```asm
> lw a?, 0(zero)
> ```
>
> means reading data from the address:
>
> ```text
> zero + 0 = 0
> ```
>
> The lab explicitly requires you to use the printed `sepc` to locate the faulting instruction in `kernel/kernel.asm`. ([MIT CSAIL](https://pdos.csail.mit.edu/6.828/2024/labs/syscall.html))
>
> You can also stop right there directly in GDB:
>
> ```gdb
> b *0x80001cf8
> c
> x/i $pc
> ```
>
> `panic: kerneltrap`
>
> When the exception occurred, the CPU was executing kernel code, so it entered:
>
> ```c
> 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:
>
> ```c
> panic("kerneltrap");
> ```
>
> So the whole reasoning process is:
>
> ```text
> 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 0
> ```
>
> In your answer file you can write:
>
> ```text
> 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:

> 1. What is struct proc? What is sysproc.c for?
> 2. 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 proc` is defined in `kernel/proc.h` and 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:
>
> ```c
> 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:
>
> ```c
> struct proc *p = myproc();
> ```
>
> means: **get the struct proc of the currently running process**
>
> Afterwards:
>
> ```c
> p->pid
> p->trapframe
> p->state
> ```
>
> reads the current process's information.
>
> `struct proc` is just a data structure. The code that creates, schedules, and exits processes mainly lives in `kernel/proc.c`.
>
> ------
>
> What is `sysproc.c` for?
>
> `kernel/sysproc.c` holds the entry points for process-related system calls, for example:
>
> ```c
> 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:
>
> ```c
> uint64
> sys_fork(void)
> {
>   return kfork();
> }
> ```
>
> Here:
>
> - `sys_fork()`: the system call entry point
> - `kfork()`: the kernel function that actually creates the process
>
> `sysproc.c` can be understood as the connecting layer between the system call layer and the process management code.
>
> ------
>
> What's the difference between `fork()` and `kfork()`?
>
> User programs call:
>
> ```c
> fork();
> ```
>
> The kernel's actual implementation of process creation is:
>
> ```c
> kfork();
> ```
>
> The full path is:
>
> ```text
> 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 to `sys_fork()`?
>
> The user-space `fork()` assembly entry is roughly:
>
> ```asm
> fork:
>   li a7, SYS_fork
>   ecall
>   ret
> ```
>
> It does not call `sys_fork()` directly; instead:
>
> ```text
> it puts the system call number SYS_fork into a7
> then executes ecall to enter the kernel
> ```
>
> The kernel's `syscall()` reads this number:
>
> ```c
> num = p->trapframe->a7;
> ```
>
> Then it looks up the system call table:
>
> ```c
> static uint64 (*syscalls[])(void) = {
>   [SYS_fork] sys_fork,
>   [SYS_exit] sys_exit,
>   [SYS_wait] sys_wait,
> };
> ```
>
> This entry:
>
> ```c
> [SYS_fork] sys_fork
> ```
>
> establishes the mapping from the number `SYS_fork` → the `sys_fork()` function
>
> Afterwards:
>
> ```c
> p->trapframe->a0 = syscalls[num]();
> ```
>
> For `fork`, this is equivalent to:
>
> ```c
> p->trapframe->a0 = sys_fork();
> ```
>
> ------
>
> Is `kfork()` where `fork` is really implemented?
>
> Yes.
>
> `kfork()` is located in:
>
> ```text
> kernel/proc.c
> ```
>
> It mainly does:
>
> 1. Allocate a new struct proc
> 2. Copy the parent's user memory
> 3. Copy the parent's trapframe
> 4. Copy open files
> 5. Set up the parent-child relationship
> 6. Set the child process to RUNNABLE
>
> A simplified structure is:
>
> ```c
> 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:
>
> ```text
> fork()
> → ecall
> → syscall()
> → sys_fork()
> → kfork()
> ```
>
> The relationships among the relevant files:
>
> ```text
> 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:

```c
if (p->syscall_mask & (1 << num)) {
  p->trapframe->a0 = -1;
} else {
  p->trapframe->a0 = syscalls[num]();
}
```

What I initially wrote was:

```c
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/_sandbox` to UPROGS in Makefile
> Add `$U/_sandbox` to 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 the `interpose` system call don't exist yet: add a prototype for `interpose` to `user/user.h`, a stub to `user/usys.pl`, and a syscall number to `kernel/syscall.h`. The Makefile invokes the perl script `user/usys.pl`, which produces `user/usys.S`, the actual system call stubs, which use the RISC-V `ecall` instruction 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 compile `user/sandbox.c` yet because the user-space stub for `interpose` is missing. Declare `interpose` in `user/user.h`, add its stub to `user/usys.pl`, and assign a syscall number in `kernel/syscall.h`. Makefile runs `user/usys.pl` to generate `user/usys.S`. These stubs use the RISC-V `ecall` instruction 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:

```c
int interpose(int, const char *);
```

Add the system call number in `kernel/syscall.h`:

```c
# kernel/syscall.h
#define SYS_interpose 22
```

Then, modify `user/usys.pl`:

The `pl` suffix here means a Perl script, something like this:

```perl
# user/usys.pl
...省略...
entry("getpid");
entry("sbrk");
entry("pause");
entry("uptime");
entry("interpose");
```

What is this actually for? `make` generates stubs like this:

```assembly
.global interpose
interpose:
  li a7, SYS_interpose
  ecall
  ret
```

> [!note]
>
> A `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:
>
> ```asm
> sbrk:
>   li a7, SYS_sbrk
>   ecall
>   ret
> ```
>
> It does very little:
>
> ```text
> put the system call number SYS_sbrk into a7
> execute ecall to enter the kernel
> return after the kernel finishes handling it
> ```
>
> It is not responsible for allocating memory itself. The real work is done by, in the kernel:
>
> ```c
> sys_sbrk()
> ```
>
> and further down:
>
> ```c
> growproc()
> uvmalloc()
> kalloc()
> ```
>
> So this path can be written as:
>
> ```text
> 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:
>
> ```text
> stub: responsible for forwarding the request
> implementation: responsible for actually doing the work
> ```
>
> In xv6:
>
> ```text
> 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 call
> ```
>
> Therefore, 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 in `kernel/sysproc.c` that implements the new system call by recording the mask argument in a new field in the `proc` structure (see `kernel/proc.h`). The functions to retrieve system call arguments from user space are in `kernel/syscall.c`, and you can see examples of their use in `kernel/sysproc.c`. Add your new `sys_interpose` to the `syscalls` array in `kernel/syscall.c`.
> In `kernel/sysproc.c`, implement `sys_interpose()` by storing the mask argument in a new field of the `proc` structure declared in `kernel/proc.h`. Argument retrieval functions are in `kernel/syscall.c`, with examples in `kernel/sysproc.c`. Add `sys_interpose` to the `syscalls` array in `kernel/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

```c
extern uint64 sys_interpose(void);
```

Then find the system call table and add `sys_interpose` to it:

```c
// 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`:

> [!note]
>
> For what this file is, refer to the xv6 book: <img src="https://image.wendaining.top/image-20260726225618978.png" style="zoom:50%;" />

```c
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()` (see `kernel/proc.c`) to copy the mask from the parent to the child process.
> Update `kfork()` in `kernel/proc.c` so 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:

```c
np->syscall_mask = p->syscall_mask;
```

and that's it.

### Step Five

> Modify the `syscall()` function in `kernel/syscall.c` to check if the system call must be rejected.
> In `kernel/syscall.c`, update `syscall()` to determine whether to reject the system call.

```c
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_interpose` into the `a7` register; the ecall hardware support transitions from user mode to kernel mode, and the user-mode stack frame is saved into `myproc()->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 via `int num; num = p->trapframe->a7;`, then jumps to the specific function call through the function pointer array `uint64 (*syscalls[])(void)`, and puts the return value into the `a0` register
- 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. `argstr` will be handy to retrieve the pathname. You can declare a buffer of size `MAXPATH` in the `proc` struct.
> - If `open` or `exec` are 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:
>
> ```c
> 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 `0` here 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:

    ```C
    open(path, mode);
    exec(path, argv);
    ```

- Therefore, inside `syscall()`, using `argstr(0, pathm MAXPATH)` gets you the argument.




<img src="https://image.wendaining.top/image-20260726203540808.png" alt="Passed successfully" style="zoom:33%;" />

## 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:

```C
#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:

```c
char *sbrk(int n);
```

So the solution is quite simple:

```C
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

<img src="https://image.wendaining.top/image-20260726221754957.png" alt="Complete lab2" style="zoom: 67%;" />

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.
