Writing a Simple Operating System — from Scratch

(Jeff_L) #1

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


MODE) 15


mov al, [0 x7c1e]
int 0x10 ; Does this print an X?

jmp $ ; Jump forever.

the_secret:
db "X"
; Padding and magic BIOS number.

times 510-($-$$) db 0
dw 0xaa

Firstly, when we declare some data in our program, we prefix it with a label (thesecret).
We can put labels anywhere in our programs, with their only purpose being to give us a
convenient offset from the start of the code to a particular instruction or data.


b4 0e b0 1e cd 10 a0 1e 00 cd 10 bb 1e 00 81 c
00 7c 8a 07 cd 10 a0 1e 7c cd 10 e9 fd ff 58 00
00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00
*
00 00 00 00 00 00 00 00 00 00 00 00 00 00 55 aa

Figure 3.5:


If we look at the assembled machine code in Figure 3.5, we can see that our ’X’,
which has an hexadecimal ASCII code0x58, is at an offset of 30 (0x1e) bytes from the
start of the code, immediately before we padded the boot sector with zeros.
If we run the program we see that only the second two attempts succeed in printing
an ’X’.
The problem with the first attempt is that it tries to load the immediate offset into
alas the character to print, but actually we wanted to print the characteratthe offset
rather than the offset itself, as attempted next, whereby the square brackets instruct the
CPU to do this very thing - store thecontentsof an address.
So why does the second attempt fail? The problem is, that the CPU treats the offset
as though it was from the start of memory, rather than the start address of our loaded
code, which would land it around about in the interrupt vector. In the third attempt,
we add the offsetthesecretto the address that we beleive BIOS to have loaded our
code,0x7c00, using the CPUaddinstruction. We can think ofaddas the higher level
language statementbx = bx + 0x7c00. We have now calculated the correct memory
address of our ’X’ and can store the contents of that address inal, ready for the BIOS
print function, with the instructionmov al, [bx].
In the fourth attempt we try to be a bit clever, by pre-calculating the address of the
’X’ after the boot sector is loaded into memory by BIOS. We arrive at the address0x7c1e
based on our earlier examination of the binary code (See Figure 3.5) which revealed that
’X’ was0x1e(30) bytes from the start of our boot sector. This last example reminds

Free download pdf