Build Your Own OS
A hands-on project guide to building a minimal operating system from scratch: boot loader, kernel, scheduler, and file system.
A hands-on project guide to building a minimal operating system from scratch: boot loader, kernel, scheduler, and file system.
Introduction
Building an operating system from scratch makes boot, memory, interrupts, and scheduling concrete. This guide’s main path builds a small 32-bit x86 kernel and boots it as a GRUB Multiboot 1 ELF image in QEMU.
Educational scope: This kernel is for learning in an emulator. It is not a production operating system, security boundary, or safe template for booting real hardware. The scheduler, FAT12, and UEFI material below are separate extensions, not features of the core build.
The first goal is deliberately small: build a kernel ELF, package it in a GRUB BIOS ISO, and display one line of text. Add hardware and operating-system features only after that handoff works.
When to Use / When Not to Use
Building an OS from scratch fits when:
- Deep learning is the goal — You want to understand boot, memory, interrupts, and process management by implementing small pieces.
- Academic or personal projects — You want a controlled experiment with a visible result.
- Emulator-based experimentation — You can test and reset the machine without risking a host system.
This approach is not appropriate when:
- You need production-ready functionality or security — Use an established operating system and its supported components.
- Time constraints are tight — Even a minimal OS takes sustained low-level debugging.
- Requirements are unclear — Define the target hardware and interfaces before choosing a boot path.
Architecture or Flow Diagram
The core path uses one target and toolchain: a 32-bit x86 Multiboot 1 kernel, GRUB 2 on a BIOS-bootable ISO, and QEMU’s qemu-system-i386.
flowchart LR
HOST["Linux build host"]
TOOLS["i686-elf GCC/binutils"]
ELF["32-bit Multiboot ELF"]
ISO["GRUB BIOS ISO"]
QEMU["QEMU qemu-system-i386"]
ENTRY["GRUB handoff in protected mode"]
KERNEL["Kernel prints VGA banner"]
HOST --> TOOLS --> ELF --> ISO --> QEMU --> ENTRY --> KERNEL
Core Concepts
Boot Loader (Core Path: GRUB Multiboot 1)
The walkthrough targets 32-bit x86 (i686 ELF), uses the i686-elf-gcc cross-compiler and binutils, packages the kernel with GRUB 2 using grub-mkrescue, and runs it with qemu-system-i386. The ISO build also needs xorriso, which grub-mkrescue uses. The build commands later in this article use only this path.
GRUB recognizes the Multiboot 1 header, loads the ELF segments at the addresses in the linker file, enters 32-bit protected mode, and passes the boot magic in EAX and the information pointer in EBX. The kernel entry below sets its own stack before calling C; the core path does not run a custom boot sector or a hand-written mode switch.
/* boot.S: Multiboot 1 header and 32-bit kernel entry, GNU assembler syntax */
.set MB_MAGIC, 0x1BADB002
.set MB_FLAGS, 0x00000003
.set MB_CHECKSUM, -(MB_MAGIC + MB_FLAGS)
.section .multiboot
.align 4
.long MB_MAGIC
.long MB_FLAGS
.long MB_CHECKSUM
.section .bss
.align 16
stack_bottom:
.skip 16384
stack_top:
.section .text
.global _start
.type _start, @function
_start:
cli
cld
mov $stack_top, %esp
sub $8, %esp /* Keep the i386 call-site stack 16-byte aligned. */
push %ebx /* Second argument: Multiboot information pointer. */
push %eax /* First argument: Multiboot boot magic. */
call kernel_main
1:
hlt
jmp 1b
.size _start, . - _start
.section .note.GNU-stack,"",@progbits
The header must remain 32-bit aligned and within the first 8 KiB of the ELF file. The linker script below uses KEEP(*(.multiboot)) to retain it at the beginning of the loaded image.
Optional Background: Custom BIOS Boot-Sector Fragment
This is background material only; the core GRUB ISO build does not assemble or run this code. It is a raw BIOS boot-sector fragment, not a partitioned MBR or a FAT12 loader. It reads ten sectors starting at sector 2 into physical address 0x10000; a separate image builder would have to place a real-mode second stage in exactly those sectors. It does not load the ELF kernel shown in the core path.
; Optional fragment only: NASM syntax, not used by the GRUB build below.
BITS 16
ORG 0x7C00
start:
jmp 0x0000:normalized
normalized:
cli
xor ax, ax
mov ds, ax
mov es, ax
mov ss, ax
mov sp, 0x7C00
mov [boot_drive], dl
cld
mov si, msg
call print_string
mov ah, 0x02
mov al, 10
mov ch, 0
mov cl, 2
mov dh, 0
mov dl, [boot_drive]
mov bx, 0x1000
mov es, bx
xor bx, bx
int 0x13
jc disk_error
jmp 0x1000:0x0000
print_string:
lodsb
or al, al
jz .done
mov ah, 0x0E
int 0x10
jmp print_string
.done:
ret
disk_error:
mov si, err_msg
call print_string
jmp $
msg db 'Loading second stage...', 0
err_msg db 'Disk read error!', 0
boot_drive db 0
times 510-($-$$) db 0
dw 0xAA55
Protected Mode Transition
The core GRUB path already enters 32-bit protected mode before _start; do not compile this transition into that kernel. The following NASM fragment is optional background for a separate custom BIOS second stage. Its GDT address and load address must match that stage; it does not call the core C kernel or form a complete boot image.
; Optional conceptual fragment only; not used by the GRUB ISO build.
BITS 16
switch_to_protected_mode:
cli
lgdt [gdt_descriptor]
; Enable A20 through the fast A20 gate (platforms may need another method).
in al, 0x92
or al, 2
out 0x92, al
mov eax, cr0
or eax, 1
mov cr0, eax
jmp 0x08:flush_pm
BITS 32
flush_pm:
mov ax, 0x10
mov ds, ax
mov es, ax
mov fs, ax
mov gs, ax
mov ss, ax
mov esp, 0x90000
; Continue in a separately implemented protected-mode stage.
.hang:
hlt
jmp .hang
gdt_start:
dq 0
dw 0xFFFF, 0x0000
db 0x00, 10011010b, 11001111b, 0x00
dw 0xFFFF, 0x0000
db 0x00, 10010010b, 11001111b, 0x00
gdt_end:
gdt_descriptor:
dw gdt_end - gdt_start - 1
dd gdt_start
Simple Kernel in C
This is the complete C portion of the core path. It writes directly to the VGA text buffer so it needs no libc or device driver:
#include <stdint.h>
#define MULTIBOOT_BOOTLOADER_MAGIC 0x2BADB002u
#define VGA_TEXT ((volatile uint16_t *)0xB8000)
#define VGA_ATTR 0x0F
void kernel_main(uint32_t magic, uint32_t multiboot_info)
{
(void)multiboot_info;
const char *message = magic == MULTIBOOT_BOOTLOADER_MAGIC
? "MyOS: Multiboot handoff OK"
: "MyOS: bad Multiboot magic";
for (uint32_t i = 0; message[i] != '\0'; i++) {
VGA_TEXT[i] = ((uint16_t)VGA_ATTR << 8) | (uint8_t)message[i];
}
}
The expected screen line after the GRUB handoff is MyOS: Multiboot handoff OK. If QEMU stays blank, first check the grub-file result and linker entry point; then confirm the assembly pushes EAX and EBX in the C calling convention order and that the VGA write uses 0xB8000.
Simple Round-Robin Scheduler
This is a separate extension sketch, not compiled by the core build. A working preemptive scheduler also needs an IDT, a configured timer IRQ, a real context-switch routine, and valid initial interrupt frames. After implementing those pieces, two logging tasks should alternate output such as A0 B0 A1 B1. If only one task runs or the machine resets, check that IRQ0 reaches the handler, the PIC is acknowledged, and the saved stack frame matches the assembly switch routine.
/* scheduler.c - Round-robin task scheduler */
#include <stdint.h>
#define MAX_TASKS 64
#define TASK_STACK_SIZE 4096
struct task {
uint32_t id;
uint32_t esp; /* Stack pointer */
uint32_t eip; /* Instruction pointer */
uint32_t priority;
enum { TASK_RUNNING, TASK_READY, TASK_BLOCKED, TASK_DEAD } state;
uint8_t stack[TASK_STACK_SIZE];
};
static struct task tasks[MAX_TASKS];
static int num_tasks = 0;
static int current_task = 0;
/* TSS for hardware context switching */
struct tss_entry {
uint16_t link, :16;
uint32_t esp0;
uint16_t ss0, :16;
uint32_t esp1, ss1, esp2, ss2;
uint32_t cr3;
uint32_t eip, eflags, eax, ecx, edx, ebx;
uint32_t esp, ebp, esi, edi;
uint16_t es, :16, cs, :16, ss, :16, ds, :16;
uint16_t fs, :16, gs, :16, ldt, :16;
} __attribute__((packed));
static struct tss_entry tss;
int create_task(void (*entry)(void), uint32_t priority)
{
if (num_tasks >= MAX_TASKS) return -1;
struct task *t = &tasks[num_tasks++];
t->id = num_tasks;
t->state = TASK_READY;
t->priority = priority;
/* Set up stack to look like we were interrupted */
t->esp = (uint32_t)&t->stack[TASK_STACK_SIZE - 1];
/* Push fake interrupt frame */
t->esp -= sizeof(uint32_t); /* EIP placeholder */
*(uint32_t *)t->esp = (uint32_t)entry;
return t->id;
}
void schedule(void)
{
/* Find next ready task */
int prev = current_task;
do {
current_task = (current_task + 1) % num_tasks;
} while (tasks[current_task].state != TASK_READY
&& current_task != prev);
if (current_task != prev) {
tasks[prev].state = (tasks[prev].state == TASK_RUNNING)
? TASK_READY : tasks[prev].state;
tasks[current_task].state = TASK_RUNNING;
switch_task(&tasks[prev].esp, tasks[current_task].esp);
}
}
/* Called from timer interrupt (IRQ0) */
void timer_interrupt_handler(void)
{
/* Acknowledge PIC */
outb(0x20, 0x20);
schedule();
}
Simple FAT12 File System
This is a separate file-system extension sketch; the GRUB ISO in the core build does not contain or mount a FAT12 volume. A working reader must use the BPB’s sector and cluster geometry, bound-check the root directory and FAT, and decode the 12-bit cluster entries correctly. The code below shows the general structures and traversal idea, but its omitted helpers and placeholder constants mean it is not a standalone implementation.
/* fs_fat12.c - Minimal FAT12 file system */
#include <stdint.h>
#define SECTOR_SIZE 512
#define FAT_START 1
#define ROOT_START 19
#define DATA_START 33
struct fat12_boot {
uint8_t jmp[3];
uint8_t OEM[8];
uint16_t bytes_per_sector;
uint8_t sectors_per_cluster;
uint16_t reserved_sectors;
uint8_t num_fats;
uint16_t root_entries;
uint16_t total_sectors;
uint8_t media_type;
uint16_t sectors_per_fat;
uint16_t sectors_per_track;
uint16_t num_heads;
uint32_t hidden_sectors;
uint32_t large_sector_count;
uint8_t drive_number;
uint8_t reserved;
uint8_t boot_signature;
uint32_t volume_id;
uint8_t volume_label[11];
uint8_t fs_type[8];
} __attribute__((packed));
struct fat12_entry {
uint8_t filename[8];
uint8_t ext[3];
uint8_t attributes;
uint8_t reserved[10];
uint16_t time;
uint16_t date;
uint16_t start_cluster;
uint32_t file_size;
} __attribute__((packed));
/* Read file from FAT12 */
int read_file(uint16_t cluster, uint8_t *buffer, int max_size)
{
int bytes_read = 0;
uint8_t fat[FAT12_MAX_SIZE];
/* Read FAT into memory */
read_sectors(FAT_START, FAT12_SECTORS, fat);
while (cluster < 0xFF8) { /* Not end-of-file marker */
if (bytes_read >= max_size) break;
/* Read data cluster */
uint32_t data_sector = DATA_START + (cluster - 2);
read_sectors(data_sector, 1, buffer + bytes_read);
bytes_read += SECTOR_SIZE;
/* Get next cluster from FAT */
uint16_t fat_index = cluster + (cluster / 2);
cluster = *(uint16_t *)&fat[fat_index];
if (cluster & 1) {
cluster >>= 1;
} else {
cluster = cluster >> 1;
}
}
return bytes_read;
}
Production Failure Scenarios
These failures apply to later experiments that add the listed subsystem; the minimal GRUB kernel only sets a stack and writes a VGA banner.
Scenario 1: Stack Overflow Corrupts Memory
Problem: Kernel stack is too small or grows into other regions, causing mysterious crashes.
Mitigation:
- Define proper stack sizes with guard pages
- Use
__attribute__((interrupt))for ISR functions (handles stack frame) - Check stack pointer against bounds before function calls
- For recursive code, ensure termination conditions are always met
Scenario 2: Triple Fault During Protected Mode Transition
This scenario applies only to the optional custom BIOS transition; GRUB performs the protected-mode handoff in the core build.
Problem: CPU triple-faults (reset) during mode transition, making debugging difficult.
Mitigation:
- Ensure GDT is correctly aligned and loaded
- Verify CS descriptor has proper access byte (0x9A for code)
- Use a boot ROM or serial debug output before the crash
- Build with debugging symbols and use a hardware debugger (QEMU + GDB)
Scenario 3: Paging Enabled Incorrectly
Problem: Enabling paging with incorrect page tables causes immediate crash.
Mitigation:
- Identity-map the kernel first (virtual == physical) before enabling
- Set CR3 to point to valid page directory
- Enable paging with
mov cr0, eaxfollowed immediately by ajmpto flush pipeline - Use QEMU with
-d intto trace interrupt/exceptions during boot
Trade-off Table
| Component | Core emulator path | Real hardware |
|---|---|---|
| Development speed | Fast reset and repeatable device model | Slower reset and device-specific setup |
| Debugging | QEMU logging and GDB stub | Depends on hardware and debug access |
| Risk | Isolated from host storage when using the ISO as a CD-ROM | A buggy boot image can disrupt or overwrite data |
| Hardware coverage | Tests the emulated x86 PC devices only | Varies by board, firmware, and peripherals |
Implementation Snippet: Linking the Kernel
The core build produces a 32-bit ELF kernel for the GRUB Multiboot 1 handoff. Keep the Multiboot header first so GRUB can find it near the start of the file; the kernel entry point is _start.
/* kernel.ld */
OUTPUT_FORMAT(elf32-i386)
OUTPUT_ARCH(i386)
ENTRY(_start)
SECTIONS
{
. = 1M;
.multiboot ALIGN(4) : {
KEEP(*(.multiboot))
}
.text ALIGN(4K) : {
*(.text*)
}
.rodata ALIGN(4K) : {
*(.rodata*)
}
.data ALIGN(4K) : {
*(.data*)
}
.bss ALIGN(4K) : {
*(COMMON)
*(.bss*)
}
/DISCARD/ : {
*(.comment)
*(.eh_frame)
*(.note*)
}
}
Use a Linux build host with i686-elf-gcc and its binutils, GRUB 2 tools (grub-file and grub-mkrescue), xorriso, and qemu-system-i386. Package names vary by distribution; if grub-mkrescue reports that xorriso is missing, install that dependency before building the ISO.
#!/usr/bin/env bash
# build.sh — build a Multiboot ELF, package a GRUB BIOS ISO, and boot it in QEMU
set -eu
mkdir -p build/iso/boot/grub
i686-elf-gcc -m32 -ffreestanding -fno-pie -fno-pic -fno-stack-protector \
-c boot.S -o build/boot.o
i686-elf-gcc -m32 -ffreestanding -fno-pie -fno-pic -fno-stack-protector \
-fno-builtin -O2 -Wall -Wextra -c kernel.c -o build/kernel.o
i686-elf-ld -m elf_i386 -T kernel.ld --build-id=none \
-o build/kernel.elf build/boot.o build/kernel.o
# Succeeds with exit status 0 when the Multiboot 1 header is recognized.
grub-file --is-x86-multiboot build/kernel.elf
cp build/kernel.elf build/iso/boot/kernel.elf
cat > build/iso/boot/grub/grub.cfg <<'EOF'
set timeout=0
set default=0
set gfxpayload=text
terminal_output console
menuentry "MyOS" {
multiboot /boot/kernel.elf
boot
}
EOF
grub-mkrescue -o build/myos.iso build/iso
qemu-system-i386 -m 128M -cdrom build/myos.iso -boot d -no-reboot
Milestone 1 — Multiboot kernel ELF. Artifact: build/kernel.elf. Expected check: grub-file --is-x86-multiboot build/kernel.elf exits with status 0. If compilation fails because i686-elf-gcc is missing, install/select that cross-compiler rather than substituting a host compiler with a different target. If grub-file rejects the kernel, confirm _start is the entry, .multiboot is kept before other loadable sections, and the aligned header remains in the first 8 KiB of the ELF file.
Milestone 2 — GRUB ISO boots in QEMU. Artifact: build/myos.iso. Expected screen: MyOS: Multiboot handoff OK. If grub-mkrescue cannot create the ISO, check for xorriso and the GRUB BIOS modules; if GRUB says the kernel is missing, check the ISO tree at build/iso/boot/kernel.elf and the matching grub.cfg path. For a blank screen, keep terminal_output console and gfxpayload=text, verify the boot magic and stack setup, and use -no-shutdown -d int -D build/qemu.log to retain a fault trace.
Observability Checklist
For the core build, the VGA banner is the first check. If the guest resets before printing it, retain a QEMU trace with -no-shutdown -d int -D build/qemu.log. For source-level debugging, start QEMU with -s -S and connect GDB to localhost:1234. Serial output and QMP are useful for later extensions, but neither is wired into the minimal kernel.
Common Pitfalls / Anti-Patterns
Boot & Environment Setup
New OS developers consistently lose months to bugs that a proper environment setup would have caught immediately. Before writing kernel code, get your toolchain and emulator verified.
Starting without a bootable environment — Build the Multiboot ELF and verify it with grub-file before packaging the ISO. Boot the ISO in QEMU and confirm the VGA banner before adding subsystems. If GRUB rejects the kernel, check the header placement and linker script; if QEMU resets, use its interrupt trace or GDB stub. An emulator makes it safe to reset and repeat the same boot sequence.
Not using a linker script — You’ll spend days debugging random crashes without proper memory layout. The default linker behavior places sections wherever it feels like, which means your kernel might land at an address that conflicts with the bootloader, overlaps with the BSS, or sits outside the region your page tables cover. A linker script gives you explicit control: what address the .text section runs at, where the kernel heap begins, how large the initial stack is, and which sections get discarded. Without one, you are guessing.
Confusing the core handoff with a custom mode switch — GRUB enters the core kernel in 32-bit protected mode, so the GRUB path needs no real-mode transition code. If you later write your own BIOS loader, the optional GDT and mode-switch example must be paired with a matching second stage and memory layout.
Hardware & Interrupt Handling
Interrupts are the kernel’s nervous system. Get them wrong and the CPU resets itself before you can blink. These two pitfalls trip up almost everyone who writes an OS for the first time.
Not handling interrupts early — Unhandled interrupts cause immediate triple-fault. When an interrupt fires and the CPU cannot find a valid handler in the IDT, it triggers a double fault. If that also fails, the CPU triple-faults and resets. Before enabling interrupts, install a valid IDT with at least stub handlers for every exception vector. Even a handler that just halts the CPU (while(1);) is better than an unhandled exception. Once you have the basics, set up the PIC to route hardware IRQs (timer, keyboard) to handlers that acknowledge the interrupt and do something useful.
Treating QEMU success as hardware validation — This guide targets one QEMU PC model and only checks a VGA banner. Other firmware, boards, storage controllers, and keyboards may behave differently. Keep the educational kernel in the emulator; a successful boot here does not make it safe or compatible on physical hardware.
Security & Platform Considerations
The following four areas need explicit decisions before you move beyond the emulator. Some can be deferred in a learning kernel, but they should not be mistaken for production protections.
UEFI secure boot (optional UEFI branch) — Custom OS may not boot on new hardware without signing. UEFI Secure Boot verifies the bootloader signature against keys stored in the firmware. Most consumer laptops ship with Secure Boot enabled and Microsoft-signed keys only. GRUB can chainload your kernel if you register it in the firmware, but doing that from scratch means managing your own keys and enrolling them in the UEFI database. If you are targeting modern hardware, budget time for Secure Boot setup or design your bootloader to work within the existing trust chain.
DMA attacks — Without IOMMU, any device can access all memory. Peripheral devices with DMA capability (SATA controllers, network cards, USB controllers) can read and write arbitrary physical memory without CPU involvement. On systems without an IOMMU (Input-Output Memory Management Unit), a malicious or buggy device driver can corrupt kernel memory or read sensitive data from other processes. Adding an IOMMU is a multi-core-level complexity addition; most hobbyist OSes skip it and accept the risk for the sake of simplicity.
No ASLR — Simple kernels typically don’t implement address space layout randomization. ASLR randomizes where the kernel, modules, and user processes are loaded in memory, making exploits that rely on knowing fixed addresses unreliable. Implementing it requires a working virtual memory system with page tables that support placing sections at arbitrary offsets. Without it, an exploit that knows your kernel base address can jump directly to known function offsets.
No userspace isolation — Bugs in kernel code affect entire system. In a minimal OS, kernel and user processes often share the same address space (or worse, the kernel runs with all privilege bits enabled for every process). A buffer overflow in a user process can overwrite kernel structures, crash the system, or elevate privileges. Proper isolation requires separate page tables per process, a privilege separation mechanism (user ring vs kernel ring), and a system call interface that validates all parameters before acting on them.
Quick Recap Checklist
- Core target: 32-bit x86, Multiboot 1 ELF, GRUB BIOS ISO, and
qemu-system-i386. - GRUB enters the core kernel in protected mode; the kernel entry sets its own stack before calling C.
- Milestone 1 is a
kernel.elfaccepted bygrub-file --is-x86-multiboot. - Milestone 2 is a QEMU screen showing
MyOS: Multiboot handoff OK. - The scheduler and FAT12 snippets are separate extensions, not part of the working core build.
- UEFI is an optional, separate firmware path; this article’s build commands do not create an EFI executable.
- Treat the result as an educational kernel, not a production OS or a real-hardware boot image.
Real-World Case Study: xv6 Educational OS
MIT’s xv6 is a teaching OS derived from Unix v6, rewritten for modern x86. It demonstrates:
- Minimal but complete - ~8,000 lines covering process management, scheduler, syscalls, file system
- Pedagogical clarity - Each component is small enough to understand in isolation
- Modernized implementation - While inspired by v6, xv6 uses modern structures like spinlocks and a proper file system layer
Studying xv6 before building your own OS provides a reference implementation that shows how components interact without the complexity of production kernels.
Optional Topic: UEFI Boot Process
Optional branch only: UEFI is not used by the core GRUB BIOS ISO, and the commands above do not create an EFI executable. A UEFI version needs its own EFI loader or stub, an EFI System Partition, and a firmware emulator such as OVMF in QEMU; do not combine its artifacts with the Multiboot 1 build without implementing that handoff.
A UEFI boot sequence is separate from the core path:
- Firmware initializes devices and loads an EFI application from the EFI System Partition.
- The loader prepares the kernel and obtains the firmware memory map.
- The loader calls
ExitBootServices()before the kernel takes over ordinary hardware management. - Runtime services may remain available if the OS keeps the required mappings and follows the UEFI contract.
To explore this path, choose and document an EFI target and toolchain first. The GRUB Multiboot 1 linker script and ISO build below are not an EFI build recipe.
Interview Questions
The multiboot header is a magic structure that GRUB (and other multiboot-compliant bootloaders) look for in the first 8KB of a kernel image. It tells the bootloader: where to find the memory map, what modules to load, and what video mode to set. If your kernel has this header, GRUB can boot it without custom boot sector code. The header contains magic numbers (0x1BADB002, 0xE4524FFB), flags, and checksum fields that GRUB validates before transferring control.
BIOS int 0x13 is a legacy BIOS service for disk I/O—it works in real mode with 16-bit addressing and has limited capabilities (no DMA, limited sector counts). Once you switch to protected mode, BIOS interrupts are unavailable. ATA/IDE registers (I/O ports 0x1F0-0x1F7, 0x3F6-0x3F7) can be accessed directly from protected mode, enabling DMA transfers, LBA48 addressing (>137GB), and full speed. Modern systems use AHCI (I/O ports 0x1F0-0x1F7, MSI-X) for SATA with command queuing.
Hardware context switching uses the Task State Segment (TSS) and `CALL`/`JMP` to a task gate—the CPU automatically saves the full task state (registers, selectors) when switching. This is slow and rarely used in modern OSes. Software context switching (what Linux and most OSes use) manually saves only the necessary registers, stack pointer, and program counter in a struct, then loads the next task's state. It's faster and more flexible. The `sysenter`/`syscall` and `iret` instructions are optimized for user/kernel transitions, not full task switches.
The GDT defines memory segments and their access privileges. Each descriptor specifies: base address (32-bit), limit (20-bit, describing segment size), access rights (present, privilege level, type, direction). The CPU uses selectors (offsets into the GDT) to reference segments. Unlike real mode's fixed segment registers, protected mode descriptors are software-defined and can enforce privilege levels (kernel ring 0 vs user ring 3). A minimal GDT needs: null descriptor, kernel code segment (0x08), kernel data segment (0x10).
A triple fault occurs when the CPU encounters an exception while trying to call the exception handler for a double fault (which itself is triggered by another exception). This typically happens during boot when an interrupt or exception occurs before the IDT (Interrupt Descriptor Table) is properly set up, or when the GDT/IDT is misconfigured. To debug: (1) boot in an emulator like QEMU with GDB stub enabled, (2) set breakpoints before the problematic code, (3) use QEMU's `-d int` flag to log interrupts and exceptions, (4) ensure you have exception handlers in place before enabling interrupts.
Real mode is the CPU's original state after reset—16-bit addressing with segment:offset pairs, allowing access to only 1MB of memory (20-bit addresses). There's no memory protection, no privilege levels, and BIOS calls are available for hardware access. Protected mode enables: (1) 32-bit addressing (up to 4GB), (2) memory protection via privilege levels (ring 0-3), (3) paging for virtual memory, (4) hardware task switching. Operating systems switch to protected mode early in boot to access more memory and enable protection.
The IDT tells the CPU where to go when an interrupt or exception occurs. Each entry (gate descriptor) contains the handler offset, code segment selector, and gate attributes. An interrupt gate clears IF on entry; a trap gate does not. Install a valid IDT before enabling interrupts; an unhandled exception can escalate to a triple fault.
Paging divides memory into fixed-size pages (typically 4KB) and uses page tables to map virtual addresses to physical addresses. Benefits: (1) Isolation—each process has its own page tables, preventing unauthorized access to other processes' memory; (2) Virtual memory—pages can be swapped to disk when not in use, allowing more processes than physical RAM; (3) Protection—hardware enforces read/write/execute bits per page; (4) Flexibility—code can assume contiguous virtual addresses while physical memory is fragmented. The TLB (Translation Lookaside Buffer) caches recent translations for speed.
GRUB loads a Multiboot 1 ELF using its ELF load segments, enters 32-bit protected mode, and transfers control to the ELF entry point. It passes the boot magic in EAX and the Multiboot information pointer in EBX. The core entry stub sets its own stack before calling C; paging remains the kernel's later initialization task. A custom loader must provide an equivalent documented handoff before the kernel can use those assumptions.
A linker script specifies how sections from input object files are arranged in the output binary and where the kernel loads in memory. Without a custom linker script, the linker uses defaults that may place code and data at addresses incompatible with your OS's expectations. A typical linker script for an OS specifies: (1) output format (e.g., elf32-i386), (2) entry point address, (3) memory layout (which addresses are valid), (4) section placement (`.text` at 0x100000). This is critical for position-independent code that needs to run at specific addresses before the MMU is fully set up.
Segmentation: Each memory reference uses a segment selector (in GDT/LDT) + offset. The selector indexes into descriptor table to get base address, limit, and access rights. Segmentation provides flat or hierarchical memory models, privilege levels (ring 0-3), and access control. In real mode, segments overlap (segment << 4 + offset); in protected mode, descriptors define arbitrary base/limit.
Paging: All addresses go through page table translation. Linear address → page directory/table → physical address. Provides virtual memory, process isolation, page-level protection (r/w/x bits), and can simulate segmentation (by identity-mapping large pages). Most modern OSes use paging exclusively, with segments providing privilege levels only.
Linux uses segmentation minimally: flat segments (base=0, limit=4GB) for both kernel and user mode. This simplifies memory management while relying on paging for protection.
8259 PIC (Programmable Interrupt Controller): 8 IRQ lines cascaded in master/slave (14 usable IRQs). Uses edge-triggered or level-triggered modes. Configured via I/O ports 0x20/0xA0. Limited to 15 devices, requires interrupt acknowledgement via EOI command.
APIC (Advanced PIC): Designed for SMP systems. Each CPU has a local APIC; I/O APIC routes interrupts to specific CPUs. Supports 24+ IRQ lines, interrupt affinity (route IRQ to specific cores), and more sophisticated priority handling. APIC is memory-mapped (typically at 0xFEE00000). Modern systems use APIC even for single-core for compatibility.
OS developers must handle both if supporting legacy hardware: switch from PIC to APIC by masking all PIC interrupts, programming APIC, then enabling local APIC. The transition is complex but necessary for multi-core support.
SMP boot sequence:
- BIOS/UEFI detects CPUs and configures MP tables or ACPI tables (MADT, DSDT)
- Bootstrap processor (BSP) starts first, others are Application Processors (APs)
- OS reads ACPI tables to find APIC entries for each CPU
- OS sends INIT IPI to all APs, then Startup IPI with trampoline code address
- APs jump to trampoline code in low memory (below 1MB), enter protected mode
- APs set up their own GDT, IDT, page tables, then jump to kernel's CPU initialization
- OS creates per-CPU data structures (task state segments, per-CPU variables via segment registers)
The trampoline code is critical — APs need real-mode entry point before paging is enabled on them. Once AP is in kernel, it can join the scheduler's run queue.
System call mechanism on x86:
- User application calls library wrapper (e.g.,
read(fd, buf, count)in libc) - Library puts syscall number in eax, args in ebx, ecx, edx, then executes
int 0x80(legacy) orsyscallinstruction (SSE) orsysenter - CPU checks CPL (Current Privilege Level) — if user mode (ring 3), allows transition to kernel (ring 0)
- CPU looks up gate descriptor in IDT (vector 0x80 maps to kernel entry point)
- CPU switches to kernel stack (from TSS), pushes error code, interrupt number, EFLAGS, CS, EIP, SS:SP
- CPU loads kernel's code segment selector into CS, jumps to kernel syscall handler
- Kernel validates parameters, executes syscall, returns via
iretorsysret
Linux uses syscall (fast, since Skylake) and returns via sysret to avoid iret's stack switch overhead.
TSS structure: Fixed-size (104 bytes on 32-bit x86) segment containing:
- I/O map base address (where I/O permission bitmap starts)
- SS0, ESP0: Stack selector and pointer for ring 0 (kernel stack)
- SS1, ESP1, SS2, ESP2: Stacks for rings 1-2 (usually unused)
- CR3: Page directory pointer (for kernel stack when using separate stacks)
- EIP, EFLAGS, EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI: Saved registers for hardware task switching
- ES, CS, SS, DS, FS, GS, LDTR: Segment selectors
Purpose: When an interrupt occurs in user mode, the CPU uses the TSS's ESP0 to switch to the kernel stack before calling the interrupt handler. The OS sets TSS.SS0 and TSS.ESP0 to point to the kernel stack for the current process. On syscall, the kernel updates ESP to point to valid kernel stack before executing kernel code.
The core path uses grub-mkrescue to package the kernel and grub.cfg into a BIOS-bootable ISO. GRUB's internal BIOS boot stages and module layout are implementation details that vary by target and version; this walkthrough does not install GRUB to a physical disk.
Multiboot 1: The 32-bit header must be 4-byte aligned and entirely within the first 8 KiB of the kernel image file:
- Magic: 0x1BADB002
- Flags: bit 0 requests page-aligned modules; bit 1 requires memory information
- Checksum: -(magic + flags), modulo 32 bits
- Address fields are used only when flag bit 16 is set
Multiboot 2: An extensible successor with tagged metadata; its entry contract is distinct from Multiboot 1, so a kernel must implement the matching header and handoff:
- Magic: 0xE4524FFB (different from v1)
- Header format uses tags (type-length-value) instead of fixed offsets
- Adds support for: framebuffer tables, ELFHDR presentation, network boot info, ACPI tables
- GRUB2 supports both; simpler kernels often implement only v1
VFS is an abstraction layer that provides a common interface to filesystem implementations. It defines:
struct super_block: Mounted filesystem metadata (block size, operations, inode)struct inode: Represents file/directory (mode, size, operations, block pointers)struct dentry: Parsed path component (name, parent, inode reference)struct file: Open file instance (position, operations)
Concrete filesystems (ext4, FAT, NTFS, network filesystems) implement these structures. When you access a path, VFS: (1) resolves path through dentry cache, (2) calls inode operations for read/write/create, (3) buffers results through page cache. Adding a new filesystem only requires implementing VFS operations — existing code works without modification.
Identity paging: Virtual address equals physical address (1:1 mapping). Page 0x1000 maps to physical 0x1000.
Usage during kernel init:
- Bootloader loads kernel at physical address 0x100000 (1MB)
- Before enabling paging, kernel sets up page tables where entry 0x100000 maps to 0x100000 and entry 0x0 maps to 0x0 (identity)
- Kernel enables paging with CR0.PG bit
- First instruction after enabling paging must be a jump to flush instruction prefetch buffer
- Because of identity mapping, kernel can still access its own code/data at the same addresses
- After full initialization, kernel often switches to virtual addresses (higher half kernel)
Identity paging is a bootstrap technique — it allows the same code to work before and after paging is enabled without complex address translation during the critical boot transition.
PIC configuration in protected mode:
- Remap IRQ vectors: legacy PIC uses vectors 0x20-0x2F for hardware interrupts, but protected mode IDT starts at 0. Must reprogram PIC to avoid conflicts
- Write ICW1 (0x11) to port 0x20/0xA0 to start initialization sequence
- Write ICW2 to set base vector (e.g., 0x20 for master, 0x28 for slave)
- Write ICW3 to configure cascading (master IRQ2 connected to slave)
- Write ICW4 for 8086 mode
- Write OCW1 to unmask only used IRQ lines
- Send EOI to PIC after handling each interrupt
The 8259 PIC is edge-triggered, limited to 15 IRQ lines, and doesn't support multi-core interrupt routing. Modern systems use APIC instead, but PIC compatibility mode must be disabled during APIC setup. If you skip PIC remapping, keyboard and timer interrupts (IRQ1, IRQ0) will fire at wrong vector numbers, causing crashes.
Further Reading
- GNU Multiboot Specification — Header layout and kernel handoff contract
- GRUB
grub-mkrescuemanual — Building a bootable rescue ISO - QEMU system emulator manual — x86 boot-device options
- osdev.org Wiki - Comprehensive OS development documentation
- Linux from Scratch - Build your own Linux system from source
- Writing a Simple Operating System from Scratch - Step-by-step tutorial
- Intel Software Developer Manual - Official x86 documentation
- Broken Thorn OS Development Series - Detailed OS development tutorial
- Boot Process Deep Dive — From firmware to kernel initialization
- Instruction Set Architecture — Understanding CPU design for OS development
Conclusion
The core walkthrough has one supported route: build a 32-bit Multiboot 1 ELF with i686-elf-gcc, package it as a GRUB BIOS ISO with grub-mkrescue, and boot it in qemu-system-i386. The expected result is the VGA message MyOS: Multiboot handoff OK; the milestone checks give recovery steps for the ELF header, ISO packaging, and blank output.
GRUB performs the protected-mode handoff for this path. The custom BIOS loader, scheduler, FAT12 reader, and UEFI material are optional background or extension exercises and are not assembled into the core artifact. Keep this project in an emulator: it is a learning kernel, not production software or a validated real-hardware image.
Category
Related Posts
System Calls Interface
System calls are the boundary between user programs and the kernel. They are the mechanism by which user-space applications request services from the operating system — opening files, creating processes, allocating memory, and more. Understanding syscalls reveals how the OS enforces isolation and provides safe access to hardware.
What Is an Operating System?
An operating system sits between hardware and applications, managing resources so programs don't have to. This guide explains what an OS does, its architecture, and why it matters.
CPU Affinity & Real-Time Operating Systems
Learn how CPU affinity changes task placement, how Linux real-time policies differ, and why deadline guarantees depend on workload, configuration, and hardware.