Implementing Operating System #6

Tharushi Chamalsha
3 min readAug 26, 2021

--

From the previous articles, we have learned to ,

Boot the kernel

Print to kernel

Read from keyboard

A kernel is not supposed to do the application logic itself, but leave that for applications. So this article is related to loading external programs. User mode, in contrast with kernel mode, is the environment in which the user’s programs execute.

We will show how to easily execute a small program in kernel mode.

Loading an external program

Normally we get external programs from drivers and file systems that enable them to load the software from a CD-ROM drive.

Instead of creating drivers, we will use a feature in GRUB called modules to load the program.

GRUB Modules

GRUB may load arbitrary files from the ISO image into memory, and these files are known as modules.

First, you have to edit the file iso/boot/grub/menu.lst. Add the following segment at the end of the file in order to load the module to the GRUB.

module /modules/program

Now create the folder iso/modules. To instruct GRUB how to load our modules, the “multiboot header” — the first bytes of the kernel — must be updated as follows.

Store following code segment inside the loader.s file.

Executing a simple program

Os can perform only a few steps at this stage. So we should write a simple program to execute. Store this file inside the modules folder.

As a result, a test program consisting of a very simple program that writes a value to a register suffices. Stopping Bochs after a while and checking the register for the proper number in the Bochs log will confirm that the program has been completed.

Compiling

Since our kernel cannot understand assembly language we have to compile the above code to binary. You can use the following command in terminal.

nasm -f bin program.s -o program

We must first locate the application in memory before proceeding. We can perform this totally in C if the contents of ebx are supplied as an argument to kmain.

In order to use arguments in kmain make a header file named multiboot.h.

multiboot.h

Now include this header file to the kmain.c, and now we can jump to the code. Since it is easier to parse the multiboot structure in C than assembly code, calling the code from C is more convenient. Try this code in kmain.

You can check whether the program is in our OS from borchlog.txt file. There should be new line looking like this.

We have successfully started a program in our OS!

You can refer to my GitHub repository if you face any difficulty when referring to the article.

--

--