Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 5. WRITING, BUILDING, AND LOADING YOUR


KERNEL 57


# This builds the binary of our kernel from two object files:
# - the kernel_entry , which jumps to main() in our kernel
# - the compiled C kernel
kernel.bin: kernel_entry.o kernel.o
ld -o kernel.bin -Ttext 0x1000 $^ --oformat binary

# Build our kernel object file.
kernel.o : kernel.c
gcc -ffreestanding -c $< -o $@

# Build our kernel entry object file.
kernel_entry.o : kernel_entry.asm
nasm $< -f elf -o $@

# Assemble the boot sector to raw machine code
# The -I options tells nasm where to find our useful assembly
# routines that we include in boot_sect.asm
boot_sect.bin : boot_sect.asm
nasm $< -f bin -I ’../../16 bit/’ -o $@

# Clear away all generated files.
clean:
rm -fr *.bin *.dis *.o os-image *.map

# Disassemble our kernel - might be useful for debugging.
kernel.dis : kernel.bin
ndisasm -b 32 $< > $@

5.3.1 Organising Our Operating System’s Code Base


We have now arrived at a very simple C kernel, that prints out an ’X’ in the corner of
the screen. The very fact that the kernel was compiled into 32-bit instructions and has
successfully been executed by the CPU means that we have come far; but it is now time
to prepare ourselves for the work ahead. We need to establish a suitable structure for
our code, accompanied by a makefile that will allow us easily to add new source files
with new features to our operating system, and to check those additions incrementally
with an emulator such as Bochs.
Similarly to kernels such as Linux and Minix, we can organise our code base into the
following folders:



  • boot: anything related to booting and the boot sector can go in here, such as
    bootsect.asmand our boot sector assembly routines (e.g. printstring.asm,
    gdt.asm,switchtopm.asm, etc.).

  • kernel: the kernel’s main file,kernel.c, and other kernel related code that is
    not device driver specific will go in here.

  • drivers: any hardware specific driver code will go in here.
    Now, within our makefile, rather than having to specify every single object file that
    we would like to build (e.g.kernel/kernel.o,drivers/screen.o,drivers/keyboard.o,
    etc.), we can use a specialwildcarddeclaration as follows:

Free download pdf