Examining Initial Requirements
\n\n
I've begun by dissecting the core request, focusing on the essential elements. The goal is clear: a basic hypervisor. The "simple" constraint immediately steers towards a learning-oriented implementation, thus influencing design choices. I am now prioritizing the fundamental features required for VM management, keeping in mind the need for a practical approach.
Mapping the Implementation Path
\n\n
My current thinking is focused on leveraging the KVM API. I'm prioritizing the creation of a streamlined process, initiating by opening /dev/kvm. Then, creating both the global KVM instance and a dedicated VM. I plan to dedicate a specific amount of physical RAM for each guest machine. I have also begun the task of creating virtual CPUs (VCPUs) within the created VM environment.
Outlining VM Memory Management
\n\n
My current thinking centers on VM memory allocation. I'm focusing on mapping userspace memory to the guest's physical space using mmap. The size and arrangement of this memory are crucial for proper function. I must decide how to handle page tables and, more specifically, the translation of guest virtual addresses to host physical addresses. I am now exploring potential data structures and system calls to manage this process.
Refining Implementation Details
\n\n
My current thinking now centers on the segment setup, specifically on the tricky nature of x86. Keeping the guest strictly in 16-bit real mode simplifies things. Further down the code, I am considering the implications of setting up the segment registers. I am also moving forward with creating a VM structure to manage the different virtual machines, ensuring that KVM is thread-safe for multi-VM support.
Fine-Tuning the VM Structure
\n\n
My current thinking involves the VM structure. I'm focusing on incorporating the register state within the VM structure to streamline the process. Furthermore, I have made significant progress in defining the necessary payloads for the virtual machines, including a focus on different arithmetic operations for demonstration. I'm also preparing for the incorporation of multi-threading, readying the code for concurrent VM execution.
Defining VM Payload Functionality
\n\n
My current thinking centers on defining specific functionalities within the VM payloads. I'm focusing on arithmetic operations to demonstrate functionality and ease of debugging. I'm preparing assembly code. Also, I am now writing the necessary functions to handle the interactions between the VM and the host. This includes the process of printing values from the VM.
Building a hypervisor is a complex task. To make this "simple" and educational, we will build a Type-2 Hypervisor using the Linux KVM (Kernel-based Virtual Machine) API. This acts similarly to how QEMU works at a very low level.
This hypervisor will:
- Use the Linux Kernel (
/dev/kvm) to handle hardware virtualization instructions (VMX/SVM).
- Create two separate VMs running raw 16-bit assembly code.
- Run them concurrently using threads.
- Trap "I/O" requests from the guest to print data to the host console.
The Code (C)
Save this as simple_hypervisor.c. You need a Linux system with an Intel or AMD processor that supports virtualization (VT-x or AMD-V).
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <pthread.h>
#include <linux/kvm.h>
/*
* MEMORY SETTINGS
* We allocate 4KB of RAM for each VM.
*/
#define RAM_SIZE 0x1000
/*
* VM CONTEXT
* This holds the state for a single Virtual Machine.
*/
typedef struct {
int id; // VM ID
int vm_fd; // File descriptor for the VM
int vcpu_fd; // File descriptor for the Virtual CPU
struct kvm_run *kvm_run;// Shared memory region to communicate with KVM
unsigned char *mem; // Pointer to the VM's physical memory
const unsigned char *code; // The code this VM should run
size_t code_len;
} VirtualMachine;
/*
* INITIALIZE THE VM
* 1. Open KVM, 2. Create VM, 3. Allocate RAM, 4. Create VCPU, 5. Set Registers
*/
void init_vm(VirtualMachine *vm) {
int kvm_fd = open("/dev/kvm", O_RDWR | O_CLOEXEC);
if (kvm_fd < 0) { perror("open /dev/kvm"); exit(1); }
// 1. Create a new VM
vm->vm_fd = ioctl(kvm_fd, KVM_CREATE_VM, 0);
if (vm->vm_fd < 0) { perror("KVM_CREATE_VM"); exit(1); }
// 2. Allocate memory for the VM (User space -> Guest Physical)
vm->mem = mmap(NULL, RAM_SIZE, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE, -1, 0);
memcpy(vm->mem, vm->code, vm->code_len);
struct kvm_userspace_memory_region region = {
.slot = 0,
.guest_phys_addr = 0,
.memory_size = RAM_SIZE,
.userspace_addr = (unsigned long)vm->mem,
};
ioctl(vm->vm_fd, KVM_SET_USER_MEMORY_REGION, ®ion);
// 3. Create a Virtual CPU (VCPU)
vm->vcpu_fd = ioctl(vm->vm_fd, KVM_CREATE_VCPU, 0);
// 4. Map the KVM_RUN structure (Communication bus between Host and Guest)
int mmap_size = ioctl(kvm_fd, KVM_GET_VCPU_MMAP_SIZE, 0);
vm->kvm_run = mmap(NULL, mmap_size, PROT_READ | PROT_WRITE, MAP_SHARED, vm->vcpu_fd, 0);
// 5. Setup Registers (Real Mode 16-bit)
struct kvm_sregs sregs;
ioctl(vm->vcpu_fd, KVM_GET_SREGS, &sregs);
sregs.cs.base = 0; sregs.cs.selector = 0;
ioctl(vm->vcpu_fd, KVM_SET_SREGS, &sregs);
struct kvm_regs regs = {
.rflags = 0x2, // Default flags
.rip = 0 // Instruction Pointer starts at 0
};
ioctl(vm->vcpu_fd, KVM_SET_REGS, ®s);
close(kvm_fd); // We don't need the main handle anymore
}
/*
* VM THREAD LOOP
* This acts as the hypervisor loop for a specific VM.
*/
void *run_vm(void *arg) {
VirtualMachine *vm = (VirtualMachine *)arg;
init_vm(vm);
printf("[Host] VM %d started.\n", vm->id);
while (1) {
// Run the VCPU! This blocks until the VM exits (IO, HLT, Error)
ioctl(vm->vcpu_fd, KVM_RUN, 0);
switch (vm->kvm_run->exit_reason) {
// VM wants to read/write to an I/O port
case KVM_EXIT_IO:
if (vm->kvm_run->io.direction == KVM_EXIT_IO_OUT && vm->kvm_run->io.port == 0x10) {
// Get the byte the guest pushed
char *p = (char *)((unsigned char *)vm->kvm_run + vm->kvm_run->io.data_offset);
printf("[VM %d] Says: %d\n", vm->id, *p);
}
break;
// VM executed the HLT instruction
case KVM_EXIT_HLT:
printf("[Host] VM %d halted naturally.\n", vm->id);
return NULL;
case KVM_EXIT_FAIL_ENTRY:
printf("[Host] VM %d Entry Failed\n", vm->id);
return NULL;
default:
printf("[Host] VM %d Unhandled exit reason: %d\n", vm->id, vm->kvm_run->exit_reason);
return NULL;
}
}
}
int main() {
/*
* GUEST CODE 1 (Assembly):
* mov al, 42
* out 0x10, al ; Output value 42 to port 0x10
* hlt ; Stop
*/
const unsigned char code1[] = {
0xB0, 42, // mov al, 42
0xE6, 0x10, // out 0x10, al
0xF4 // hlt
};
/*
* GUEST CODE 2 (Assembly):
* mov al, 10
* add al, 5 ; 10 + 5 = 15
* out 0x10, al ; Output result to port 0x10
* hlt
*/
const unsigned char code2[] = {
0xB0, 10, // mov al, 10
0x04, 0x05, // add al, 5
0xE6, 0x10, // out 0x10, al
0xF4 // hlt
};
pthread_t t1, t2;
VirtualMachine vm1 = { .id = 1, .code = code1, .code_len = sizeof(code1) };
VirtualMachine vm2 = { .id = 2, .code = code2, .code_len = sizeof(code2) };
// Spawn two VMs simultaneously
pthread_create(&t1, NULL, run_vm, &vm1);
pthread_create(&t2, NULL, run_vm, &vm2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
printf("[Host] All VMs finished.\n");
return 0;
}
How to Run
- Verify KVM permissions: You usually need sudo or need to be in the
kvm group.
ls -l /dev/kvm
- Compile:
gcc simple_hypervisor.c -o hypervisor -lpthread
- Run:
./hypervisor
How it Works
-
The API (/dev/kvm):
Instead of writing direct assembly to handle CPU modes (which is what a Type-1 bare metal hypervisor does), we ask the Linux Kernel to do it. We open a file descriptor to KVM.
-
VM Initialization (ioctl):
KVM_CREATE_VM: Creates a sandbox.
KVM_SET_USER_MEMORY_REGION: We malloc standard RAM in our host program, then tell KVM, "treat this pointer as physical address 0 inside the guest."
KVM_CREATE_VCPU: Creates a virtual processor core.
-
Real Mode (16-bit):
x86 processors start in "Real Mode" (compatibility mode from the 1980s). We set the Instruction Pointer (RIP) to 0, meaning the CPU starts executing bytes at the very beginning of the memory we allocated.
-
The Guest Code:
We inject raw hex machine code into the memory.
- VM 1 Code: Moves
42 into register AL. Calls OUT 0x10, AL.
- VM 2 Code: Does
10 + 5. Calls OUT 0x10, AL.
-
The Exit Handler (The Hypervisor Loop):
When we call KVM_RUN, the CPU switches context. The host OS pauses, and the Guest OS runs directly on the hardware.
The Guest runs until it hits an instruction the hardware can't handle or involves hardware I/O (like out 0x10). The CPU pauses the Guest and returns control to our C program.
- We catch
KVM_EXIT_IO.
- We check if it's port
0x10.
- We read the data associated with that event and print it.
- Normally, we would update the registers and tell the VM to resume, but here we just let it hit
hlt.
-
Concurrency:
Because we wrap the KVM logic in pthread, both VMs are running on separate host CPU threads simultaneously, demonstrating multi-VM capabilities.