How to write an operating system

This is a quick guide to creating a ‘Hello World’ Operating system that can be booted by Grub First of all you will need to create the assembly file the contains the entry point for grub. Call this ‘start.S

* initial stack

.globl	_os_stack
.align 	4, 0x90
.space 	0x100
.long 0

* lets roll

.globl 	_start
.align 	4, 0x90
jmp	boot_entry

* multiboot compliant header
* the layout of this thing depends on image format

.align 4, 0x90

.long	0x1BADB002		/* magic */
.long   0x00000000		/* no flags if ELF */
.long	0-0x1BADB002-0x00000000	/* checksum */

/* the actual code starts here ... */
* clear NT, learned the hard way...
pushl 	$0

* setup our stack
lea   	_os_stack, %edx
movl  	%edx, %esp

* mulitboot compliant loader (read: grub)
* should put magic value in %eax
pushl	%eax

* clear bss
xorl  	%eax, %eax
movl  	$edata, %edi
movl  	$end, %ecx
subl  	%edi, %ecx

* call our C code initialization ...
pushl 	%ebx
call  	main

incw	(0xb8000)
jmp	darn

Now you will need to create your ‘main.c‘ program

int main(){
	char * vidmem = (char*)0xB8000;
	vidmem[0]  = 'H';
	vidmem[1]  = 0x7;
	vidmem[2]  = 'e';
	vidmem[3]  = 0x7;
	vidmem[4]  = 'l';
	vidmem[5]  = 0x7;
	vidmem[6]  = 'l';
	vidmem[7]  = 0x7;
	vidmem[8]  = 'o';
	vidmem[9]  = 0x7;
	vidmem[10] = ' ';
	vidmem[11] = 0x7;
	vidmem[12] = 'W';
	vidmem[13] = 0x7;
	vidmem[14] = 'o';
	vidmem[15] = 0x7;
	vidmem[16] = 'r';
	vidmem[17] = 0x7;
	vidmem[18] = 'l';
	vidmem[19] = 0x7;
	vidmem[20] = 'd';
	vidmem[21] = 0x7;
	vidmem[22] = '!';
	vidmem[23] = 0x7;

Now we need to compile our program

gcc -nostdinc -c main.c -o main.o
gcc -nostdinc -c start.S -o start.o
ld -nostdinc -Ttext 0x100000 main.o start.o -o kernel
mv kernel /boot/mykernel

…And thats it, you add an entry to your grub ‘menu.lst‘ or using the interactive grub terminal something along the lines of:

grub>root (hd0,a)
grub>kernel /boot/mykernel

3 thoughts on “How to write an operating system”

  1. I realize you posted this in the distant past, but may I ask (if you can remember so far back – “clear NT, learned the hard way…”; what happens if you don’t clear NT?

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s