Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 5. WRITING, BUILDING, AND LOADING YOUR


KERNEL 42


int my_function () {
return 0xbaba;
}

Save the code in Figure XXXX into a file calledbasic.c, and compile it as follows:


$gcc -ffreestanding -c basic.c -o basic.o
This will produce anobject file, which, being completely unrelated, is not to be con-
fused with the concept of object-oriented programming. Rather than compiling directly
into machine code, the compiler outputsannotatedmachine code, where meta informa-
tion, such as textual labels, that are redundant for execution, remain present to enable
more flexibilty in how the code is eventually put together. One big advantage of this
intermediary format is that the code may be easily relocated into a larger binary file
when linked in with routines from other routines in other libraries, since code in the
object file uses relative rather than absolute internel memory references. We can get a
good view of an object file’s contents with the following command:


$objdump -d basic.o
The output of this command will give something like that in Figure XXX. Note that
we can see some assembly instructions and some additional details about the code. Note
that the syntax of the assembly is very slightly different to that used by nasm, so simply
ignore this part, since we will soon see it in a more familiar format.


basic.o: file format elf32 -i386

Disassembly of section .text:

00000000 <my_function >:
0: 55 push %ebp
1: 89 e5 mov %esp ,%ebp
3: b8 ba ba 00 00 mov $0xbaba ,%eax
8: 5d pop %ebp
9: c3 ret

In order to create the actual executable code (i.e. that will run on our CPU),
we have to use alinker, whose role is to link together all of the routines described in
the input object files into one executable binary file, effectively stitching them together
and converting those relative addresses into absolute addresses within the aggregated
machine code, for example: callwill becomecall 0x12345,
where0x12345is the offset within the output file that the linker decided to place the
code for the routine denoted byfunctionXlabel.
In our case, though, we do not want to link with any routines from any other object
files --- we will look at this shortly --- but nevertheless the linker will convert our anno-
tated machine code file into a raw machine code file. To output raw machine code into
a filebasic.bin, we can use the following command:

Free download pdf