From Grub to protected mode (2)

In this second post I’ll try to explain, how to produce the binary image to use with grub.

As we saw in the last post we have choose an ELF Multiboot binary. The layout for the binary will be:

  • The Multiboot header at the beginning of the binary.
  • Our whole binary will be loaded at 1Mb physical memory.
  • With the ELF headers (using the linker) we will specify that our entry point is the start function.
  • The first stage of our binary, the one that executes before paging is enabled, will be linked starting at physical address 1Mb, a second part of our binary will be linked using the logical address 0xC0000000, this logical address will correspond, after enabling paging, to the physical address of 1 Mb.

The Multiboot header in our case is contained in the loader.asm file, and only consists on the MAGIC label, the FLAGS and the CHECKSUM. What follows is the declaration for the Multiboot header in nasm format.

ALIGN_VAR  equ   0x01 ; align loaded modules on page boundaries
MEMINFO equ  0x2 ; provide memory map
FLAGS equ  ALIGN_VAR | MEMINFO  ; this is the Multiboot 'flag' field
MAGIC equ    0x1BADB002       ; 'magic number' lets bootloader find the header
CHECKSUM equ -(MAGIC + FLAGS) ; checksum required

;; Align to 32 bit, as Multiboot header needs it,http://www.nilo.org/multiboot.html
align 4

;;Multiboot header
dd MAGIC
dd FLAGS
dd CHECKSUM

So after this our kernel needs to setup it own descriptor table, as the Multiboot specification says that the descriptors left by a Multiboot compliant bootloader do not need to be valid after boot, so the first thing our bootloader has to do is setup a 3 segment descriptors, a null segment descriptor, a code and a data ones. Then load their base to the GDTR and load again CR3, to make the change persistent.

Now we have ours segment selector registers loaded with our segment descriptors. We can now initialize the paging structure. Once the paging structure has been created we can safely activate paging and jump to the main function linked at 0xC0000000.

Leave a Reply