hello: Creating your own xv6 program
Easy
You can find the source code for all xv6 user programs in the user directory of the kul-xv6 Git repository.
Start by inspecting the cat program. Open user/cat.c in VSCode and read through the code. Do you understand it? If not, make sure to review Chapter 1 of the xv6 book.
Remember, the xv6 shell is also just another program that you can inspect (and even modify) in
user/sh.c.
Note that in xv6, a user-space program terminates with the call
exit(0);instead of returning frommain. This is because xv6 does not implement a standard C runtime. A C runtime, such as crt0, is typically responsible for invoking themainfunction and properly terminating the process after a return frommain. For more information, see here.
Using library functionality
Reusable functionality is typically organized into libraries for C programs. However, for xv6 programs, the libraries referenced in the #include statements are not the standard libraries you may be familiar with in C programming.
The C Standard Library consists of a collection of useful functions that can be used by C programs. However, the implementation of these functions depends on the underlying operating system. On Ubuntu GNU/Linux and many other UNIX distributions, this implementation is known as
glibcor The GNU C Library. Another popular implementation ismusl.
xv6 provides a very limited implementation of libc, so we cannot simply use #include <stdio.h> to call functions like printf. The libc functions available in xv6 can be found in user/user.h, with their implementations in user/ulib.c.
- Check out
user/user.hin VSCode to understand which functionality xv6 user programs can use.
Instead of including standard C header files (like stdio.h), we will include user/user.h in our xv6 programs. Therefore, always start your user-space program for xv6 with:
#include "user/user.h"
Adding your own user-space program
Now, let’s add a simple user-space program to xv6:
- Create a file named
hello.cin theuserdirectory (in VSCode: use the explorer on the left, right-click, and select “New File”). - Write a simple C program in this file with a
mainfunction that prints the string “Hello, World!” to the terminal.
When you compile the operating system using make qemu, all programs in the user directory will be automatically compiled for RISC-V. This is specified in the Makefile in the top-level xv6-riscv directory.
Next, we will add the hello program to the Makefile:
- Open
Makefilein VSCode. - Look for the definition of
UPROGSand add your program:
UPROGS=\
$U/_cat\
...
$U/_hello\
...
$U/_zombie\
The
UPROGSMakefile variable contains all user-space programs that need to be compiled. The Makefile ensures that an entry of the form$U/_progwill compile the fileuser/prog.cand install it in the root directory as an executable namedprog.
- Compile xv6 and start it using QEMU:
[vscode-terminal]$ make qemu
- Run your program:
[xv6-shell]$ hello
Hello, World!