Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 5. WRITING, BUILDING, AND LOADING YOUR


KERNEL 46


So the value0xbabais stored directly to the appropriate position of the stack, such that
it will occupy the first 4 bytes above (though physically below, since the stack grows
downwards) the base pointer.
Now, being a computer program, our compiler can distinguish different numbers as
easily as we can distinguish different variable names, so what we think of as the variable
myvar, the compiler will think of as the addressebp-0x4(i.e. the first 4 bytes of the
stack). We see this in the next instruction,mov eax,[ebp-0x4], which basically means,
’store the contents ofmyvarineax’, again using efficiently address computation; and
we know from the previous function thateaxis used to return a variable to the caller of
our function.
Now, before theretinstruction, we see something new: theleave instruction.
Actually, theleaveinstruction is an alternative to the following steps, that restore the
original stack of the caller, recipricol of the first two instruction of the function:


mov esp , ebp ; Put the stack back to as we found it.
pop ebp

Though only a single instruction, it is not always the case thatleaveis more efficient
than the seperate instructions [?]. Since our compiler chose to use this instruction, we
will leave that particular discussion to other people.


5.1.3 Calling Functions


Not let’s look at the C code in Figure XXX, which has two functions, where one function,
callerfunction, calls the other,calleefunction, passing it an integer argument.
The called function simply returns the argument it was passed.


void caller_function () {
callee_function (0 xdede);
}

int callee_function(int my_arg) {
return my_arg;
}

If we compile and disassemble the C code, we will get something similar to that in
Figure XXX.


00000000 55 push ebp
00000001 89E5 mov ebp ,esp
00000003 83EC08 sub esp ,byte +0x8
00000006 C70424DEDE0000 mov dword [esp],0xdede
0000000D E802000000 call dword 0x14
00000012 C9 leave
00000013 C3 ret
00000014 55 push ebp
00000015 89E5 mov ebp ,esp
00000017 8B4508 mov eax ,[ebp+0x8]
Free download pdf