Building your own Operating System (Week 09)

Segments for User Mode

To enable user mode we need to add two more segments to the GDT.

Setting Up For User Mode

Every user mode process requires a few things:

  • The binary from the GRUB module has to be copied to the page frames used for the programs code.
  • A page directory and page tables are needed to map the page frames described above into memory. Because the code and data should be mapped in at 0x00000000 and rising, and the stack should start immediately below the kernel, at 0xBFFFFFFB, and expand towards lower addresses, at least two page tables are required.

Entering User Mode

Executing an iret or lret instruction interrupt return or long return, respectively is the only option to run code with a lower privilege level than the current privilege level (CPL). We build up the stack as though the CPU had raised an inter-privilege level interrupt to enter user mode. The stack should look something like this.

Using C for User Mode Programs

Allowing user mode programs to be written in C but compiling them to flat binaries rather than ELF binaries is one way to make it easier to build user mode applications. The resulting code structure in C is more unexpected, and the entry point, main, may not be at binary offset 0 in the binary. To do that we need to use this code named “start.s”.

-m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles
-nodefaultlibs
-T link.ld -melf_i386  # emulate 32 bits ELF, the binary output is specified
# in the linker script

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store