w1coding.comAll tutorials

Assembly Bootloader

Assembly lessons
  1. Environment Setup
  2. Introduction
  3. Syntax
  4. Datamovement
  5. Operators
  6. Control
  7. Loops
  8. Interupts
  9. Functions
  10. Memory
  11. System
  12. Debugging
  13. Macros
  14. Execution
  15. Floating
  16. Interupts
  17. Optimization
  18. Linking
  19. Inline
  20. Registers
  21. Bootloader
  22. Macros
  23. Stack
  24. Call
  25. Technique
  26. Responsive

Writing a Bootloader in Assembly

A bootloader is a small program that runs when a computer is powered on or restarted. It’s responsible for loading the operating system into memory.

Step 1: Bootloader Structure

The bootloader must be less than 512 bytes, as it will be loaded into the first sector of the disk. The bootloader should be in the Master Boot Record (MBR), which is the first sector (sector 0) of the disk.

The MBR consists of:

  • Bootloader Code: The first 446 bytes.
  • Partition Table: The next 64 bytes (optional).
  • Boot Signature: The last 2 bytes (0x55, 0xAA).

Step 2: Basic Bootloader Code

The bootloader is written in assembly. A basic bootloader simply prints a message to the screen and then halts.

; bootloader.asm
section .text
    global _start

_start:
    ; Set video mode to 0x03 (80x25 text mode)
    mov ah, 0x00
    mov al, 0x03
    int 0x10

    ; Print message to screen
    mov si, msg
print_char:
    lodsb
    cmp al, 0
    je done
    mov ah, 0x0E
    int 0x10
    jmp print_char
done:

    ; Halt the system
    hlt

section .data
msg db 'Bootloader Initialized', 0
    

Step 3: Assemble and Link the Bootloader

To create the bootloader, you need to assemble it and then add a boot signature at the end:

; Assemble the bootloader
nasm -f bin -o bootloader.bin bootloader.asm

; Add the boot signature (0x55, 0xAA) to the bootloader
dd if=bootloader.bin of=bootloader.img bs=512 seek=1
    

Step 4: Testing the Bootloader

You can test the bootloader using a virtual machine (VM) or an emulator like QEMU:

qemu-system-x86_64 -drive file=bootloader.img,format=raw
    

Key Notes

  • The bootloader must follow a strict layout, including the 512-byte limit for the MBR.
  • The bootloader is often the first step in creating an operating system.
  • Remember to add the boot signature (0x55, 0xAA) to indicate a valid bootloader to the system.