Saturday, October 13, 2012

Writing a Basic Boot Code

When we first power on a PC, it usually does not have an operating system in ROM or RAM. BIOS is the first prog. that runs at start-up. BIOS is actually the firmware in ROM. The actual job of BIOS is to load the first sector of available boot-able disc and execute it. This is The only thing BIOS knows. So the small program situated in the first sector of the boot-able disc is known as a bootstrap loader, bootstrap or boot loader. This small program's job is to load other data and programs which are then executed from RAM.

This boot sector program is directly loaded by the BIOS at boot time. It is only 512 bytes in size.This sector of a hard disk is also known as Master Boot Record. This code is get loaded at 7C00. The last two bytes of the sector are checked for the values 0x55 and 0xAA while loading this in memory. If these are OK, the BIOS jumps to the address 7C00.

Generally this Master Boot Code can do following things:
  • It can load another boot sector.
  • It can load a second stage boot loader
  • It can load the kernel directly.
So it was all about boot primary booting.Another thing,which is very important to understand,that is BIOS interrupts.
"BIOS interrupt calls are a facility that DOS programs and some other software, such as boot loaders, use to invoke the facilities of the Basic Input/Output System.Boot loaders rely on them, most operating systems do not (the Linux kernel does not use BIOS interrupts once it has been started). MSDOS does use BIOS interrupts.The boot loader has access to BIOS interrupts, which are subroutines that can be invoked by the INT instruction (software interrupts)."

In this example we will only use "INT 0x10".
It is recommended to use virtual machine and virtual floppy/disc image for this work.
So Lets get started,
So first we we need to create an empty floppy disc image.

fallocate -l 1474560 image.vfd

This will create an empty floppy image called "image.vfd"After that we need to attach this image to our virtual machine.
So now let's have look at the code. Generally all boot sector programs,(e.g. GRUB), are written in assembly. So here is a very basic code Boot Code that will only prints a line on Monitor while booting.

We have to compile this code using nasm:

nasm bootloader.asm -f bin -o bootloader.bin

After successful compilation we will get the binary and we need to write this to the first sector of the booatble disc so that the BIOS can load and execute it. In this case we will write it into our virtual floppy image we have created earlier. This can be done is this way

dd if=bootloader.bin bs=512 of=/dev/fd0

After writing this code to your disc just reboot your virtual system attaching the bootable disc,it will print "Hi!I am Debasish and this is my first Bootloader! :) :) :)" and halt.

Reference : an interrupt