Skip to content
systemcoding.dev
Assembly

The Complete Guide to Writing a Bootloader in Assembly

Build an x86 bootloader in NASM from a 512-byte boot sector to a loaded kernel, covering disk reads, A20, the memory map, protected mode and long mode.

29 min read
Summarize in AI
Flat illustration of an assembly listing with addresses and mnemonics, with the Linux, Intel and Arm logos.

A bootloader is the first code you write that runs on a machine with nothing under it. There is no operating system to call, no standard library and no debugger attached. The processor wakes up in a mode designed in 1978, the firmware hands you 512 bytes at a fixed address, and everything after that is yours: finding the rest of your own code on disk, learning how much memory the machine has, climbing from 16-bit real mode to 32-bit protected mode and then to 64-bit long mode, and handing control to a kernel. It is a small program, usually well under two thousand lines, and writing one is the fastest way to learn how an x86 computer really starts.

This guide builds a complete two-stage BIOS bootloader in NASM 2.16, tested in QEMU 9 and written for a PC that boots from a legacy BIOS. It starts with the 512-byte sector, then adds each capability in the order a real bootloader needs it: diagnostics, a disk read, the A20 line, the memory map, the switch to protected mode, loading a kernel above 1 MiB and finally the switch to long mode. Each section is a working piece you can assemble and run before moving to the next. The guide assumes you can read basic assembly and know what a register is. If you have never looked at compiler output, the guide on reading compiler-generated assembly is a good warm-up, and the shorter posts in this series on the boot sector, BIOS printing, the MBR layout, extended disk reads and A20 each cover one section here in more depth.

Code in this guide is written against the documented behavior of the BIOS, the Intel architecture manuals and NASM. It is meant to be typed in and built, and each listing is complete enough to do that, but the part of it you should trust most is the structure: the order of operations in each stage is dictated by the hardware, and getting that order wrong is the cause of nearly every failure.

What a bootloader has to do

The path from power-on to a running kernel is a relay, and each runner is limited by what the previous one could do. When the machine starts, the firmware, the BIOS, initializes the hardware and looks for a bootable device. It reads the first 512 bytes of the device, the boot sector, to the physical address 0x7C00, checks that the last two bytes are 0x55 and 0xAA, and jumps to the first byte. The CPU is in real mode, a 16-bit mode in which addresses are formed from a segment and an offset and only the first megabyte of memory is reachable. The BIOS leaves the number of the boot drive in the dl register.

512 bytes is not enough for anything useful, so the first job of that sector, the first stage, is to load a larger second stage from disk. The second stage has room to do the real work: print diagnostics, enable access to memory above 1 MiB, ask the BIOS for a map of the machine's memory while the BIOS is still available, load the kernel, switch the CPU to protected or long mode and jump to the kernel. It is the last thing that can call the BIOS, since both protected and long mode have no use for the real-mode interrupt table.

The relay therefore looks like this:

StageWhere it runsModeSize limitJob
BIOSROMRealNoneInitialize hardware, load sector 0 to 0x7C00
Stage 10x7C00Real446 to 510 bytesLoad stage 2 from disk, jump to it
Stage 20x7E00Real, then protected, then longSeveral KiBA20, memory map, load kernel, mode switches
Kernel0x100000Protected or longNoneYour operating system

The design principle is to keep stage 1 as small as possible and put every feature in stage 2, because stage 1 has no room and no way to be updated without rewriting the sector.

The toolchain and layout

You need three tools: NASM to assemble, make to run the steps and QEMU to run the result. A C compiler is optional until the kernel. Install NASM and QEMU from your distribution, for example apt install nasm qemu-system-x86 make.

Lay out a project like this:

Text
boot/
  Makefile
  stage1.asm
  stage2.asm
  kernel.asm

The Makefile builds each stage as a flat binary and concatenates them into one disk image. Flat binary output, the -f bin format, is what a bootloader needs: no headers, no relocations, just the bytes in the order they will sit in memory.

MakefileText
all: disk.img

stage1.bin: stage1.asm
	nasm -f bin $< -o $@

stage2.bin: stage2.asm
	nasm -f bin $< -o $@

kernel.bin: kernel.asm
	nasm -f bin $< -o $@

disk.img: stage1.bin stage2.bin kernel.bin
	cat stage1.bin stage2.bin kernel.bin > $@
	truncate -s 1M $@

run: disk.img
	qemu-system-x86_64 -drive format=raw,file=disk.img -no-reboot

debug: disk.img
	qemu-system-x86_64 -drive format=raw,file=disk.img -no-reboot -S -gdb tcp::1234

clean:
	rm -f *.bin disk.img

The image has the first stage at LBA 0, the second at LBA 1 and the kernel after it. truncate -s 1M pads the image so that every read the loader makes lands inside the file. The convention used throughout is that stage 1 loads exactly STAGE2_SECTORS sectors starting at LBA 1, and stage 2 is padded to that size.

The run target adds -no-reboot, which makes QEMU exit on a triple fault instead of resetting forever, and the debug target pauses the CPU and opens a GDB server on port 1234. Both options get used often.

Stage 1: the boot sector

The first stage has four jobs: put the CPU in a known state, remember which drive it booted from, check that the BIOS offers the extended disk services, and read stage 2.

stage1.asmnasm
bits 16
org 0x7C00

STAGE2_SECTORS equ 8
STAGE2_ADDR    equ 0x7E00

start:
    cli
    xor  ax, ax
    mov  ds, ax
    mov  es, ax
    mov  ss, ax
    mov  sp, 0x7C00
    sti
    cld
    mov  [boot_drive], dl

    mov  ah, 0x41
    mov  bx, 0x55AA
    int  0x13
    jc   fail
    cmp  bx, 0xAA55
    jne  fail

    mov  si, dap
    mov  ah, 0x42
    mov  dl, [boot_drive]
    int  0x13
    jc   fail

    mov  dl, [boot_drive]
    jmp  0x0000:STAGE2_ADDR

fail:
    mov  si, msg_fail
.p: lodsb
    test al, al
    jz   .h
    mov  ah, 0x0E
    int  0x10
    jmp  .p
.h: cli
    hlt
    jmp  .h

boot_drive: db 0
msg_fail:   db "stage1: disk error", 0

dap:
    db   0x10, 0
    dw   STAGE2_SECTORS
    dw   STAGE2_ADDR
    dw   0
    dq   1

times 510 - ($ - $$) db 0
dw 0xAA55

Several details here matter, and each is a lesson learned from a real failure.

The segment registers are set explicitly. The BIOS may enter at 0000:7C00 or 07C0:0000, which are the same physical address with different segment values, and code that assumes one breaks on a machine that does the other. Setting ds, es and ss to zero and using org 0x7C00 makes every label an offset from physical zero.

The stack sits at 0x7C00 and grows downward, below the sector. Interrupts are disabled while ss and sp change, because an interrupt arriving between the two instructions would push onto a stack that is not yet valid. The cld clears the direction flag so that lodsb and the string instructions step forward, since the BIOS does not promise it.

The boot drive is saved in memory immediately. dl is overwritten by any BIOS call that touches it, and every later disk read needs it. A bootloader that reads from the wrong drive is a common mistake that only shows up when you boot from something other than the first hard disk.

The extended read, function 0x42, takes a disk address packet that holds the sector count, the destination segment and offset and the 64-bit starting LBA. Here it asks for eight sectors from LBA 1 into 0x7E00, which is the memory directly after the boot sector. The earlier post on the extended read covers the packet and error codes.

When the read succeeds, stage 1 reloads dl so stage 2 receives the drive number in the same register the BIOS used, then far-jumps to 0000:7E00. That jump also sets cs to zero, so both stages agree on the segment.

The padding line makes the file exactly 510 bytes of code and data followed by the signature. NASM fails the build if the stage grows past 510, so you find out at assembly time.

Diagnostics: a print routine that every stage reuses

Stage 2 starts with two routines you will use constantly. Put them in a file print16.inc that stage 2 includes:

print16.incnasm
; print_string: ds:si -> zero-terminated string
print_string:
    pusha
    mov  ah, 0x0E
    xor  bh, bh
.next:
    lodsb
    test al, al
    jz   .done
    int  0x10
    jmp  .next
.done:
    popa
    ret

; print_hex: print the 16-bit value in ax as four hex digits
print_hex:
    pusha
    mov  cx, 4
    mov  dx, ax
.digit:
    rol  dx, 4
    mov  bx, dx
    and  bx, 0x000F
    mov  al, [hexdigits + bx]
    mov  ah, 0x0E
    int  0x10
    loop .digit
    popa
    ret

hexdigits: db "0123456789ABCDEF"

These save and restore every register with pusha and popa, so a call never disturbs the caller's state. That costs a few bytes, which stage 2 can afford and stage 1 cannot. The point of print_hex is debugging: printing the value of a register or an error code in hexadecimal is the first tool you reach for when something fails, and without it a failing read gives you a hang and no information.

Stage 2 skeleton

Stage 2 begins at 0x7E00 in real mode. Start with a skeleton that prints a banner and halts, and add the rest one section at a time:

stage2.asmnasm
bits 16
org 0x7E00

KERNEL_LOAD_SEG  equ 0x1000       ; physical 0x10000
KERNEL_SECTORS   equ 16
KERNEL_LBA       equ 9            ; after stage 1 and 8 stage-2 sectors
MMAP_BUFFER      equ 0x9000

stage2_start:
    mov  [boot_drive], dl
    mov  si, msg_banner
    call print_string

    call enable_a20
    call detect_memory
    call load_kernel
    jmp  enter_protected_mode

%include "print16.inc"

boot_drive:  db 0
msg_banner:  db "stage2: hello", 13, 10, 0

%include pulls the print routines into the same output file. The constants at the top name the layout in one place. The kernel is read to physical address 0x10000, 64 KiB, because real mode can only reach below 1 MiB with segment arithmetic. The protected-mode code will later copy it to 0x100000, the 1 MiB mark, where most kernels expect to live.

Pad stage 2 to a fixed size so that the kernel begins at a known LBA. This line must stay the last line of the file as you add the sections that follow:

nasm
times (8 * 512) - ($ - $$) db 0

If stage 2 grows past eight sectors, NASM reports a negative count and the build fails, at which point you raise STAGE2_SECTORS in stage 1 and KERNEL_LBA here together. Keeping those two numbers in step is the main bookkeeping chore of a multi-stage bootloader, and a shared include file with the constants is worth the trouble once you have more than a few.

The A20 line

The first thing stage 2 does with the hardware is open the A20 line. The 8086 had 20 address lines, so addresses above 1 MiB wrapped around to zero, and when later processors added a 21st line, the PC gated it off by default for compatibility with software that relied on the wrap. Until the gate is open, bit 20 of every address is forced to zero, and every odd-numbered megabyte aliases the one below it. Your kernel at 0x100000 would overwrite your real-mode data at 0x000000.

Enabling it takes a test and up to three methods. First, test, because on many machines and in QEMU the line is already open:

nasm
check_a20:
    pushf
    push ds
    push es
    push di
    push si
    cli
    xor  ax, ax
    mov  es, ax
    mov  di, 0x0500
    not  ax
    mov  ds, ax
    mov  si, 0x0510
    mov  al, [es:di]
    push ax
    mov  al, [ds:si]
    push ax
    mov  byte [es:di], 0x00
    mov  byte [ds:si], 0xFF
    cmp  byte [es:di], 0xFF
    pop  ax
    mov  [ds:si], al
    pop  ax
    mov  [es:di], al
    mov  ax, 0
    je   .out
    mov  ax, 1
.out:
    pop  si
    pop  di
    pop  es
    pop  ds
    popf
    ret

The test writes different values to 0000:0500 and FFFF:0510. With the line closed, both addresses are physical 0x000500, so the second write overwrites the first and the comparison sees 0xFF. It restores both bytes before returning, and returns 1 in ax if the line is open. The dedicated post on A20 walks through this test in detail.

Then enable it, trying the safest method first and testing after each:

nasm
enable_a20:
    call check_a20
    test ax, ax
    jnz  .done
    mov  ax, 0x2401
    int  0x15
    call check_a20
    test ax, ax
    jnz  .done
    in   al, 0x92
    test al, 2
    jnz  .skip
    or   al, 2
    and  al, 0xFE
    out  0x92, al
.skip:
    call check_a20
    test ax, ax
    jnz  .done
    mov  si, msg_a20
    call print_string
    cli
    hlt
.done:
    ret

msg_a20: db "A20 failed", 0

The BIOS call int 0x15 with ax = 0x2401 is the polite method. The fast gate through port 0x92 is the next. The code sets bit 1 and clears bit 0, because writing a 1 to bit 0 of that port resets the machine. A fuller loader adds the keyboard-controller method as a third fallback, and the A20 post gives that routine. When every method fails, the loader prints a message and halts, because continuing would corrupt memory in ways that are hard to trace.

Asking the BIOS for the memory map

A kernel needs to know which parts of physical memory are usable, and the only reliable source is the firmware. The BIOS answers through int 0x15 function 0xE820, which returns one range at a time: its base address, its length and a type. The types that matter are 1 for usable RAM, 2 for reserved, 3 for ACPI tables that can be reclaimed, 4 for ACPI non-volatile storage and 5 for bad memory. A kernel that ignores the map and assumes all memory above 1 MiB is free will eventually overwrite a firmware table or a memory-mapped device.

The call is a loop. Each call takes a continuation value in ebx, starting at zero, and returns the next one, which is zero when the list is finished:

nasm
detect_memory:
    xor  ebx, ebx
    xor  bp, bp
    mov  di, MMAP_BUFFER + 4
.next:
    mov  eax, 0xE820
    mov  edx, 0x534D4150            ; "SMAP"
    mov  ecx, 24
    mov  dword [es:di + 20], 1
    int  0x15
    jc   .done
    cmp  eax, 0x534D4150
    jne  .fail
    jcxz .skip
    inc  bp
    add  di, 24
.skip:
    test ebx, ebx
    jnz  .next
.done:
    mov  [MMAP_BUFFER], bp
    ret
.fail:
    mov  si, msg_mmap
    call print_string
    cli
    hlt

msg_mmap: db "E820 failed", 0

The code stores each entry in a 24-byte slot starting at MMAP_BUFFER + 4, with the number of entries in the first four bytes. Entry layout is a 64-bit base, a 64-bit length, a 32-bit type and a 32-bit attribute field, which the call writes into es:di. The line mov dword [es:di + 20], 1 presets the extended attributes to 1 before the call, so a BIOS that writes only 20 bytes still leaves a valid value. The magic 0x534D4150 is the ASCII SMAP, which the BIOS echoes back in eax if it supports the call, and a mismatch on the first call means the service is not there. Carry set after a call, with ebx zero, means the list ended. jcxz skips an entry the BIOS returned with zero length, since some firmware does.

After the loop the table sits at 0x9000, below the 64 KiB mark where the kernel will land, and the kernel finds it by a fixed address agreed in the boot protocol. Printing it during development is useful, and the print routines make that a loop over the entries. Real memory maps have gaps and overlapping reservations, and a robust kernel sorts and merges them. The ACPI specification documents the E820 types, and the type 1 ranges are the only ones a kernel allocator should hand out.

Loading the kernel

The kernel is a flat binary appended to the image after stage 2. Stage 2 reads it into low memory with the extended read, which the BIOS can only target below 1 MiB, in chunks so that no single read crosses a 64 KiB boundary:

nasm
load_kernel:
    mov  word [kdap + 2], 16               ; sectors per read
    mov  word [kdap + 4], 0                ; offset
    mov  word [kdap + 6], KERNEL_LOAD_SEG  ; segment
    mov  dword [kdap + 8], KERNEL_LBA      ; low dword of the LBA
    mov  cx, KERNEL_SECTORS / 16
.read:
    push cx
    mov  si, kdap
    mov  ah, 0x42
    mov  dl, [boot_drive]
    int  0x13
    jc   .error
    add  word [kdap + 6], 0x200            ; next 8 KiB: 16 sectors = 0x200 paragraphs
    add  dword [kdap + 8], 16
    pop  cx
    loop .read
    ret
.error:
    mov  al, ah
    xor  ah, ah
    call print_hex
    mov  si, msg_disk
    call print_string
    cli
    hlt

kdap:
    db   0x10, 0
    dw   16
    dw   0
    dw   KERNEL_LOAD_SEG
    dq   KERNEL_LBA
msg_disk: db " disk error", 0

The packet is a data structure in memory that the loop edits between calls: advance the destination segment by 0x200 paragraphs, which is 8 KiB, and the LBA by 16 sectors. Using segment arithmetic for the advance avoids carrying into the offset field. With 16 sectors per call, the read size is 8 KiB, and all reads stay inside the first megabyte. Each failure prints the BIOS error code from ah in hexadecimal, which tells you whether a sector was not found, the drive was not ready or a timeout occurred.

The kernel size is a build-time constant here, KERNEL_SECTORS. A real image would store the size in a header, written by the build, and stage 2 would read the first sector to learn it.

Switching to protected mode

The BIOS cannot run in protected mode, so everything that needs it is finished by now: the video output used for diagnostics, the disk reads and the memory map. The switch has five steps in a fixed order: disable interrupts, load a GDT, set the PE bit in cr0, far-jump to flush the prefetch queue and load cs, and load the data segment registers.

nasm
enter_protected_mode:
    cli
    lgdt [gdt_desc]
    mov  eax, cr0
    or   eax, 1
    mov  cr0, eax
    jmp  dword 0x08:pm_entry

align 8
gdt:
    dq 0x0000000000000000           ; 0x00 null
    dq 0x00CF9A000000FFFF           ; 0x08 32-bit code, flat 4 GiB
    dq 0x00CF92000000FFFF           ; 0x10 32-bit data, flat 4 GiB
    dq 0x00AF9A000000FFFF           ; 0x18 64-bit code
gdt_end:

gdt_desc:
    dw gdt_end - gdt - 1
    dd gdt

A GDT entry packs a base, a limit and access flags into eight bytes. The code descriptor 0x00CF9A000000FFFF reads from the low end as: limit bits 0 to 15 are 0xFFFF, base bits 0 to 23 are zero, access byte 0x9A is present, ring 0, code, readable, then the byte 0xCF holds limit bits 16 to 19 (0xF) and the flags 0xC, meaning 4 KiB granularity and a 32-bit default operand size. With a limit of 0xFFFFF pages, the segment spans 4 GiB. The data descriptor differs only in the access byte, 0x92, writable data. The fourth descriptor, 0x00AF9A000000FFFF, has the flags nibble 0xA, which sets the long-mode bit L and clears the 32-bit D bit, and is the code segment for 64-bit mode. Defining it now means the same table serves both modes.

The far jump jmp dword 0x08:pm_entry does two things. It loads cs with selector 0x08, the 32-bit code descriptor, which is what actually makes the processor execute 32-bit instructions, and it flushes instructions already fetched under the old mode. The dword forces a 32-bit offset in the far pointer. The code after it is assembled for 32-bit mode:

nasm
bits 32
pm_entry:
    mov  ax, 0x10
    mov  ds, ax
    mov  es, ax
    mov  fs, ax
    mov  gs, ax
    mov  ss, ax
    mov  esp, 0x90000

    mov  esi, KERNEL_LOAD_SEG * 16
    mov  edi, 0x100000
    mov  ecx, (KERNEL_SECTORS * 512) / 4
    cld
    rep  movsd

    jmp  0x08:0x100000

The data segments get selector 0x10, the flat data descriptor, and esp is set to a stack in free low memory. With a flat 4 GiB address space, the code can write above 1 MiB, now that A20 is open, so rep movsd copies the kernel from 0x10000 to 0x100000 four bytes at a time. The final far jump enters the kernel with cs still set to the 32-bit code selector.

If the machine reboots instead of reaching the kernel, the cause is a triple fault: an exception with no valid handler. In protected mode with no IDT loaded, any fault becomes a triple fault, so the symptom of a wrong selector, a missing A20 or a bad stack is an immediate reset. QEMU's -d int log, together with -no-reboot, prints the fault and the register state at the moment, which is the way to diagnose it.

A kernel to jump to

To close the loop, write the smallest possible kernel in assembly. It writes a message to the VGA text buffer and halts:

kernel.asmnasm
bits 32
org 0x100000

kernel_start:
    mov  edi, 0xB8000
    mov  esi, msg
    mov  ah, 0x0F
.next:
    lodsb
    test al, al
    jz   .halt
    mov  [edi], ax
    add  edi, 2
    jmp  .next
.halt:
    cli
    hlt
    jmp  .halt

msg: db "Kernel running in 32-bit mode", 0

times (16 * 512) - ($ - $$) db 0

The padding makes the image exactly 16 sectors, matching KERNEL_SECTORS. In this kernel org 0x100000 tells NASM the code runs at 1 MiB, even though it is assembled as a flat file and read to a different place. A kernel written in C is built the same way, with a linker script that places .text at 0x100000 and an --oformat binary output, as the post on calling C from a bootloader shows.

Going on to long mode

A 64-bit kernel needs one more transition: long mode requires paging, so the loader must build page tables first. The minimum is an identity map of the first gigabyte, built from 2 MiB pages so only three tables are needed. Do it in 32-bit code, after the kernel is copied:

nasm
setup_long_mode:
    mov  edi, 0x70000
    xor  eax, eax
    mov  ecx, 0x3000 / 4
    rep  stosd                       ; clear PML4, PDPT and PD

    mov  dword [0x70000], 0x71003    ; PML4[0] -> PDPT, present + writable
    mov  dword [0x71000], 0x72003    ; PDPT[0] -> PD, present + writable

    mov  edi, 0x72000
    mov  eax, 0x00000083             ; present + writable + 2 MiB page
    mov  ecx, 512
.map:
    mov  [edi], eax
    add  eax, 0x200000
    add  edi, 8
    loop .map

    mov  eax, 0x70000
    mov  cr3, eax

    mov  eax, cr4
    or   eax, 1 << 5                 ; PAE
    mov  cr4, eax

    mov  ecx, 0xC0000080             ; IA32_EFER
    rdmsr
    or   eax, 1 << 8                 ; LME
    wrmsr

    mov  eax, cr0
    or   eax, 1 << 31                ; PG
    mov  cr0, eax

    jmp  0x18:long_entry

bits 64
long_entry:
    mov  ax, 0x10
    mov  ds, ax
    mov  es, ax
    mov  ss, ax
    mov  rsp, 0x90000
    mov  rax, 0x100000
    jmp  rax

Follow the sequence, because the order is architectural. Long mode needs physical address extension, so cr4 bit 5 is set. The page tables must be reachable through cr3. The long-mode-enable bit in the IA32_EFER model-specific register, bit 8, is set with rdmsr and wrmsr. Then setting paging, bit 31 of cr0, activates long mode: the processor enters a compatibility sub-mode that still executes 32-bit code under the 64-bit paging rules. The far jump to selector 0x18, the descriptor whose L bit is set, moves it into true 64-bit mode.

Each page-table entry is eight bytes. The value 0x72003 is the address of the next table with the present and writable bits, bits 0 and 1. The page directory entries use 0x83, which adds bit 7, the page-size flag, to make each a 2 MiB mapping, and the loop writes 512 of them, covering 1 GiB. The address in eax advances by 0x200000 each time. Only the low dword of each entry is written because the tables were cleared first, so the upper dword stays zero.

The kernel must be assembled with bits 64 code from 0x100000 onward. When it starts, interrupts are off, the identity map is live and there is no IDT, so the first task of a 64-bit kernel is to install one.

Telling the kernel what the loader learned

A loader collects facts that only it can get: which drive the machine booted from, where the memory map is, how big the kernel is and which video mode is active. The kernel needs them, and the cleanest way to pass them is a small structure at a fixed address with a version number, so both sides can change independently. A minimal one looks like this in the loader's data:

nasm
BOOT_INFO equ 0x8F00

; layout: dword magic, dword boot drive, dword memory map address, dword kernel sectors
fill_boot_info:
    mov  dword [BOOT_INFO + 0],  0x544F4F42       ; "BOOT"
    movzx eax, byte [boot_drive]
    mov  dword [BOOT_INFO + 4],  eax
    mov  dword [BOOT_INFO + 8],  MMAP_BUFFER
    mov  dword [BOOT_INFO + 12], KERNEL_SECTORS
    ret

The kernel reads the magic first and refuses to continue if it is wrong, which turns a silent misconfiguration into a clear failure. Passing the address in a register at the jump, ebx for 32-bit kernels as Multiboot does, is cleaner than a fixed address, because the structure can then live anywhere. In protected mode the call is mov ebx, BOOT_INFO before the jump. Multiboot2 formalizes the idea with a tag list so the loader can add information without breaking old kernels, and following its layout costs little if you ever want to boot under GRUB as well.

Keep the memory map in a place the kernel's own allocator will not reuse until it has copied the map. The simplest rule is to reserve the first megabyte entirely: the map, the boot info, the stack and the page tables are all below 0x100000, and the kernel begins its page allocator above its own end. The kernel copies the map into its own storage early, and only then marks the low megabyte as free.

Retrying reads and supporting floppies

Real disks fail occasionally on the first attempt. A USB stick that was idle may need a moment to spin up, and a floppy needs the motor to start. The BIOS specification's advice is to reset the controller with function 0x00 and try again, and three tries is the usual limit. Wrap the read:

nasm
read_retry:
    mov  bp, 3
.again:
    pusha
    mov  ah, 0x42
    mov  dl, [boot_drive]
    int  0x13
    popa
    jnc  .ok
    xor  ax, ax
    mov  dl, [boot_drive]
    int  0x13                     ; reset the drive
    dec  bp
    jnz  .again
    stc
.ok:
    ret

The pusha and popa around the call preserve registers the BIOS may destroy, and the carry flag survives popa because that instruction does not touch flags. After three failures the routine returns with carry set so the caller can print the error.

Floppy disks and a few old BIOSes do not offer the extended read. For those the loader falls back to the CHS function, ah = 0x02, which needs the drive geometry. Get it from function ah = 0x08, which returns the maximum head in dh and the sectors per track in the low six bits of cl, then convert each LBA to cylinder, head and sector with the standard division: sector is (LBA mod sectors-per-track) + 1, head is (LBA / sectors-per-track) mod heads and cylinder is LBA / (sectors-per-track * heads). Most hobby loaders skip this and target hard disks and USB sticks, which is reasonable, but a guide that claims to cover floppies has to include it. If you ever need it, write the conversion once as a function with the geometry in memory, and test it in QEMU with a floppy image and -fda.

Unreal mode as an alternative to the copy

Everything above reads the kernel into low memory and copies it above 1 MiB after the switch to protected mode. An older trick avoids the intermediate copy: unreal mode. The segment registers hold hidden descriptor caches that the processor keeps after a mode change. If you enter protected mode, load ds and es with a flat 4 GiB data selector and return to real mode without reloading them, the caches keep the 4 GiB limit, and real-mode code can address memory above 1 MiB with 32-bit offsets through [esi] and [edi] style operands. The BIOS disk read still cannot target high memory, so a loader reads into a low buffer and copies chunks up with a32 rep movsd in this mode, then enters protected mode properly at the end.

The advantage is that the copy can happen while the BIOS is still reachable, so the loader can print progress and handle disk errors between chunks. The cost is that the trick depends on processor and BIOS behavior that is documented only indirectly, and any BIOS routine that reloads the segment registers, which some do, silently resets the limit to 64 KiB. For a first loader the straightforward approach in this guide is easier to reason about, and unreal mode is worth knowing for the day you meet it in someone else's code.

Serial output for debugging after the switch

The BIOS print routines vanish at the mode switch, and a loader that fails after that point shows nothing on screen. Serial output is the fix: the UART at I/O port 0x3F8, the first serial port, works in every mode, and QEMU can route it to your terminal with -serial stdio. A minimal routine writes a byte when the transmitter is empty:

nasm
serial_putc:
    push dx
    push ax
    mov  dx, 0x3FD                ; line status register
.wait:
    in   al, dx
    test al, 0x20                 ; transmitter holding register empty
    jz   .wait
    pop  ax
    mov  dx, 0x3F8                ; data register
    out  dx, al
    pop  dx
    ret

The same code works in 16-bit and 32-bit mode with the register names adjusted. Real machines need the port initialized first, with the baud rate divisor set through the line control register, but QEMU's emulated port accepts bytes without it, which makes it the cheapest way to get debugging output out of the 32-bit stage and the kernel's first instructions. Write a short routine that prints a string through it, add a serial_putc call at each milestone of the loader, and the log of a failing boot shows exactly which milestone was the last one reached.

Checking the build

A bootloader's failure modes are silent, so make the build refuse to produce a bad image. Three checks pay for themselves. Verify that stage1.bin is exactly 512 bytes and ends in 55 AA: NASM guarantees it if the times line is correct, but a script check catches an edit that removed it. Verify that stage2.bin is exactly STAGE2_SECTORS * 512 bytes, since the kernel's LBA depends on it. And verify that the kernel's size in sectors matches the constant stage 2 uses. A short shell fragment in the Makefile does all three:

Shell
test "$(stat -c %s stage1.bin)" = 512
test "$(tail -c 2 stage1.bin | xxd -p)" = 55aa
test "$(stat -c %s stage2.bin)" = 4096

The stat -c form is GNU coreutils; on macOS use stat -f %z. When a constant changes, the build fails at the check instead of the machine failing at boot, and the fix is one number in one file.

Debugging a bootloader

Failures cluster around a handful of causes, and recognizing the symptom saves hours.

SymptomLikely cause
"No bootable device" or blank screenSector missing 55 AA, wrong size or not attached as a boot drive
Prints nothing, then hangs-nographic hides VGA output; or segment registers not set
Garbage textWrong ds or missing org, so string addresses are off
Reboot loop right after the mode switchTriple fault: bad GDT, wrong selector or a bad far jump
Works in QEMU, fails on hardwareAssumed BIOS state, such as segment values or dl; A20 already on in QEMU
Kernel overwrites itself or dataA20 closed, or the copy and the stack overlap
Disk read fails with 0x01 or 0x80Wrong drive in dl, or the image is too short

Use the tools in layers. QEMU with -S -gdb tcp::1234 lets GDB stop at 0x7C00; run set architecture i8086 for real-mode code and switch to i386 and then i386:x86-64 as the code changes mode. -d int,cpu_reset -D qemu.log records every interrupt and reset. For printing, the diagnostic routines are the first tool and a serial port is the second: a few out dx, al instructions to port 0x3F8 write bytes to QEMU's serial output with -serial stdio, which keeps working after the switch to protected mode when the BIOS is gone.

The classic mistake in a hobby bootloader is to debug three things at once. Add one stage at a time, run it, and commit when it works. A bootloader that has to be correct in its first 512 bytes rewards that discipline more than most programs do.

Putting it on real hardware

An emulator hides differences that real machines expose. The BIOS may leave different values in registers, treat a USB stick as a hard disk or a floppy depending on its settings, report a memory map with gaps your emulator never showed and take a moment to open A20. To test on a real machine, write the image to a spare USB stick with dd, and be certain of the device name: writing to the wrong device destroys its contents. Check with lsblk before and after plugging the stick in, and prefer a stick you can afford to wipe:

Shell
sudo dd if=disk.img of=/dev/sdX bs=512 conv=fsync status=progress

Replace /dev/sdX with the stick's device and never with a partition number or your system disk. Then boot the machine in legacy or compatibility mode, since a UEFI-only machine will not run a BIOS bootloader at all. Keep a serial or on-screen print at every stage so that a failure tells you how far it got.

A trace of the whole boot

It helps to walk the complete sequence once with the memory addresses in mind, because most bugs are two stages disagreeing about where something lives. The machine powers on and the BIOS runs its self-test, finds the disk and copies sector 0 to 0x7C00. Stage 1 runs there, sets the stack to grow downward from 0x7C00 and reads eight sectors, 4 KiB, to 0x7E00, so stage 2 occupies 0x7E00 to 0x8DFF. Stage 2 prints its banner, opens A20 and writes the memory map to 0x9000, which is above the end of stage 2 and below the 64 KiB mark where the kernel buffer begins. It reads the kernel to 0x10000, builds nothing yet and switches to protected mode. Its stack in 32-bit mode is at 0x90000, which grows downward through free memory and never reaches the map or the boot info. The copy then moves the kernel to 0x100000, and the jump transfers control.

If long mode is wanted, the page tables are built at 0x70000 to 0x72FFF, which is clear of everything else, before the final jump. The picture to keep is a column of addresses: the real-mode vectors and BIOS data at the bottom, a small free area at 0x500, the boot sector and stage 2 at 0x7C00, the map and boot info just above, the kernel buffer at 0x10000, the page tables and stack in the 0x70000 to 0x90000 range and the video memory at 0xB8000, with the kernel itself at 1 MiB. Write the table into a comment at the top of stage 2 and keep it current as you add things. A collision between two of these regions is a bug that produces crashes far from the cause.

Decisions that look small and are not

A few choices in a bootloader are easy to make carelessly and expensive to change. Where the stack lives is the first: below 0x7C00 is safe in stage 1 because the BIOS data area is below it, but only about 30 KiB are free there, and a stage 2 that uses deep recursion or large local buffers will overwrite the interrupt vector table. Move the stack to a known free region as soon as you have a second stage, and write down its limits.

The second is how stages find each other. Hard-coded sector counts are fine for a toy loader, and fragile for anything else. The first improvement is a tiny header at the start of stage 2, holding its own size and the kernel's location and size, written by a build script, so the numbers exist in one place. The second is a file system: reading a kernel by name from a FAT partition removes the constants altogether but adds hundreds of lines of code, which is why many loaders put a file system driver in stage 2 and keep stage 1 as small as possible.

The third is the memory map format you hand the kernel. The raw E820 entries are 24 bytes with an extended attribute, and a kernel that hard-codes 20-byte entries breaks on a BIOS that returns more. Pass the entry size along with the map, and let the kernel handle both.

The fourth is whether to make the loader aware of the video mode. Text mode is free and reliable. A graphical mode needs the VESA BIOS extensions, int 0x10 with function 0x4F00 and following, which must also be called before leaving real mode, and the framebuffer address and pitch it returns must be passed to the kernel. Decide early, because retrofitting a video mode into a finished loader means touching every stage.

What to use instead

Writing your own bootloader is a learning exercise and sometimes a real need, but most projects should not ship one. A boot protocol removes the work: GRUB loads a kernel that follows the Multiboot2 specification, leaving the CPU in 32-bit protected mode with a memory map and a boot information structure already built, and Limine does the same for 64-bit kernels and supports both BIOS and UEFI. They handle file systems, different disk layouts and many firmware quirks that a hand-written loader will meet one at a time.

Firmware matters too. Modern PCs boot with UEFI, which starts a PE executable from a FAT partition in 64-bit mode with a memory map, framebuffer and file access already available, and many have no legacy BIOS mode at all. The loader in this guide does not run on them. For hardware from the last several years, the choice is a UEFI application or a boot protocol that supports it, and a separate guide covers UEFI boot for OS developers.

Finally, the techniques here assume x86. Arm and RISC-V systems boot from other firmware, with their own conventions, such as a device tree handed to the kernel, and the ideas carry over while the code does not.

Also inKernels
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.