This is the 17th day of my participation in the August Challenge

Xv6 writes user programs

How to add your own user program in Xv6 (Xv6-RISCV), such as implementing a HelloWorld?

1. Write code

First, of course, write the code first (duh).

But how do you write it? Would it be the same as writing a program on a real operating system using the standard C compiler suite?

Let’s write a Hello World as an example:

Create a new helloWorld.c file in xv6-riscv/user/ and write the code:

#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int main(a) {
	printf("Hello World! \n");
	exit(0);
}
Copy the code

Notice that this is a little different from the code we would normally write on a real system:

  1. Guide library:kernel/types.h.kernel/stat.h.user/user.h. You can seexv6-riscv/user/*.cThe first three lines are basically like this, so let’s just follow suit. These three lines are probably include<stdio.h>.<stdlib.h>.<unistd.h>
  2. Don’treturn 0;,exit(0);Otherwise you’ll get a runtime unexpected scause 0x000000000000000f). This can also be done by referring to the procedures that come with other systems.

Just note these two points, and note that you can only use the C libraries provided by Xv6, not the STL on a real system. The rest is not much different than writing C programs.

2. Modify the Makefile

The Xv6 system itself does not have a compiler implementation, so we need to compile the program along with the system. Modify xv6 riscv/Makefile:

$ vim Makefile
Copy the code

Find UPROGS (around line 118), keep the format, and add the registration new program later:

UPROGS=\
	$U/_cat\
	$U/_echo\
	...
	$U/_helloworld\
Copy the code

If the source file is user/xxx.c, this corresponds to a line of $U/_xxx\.

3. Compile and run Xv6

Compile and run Xv6:

$ make qemu
Copy the code

In Xv6 ls, you can see our helloWorld program:

$ ls
...
helloworld   2 20 22352
Copy the code

Run the program:

$ helloworld
Hello World!
Copy the code

That’s it! Hello World!

This successfully runs our own program on Xv6.


By CDFMLR 2021-02-17

echo “See you.”

The picture at the top is from xiaowei API, which is randomly selected and only used to test the mechanical and photoelectric performance of the screen. It has nothing to do with any content or opinion of the article, and does not mean that I agree with, support or oppose any content or opinion in part or in whole. If there is infringement, contact delete.