Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 5. WRITING, BUILDING, AND LOADING YOUR


KERNEL 50


The involved steps are as follows:


  • Write and compile the kernel code.

  • Write and assemble the boot sector code

  • Create a kernel image that includes not only our boot sector but our compiled
    kernel code

  • Load our kernel code into memory

  • Switch to 32-bit protected mode

  • Begin executing our kernel code


5.2.1 Writing our Kernel


This will not take long, since, for the moment, the main function of our kernel mearly
is to let us know it has been successfully loaded and executed. We can elaborate on the
kernel later, so it is important initially to keep things simple. Save the code in Figure
XXX into a file calledkernel.c.


void main() {
// Create a pointer to a char , and point it to the first text cell of
// video memory (i.e. the top -left of the screen)
char* video_memory = (char*) 0xb8000;
// At the address pointed to by video_memory , store the character ’X’
// (i.e. display ’X’ in the top -left of the screen ).
*video_memory = ’X’;
}

Compile this to raw binary as follows:
$gcc -ffreestanding -c kernel.c -o kernel.o
$ld -o kernel.bin -Ttext 0x1000 kernel.o --oformat binary
Note that, now, we tell the linker that the origin of our code once we load it into
memory will be0x1000, so it knows to offset local address references from this origin,
just like we use[org 0x7c00]in our boot sector, because that is where BIOS loads and
then begins to exectute it.


5.2.2 Creating a Boot Sector to Bootstrap our Kernel


We are going to write a boot sector now, that must bootstrap (i.e. load and begin
executing) our kernel from the disk. Since the kernel was compiled as 32-bit instructions,
we are going to have to switch into 32-bit protected mode before executing the kernel
code. We know that BIOS will load only our boot sector (i.e the first 512 bytes of the
disk), and so not our kernel, when the computer boots, but in Section XXX we have seen
how we can use the BIOS disk routines to have our boot sector load additional sectors
from a disk, and we are vaguely aware that, after we switch into protected mode, the

Free download pdf