Memory manager
Description
A new stack
Your kernel booted, and you can use printf, now it’s time to set up the memory.
The bootloader has very few guarantees on the machine state, so you will need to reserve a new stack, and set up a new GDT.
Your first task is to reserve a new stack, using the provided memory allocator (don’t forget to initialize it).
Simply reserve a large block of memory, and assign ESP and EBP to it’s base.
Again, don’t forget the stack grows downwards, so the base is the stack’s highest address.
A new GDT
Then, you will have to setup these segments in your GDT:
- The null segment
- A kernel code segment
- A kernel data segment
- A userland code segment
- A userland data segment
- A TSS to be able to switch from userland to kernelland.
The creation of the userland segment may be postponed to the binary loading. In fact, you cannot determine the size of the code segment without looking at the binary.
After that, reload the segment registers with their new values (CS, DS, SS, ES, FS, GS)
Recommended methodology
- Set up your own GDT
- You will need a kernel allocator for some libc functions, a dummy one will suffice, but don’t forget that kernel data should not appear in the rom address space.
- When setting up your GDT, you will face tons of reboot. It often means that your GDT is not set correctly.
Notes
Some memory areas are already busy, you should take care of this when creating
the user data and code segment. You can use the multiboot_info_t structure
given by GRUB to find those areas:
- the kernel code
- the user program
- I/O mappings (video framebuffer)
- etc…
References
- Intel manual Vol. 3A chapter 3.4 (LOGICAL AND LINEAR ADDRESSES)
- https://wiki.osdev.org/GDT_Tutorial (Flat setup)