Skip to content
systemcoding.dev
Assembly

Set Up a Stack and Call C From Your Bootloader

Move a NASM boot sector into 32-bit protected mode, set up a flat GDT and a stack, then call a freestanding C function that writes to VGA text memory.

6 min read
Summarize in AI
Flat illustration of settings switches, a slider and a gear, with the C, Linux and Intel logos.

Assembly gets a bootloader started, and C is what you want to write the rest in. The step between them is small but has to be exact: the C compiler assumes a flat 32-bit address space, a valid stack and the C calling convention, and a boot sector starts with none of those. The 16-bit real mode the BIOS leaves you in cannot run 32-bit C at all. This post builds the bridge with NASM 2.16, GCC 14 and GNU ld on Linux: a boot sector that enables the A20 line, loads a flat global descriptor table, enters 32-bit protected mode, sets up a stack and calls a C function kmain, which writes text straight to the VGA buffer. Every file fits in the 510 bytes a boot sector allows, and the build produces one boot.bin.

The plan

Four things must be true before the first C instruction runs.

The CPU must be in 32-bit protected mode, so that 32-bit instructions and a flat address space work. That means a GDT with code and data segments, a write to the PE bit of cr0 and a far jump to reload the code segment.

The segment registers must hold selectors for the data segment, otherwise every memory access in C goes through a stale real-mode segment.

esp must point at free memory with room to grow downward. C pushes the return address and locals on it.

The C code must not rely on anything an operating system supplies: no libc, no runtime start-up, no main. It must be compiled freestanding, as 32-bit code with no position-independent tricks and no stack protector, which needs a runtime library function.

The assembly side

boot.asmnasm
bits 16
section .boot
global start
extern kmain

start:
    cli
    xor  ax, ax
    mov  ds, ax
    mov  es, ax
    mov  ss, ax
    mov  sp, 0x7C00

    in   al, 0x92          ; fast A20 gate
    or   al, 2
    out  0x92, al

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

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
    call kmain
.hang:
    cli
    hlt
    jmp  .hang

align 8
gdt:
    dq 0x0000000000000000      ; null descriptor
    dq 0x00CF9A000000FFFF      ; selector 0x08: code, base 0, limit 4 GiB
    dq 0x00CF92000000FFFF      ; selector 0x10: data, base 0, limit 4 GiB
gdt_end:

gdt_desc:
    dw gdt_end - gdt - 1
    dd gdt

Read it in the order it executes. The first block is the real-mode setup from the earlier posts. The in, or, out sequence on port 0x92 is the fast A20 gate, which opens the 21st address line so that memory above 1 MiB is reachable; the next post covers more careful ways to enable it. lgdt [gdt_desc] loads the descriptor table register from a six-byte pseudo-descriptor: a 16-bit limit and a 32-bit base. The three table entries are 8 bytes each. The null descriptor is required. The code descriptor 0x00CF9A000000FFFF decodes to base 0, limit 0xFFFFF with 4 KiB granularity (so 4 GiB), present, ring 0, executable and readable, 32-bit. The data descriptor 0x00CF92000000FFFF is the same with the writable data type. Both being flat is what lets C use ordinary pointers.

Setting bit 0 of cr0 turns on protected mode. The CPU keeps decoding 16-bit code until a far jump reloads cs with a selector from the new table, so jmp dword 0x08:pm_entry loads selector 0x08, the code descriptor, and lands in the 32-bit code after bits 32. The dword forces a 32-bit offset in the far pointer. Right after the jump the code reloads every data segment register with 0x10 and sets esp to 0x90000, a stack in free low memory, well above the sector at 0x7C00, below the 640 KiB boundary and 16-byte aligned, as the 32-bit System V ABI wants at a call. call kmain pushes the return address and enters C. If kmain returns, the code halts.

The C side

kmain.cc
void kmain(void)
{
    volatile unsigned short *vga = (volatile unsigned short *)0xB8000;
    const char *msg = "Hello from C";

    for (int i = 0; msg[i] != '\0'; i++)
        vga[i] = (unsigned short)(0x0F00 | (unsigned char)msg[i]);

    for (;;)
        __asm__ volatile ("hlt");
}

The VGA text buffer sits at physical address 0xB8000, and since the GDT maps linear addresses to physical ones one to one, the pointer works as written. Each screen cell is a 16-bit value: the low byte is the character and the high byte the attribute, so 0x0F00 | ch is white on black. volatile stops the compiler from deleting or reordering stores to memory it believes nothing reads. The halt loop keeps the function from returning into the assembly's own hlt loop, which is also fine, but making the C function the end of the program is clearer.

The linker script

The two object files must be placed at 0x7C00 and the signature must land at offset 510. A linker script does both:

link.ldText
ENTRY(start)
SECTIONS
{
    . = 0x7C00;
    .text   : { *(.boot) *(.text*) }
    .rodata : { *(.rodata*) }
    .sig 0x7DFE : { SHORT(0xAA55) }
}

*(.boot) comes first so that start, the first code in the file, is at 0x7C00. The .sig output section is pinned to 0x7DFE, which is 0x7C00 + 510, and SHORT(0xAA55) emits the two bytes 55 AA in little-endian order. With a flat binary output format, ld fills the gap between the end of .rodata and the signature with zeros.

Build

Shell
nasm -f elf32 boot.asm -o boot.o
gcc -m32 -ffreestanding -fno-pie -fno-stack-protector \
    -fno-asynchronous-unwind-tables -Os -c kmain.c -o kmain.o
ld -m elf_i386 -T link.ld --oformat binary -o boot.bin boot.o kmain.o
ls -l boot.bin
Text
-rw-r--r-- 1 user user 512 Nov 23 10:00 boot.bin

Each flag has a reason. -m32 and -m elf_i386 produce and link 32-bit code. -ffreestanding says the program has no hosted environment, so the compiler does not assume a main or the standard library functions. -fno-pie stops the compiler from emitting position-independent code, which on 32-bit x86 uses a helper to find its own address that does not exist here. -fno-stack-protector removes the canary check that would call __stack_chk_fail, a function you do not have. -Os keeps the code small enough to fit. The size must be 512 bytes; the linker script puts the signature at the end, and if the code grew past 0x7DFE the link would fail with an overlap error, which is a better way to find out than a silent corruption.

Confirm the signature with xxd boot.bin | tail -1, which should end 55aa. Then run the file in an emulator as in the previous post, and the screen shows the text in white on black.

What can go wrong

If the machine resets as soon as cr0 changes, the GDT is wrong or the far jump targets a bad selector, because a fault with no handler is a triple fault and the CPU resets. In QEMU, -no-reboot -d int shows the fault. If the text shows but looks garbled, check that the stores go through a volatile pointer and that esp is not overlapping the screen buffer or the code. If the build fails with a relocation error, the usual cause is mixing 16-bit and 32-bit sections without the elf32 format: an R_386_16 relocation for gdt_desc is accepted by GNU ld because the address is below 64 KiB, but it overflows if the code grows beyond that. And if kmain crashes on its first call, esp was never set or points to unmapped space.

Passing arguments

C code on 32-bit x86 reads arguments from the stack in the cdecl convention. To pass a value from assembly, push it before the call, and remove it afterward:

nasm
    push dword 0x7C00
    call kmain
    add  esp, 4

Then declare void kmain(unsigned int base). A common use is passing the boot drive number, saved from dl in the real-mode part before the mode switch, so the kernel knows which disk to read.

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.