Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 3. BOOT SECTOR PROGRAMMING (IN 16-BIT REAL


MODE) 17


3.4.4 Using the Stack


When on the topic of low-level computing, we often hear people talking about thestack
like it is some special thing. The stack is really just a simple solution to the following
inconvenience: the CPU has a limited number of registers for the temporary storage of
our routine’s local variables, but we often need more temporary storage than will fit into
these registers; now, we can obviously make use of main memory, but specifying specific
memory addresses when reading and writing is inconvenient, especially since we do not
care exactly where the data is to be stored, only that we can retrieve it easily enough.
And, as we shall see later, the stack is also useful for argument passing to realise function
calls.
So, the CPU offers two instructionspushandpopthat allow us, respectively, to store
a value and retrieve a value from the top of the stack, and so without worrying exactly
where they are stored. Note, however, that we cannot push and pop single bytes onto
and off the stack: in 16-bit mode, the stack works only on 16-bit boundaries.
The stack is implemented by two special CPU registers,bpandsp, which maintain
the addresses of the stack base (i.e. the stack bottom) and the stack top respectively.
Since the stack expands as we push data onto it, we usually set the stack’s base far away
from important regions of memory (e.g. such as BIOS code or our code) so their is no
danger of overwriting if the stack grows too large. One confusing thing about the stack
is that it actually growsdownwardsfrom the base pointer, so when we issue apush,
the value actually gets stored below --- and not above --- the address ofbp, andspis
decremented by the value’s size.
The following boot sector program in Figure 3.6 demonstrates use of the stack.


Question 2


What will be printed in what order by the code in Figure 3.6? And at what absolute
memory address will the ASCII character ’C’ be stored? You may find it useful to modify
the code to confirm your expectation, but be sure to explainwhyit is this address.


3.4.5 Control Structures


We’d never be comfortable using a programming language if we didn’t know how to
write some basic control structures, such asif..then..elseif..else,for, andwhile.
These structures allow alternative branches of execution and form the basis of any useful
routine.
After compilation, these high-level control structures reduce to simple jump state-
ments. Actually, we’ve already seen the simplest example of loops:


some_label:
jmp some_label ; jump to address of label

Or alternatively, with identical effect:


jmp $ ; jump to address of current instruction

So this instruction offers us anunconditionaljump (i.e. it willalwaysjump); but we
often need to jump based on some condition (e.g. carry on loopinguntil we have looped
ten times, etc.).

Free download pdf