Stepping into a Simple Operating System

Ishini Hettiarachchi
3 min readOct 10, 2022

--

#Step 02 : Implement with C language

In our previous article we discussed how to get the start to build a simple OS using assembly language. This time let’s pay our attention on how to use C language instead of Assembly to the implementation of building OS.

Setting Up a Stack

Point the esp register to the end of an area of free memory so that correctly aligned is little bit harder than setting up a stack. Using bss section is better rather than using data section in order to reduce the size of the OS executable. Because, GRUB may understand ELF and it will allocate any memory reserved in the bss section when loading the OS.

The following NASM pseudo-instruction resb is used to declare uninitialized data. For that we need to copy this code to ‘loader.s’ file:

Then, the stack pointer can be set up by pointing esp to the end of the kernel_stack memory:

Calling C Code from Assembly

As the next step we have to call a C function from assembly code. Here we use cdecl calling convention since it is the one used by GCC. According to this convention arguments to a function should be passed via the stack. The return value of the function is placed in the eax register. The following code shows an example for C function and we may have to save it as kmain.c :

Then we have to call this function using assembly language. For that we can include following code segment to the loader.s file.

Compiling C Code

Compiling the C code for the Operating System needs a lot of flags to GCC need to be used.

The flags used here for compiling the C code are:

-m32 -nostdlib -nostdinc -fno-builtin -fno-stack-protector -nostartfiles
-nodefaultlibs

As a whole here is how the loader.s file can be seen after including all the code segments.

3.4 Build Tools

Setting up some build tools make it easier to compile and test-run the OS. , Although there are many build systems available, we use make in this implementation. You can see a simple Makefile that we created to define how to compile the kernel and boot up the OS.

Now your working directory should look like this.

.
|-- bochsrc.txt
|-- iso
| |-- boot
| |-- grub
| |-- menu.lst
| |-- stage2_eltorito
|-- kmain.c
|-- loader.s
|-- Makefile

Now we can compile the kernel and boot up the OS in Bochs by using “make run” command. Then you will get the following output.

If you have carefully followed above mentioned steps, you can see EAX=00000006 in the bochslog.txt logfile. Following command will generate the log file.

cat bochslog.txt

Hope this process provide an easier way to develop OS compared to the using Assembly to go with the implementation. You can find my GitHub Repo through following link:

ishinihettiarachchi/IshiniHD_minimal_OS at Setup_Booting_OS (github.com)

Thank you for reading and invite you gather with the next article to move forward with the developing OS.

--

--