若您覺得文章寫得不錯,請點選文章上的廣告,來支持小編,謝謝。
想要寫個開機就執行的程式,要先了解電腦的開機過程,電腦開機過程有:
想要寫個開機就執行的程式,要先了解電腦的開機過程,電腦開機過程有:
1. 加電:機器開始供電時,CPU會從 0xffff0 處開始執行指令。
2. 自我檢測(POST):檢查設備是否存在與正常運作,有問題會發出聲音。
3. 初始化設備:系統 BIOS 會先在 ROM 的起始位址 0xC0000 處找顯示卡 BIOS,並由顯示卡 BIOS 來初始化顯示卡,接著系統BIOS 會再找其他設備的 BIOS 程序,用這些 BIOS 內部的初始化代碼來初始化相關設備。
4. 測試設備:測試 CPU 的工作頻率、RAM、硬碟、串列埠、並列埠等。
5. 更新 ESCD。
6. 啟動作業系統:根據指定的順序從軟碟、硬碟或是CD ROM來啟動作業系統,會從此裝置的 cylinder 0, head 0, sector 1 (對 hard disk 來說就是 Master Boot Record, MBR),讀取 512 bytes 載入至記憶體的 0x7C00,並檢查最後兩 bytes 是否為 0x55AA,若是則跳到該程式去。
詳細內容可參考<自己動手寫作業系統>第一章,而我們所要做的事就是如何把程式載到記憶體裡,測試環境為Ubuntu 14.04 LTS Desktop 32-bit。
程式碼
Makefile
qemu 指令
結果

程式碼
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
.text | |
.globl start | |
.code16 | |
start: | |
movb $0xE, %ah # write character in text mode for int 10h | |
movb $'H', %al # write 'H', 'o', 'l', 'a', 'n', ' ', 'w', 'o', 'r', 'l', 'd' | |
int $0x10 | |
movb $'o', %al | |
int $0x10 | |
movb $'l', %al | |
int $0x10 | |
movb $'a', %al | |
int $0x10 | |
movb $'n', %al | |
int $0x10 | |
movb $' ', %al | |
int $0x10 | |
movb $'w', %al | |
int $0x10 | |
movb $'o', %al | |
int $0x10 | |
movb $'r', %al | |
int $0x10 | |
movb $'l', %al | |
int $0x10 | |
movb $'d', %al | |
int $0x10 | |
ret | |
# Fill NOP instruction (opcde = 0x90) till base offset 0x1FE. | |
.org 0x1FE, 0x90 | |
# This indicates boot disk | |
boot_flag: .word 0xAA55 |
Makefile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AS = as | |
LD = ld | |
OBJCOPY = objcopy | |
.s.o: | |
$(AS) -a $< -o $*.o > $*.map | |
all: disk.img | |
disk.img: holanBoot.out | |
$(OBJCOPY) -O binary -j .text $< $@ | |
holanBoot.out: holanBoot.o | |
${LD} -r -Ttext 0x7c00 -e start -s -o holanBoot.out holanBoot.o | |
clean: | |
rm -f disk.img holanBoot.out holanBoot.o holanBoot.map |
qemu 指令
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
qemu-system-i386 -hda disk.img |

參考資料
[1] 開機見 Hello World
[2] 自己動手寫作業系統
沒有留言:
張貼留言