Boot Sector Programming
1. Introduction
A Boot sector program is a type of software that fits into very first 510 bytes of Master Boot Record (MBR). When the computer boots, this program is loaded by the BIOS firmware into RAM and then executed in real mode.
Today, the BIOS has been replaced by the UEFI BIOS. In brief, the UEFI BIOS uses the GUID Partition Table (GPT) scheme, and can launch an 64 bits EFI app with the PE32+ binary format (UEFI follows the Microsoft standard). If you are looking to develop something modern, you should use the UEFI BIOS and not the legacy BIOS.
In this article I will demonstrate how easy is to develop a stage 1 bootloader for the legacy BIOS.
Note: Be aware that the main purpose here isn’t to teach the assembly programming language.
2. Development Environment
To develop boot sector programs you don’t need a big toolkit, three open source tools will suffice.
- NASM: Assembler with 16 bits support
- QEMU: Hardware emulator
- GDB: Assembly debugger
For example, we can easily install this tools using APT package manager on debian-based distros.
2.1 First Program
To do the first test of the development environment, we will use a simple hello world program.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[bits 16]
[org 0x7c00]
jmp 000000h:07c00h
mov al, 1 ; set atributte string write mode
mov bh, 0 ; VGA page number
mov bl, 0000_1111b ; background - foreground colors
mov cx, msg_size
mov dl, 10 ; line
mov dh, 1 ; column
push cs ; alternative: mov si, cs
pop es ; mov es, si
mov bp, msg
mov ah, 13h ; write string
int 10h ; call BIOS
cli ; disable interrupts
hlt ; halt execution until interrupt raise (when?)
msg: db "hello world"
msg_size: equ $-msg
times 510-($-$$) db 0 ; padding to fiil the bootsector
dw 0AA55h ; bootable flag always goes at 0x01B8 offset
Let’s assemble it using NASM. The argument -f flat means that we are using a FLAT file format.
$ nasm -f bin hello_world.asm -o hello_world.bin
Before run, let’s check if this really is a bootable program with the Linux file command.
$ file ./hello_world.bin
hello_world.bin: DOS/MBR boot sector
The output of file command confirm, we have a MBR bootable program. Now, let’s start the emulation with QEMU.
$ qemu-system-i386 ./hello_world.bin
If you see this screen above, cool, it’s working.
3. MBR
3.1 Floopy Disk
4. BIOS
The BIOS is a firmware that is recorded on.