Write a Minimal Hypervisor With the KVM API in C
Build a small KVM hypervisor in C that loads a flat 16-bit guest binary, serves a serial port and a result port, counts exits and halts cleanly.

A hypervisor is less code than people expect. Linux does the hard parts, and the program that uses KVM is mostly a loop. This post builds one from scratch in C, structured as a small reusable tool instead of a single main: it loads a flat binary into guest memory, starts a virtual CPU in real mode at a chosen address, emulates a serial port and a one-word result port, counts the exits by kind and stops cleanly on HLT or on any error. The guest is a short 16-bit program written in NASM. The code targets Linux 6.12 headers on x86-64, builds with GCC 14 and needs only access to /dev/kvm. It assumes the API vocabulary from the complete guide to the Linux KVM API, and the setup from the post on a KVM workstation.
The design
A hypervisor in this style has four jobs, and the program mirrors them as four functions.
Create the machine: open
/dev/kvm, create a VM, allocate and register memory.Load the guest: copy the binary into guest memory at the address it expects.
Create and reset the vCPU: map
kvm_run, set the registers so execution starts at the entry point.Run: loop on
KVM_RUN, dispatch each exit to a handler, stop onHLT.
The state lives in one struct, so each function takes it by pointer and there are no globals.
The guest
The guest is a 16-bit real-mode program assembled with NASM into a flat binary. It prints a message one byte at a time to the serial port at 0x3f8, adds the numbers from 1 to 10 and writes the sum as a 16-bit word to port 0x500, which our hypervisor treats as a result register, then halts.
bits 16
org 0x1000
start:
mov si, message
mov dx, 0x3f8
print:
lodsb
test al, al
jz done
out dx, al
jmp print
done:
xor ax, ax
mov cx, 10
sum:
add ax, cx
loop sum
mov dx, 0x500
out dx, ax
hlt
message: db "hello from the guest", 10, 0Assemble it with nasm -f bin guest.asm -o guest.bin. The org 0x1000 directive tells NASM the code will run at address 0x1000, so the message label resolves to the right absolute address. The loop sum instruction decrements cx and jumps while it is non-zero, so ax ends at 10 + 9 + ... + 1 = 55. Each out dx, al is a one-byte port write that causes a KVM_EXIT_IO, and out dx, ax is a two-byte write.
The hypervisor
#include <errno.h>
#include <fcntl.h>
#include <linux/kvm.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#define GUEST_MEM_SIZE (1UL << 20) /* 1 MiB of guest RAM */
#define LOAD_ADDR 0x1000
#define PORT_SERIAL 0x3f8
#define PORT_RESULT 0x500
struct vmm {
int kvm_fd;
int vm_fd;
int vcpu_fd;
uint8_t *mem;
struct kvm_run *run;
unsigned long exits_io;
unsigned long exits_hlt;
};
static void die(const char *what)
{
fprintf(stderr, "%s: %s\n", what, strerror(errno));
exit(1);
}
static void vmm_create(struct vmm *v)
{
v->kvm_fd = open("/dev/kvm", O_RDWR | O_CLOEXEC);
if (v->kvm_fd < 0)
die("open /dev/kvm");
if (ioctl(v->kvm_fd, KVM_GET_API_VERSION, 0) != KVM_API_VERSION) {
fprintf(stderr, "unsupported KVM API version\n");
exit(1);
}
v->vm_fd = ioctl(v->kvm_fd, KVM_CREATE_VM, 0);
if (v->vm_fd < 0)
die("KVM_CREATE_VM");
v->mem = mmap(NULL, GUEST_MEM_SIZE, PROT_READ | PROT_WRITE,
MAP_SHARED | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
if (v->mem == MAP_FAILED)
die("mmap guest memory");
struct kvm_userspace_memory_region region = {
.slot = 0,
.guest_phys_addr = 0,
.memory_size = GUEST_MEM_SIZE,
.userspace_addr = (uint64_t)(uintptr_t)v->mem,
};
if (ioctl(v->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion) < 0)
die("KVM_SET_USER_MEMORY_REGION");
}
static void vmm_load(struct vmm *v, const char *path)
{
FILE *f = fopen(path, "rb");
if (!f)
die(path);
size_t n = fread(v->mem + LOAD_ADDR, 1, GUEST_MEM_SIZE - LOAD_ADDR, f);
if (ferror(f))
die("read guest image");
fclose(f);
fprintf(stderr, "loaded %zu bytes at 0x%x\n", n, LOAD_ADDR);
}
static void vmm_reset_vcpu(struct vmm *v)
{
v->vcpu_fd = ioctl(v->vm_fd, KVM_CREATE_VCPU, 0);
if (v->vcpu_fd < 0)
die("KVM_CREATE_VCPU");
int size = ioctl(v->kvm_fd, KVM_GET_VCPU_MMAP_SIZE, 0);
if (size < 0)
die("KVM_GET_VCPU_MMAP_SIZE");
v->run = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, v->vcpu_fd, 0);
if (v->run == MAP_FAILED)
die("mmap kvm_run");
struct kvm_sregs sregs;
if (ioctl(v->vcpu_fd, KVM_GET_SREGS, &sregs) < 0)
die("KVM_GET_SREGS");
sregs.cs.base = 0;
sregs.cs.selector = 0;
if (ioctl(v->vcpu_fd, KVM_SET_SREGS, &sregs) < 0)
die("KVM_SET_SREGS");
struct kvm_regs regs;
memset(®s, 0, sizeof(regs));
regs.rip = LOAD_ADDR;
regs.rflags = 0x2;
if (ioctl(v->vcpu_fd, KVM_SET_REGS, ®s) < 0)
die("KVM_SET_REGS");
}
static int handle_io(struct vmm *v)
{
struct kvm_run *run = v->run;
uint8_t *data = (uint8_t *)run + run->io.data_offset;
v->exits_io++;
if (run->io.direction != KVM_EXIT_IO_OUT) {
fprintf(stderr, "unexpected port read at 0x%x\n", run->io.port);
return -1;
}
for (uint32_t i = 0; i < run->io.count; i++) {
if (run->io.port == PORT_SERIAL && run->io.size == 1) {
putchar(data[i]);
} else if (run->io.port == PORT_RESULT && run->io.size == 2) {
uint16_t value;
memcpy(&value, data + i * 2, sizeof(value));
printf("guest result: %u\n", value);
} else {
fprintf(stderr, "unhandled write: port 0x%x size %u\n",
run->io.port, run->io.size);
return -1;
}
}
return 0;
}
static int vmm_run(struct vmm *v)
{
for (;;) {
if (ioctl(v->vcpu_fd, KVM_RUN, 0) < 0) {
if (errno == EINTR)
continue;
die("KVM_RUN");
}
switch (v->run->exit_reason) {
case KVM_EXIT_HLT:
v->exits_hlt++;
return 0;
case KVM_EXIT_IO:
if (handle_io(v) < 0)
return 1;
break;
case KVM_EXIT_FAIL_ENTRY:
fprintf(stderr, "entry failed: reason 0x%llx\n",
(unsigned long long)v->run->fail_entry.hardware_entry_failure_reason);
return 1;
case KVM_EXIT_INTERNAL_ERROR:
fprintf(stderr, "internal error: suberror %u\n", v->run->internal.suberror);
return 1;
case KVM_EXIT_SHUTDOWN:
fprintf(stderr, "guest shut down (triple fault)\n");
return 1;
default:
fprintf(stderr, "unhandled exit reason %u\n", v->run->exit_reason);
return 1;
}
}
}
int main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "usage: %s guest.bin\n", argv[0]);
return 2;
}
struct vmm v = {0};
vmm_create(&v);
vmm_load(&v, argv[1]);
vmm_reset_vcpu(&v);
int status = vmm_run(&v);
fprintf(stderr, "exits: io=%lu hlt=%lu\n", v.exits_io, v.exits_hlt);
return status;
}Build and run:
nasm -f bin guest.asm -o guest.bin
gcc -O2 -Wall -Wextra minivmm.c -o minivmm
./minivmm guest.binloaded 54 bytes at 0x1000
hello from the guest
guest result: 55
exits: io=22 hlt=1The first and last lines go to standard error and the rest to standard output, so they may interleave differently in a terminal. The exit count is exact: the message has 20 characters plus a newline, 21 byte writes to the serial port, one write to the result port and one halt. The loaded size depends on how NASM assembles the program, so treat the 54 as an example and not an expectation.
Why it is written this way
A few choices are deliberate, and they point at what a real VMM does as it grows.
Everything is in one struct. Passing a struct vmm * to each function removes globals and makes it possible to create more than one VM in a process, the first step toward testing.
**The I/O handler loops over io.count.** A string instruction such as rep outsb produces one exit with count greater than one and the data laid out consecutively. A handler that assumes count == 1 silently drops bytes for such guests. Handling the count costs one loop and means the device model is correct for string I/O. The guest above uses only single out instructions, so count is 1 every time.
Errors are explicit and non-zero. An exit the program does not understand returns a failure with a message, rather than ignoring it. Silent defaults in a VMM turn guest bugs into hangs. KVM_EXIT_INTERNAL_ERROR and KVM_EXIT_FAIL_ENTRY get separate messages because they have different causes: the first means KVM could not emulate something and the second means the processor refused the state.
**EINTR is retried.** A signal during KVM_RUN, such as a profiler's timer, returns -1 with EINTR. It is not a failure, and the loop re-enters the guest. Without this, attaching strace -f or sending the process a signal would end the run.
**MAP_NORESERVE.** Guest RAM is allocated lazily by the kernel, and the flag tells the kernel not to reserve swap for it up front, which matters if you later raise the size to several gibibytes.
Extending it, in the right order
Each improvement adds one concept, and doing them in this order keeps the program working at every step.
Port reads. Handle
KVM_EXIT_IO_INby writing the result atdata_offsetbefore the nextKVM_RUN, as covered in the post on handling exits. A status register for the serial port is the usual first device.MMIO. Handle
KVM_EXIT_MMIOfor a device at a high address, so the guest can use memory-mapped registers.A debug dump. On any fatal exit, print the registers with
KVM_GET_REGSandKVM_GET_SREGS, as the guide shows. This single function saves hours.Protected and long mode. Build a GDT and page tables, set
CR0,CR4andEFER, and validate the state before running, as in the validation post.Interrupts. Create an in-kernel interrupt controller with
KVM_CREATE_IRQCHIPbefore creating the vCPU and raise lines withKVM_IRQ_LINE.More vCPUs. One thread per vCPU, each in its own
KVM_RUNloop, with a shared exit handler that is safe to call concurrently.A real kernel. Load a Linux
bzImageaccording to the boot protocol, build the zero page and command line, and provide a serial device and a timer. Projects such askvmtooland Firecracker show the shape of that work.
Testing the hypervisor itself
Because the guest is a few bytes, each feature has a small test guest. Keep guest.asm files beside the VMM and a script that runs each, comparing output to an expected file:
for g in guests/*.asm; do
nasm -f bin "$g" -o /tmp/guest.bin
./minivmm /tmp/guest.bin 2>/dev/null | diff - "${g%.asm}.expected" || echo "FAILED: $g"
doneA test that prints nothing and passes means every guest matched. One test per exit kind, plus a guest that deliberately executes an undefined instruction or writes to an unmapped port to check the error paths, gives good coverage for a very small amount of code.
Boundaries
This program is a teaching tool and a starting point. It runs trusted guests: a hostile guest could try to exploit the device emulation, which here is a putchar, but in a larger VMM is the main attack surface. It has no interrupts, so a guest that expects a timer will hang. It does not set up CPUID, so it works only for guests that do not depend on it. And it uses real mode on a processor with unrestricted guest support, which any CPU from the last decade has, but an old Intel part would need the TSS and identity-map setup described in the KVM API guide.


