There will be times when I want to explain a particular bit of bare-metal or low-level systems detail.
This is often easiest by running a bare-metal application, one which does not require an operating system.
Of course, not everyone has spare hardware lying around, making QEMU/KVM a perfect tool for these demonstrations.
In the spirit of keeping things simple, however, I'd rather not constantly build a bootloader, copy our code to memory, and set up the x86 execution environment.
Sure, we could use UEFI for this, but this brings its own set of complexities like a filesystem.
I'm going to demonstrate what I found to be the simplest way to run a bare-metal 32-bit x86 application on QEMU with the fewest moving parts, using Zig because I really enjoy systems programming in it.
All the code in this post can be found at https://github.com/AllHailTheTopology/zig-bootstrap.
The Multiboot loader
The x86 QEMU machine implements a Multiboot V1 loader, driven by the -kernel flag.
Multiboot is an application-loading specification that, when implemented by both bootloaders and application images, allows the image to be automatically loaded by the bootloader.
There are v1 and v2 versions, but QEMU x86 machines only implement the V1 standard.
I'll leave it up to the reader to dig into the full specification; we'll cover just what we need to get our bare-metal app running.
A Multiboot v1 image contains a Multiboot v1 header within the first 8192 bytes of the bare-metal application image; canonically, this header is simply the first several bytes of the image.
Within this header, we'll need to place a magic value which signals to QEMU that the ELF binary is indeed a Multiboot V1 image.
Once QEMU sees the Multiboot V1 header in the ELF binary, it will use the ELF headers to load the binary into memory and jump to the ELF-provided entry point.
Where the binary is loaded into memory corresponds to the ELF segments' load addresses.
When the QEMU loader jumps to your bare-metal application, the system will be in a standard state, and the EBX register will point to an information record.
The system will be in 32-bit protected mode, and the bare-metal application is free to change to 64-bit mode if the selected virtual CPU supports long mode.
So, if we require a very particular binary layout alongside a specific load address of our bare-metal application's segments, the linker is the tool to concentrate on.
This is because the linker is responsible for the ultimate address resolution for sections and the generation of loadable (and non-loadable) segments.
Creating a linker script
One of the jobs of the linker is to take ELF sections from multiple object files and combine them into one large section of the same name and parameters in the output file.
Another job of the linker is to compute both physical addresses, sometimes referred to as load addresses, and virtual addresses for sections and references.
As the linker combines sections, it will update the offset of the start of the section along with references to data and code.
As application developers, we seldom think about the linker because our linkers use standard configurations that craft binary layouts the operating system knows how to load.
For our Multiboot V1 bare-metal application, however, we must tell the linker the exact binary layout of the resulting image, along with where to load it, and what symbol to jump to to begin execution.
This can all be done with a linker script.
bootstrap.lds
ENTRY(_start)
SECTIONS {
. = 1M;
.multiboot : {
KEEP(*(.multiboot))
}
.text ALIGN(4K) : {
*(.text .text.*)
}
.rodata ALIGN(4K) : {
*(.rodata .rodata.*)
}
.data ALIGN(4K) : {
*(.data .data.*)
}
.bss ALIGN(4K) : {
bss_start = .;
*(.bss .bss.*)
. = ALIGN(4K);
bss_end = .;
}
.stack ALIGN(4K) (NOLOAD) : {
. = . + 16K;
stack = .;
}
}This linker script first declares the entry point symbol with the ENTRY command.
This will encode in the ELF header what symbol's address to jump to, and the QEMU loader will utilize this to execute our bare-metal application.
Next, we start a SECTIONS stanza where we can tell the linker exactly how we expect the binary to be laid out in memory.
As the linker lays out our binary, it keeps track of the next address to use in the . variable.
We immediately set the linker's address to 0x100000, the 1-megabyte boundary.
By doing so, we are effectively placing the first section .multiboot at the physical load address of 0x100000, which is the canonical address to load a kernel or bare-metal application, at least for toy kernels and systems.
After this, we begin to lay out our binary image; the .multiboot section will contain our Multiboot V1 header and will always reside within the 8192-byte limit since it's the very first section in our resulting image.
The following sections are the standard ELF sections used in C host environments, which cover most compiled languages on Linux, including Zig.
Aligning each section to a 4K page is a best practice, ensuring the main runtime sections start on separate page boundaries and can maintain their own paging permissions.
This is really more of a concern if you want to enable paging later in your bare-metal application.
A cool thing we can do in our linker script as well is to define global variables and reference them in our Zig code.
We do this for the following variables:
bss_start, bss_end: The half-open range covering the BSS section, helpful for zeroing it out.
stack: The top of our hardware stack, which grows down. The stack pointer (ESP) must be set to this address to support the C environment.
We define our stack as a section to ensure QEMU reserves this space as it loads our bare-metal application.
If we did not, QEMU would put some metadata, available to our bare-metal application as a convenience, in the space we want our stack to be.
The Zig bootstrap
With the linker script finalized, we can write our Zig bootstrap code which will be compiled as a free-standing (no glibc linking) binary.
main.zig
const qemu = @import("debug.zig");
const multiboot = @import("multiboot.zig");
// Variables generated by the linker.
extern var bss_start: u8;
extern var bss_end: u8;
extern var stack: u8;
// Multiboot v1 header, must be within the first 8192 bytes of the ELF file.
// Placed in its own section at the beginning of the linker script's layout.
export const header: [3]u32 align(4) linksection(".multiboot") = .{
// magic
multiboot.MULTIBOOT_MAGIC,
// flags
0,
// checksum, -% forces unsigned wrap around subtraction.
-%@as(u32, multiboot.MULTIBOOT_MAGIC),
};
// Multiboot v1 entry point.
// Set up the stack, then call the Zig kernel entry using the C ABI.
// The EBX register holds the multiboot information structure and will
// be passed as the only argument to startKernel.
export fn _start() callconv(.naked) noreturn {
asm volatile (
\\movl $stack, %%esp
\\cld
\\sub $12, %%esp
\\push %%ebx
\\call startKernel
);
}
// kernel initialization routine.
export fn startKernel(info: *multiboot.mb_info) noreturn {
// clear the BSS section
const bss: [*]u8 = @ptrCast(&bss_start);
const bss_len = @intFromPtr(&bss_end) - @intFromPtr(&bss_start);
@memset(bss[0..bss_len], 0);
qemu.writeString("Hello World!!\n");
if (info.flags > 0) {
qemu.writeString("Multiboot information available.");
}
// The world is your oyster from here...
while (true) {
asm volatile ("hlt");
}
}multiboot.zig
pub const MULTIBOOT_MAGIC = 0x1BADB002;
pub const mb_info = extern struct {
flags: u32,
mem_lower: u32,
mem_upper: u32,
boot_device: u32,
cmdline: u32,
mods_count: u32,
mods_addr: u32,
syms: [16]u8,
mmap_length: u32,
mmap_addr: u32,
drives_length: u32,
drives_addr: u32,
config_table: u32,
boot_loader_name: u32,
apm_table: u32,
vbe_control_info: u32,
vbe_mode_info: u32,
vbe_mode: u16,
vbe_interface_seg: u16,
vbe_interface_off: u16,
vbe_interface_len: u16,
};Our main.zig file imports two Zig modules: debug.zig, which we will cover in the following section, and multiboot.zig, which simply holds the model for the Multiboot V1 information record and Multiboot-related constants.
Next, we define our variables created by the linker as extern; their references will be resolved by the linker, which defines those variables within our linker script.
Next, we define the Multiboot v1 header in its own .multiboot section that will be placed first into the output binary.
Our ENTRYPOINT is defined next, where we set up our hardware stack and use the call assembly function to jump to startKernel.
Just prior to the call instruction, we configure the stack to push the pointer in EBX as the only argument to the startKernel routine.
We need our entry point to declare the callconv(.naked) attribute so the Zig compiler does not generate any calling convention instructions; we just need to stub in some assembly and call our startKernel routine.
We use the call assembly function since C functions expect to be entered with ESP+4, where 4 bytes is the size of the return address pushed to the stack via the instruction.
startKernel is declared with the export attribute, making Zig use the C calling convention for this function.
startKernel can now call into Zig code or other C code.
We can now introduce the build file to build the binary.
build.zig
const std = @import("std");
pub fn build(b: *std.Build) void {
const bootstrap = b.addExecutable(.{
.name = "bootstrap",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = b.resolveTargetQuery(.{
.cpu_arch = .x86,
.os_tag = .freestanding,
.abi = .none,
}),
.optimize = b.standardOptimizeOption(.{}),
}),
.use_llvm = true,
.use_lld = true,
});
bootstrap.setLinkerScript(b.path("bootstrap.lds"));
b.installArtifact(bootstrap);
}And let's introduce a Makefile for convenience.
Makefile
.PHONY: bootstrap run run-debug
bootstrap:
zig build -Doptimize=ReleaseSafe
run:
qemu-system-i386 -nographic -kernel ./zig-out/bin/bootstrap
run-debug:
qemu-system-i386 -S -s -nographic -kernel ./zig-out/bin/bootstrap \
-debugcon file:debug.logTesting our bootstrap
We need a way to prove we entered our bare-metal application.
Luckily, QEMU has us covered once again and provides an x86 I/O port that, when written to, can output to various devices.
Let's introduce a small debug printer to our project.
qemu/debug.zig
/// Methods for writing to QEMU's virtual console.
/// The virtual console's output facility is defined by the -debugcon flag; see
/// the MAN page for more details.
const DEBUG_IO_PORT: u16 = 0xE9;
pub fn writeByte(byte: u8) void {
asm volatile (
\\outb %[byte], %[port]
:
: [byte] "{al}" (byte),
[port] "{dx}" (DEBUG_IO_PORT),
);
}
pub fn writeString(string: []const u8) void {
for (string) |byte| {
writeByte(byte);
}
}The above will write a string, one character at a time, to the virtual port QEMU implements.
Both our bootstrap source code above and our Makefile already take advantage of this function.
Let's run make, generate the binary, and take a look at the ELF headers.
$ readelf --all zig-out/bin/bootstrap
ELF Header:
Magic: 7f 45 4c 46 01 01 01 00 00 00 00 00 00 00 00 00
Class: ELF32
Data: 2's complement, little endian
Version: 1 (current)
OS/ABI: UNIX - System V
ABI Version: 0
Type: EXEC (Executable file)
Machine: Intel 80386
Version: 0x1
Entry point address: 0x1010d0
Start of program headers: 52 (bytes into file)
Start of section headers: 684888 (bytes into file)
Flags: 0x0
Size of this header: 52 (bytes)
Size of program headers: 32 (bytes)
Number of program headers: 5
Size of section headers: 40 (bytes)
Number of section headers: 19
Section header string table index: 17
Section Headers:
[Nr] Name Type Addr Off Size ES Flg Lk Inf Al
[ 0] NULL 00000000 000000 000000 00 0 0 0
[ 1] .multiboot PROGBITS 00100000 001000 00000c 00 A 0 0 4
[ 2] .eh_frame_hdr PROGBITS 0010000c 00100c 000024 00 A 0 0 4
[ 3] .eh_frame PROGBITS 00100030 001030 000098 00 A 0 0 4
[ 4] .text PROGBITS 00101000 002000 0001c5 00 AX 0 0 16
[ 5] .bss NOBITS 00102000 003000 000000 00 WA 0 0 1
[ 6] .stack NOBITS 00102000 003000 004000 00 WA 0 0 1
[ 7] .debug_loc PROGBITS 00000000 003000 0423f9 00 0 0 1
[ 8] .debug_abbrev PROGBITS 00000000 0453f9 000768 00 0 0 1
[ 9] .debug_info PROGBITS 00000000 045b61 031202 00 0 0 1
[10] .debug_str PROGBITS 00000000 076d63 00b585 01 MS 0 0 1
[11] .debug_pubnames PROGBITS 00000000 0822e8 004b6a 00 0 0 1
[12] .debug_pubtypes PROGBITS 00000000 086e52 0010e7 00 0 0 1
[13] .debug_line PROGBITS 00000000 087f39 01a93f 00 0 0 1
[14] .debug_ranges PROGBITS 00000000 0a2878 004890 00 0 0 1
[15] .comment PROGBITS 00000000 0a7108 00001c 01 MS 0 0 1
[16] .symtab SYMTAB 00000000 0a7124 0000e0 10 18 8 4
[17] .shstrtab STRTAB 00000000 0a7204 0000c3 00 0 0 1
[18] .strtab STRTAB 00000000 0a72c7 000090 00 0 0 1
Key to Flags:
W (write), A (alloc), X (execute), M (merge), S (strings), I (info),
L (link order), O (extra OS processing required), G (group), T (TLS),
C (compressed), x (unknown), o (OS specific), E (exclude),
D (mbind), p (processor specific)
There are no section groups in this file.
Program Headers:
Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align
LOAD 0x001000 0x00100000 0x00100000 0x000c8 0x000c8 R 0x1000
LOAD 0x002000 0x00101000 0x00101000 0x001c5 0x001c5 R E 0x1000
LOAD 0x003000 0x00102000 0x00102000 0x00000 0x04000 RW 0x1000
GNU_EH_FRAME 0x00100c 0x0010000c 0x0010000c 0x00024 0x00024 R 0x4
GNU_STACK 0x000000 0x00000000 0x00000000 0x00000 0x1000000 RW 0
Section to Segment mapping:
Segment Sections...
00 .multiboot .eh_frame_hdr .eh_frame
01 .text
02 .bss .stack
03 .eh_frame_hdr
04 .bss .stack
There is no dynamic section in this file.
There are no relocations in this file.
No processor specific unwind information to decode
Symbol table '.symtab' contains 14 entries:
Num: Value Size Type Bind Vis Ndx Name
0: 00000000 0 NOTYPE LOCAL DEFAULT UND
1: 00000000 0 FILE LOCAL DEFAULT ABS bootstrap
2: 00101000 197 FUNC LOCAL DEFAULT 4 main.startKernel
3: 001010d0 17 FUNC LOCAL DEFAULT 4 main._start
4: 00100000 12 OBJECT LOCAL DEFAULT 1 main.header
5: 00000000 0 FILE LOCAL DEFAULT ABS compiler_rt
6: 001010f0 213 FUNC LOCAL DEFAULT 4 compiler_rt.fastMemset
7: 001010f0 213 FUNC LOCAL HIDDEN 4 memset
8: 00102000 0 NOTYPE GLOBAL DEFAULT 5 bss_end
9: 00102000 0 NOTYPE GLOBAL DEFAULT 5 bss_start
10: 00106000 0 NOTYPE GLOBAL DEFAULT 6 stack
11: 00101000 197 FUNC GLOBAL DEFAULT 4 startKernel
12: 001010d0 17 FUNC GLOBAL DEFAULT 4 _start
13: 00100000 12 OBJECT GLOBAL DEFAULT 1 headerWe can see our linker variables defined and our section layout just like we wanted.
We can also see our physical load addresses in the Program Headers section.
Running make run-debug will run our bare-metal application in QEMU, allow us to attach GDB to it, and write to a log file at ./debug.log.
I like to do this so I can inspect the execution of the bare-metal application closely.
$ make run-debug In another terminal, you can use gdb to connect to the bootstrap machine and set a breakpoint on the startKernel routine.
$ gdb -ex "target remote :1234" -ex "tui enable" ./zig-out/bin/bootstrap
(gdb) break startKernel
Breakpoint 1 at 0x101000: file main.zig, line 38.
(gdb) continue
Continuing.
Breakpoint 1, main.startKernel (info=0x9500) at main.zig:38
38 const bss_len = @intFromPtr(&bss_end) - @intFromPtr(&bss_start);
(gdb) next
39 @memset(bss[0..bss_len], 0);
(gdb)You can step the debugger over our debug function and confirm a debug.log file is created and the hello world string is present in it.
Where to go from here?
We now have a very simple bare-metal application running on a virtual x86 system.
It's possible to now extend this bootstrap to demonstrate low-level OS concepts like APIC programming, PCIe concepts, etc.
In fact, we will be using this bootstrap for just that in the near future!



I love this