Boot Loader

October 17, 2009

I’ve been busy writing my own boot loader for the past few days, it’s really quite simple to make a basic boot loader so I’m going to explain it a bit here.
What is a boot loader
A boot loader is a very small program (512 bytes) that is loaded by the BIOS when you turn on your computer, boot loaders can be placed on many forms of media, such as, hard drive disk, floppy disk, CD/DVD-ROM, flash memory and others.
The job of the boot loader is, in the most basic form, is the loading the kernel of whatever operating system you are using, such as Windows or Linux, more advanced boot loaders can do other stuff to prepare the system such as switching into Protected Memory mode.

While a very basic boot loader is very simple to make, in general you need to do a lot of work to make something that is functional, for example the size of the initial boot loader is extremely limited, 510 bytes is very very little space to work in so most of the code in this part is designed to load a additional boot loader in higher memory.
When the computer first boots it is placed in Real Mode, in this mode you can only use the 8 and 16 bit registers and you can only address memory up to the 1MB mark, so kernels larger that 1MB need to be loaded by using UnReal mode which allows access above the 1MB mark while not fully switching into Protected Mode.
Code Example

org 0x7C00
jmp 0x0:_start
_start:
push cs
pop ds
cli
hlt
times 510-($-$$) db 0
dw 0xAA55

org 0×0000

This is the code origin, the actual bootloader is loaded by the BIOS at 0x7C00 however the BIOS can place the address as 0×0000:7C00 or 0x07C0:0×0000 (CS:IP), the org 0x7C00 ensures IP = 0x7C00

jmp 0×0000:_start

This jumps to the _start label while also making sure CS = 0×0000

push cs
pop ds

This is just to make sure CS and DS are equal

cli
hlt

Disables interrupts and halts the processor, you would normally place your boot loader code before this.

times 510-($-$$) db 0

This zeros the remaining bytes up to the 510th byte.

dw 0xAA55

Boot signature, this two byte code at bytes 511 and 512 tells the BIOS that there is a boot loader and it should load the code into memory.

To compile and write the boot loader do the following:

nasm loader.asm -o loader.bin
dd if=loader.bin of=/dev/fd0 bs=512

Replace /dev/fd0 with the device you want to write to.


Follow

Get every new post delivered to your Inbox.