自定义引导加载程序找不到内核

Custom Bootloader doesn't find Kernel

我一直在研究一个业余爱好引导加载程序和内核,但无论如何引导加载程序都找不到内核。 这是引导加载程序:

%define BUFFER_SEG 0x2000
%define BUFFER_OFF 0x0000
%define LOAD_SEG 0x1000
%define LOAD_OFF 0x0000

[bits 16]
[org 0x7c00]

jmp short start
nop

;DISK DESCRIPTION(BIOS PARAMETER BLOCK)
OEMLabel        db "BOOT    "
BytesPerSector      dw 512
SectorsPerCluster   db 1
ReservedForBoot     dw 1
NumberOfFats        db 2
RootDirEntries      dw 224      ; Number of entries in root dir
                    ; (224 * 32 = 7168 = 14 sectors to read)
LogicalSectors      dw 2880
MediumByte      db 0F0h
SectorsPerFat       dw 9
SectorsPerTrack     dw 18       ; Sectors per track (36/cylinder)
Sides           dw 2
HiddenSectors       dd 0
LargeSectors        dd 0
DriveNo         dw 0
Signature       db 0x29 
VolumeID        dd 00000000h
VolumeLabel     db "myOS       "
FileSystem      db "FAT12   "

;BOOTLOADER
start:
    xor ax, ax
    mov ds, ax
    cli
    mov ss, ax
    mov sp, 0x7c00
    cld
    clc
    sti
    mov [drive], dl

load_root:
    mov ax, 19
    call lba_to_hts
    mov ah, 2
    mov al, 14
    mov si, BUFFER_SEG
    mov es, si
    mov bx, BUFFER_OFF
    int 13h
    jc reset
    mov si, load_root_str
    call print

search_file:
    mov di, BUFFER_OFF
    mov cx, word [RootDirEntries]
    xor ax, ax
.loop_search:
    xchg cx, dx
    mov si, filename
    mov cx, 11
    rep cmpsb
    je file_found
    add ax, 32
    mov di, BUFFER_OFF
    add di, ax
    xchg dx, cx
    loop .loop_search
    jmp file_not_found

file_found:
    mov ax, word [es:di+15]
    mov [cluster], ax
    mov ax, 1
    call lba_to_hts
    mov di, BUFFER_OFF
    mov bx, di
    mov ah, 2
    mov al, 9

load_FAT:
    mov si, FAT_str
    call print
    int 13h
    jnc load_file
    call reset
    jnc load_FAT
    jmp disk_error

load_file:
    mov si, load_file_str
    call print
    mov ax, LOAD_SEG
    mov es, ax
    xor bx, bx
    mov ah, 2
    mov al, 1
.load_sector:
    mov ax, word [cluster]
    add ax, 31
    call lba_to_hts
    mov ax, LOAD_SEG
    mov es, ax
    mov bx, word [pointer]
    pop ax
    push ax
    ;stc
    int 13h
    jnc next_cluster
    call reset
    jmp .load_sector

next_cluster:
    mov ax, [cluster]
    xor dx, dx
    mov bx, 3
    mul bx
    mov bx, 2
    div bx
    mov si, BUFFER_OFF
    add si, ax
    mov ax, word [ds:si]
    or dx, dx
    jz .even
.odd:
    shr ax, 4
    jmp short finish_load
.even:
    and ax, 0FFFh

finish_load:
    mov word [cluster], ax
    cmp ax, 0FF8h
    jae .jump_to_file
    add word [pointer], 512
    jmp next_cluster
.jump_to_file:
    pop ax
    mov dl, byte [drive]
    jmp LOAD_SEG:LOAD_OFF

;SUBROUTINES
file_not_found:
    mov si, not_found_str
    call print
    jmp reboot
print:
    pusha
    mov ah, 0x0E
.next:
    lodsb
    cmp al,0
    je .done
    int 0x10
    jmp .next
.done:
    popa
    ret
lba_to_hts:
    push ax
    push bx
    mov bx, ax
    xor dx, dx
    div word [SectorsPerTrack]
    add dl, 1
    mov cl, dl
    mov ax, bx
    xor dx, dx
    div word [SectorsPerTrack]
    xor dx, dx
    div word [Sides]
    mov dh, dl
    mov ch, al
    pop ax
    pop bx
    mov dl, [drive]
    ret
reset:
    mov ah, 0
    int 13h             ;reset disk
    jc disk_error           ;if failed jump to search fail
    ret
disk_error:
    mov si, disk_error_str
    call print
reboot:
    mov si, reboot_pmpt
    call print
    mov ax, 0
    int 16h
    mov ax, 0
    int 19h

;DATA
load_root_str db 'Loading Root',13,10,0
disk_error_str db 'Disk Error!',13,10,0
reboot_pmpt db 'PRESS A KEY TO REBOOT',13,10,0
not_found_str db 'KERNEL NOT FOUND',13,10,0
FAT_str db 'Loading FAT',13,10,0
load_file_str db 'Loading KERNEL',13,10,0
drive dw 0
cluster dw 0
pointer dw 0
filename db 'KERNEL  BIN',0
;PADDING AND SIGNATURE
times (510-($-$$)) db 0x00
dw 0AA55h

这是内核:

[bits 16]               ;16-bit binary format

;VECTORS
os_vectors:
    jmp os_main

;KERNEL
os_main:
    cli             ;clear interrupts
    mov ss, ax          ;set stack segment and pointer
    mov sp, 0FFFFh
    sti             ;restore interrupts
    cld             ;set RAM direction(for strings)
    mov ax, 1000h           ;set registers to match kernel location
    mov ds, ax
    mov es, ax
    mov fs, ax
    mov gs, ax
    mov si, hello           ;print welcome
    call print_string
    hlt

;SUBROUTINES
print_string:
    mov ah, 0x0e

.next_char:
    lodsb
    cmp al,0
    je .done_print
    int 0x10
    jmp .next_char

.done_print:
    ret

;DATA
hello db 'Hello',0

;PADDING
times (512-($-$$)) db 0x00

我填充了扇区的其余部分,因为我听说如果它不是一个完整的扇区大小,一些模拟器无法正确读取它。我使用命令

#! bin/bash
cd image
hdiutil create -fs MS-DOS -sectors 2880 floppy
cd ../system
nasm -f bin boot.asm -o boot.bin
nasm -f bin kernel.asm -o kernel.bin
cd ..
dd conv=notrunc if=system/boot.bin of=image/floppy.dmg
dev=`hdid -nomount image/floppy.dmg`
sudo mkdir tmp-loop
sudo cp system/kernel.bin tmp-loop/
sudo mount -t msdos ${dev} tmp-loop
diskutil umount tmp-loop
hdiutil detach ${dev}
sudo rm -rf tmp-loop
hdiutil convert image/floppy.dmg -format UDTO -o image/image.iso

构建然后在 qemu 中模拟它。我正在 Macbook Air 上执行此操作。 当我在 qemu 中模拟我的引导加载程序时,我总是得到字符串告诉我它找不到内核。我不知道为什么也不知道如何解决这个问题。

在大多数情况下,您的代码具有正确的想法。引导加载程序中的主要问题在 load_filenext_cluster 中。 lba_to_hts 中也存在错误。您的内核也有一些错误需要更正。

考虑这是一个严肃的建议 - 安装 BOCHs 的副本并使用它的调试器而不是 QEMU。 BOCHs 是引导加载程序的理想选择,因为它可以正确处理 20 位 segment:offset 寻址。对于任何实模式代码,BOCHs 都是一个极好的工具。学习正确使用调试器可以让您看到寄存器中的内容;检查内存,设置断点等。您应该能够通过一些经验发现此答案中确定的错误。


boot.asm

中的问题

lba_to_hts中的错误可以在这里看到:

lba_to_hts:
    push ax
    push bx

    ...

    pop ax
    pop bx

你在开始时将 AX 然后 BX 压入堆栈,但你需要以 反向 顺序将它们弹出。应该是:

push ax
push bx

...

pop bx
pop ax

next_cluster 中,这一行有问题:

mov ax, word [ds:si]

您已经计算出 FAT (FAT12) 中的偏移量 table 可以在其中找到下一个簇。问题是 DS 没有指向 FAT table 在内存中的段,它被设置为 0000h。您不能使用:

mov ax, word [es:si]

因为你设置了ES到内核加载段(LOAD_SEG = 1000h)。您可以选择保存 DS 寄存器(压栈),用 BUFFER_SEG 加载 DS。那么你可以使用:

mov ax, word [ds:si]

然后,当 next_cluster 完成时,您必须通过从堆栈中弹出旧值来恢复 DS。需要注意的是,mov ax, word [ds:si]mov ax, word [si]是一样的,只是在指令上会不必要地输出DS前缀。如果内存操作数中的寄存器不包含 BP 则内存访问通过 DS 隐式完成,否则隐式 SS。经验法则:不要添加不必要的覆盖,因为它们会增加代码大小。

我不推荐这种方法。解决这个问题的最简单方法是将 BUFFER_OFF 放在与引导加载程序相同的段(段 0000h)中。从 0000h:8000h 到 0000h:0ffffh 有 32KiB 的空闲内存。如果您修改代码以将 FAT 和根目录结构加载到 0000h:8000h,那么您可以通过 DS 访问引导加载程序数据、FAT 结构和根目录条目。当您加载内核时,您可以将 ES 切换为 LOAD_SEG.

这段代码还有一个问题:

finish_load:
    mov word [cluster], ax
    cmp ax, 0FF8h
    jae .jump_to_file
    add word [pointer], 512
    jmp next_cluster

您通过将文件与 0FF8h 进行比较来检查是否已到达文件的最后一个簇。如果它小于 0FF8h,则将 512 添加到 [pointer] 以前进到要读取的缓冲区中的下一个偏移量。问题是 jmp next_cluster 不会返回读取下一个簇! jmp next_cluster 应该是 jmp load_sector


load_file 你有这个代码:

load_file:
    mov si, load_file_str
    call print
    mov ax, LOAD_SEG
    mov es, ax
    xor bx, bx
    mov ah, 2
    mov al, 1


.load_sector:
    mov ax, word [cluster]
    add ax, 31
    call lba_to_hts
    mov ax, LOAD_SEG
    mov es, ax
    mov bx, word [pointer]
    pop ax
    push ax
    ;stc
    int 13h
    jnc next_cluster
    call reset
    jmp .load_sector

next_cluster:

就在 .load_sector 标签之前,您为 Int 13h BIOS 调用设置了 AX 和 BX 寄存器。不幸的是,您在标签 .load_sector: 之后的行中破坏了 AX 和 BX。中间还有一个不正常的POP/PUSH,没有意义。您可以将这部分代码更改为:

load_file:
    mov si, load_file_str
    call print
    mov ax, LOAD_SEG           ; ES=load segment for kernel
    mov es, ax

load_sector:
    mov ax, word [cluster]     ; Get cluster number to read
    add ax, 33-2               ; Add 31 to cluster since FAT data area
                               ; starts at Logical Block Address (LBA) 33
                               ; and we need to subtract 2 since valid
                               ; cluster numbers start at 2
    call lba_to_hts

    mov bx, word [pointer]     ; BX=Current offset in buffer to read to
    mov ax, 201h               ; AH=2 is read, AL=1 read 1 sector

    ;stc
    int 13h
    jnc next_cluster
    call reset
    jmp load_sector

next_cluster:

修改后的代码如下:

%define BUFFER_OFF 0x8000
%define BUFFER_SEG 0x0000
%define LOAD_SEG 0x1000
%define LOAD_OFF 0x0000

[bits 16]
[org 0x7c00]

jmp short start
nop

;DISK DESCRIPTION(BIOS PARAMETER BLOCK)
OEMLabel        db "BOOT    "
BytesPerSector      dw 512
SectorsPerCluster   db 1
ReservedForBoot     dw 1
NumberOfFats        db 2
RootDirEntries      dw 224     ; Number of entries in root dir
                               ; (224 * 32 = 7168 = 14 sectors to read)
LogicalSectors      dw 2880
MediumByte      db 0F0h
SectorsPerFat       dw 9
SectorsPerTrack     dw 18      ; Sectors per track (36/cylinder)
Sides           dw 2
HiddenSectors       dd 0
LargeSectors        dd 0
DriveNo         dw 0
Signature       db 0x29
VolumeID        dd 00000000h
VolumeLabel     db "myOS       "
FileSystem      db "FAT12   "

;BOOTLOADER
start:
    xor ax, ax
    mov ds, ax
    cli
    mov ss, ax
    mov sp, 0x7c00
    sti
    cld
    mov [drive], dl

    mov si, BUFFER_SEG         ; ES=buffer segment. Only has to be set once
    mov es, si
    mov bx, BUFFER_OFF

load_root:
    mov ax, 19                 ; Root directory starts at LBA 19
    call lba_to_hts
    mov ax, (2<<8) | 14        ; Root directory for this media fits in 14 sectors
                               ; Combine 2 moves (AH/AL) into one
                               ; same as 'mov ah, 2' and 'mov al, 14'
    int 13h
    jc reset
    mov si, load_root_str
    call print

search_file:
    mov di, BUFFER_OFF
    mov cx, word [RootDirEntries]
    xor ax, ax
.loop_search:
    xchg cx, dx
    mov si, filename
    mov cx, 11
    rep cmpsb
    je file_found
    add ax, 32
    mov di, BUFFER_OFF
    add di, ax
    xchg dx, cx
    loop .loop_search
    jmp file_not_found

file_found:
    mov ax, word [di+15]       ; Buffer and Bootloader now in same segment DS
                               ; Don't need ES:
    mov [cluster], ax
    mov ax, 1
    call lba_to_hts
    mov bx, BUFFER_OFF
    mov ax, (2<<8) | 9         ; Combine 2 moves (AH/AL) into one
                               ; same as 'mov ah, 2' and 'mov al, 9'    

load_FAT:
    mov si, FAT_str
    call print
    int 13h
    jnc load_file
    call reset
    jnc load_FAT
    jmp disk_error

load_file:
    mov si, load_file_str
    call print
    mov ax, LOAD_SEG           ; ES=load segment for kernel
    mov es, ax

load_sector:
    mov ax, word [cluster]     ; Get cluster number to read
    add ax, 33-2               ; Add 31 to cluster since FAT data area
                               ; starts at Logical Block Address (LBA) 33
                               ; and we need to subtract 2 since valid
                               ; cluster numbers start at 2
    call lba_to_hts
    mov bx, word [pointer]     ; BX=Current offset in buffer to read to
    mov ax, (2<<8) | 1         ; AH=2 is read, AL=1 read 1 sector
                               ; Combine 2 moves (AH/AL) into one
                               ; same as 'mov ah, 2' and 'mov al, 1'
    int 13h
    jnc next_cluster
    call reset
    jmp load_sector

next_cluster:
    mov ax, [cluster]
    xor dx, dx
    mov bx, 3
    mul bx
    mov bx, 2
    div bx
    mov si, BUFFER_OFF
    add si, ax
    mov ax, word [si]
    or dx, dx
    jz .even
.odd:
    shr ax, 4
    jmp short finish_load
.even:
    and ax, 0FFFh

finish_load:
    mov word [cluster], ax
    cmp ax, 0FF8h
    jae .jump_to_file
    add word [pointer], 512    ; We haven't reached end of kernel. Add 512 for next read
    jmp load_sector            ; Go back and load the next sector
.jump_to_file:
    mov dl, byte [drive]
    jmp LOAD_SEG:LOAD_OFF

;SUBROUTINES
file_not_found:
    mov si, not_found_str
    call print
    jmp reboot
print:
    pusha
    mov ah, 0x0E
.next:
    lodsb
    cmp al,0
    je .done
    int 0x10
    jmp .next
.done:
    popa
    ret
lba_to_hts:
    push ax
    push bx
    mov bx, ax
    xor dx, dx
    div word [SectorsPerTrack]
    add dl, 1
    mov cl, dl
    mov ax, bx
    xor dx, dx
    div word [SectorsPerTrack]
    xor dx, dx
    div word [Sides]
    mov dh, dl
    mov ch, al
    pop bx                     ; Need to POP in reverse order to the pushes!
    pop ax
    mov dl, [drive]
    ret
reset:
    mov ah, 0
    int 13h                    ;reset disk
    jc disk_error              ;if failed jump to search fail
    ret
disk_error:
    mov si, disk_error_str
    call print
reboot:
    mov si, reboot_pmpt
    call print
    mov ax, 0
    int 16h
    mov ax, 0
    int 19h

;DATA
load_root_str db 'Loading Root',13,10,0
disk_error_str db 'Disk Error!',13,10,0
reboot_pmpt db 'PRESS A KEY TO REBOOT',13,10,0
not_found_str db 'KERNEL NOT FOUND',13,10,0
FAT_str db 'Loading FAT',13,10,0
load_file_str db 'Loading KERNEL',13,10,0
drive dw 0
cluster dw 0
pointer dw 0
filename db 'KERNEL  BIN',0
;PADDING AND SIGNATURE
times (510-($-$$)) db 0x00
dw 0AA55h

kernel.asm

中的问题

您错误地设置了段寄存器,堆栈应该位于偶数字节边界上。如果将 SP 设置为零,则第一次推送将从 SP 中减去 2,将数据放置在段顶部的 0000-2=0fffe 处。我会简单地将 ES=DS=FS=GS=SS 设置为 CS。其次,当你执行 HLT 指令时,它只会暂停直到下一个中​​断,然后进入 HLT 之后的指令。如果你想 HLT 无限期关闭中断,请先使用 CLI。如果您收到未被 CLI.

屏蔽的 Non-Maskable 中断(NMI),将 HLT 置于循环中仍然是一个好主意

您的内核可以这样修改:

[bits 16]               ;16-bit binary format

;VECTORS
os_vectors:
    jmp os_main

;KERNEL
os_main:
    mov ax, cs      ;CS is segment where we were loaded
    cli             ;clear interrupts
    mov ss, ax      ;set stack segment and pointer
    xor sp, sp      ;SP=0. First push will wrap SP to 0fffeh
    sti             ;restore interrupts
    cld             ;set RAM direction(for strings)
    mov ds, ax      ;DS=ES=FS=GS=CS
    mov es, ax
    mov fs, ax
    mov gs, ax
    mov si, hello   ;print welcome
    call print_string
    cli             ;Turn off interrupts so that HLT doesn't continue
                    ;when an interrupt occurs
.hlt_loop:
    hlt
    jmp .hlt_loop   ; Infinite loop to avoid NMI dropping us into the code of
                    ; print_string

;SUBROUTINES
print_string:
    mov ah, 0x0e

.next_char:
    lodsb
    cmp al,0
    je .done_print
    int 0x10
    jmp .next_char

.done_print:
    ret

;DATA
hello db 'Hello',0

其他观察结果

您的代码中存在许多低效问题,但我会解决一些较大的问题。尽管您的 next_cluster 代码有效,但它使用的寄存器比需要的多,并且在内存中的编码方式更长。为了将任何值乘以 3,您可以将该值乘以 2 并将原始值添加到该值。该公式如下所示:

valtimes3 = (value * 2) + value

这很重要,因为要将寄存器中的值乘以 2,只需使用 SHL 指令将位左移 1 位即可。除以 2 是通过使用 SHR 指令将寄存器中的位右移 1 来完成的。 SHR 的优点是您移出寄存器的位被放置在进位标志 (CF) 中。如果 CF 置位则值为奇数,如果清零则值为偶数。 next_cluster 代码可能如下所示:

next_cluster:
    mov bx, [cluster]          ; BX = current cluster number
    mov ax, bx                 ; AX = copy of cluster number
    shl bx, 1                  ; BX = BX * 2
    add bx, ax                 ; BX = BX + AX (BX now contains BX * 3)
    shr bx, 1                  ; Divide BX by 2
    mov ax, [bx+BUFFER_OFF]    ; Get cluster entry from FAT table
    jnc .even                  ; If carry not set by SHR then result was even
.odd:
    shr ax, 4                  ; If cluster entry is odd then cluster number is AX >> 4
    jmp short finish_load
.even:
    and ah, 0Fh                ; If cluster entry is even then cluster number is AX & 0fffh
                               ; We just need to and AH with 0fh to achieve the same result
finish_load:

您可以通过重新排列标准计算来简化 lba_to_hts。我已经写了previous Whosebug 就这样做了,并且使用修改后的公式替换掉了:

lba_to_chs function that takes an LBA and converts it to CHS and only works for well known IBM compatible floppy disk formats.

;    Function: lba_to_chs
; Description: Translate Logical block address to CHS (Cylinder, Head, Sector).
;              Works **ONLY** for well known IBM PC compatible **floppy disk formats**.
;
;   Resources: http://www.ctyme.com/intr/rb-0607.htm
;              https://en.wikipedia.org/wiki/Logical_block_addressing#CHS_conversion
;              
;              Sector    = (LBA mod SPT) + 1
;              Head      = (LBA / SPT) mod HEADS
;              Cylinder  = (LBA / SPT) / HEADS
;
;      Inputs: SI = LBA
;     Outputs: DL = Boot Drive Number
;              DH = Head
;              CH = Cylinder
;              CL = Sector
;
;       Notes: Output registers match expectation of Int 13h/AH=2 inputs
;
lba_to_chs:
    push ax                    ; Preserve AX
    mov ax, si                 ; Copy 16-bit LBA to AX
    div byte [SectorsPerTrack] ; 16-bit by 8-bit DIV : LBA / SPT
    mov cl, ah                 ; CL = S = LBA mod SPT
    inc cl                     ; CL = S = (LBA mod SPT) + 1
    xor ah, ah                 ; Upper 8-bit of 16-bit value set to 0 for DIV
    div byte [NumberOfHeads]   ; 16-bit by 8-bit DIV : (LBA / SPT) / HEADS
    mov ch, al                 ; CH = C = (LBA / SPT) / HEADS
    mov dh, ah                 ; DH = H = (LBA / SPT) mod HEADS
    mov dl, [boot_device]      ; boot device, not necessary to set but convenient
    pop ax                     ; Restore scratch register
    ret

你只需要把函数名改成lba_to_hts;将 NumberOfHeads 更改为 Sides;将 boot_drive 更改为 drive;并修改代码,使 LBA 通过 AX 而不是 SI 传递。 AX 甚至不需要保留现有代码的编写方式。


当您发现需要将另一个簇读入内存时,您可以有效地将 512 添加到 [pointer] 以转到内存中的下一个位置。问题是您将自己限制为 65536 字节长的内核。一旦达到 128 个 512 字节的扇区读入内存,您将超过 65536 (128*512=65536)。 [pointer] 将换行并从 0 开始,您将覆盖您已经阅读的内核部分。您可以通过始终执行磁盘读取到偏移量 0 (BX=0) 并将 32 添加到 ES 来解决此问题。当您将 1 加到段寄存器时,您会在内存中前进 16 个字节(一个段落)。如果要前进 512 个字节,请将 32 添加到 ES (32*16=512)。在您的 load_sectors 代码中,您可以更改:

    call lba_to_hts
    mov bx, word [pointer]     ; BX=Current offset in buffer to read to

至:

    call lba_to_hts
    xor bx, bx

Finish_load中你可以改变:

finish_load:
    mov word [cluster], ax
    cmp ax, 0FF8h
    jae .jump_to_file
    add word [pointer], 512    ; We haven't reached end of kernel. Add 512 for next read
    jmp load_sector            ; Go back and load the next sector
.jump_to_file:
    mov dl, byte [drive]
    jmp LOAD_SEG:LOAD_OFF

至:

finish_load:
    mov word [cluster], ax
    cmp ax, 0FF8h
    jae .jump_to_file
    mov ax, es
    add ax, 32                 ; Increasing segment by 1 advances 16 bytes (paragraph)
                               ; in memory. Adding 32 is same advancing 512 bytes (32*16)
    mov es, ax                 ; Advance ES to point at next 512 byte block to read into
    jmp load_sector            ; Go back and load the next sector
.jump_to_file:
    mov dl, byte [drive]
    jmp LOAD_SEG:LOAD_OFF

实施这些更改的 boot.asm 版本可能如下所示:

%define BUFFER_OFF 0x8000
%define BUFFER_SEG 0x0000
%define LOAD_SEG 0x1000
%define LOAD_OFF 0x0000

[bits 16]
[org 0x7c00]

jmp short start
nop

;DISK DESCRIPTION(BIOS PARAMETER BLOCK)
OEMLabel        db "BOOT    "
BytesPerSector      dw 512
SectorsPerCluster   db 1
ReservedForBoot     dw 1
NumberOfFats        db 2
RootDirEntries      dw 224     ; Number of entries in root dir
                               ; (224 * 32 = 7168 = 14 sectors to read)
LogicalSectors      dw 2880
MediumByte      db 0F0h
SectorsPerFat       dw 9
SectorsPerTrack     dw 18      ; Sectors per track (36/cylinder)
Sides           dw 2
HiddenSectors       dd 0
LargeSectors        dd 0
DriveNo         dw 0
Signature       db 0x29
VolumeID        dd 00000000h
VolumeLabel     db "myOS       "
FileSystem      db "FAT12   "

;BOOTLOADER
start:
    xor ax, ax
    mov ds, ax
    cli
    mov ss, ax
    mov sp, 0x7c00
    sti
    cld
    mov [drive], dl

    mov si, BUFFER_SEG         ; ES=buffer segment. Only has to be set once
    mov es, si
    mov bx, BUFFER_OFF

load_root:
    mov ax, 19                 ; Root directory starts at LBA 19
    call lba_to_hts
    mov ax, (2<<8) | 14        ; Root directory for this media fits in 14 sectors
                               ; Combine 2 moves (AH/AL) into one
                               ; same as 'mov ah, 2' and 'mov al, 14'
    int 13h
    jc reset
    mov si, load_root_str
    call print

search_file:
    mov di, BUFFER_OFF
    mov cx, word [RootDirEntries]
    xor ax, ax
.loop_search:
    xchg cx, dx
    mov si, filename
    mov cx, 11
    rep cmpsb
    je file_found
    add ax, 32
    mov di, BUFFER_OFF
    add di, ax
    xchg dx, cx
    loop .loop_search
    jmp file_not_found

file_found:
    mov ax, word [di+15]       ; Buffer and Bootloader now in same segment DS
                               ; Don't need ES:
    mov [cluster], ax
    mov ax, 1
    call lba_to_hts
    mov bx, BUFFER_OFF
    mov ax, (2<<8) | 9         ; Combine 2 moves (AH/AL) into one
                               ; same as 'mov ah, 2' and 'mov al, 9'    

load_FAT:
    mov si, FAT_str
    call print
    int 13h
    jnc load_file
    call reset
    jnc load_FAT
    jmp disk_error

load_file:
    mov si, load_file_str
    call print
    mov ax, LOAD_SEG           ; ES=load segment for kernel
    mov es, ax

load_sector:
    mov ax, word [cluster]     ; Get cluster number to read
    add ax, 33-2               ; Add 31 to cluster since FAT data area
                               ; starts at Logical Block Address (LBA) 33
                               ; and we need to subtract 2 since valid
                               ; cluster numbers start at 2
    call lba_to_hts
    xor bx, bx                 ; Always read a kernel sector to offset 0

    mov ax, (2<<8) | 1         ; AH=2 is read, AL=1 read 1 sector
                               ; Combine 2 moves (AH/AL) into one
                               ; same as 'mov ah, 2' and 'mov al, 1'
    int 13h
    jnc next_cluster
    call reset
    jmp load_sector

next_cluster:
    mov bx, [cluster]          ; BX = current cluster number
    mov ax, bx                 ; AX = copy of cluster number
    shl bx, 1                  ; BX = BX * 2
    add bx, ax                 ; BX = BX + AX (BX now contains BX * 3)
    shr bx, 1                  ; Divide BX by 2
    mov ax, [bx+BUFFER_OFF]    ; Get cluster entry from FAT table
    jnc .even                  ; If carry not set by SHR then result was even
.odd:
    shr ax, 4                  ; If cluster entry is odd then cluster number is AX >> 4
    jmp short finish_load
.even:
    and ah, 0Fh                ; If cluster entry is even then cluster number is AX & 0fffh
                               ; We just need to and AH with 0fh to achieve the same result
finish_load:
    mov word [cluster], ax
    cmp ax, 0FF8h
    jae .jump_to_file
    mov ax, es
    add ax, 32                 ; Increasing segment by 1 advances 16 bytes (paragraph)
                               ; in memory. Adding 32 is same advancing 512 bytes (32*16)
    mov es, ax                 ; Advance ES to point at next 512 byte block to read into
    jmp load_sector            ; Go back and load the next sector
.jump_to_file:
    mov dl, byte [drive]
    jmp LOAD_SEG:LOAD_OFF

;SUBROUTINES
file_not_found:
    mov si, not_found_str
    call print
    jmp reboot
print:
    pusha
    mov ah, 0x0E
.next:
    lodsb
    cmp al,0
    je .done
    int 0x10
    jmp .next
.done:
    popa
    ret

;    Function: lba_to_hts
; Description: Translate Logical block address to CHS (Cylinder, Head, Sector).
;              Works ONLY for well known IBM PC compatible floppy disk formats.
;
;   Resources: http://www.ctyme.com/intr/rb-0607.htm
;              https://en.wikipedia.org/wiki/Logical_block_addressing#CHS_conversion
;              
;              Sector    = (LBA mod SPT) + 1
;              Head      = (LBA / SPT) mod HEADS
;              Cylinder  = (LBA / SPT) / HEADS
;
;      Inputs: AX = LBA
;     Outputs: DL = Boot Drive Number
;              DH = Head
;              CH = Cylinder
;              CL = Sector
;
;       Notes: Output registers match expectation of Int 13h/AH=2 inputs
;
lba_to_hts:
    div byte [SectorsPerTrack] ; 16-bit by 8-bit DIV : LBA / SPT
    mov cl, ah                 ; CL = S = LBA mod SPT
    inc cl                     ; CL = S = (LBA mod SPT) + 1
    xor ah, ah                 ; Upper 8-bit of 16-bit value set to 0 for DIV
    div byte [Sides]           ; 16-bit by 8-bit DIV : (LBA / SPT) / HEADS
    mov ch, al                 ; CH = C = (LBA / SPT) / HEADS
    mov dh, ah                 ; DH = H = (LBA / SPT) mod HEADS
    mov dl, [drive]            ; boot device, not necessary to set but convenient
    ret

reset:
    mov ah, 0
    int 13h                    ;reset disk
    jc disk_error              ;if failed jump to search fail
    ret
disk_error:
    mov si, disk_error_str
    call print
reboot:
    mov si, reboot_pmpt
    call print
    mov ax, 0
    int 16h
    mov ax, 0
    int 19h

;DATA
load_root_str db 'Loading Root',13,10,0
disk_error_str db 'Disk Error!',13,10,0
reboot_pmpt db 'PRESS A KEY TO REBOOT',13,10,0
not_found_str db 'KERNEL NOT FOUND',13,10,0
FAT_str db 'Loading FAT',13,10,0
load_file_str db 'Loading KERNEL',13,10,0
drive dw 0
cluster dw 0
filename db 'KERNEL  BIN',0
;PADDING AND SIGNATURE
times (510-($-$$)) db 0x00
dw 0AA55h

当在 QEMU 中 运行 时,显示如下: