User:Derekbank/C Kernel

From OSDev Wiki
(Redirected from Tutorial:C Kernel)
Jump to: navigation, search

Prerequisites

You will need to have the GRUB files stage1 & stage2. Download GRUB and copy these files into your os's directory. You will also need nasm, gcc, ld, and qemu. NOTE: Examples are written for linux.

Source Code

Loader.asm:

global loader
extern main
 
MODULE_ALIGN equ 1<<0
MEM_INFO equ 1<<1
FLAGS equ MODULE_ALIGN | MEM_INFO
MAGIC equ 0x1BADB002
CHECKSUM equ -(MAGIC + FLAGS)
 
section .text
align 4
MultiBootHeader:
dd MAGIC
dd FLAGS
dd CHECKSUM
 
STACKSIZE equ 0x4000
 
loader:
call main
cli
hang:
hlt
jmp hang
section .bss
align 4
stack:
resb STACKSIZE

This code basically sets up GRUB and jumps to the kernel

Now for the actually kernel. Kernel.C:

void main(){
    unsigned char* video = (unsigned char*) 0xB8000;
    video[0] = 'O';
    video[1] = 0x07;
    video[2] = 'S';
    video[3] = 0x07;
}

This simple kernel writes 'OS' to the screen. It should be self-examplatory, except for 0x07. That tells the graphics card the it will be written in white on black and doesn't blink.

Now we need to a linker script Link.ld:

ENTRY (loader)
 
SECTIONS{
  . = 0x00100000;
  .text :{
    *(.text)
  }
 
  .rodata ALIGN (0x1000) : {
    *(.rodata)
  }
 
  .data ALIGN (0x1000) : {
    *(.data)
  }
 
  .bss : {
    sbss = .;
    *(COMMON)
    *(.bss)
    ebss = .;
  }
}

Last but not least, the build script. Build.sh:

nasm -f elf -o loader.o Loader.asm
gcc -o kernel.o -c Kernel.C -Wall -Wextra -nostdlib
ld -T Link.ld -o os.bin loader.o kernel.o
cat stage1 stage2 pad os.bin > image.img

Building and Booting

There is one file that is still missing, pad. Use the linux command "dd if=/dev/zero of=pad bs=1 count=750" to create it. (without the quotation marks) Type the command chmod 777 Build.sh Then type ./Build.sh This should take a moment. Debug any errors occurred. Now to boot it, type qemu -fda image.img It will show some grub stuff. Type in kernel 200+18 <enter> boot <enter>

Voila, the letters O and S are printed at the top.

Personal tools
Namespaces
Variants
Actions
Navigation
About
Toolbox