Writing a Simple Operating System — from Scratch

(Jeff_L) #1

CHAPTER 2. COMPUTER ARCHITECTURE AND THE BOOT


PROCESS 4


Again, an unsophisticated means is adopted here by BIOS, whereby the last two
bytes of an intended boot sector must be set to the magic number0xaa55. So, BIOS
loops through each storage device (e.g. floppy drive, hard disk, CD drive, etc.), reads
the boot sector into memory, and instructs the CPU to begin executing the first boot
sector it finds that ends with the magic number.
This is where we seize control of the computer.


2.2 BIOS, Boot Blocks, and the Magic Number


If we use a binary editor, such as TextPad [?] or GHex [?], that will let us write raw byte
values to a file --- rather than a standard text editor that will convert characters such as
’A’ into ASCII values --- then we can craft ourselves a simple yet valid boot sector.


e9 fd ff 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 00 00 00 00 00 00 00 00 00 00 00 00 55 aa

Figure 2.1: A machine code boot sector, with each byte displayed in


hexadecimal.


Note that, in Figure 2.1, the three important features are:


  • The initial three bytes, in hexadecimal as0xe9,0xfdand0xff, are actually
    machine code instructions, as defined by the CPU manufacturer, to perform an
    endless jump.

  • The last two bytes,0x55and0xaa, make up the magic number, which tells BIOS
    that this is indeed a boot block and not just data that happens to be on a drive’s
    boot sector.

  • The file is padded with zeros (’*’ indicates zeros omitted for brevity), basically to
    position the magic BIOS number at the end of the 512 byte disk sector.
    An important note on endianness. You might be wondering why the magic BIOS
    number was earlier described as the 16-bit value0xaa55but in our boot sector was
    written as the consecutive bytes0x55and0xaa. This is because the x86 architecture
    handles multi-byte values inlittle-endianformat, whereby less significant bytes proceed
    more significant bytes, which is contrary to our familiar numbering system --- though if
    our system ever switched and I had£0000005 in my bank account, I would be able to
    retire now, and perhaps donate a couple of quid to the needy Ex-millionaires Foundation.
    Compilers and assemblers can hide many issues of endianness from us by allowing
    us to define the types of data, such that, say, a 16-bit value is serialised automatically
    into machine code with its bytes in the correct order. However, it is sometimes useful,

Free download pdf