这是github上os-tutorial的学习笔记。

(一)创建一个可引导的磁盘

首先要创建一个可以bootable(可引导)的disk(磁盘)。根据1

That location is the first sector of the disk (cylinder 0, head 0, sector 0) and it takes 512 bytes. To make sure that the “disk is bootable”, the BIOS checks that bytes 511 and 512 of the alleged boot sector are bytes 0xAA55.

也就是说,bios通过检查磁盘的前512 bytes的最后两个bytes(511和512)是否是一个特殊标记0xAA55来判断这个磁盘是不是bootable的。不知道UEFI是不是也是这样判断的?

所以根据这个标准,可以创建一个可引导的磁盘文件,大小只需要512 bytes,分为3部分1

  • 0xe9 0xfd 0xff:无限循环指令
  • 0x00:中间填充0
  • 0xAA55:特殊标记

也就是:

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

总共512 bytes。1也提到可以用编辑器直接写这样的一个文件,我写了一个python的脚本来创建:

BOOT_SECTOR_SZ = 512

INFINITE_JMP  = b'\xE9\xFD\xFF'
BOOTABLE_FLAG = b'\x55\xAA' 
BYTE_STUFFING = b'\x00'

boot_sector = INFINITE_JMP \
        + BYTE_STUFFING * (BOOT_SECTOR_SZ - len(INFINITE_JMP) - len(BOOTABLE_FLAG) ) \
        + BOOTABLE_FLAG

with open("boot_sector_simple.bin", "wb") as fo:
  fo.write(boot_sector)
  fo.close()

磁盘内容:

Fig.1 引导磁盘内容
Fig.1 引导磁盘内容

通过Qemu来引导:

i386-softmmu/qemu-system-i386 -hda boot_sector_simple.bin -monitor stdio

Fig.2 Qemu运行引导磁盘
Fig.2 Qemu运行引导磁盘

Booting from Hard Disk...表示引导成功,然后进入无限循环。