Writing a Hypervisor in 1,000 Lines
2025-08-29
I've wrote a tutorial on building a hypervisor from scratch in 1,000 lines of code (website). Few chapters are still in progress, but it's already good enough to get you started.
More specifically, type-1 hypervisor on 64-bit RISC-V with the hypervisor extension (on QEMU).
The book is for developers who have finished Operating System in 1,000 Lines and want to learn more about how hypervisors work.
Rust
C is the best language for writing and learning from scratch, however, the most common feedback I got from the OS book readers is: can you write a tutorial in Rust?
While this "Hypervisor in 1,000 Lines" focuses on hypervisor, it starts from scratch again, in Rust! The first few chapters are the same as the OS book, but in Rust. It means this book also partially covers OS in 1,000 Lines in Rust. Enjoy!
Stable Rust
Another interesting aspect of this book is that I used stable Rust, not nightly. This is a big win for Rust - you used to always need nightly Rust due to unstable language features, such as inline assembly.
However, thanks to the continuous efforts of the Rust community, stable Rust now has all the features you need to write a hypervisor!
Hardware-assisted hypervisors are event handlers
This is all what I want you to learn from this book. Hardware-assisted hypervisors are event handlers. They are not like a CPU emulator.
In JavaScript, the life of a hypervisor looks like this:
const memory = new GuestMemory();
memory.loadLinuxImage("linux.bin");
const vcpu = new VirtualCPU(memory);
while (true) {
try {
vcpu.resume();
} catch (event) {
handleEvent(event); // Memory-mapped I/O, etc.
}
}
A hypervisor runs the guest OS in a try
block, catch
es events (VM exits), and goes back to the guest mode again.
That is, the most of hypervisor's work is like a catch
block (with continuation).
This gives us a huge potential to build applications beyond running tradtional OSes. You might emulate real-world hardware to run existing OSes as they are. You can build a strong security boundary like gVisor. Ultimately, you can define an application-specific environment like Hyperlight.
Where can I find the book?
The book is public on 1000hv.seiya.me.
I hope you experience the joy of building hypervisors!