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
*/
.data

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

/*
* lets roll
*/
.text

.globl 	_start
.align 	4, 0x90
_start:
jmp	boot_entry

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

.align 4, 0x90
boot_hdr:

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

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

/*
* 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
cld
rep
stosb

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

/*
* NOTREACHED
*/
darn:
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
grub>boot
Advertisements

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:

WordPress.com Logo

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

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s