从引导加载程序问题进入保护模式

时间:2019-01-06 15:44:09

标签: assembly x86 nasm bootloader protected-mode

此汇编代码从引导加载程序进入保护模式,但是在调用远跳转并重新引导后无法重置CS段(或执行远跳转)。如果我删除了远距离跳转,它将进入保护模式下的无限循环(0x66,jmp $),而无需重新启动。

[bits 16]
[org 0x7c00]
xor ax,ax
xor eax,eax
add eax,ENTRY_POINT_32 ;address to plug to far jmp
mov [ENTRY_OFF],eax
xor eax,eax
mov eax,GDT                ;load GDT label address
mov [GDTR+2],eax ; load it into address space in GDTR
lgdt [GDTR]                   ;load GDTR
cli                                    ;turn off masked interrupts
in al,0x70
or al,0x80
out 0x70,al                     ;turn off nonmasked interrupts
in al,0x92
or al,2
out 0x92, al ;open line A20 (change address 20 to 32 bits)
mov eax,cr0
or al,1
mov cr0,eax                 ;switch to protected mode
db 0x66                        ;prefix of opcode to change bitness
db 0xEA                       ;opcode of jmp far
ENTRY_OFF dd 0x0 ;32 bit offset of 32 bit instructions
dw 00001000b ; selector 1st descriptor CODE_descr,=1
ENTRY_POINT_32:
db 0x66                      ;prefix of opcode to change bitness
jmp $                          ;infinite jump to the same location
GDT:
NULL_descr dd 0x0,0x0 ; must be present in GDT
CODE_descr db  0xFF,0xFF,0x0,0x0,0x0,10011010b,11001111b,0x0
;descriptor of 32 bit code segment, base 0, size ffffffff
DATA_descr db 0xFF,0xFF,0x0,0x0,0x0,10010010b,11001111b,0x0
;descriptor of 32 bit data segment, base 0, size ffffffff
VIDEO_descr 0xFF,0xFF,0x0,0x80,0x0B,10010010b,01000000b,0x0
;descriptor of video buffer, base 0x000B8000, size ffff
GDT_size db $-GDT ;size of GDT table
GDTR dw GDT_size-1 ;next 3 words are size &
dd 0x0 ;address of beginning of GDT, loaded in code
times 510 - ($ - $$) db 0
dw 0xaa55

wasm.in的原始代码,稍作修改。

1 个答案:

答案 0 :(得分:2)

在实模式下,所有内存操作数上都有一个隐含段。如果内存操作数不包含 BP 作为基数,则隐含段为 DS 。如果内存操作数确实包含BP,则隐含的基数是SS。您的内存操作数不使用 BP ,因此隐含的段为 DS 。带有这样的内存操作数的指令:

mov [ENTRY_POINT_32],eax

相当于:

mov [ds:ENTRY_POINT_32],eax

实模式使用segment:offset addressing到达物理内存地址。如果 DS 错误,则将写入错误的存储位置。 20位物理地址=(segment << 4)+偏移量。

话虽这么说,当引导加载程序启动时,您不能依赖段和通用寄存器作为期望的值,除了 DL 之外,它包含BIOS传递的引导驱动器。您可以阅读我的Bootloader Tips以获得有关引导加载程序开发的更多信息。

您需要显式设置 DS 寄存器。由于您的代码使用的是org 0x7c00,因此需要将 DS 段设置为零。 (0x0000 << 4)+ 0x7c00 = 0x07c00(物理地址)。引导加载程序始终由BIOS加载到物理地址0x07c00。

您也有这两行:

xor ax,ax
xor eax,eax

第一个是不必要的,因为您将所有 EAX 都设置为零。如果在32位代码之前使用bits 32 NASM 指令,则以下行是不必要的:

db 0x66                      ;prefix of opcode to change bitness

GDTR的设置也不正确。您计算大小不正确。您有以下代码:

GDT_size db $-GDT ;size of GDT table
GDTR dw GDT_size-1 ;next 3 words are size &

您使用一个包含GDT大小的字节创建一个内存位置。 GDTR dw GDT_size-1取标签GDT_size的偏移量并从中减去1。这仅适用,因为标签GDT_size的偏移量大于GDT的大小。您可以执行以下操作:

GDT:
    NULL_descr: dd 0x0,0x0      ; must be first entry in GDT

    ; descriptor of 32 bit code segment, base 0, size ffffffff
    CODE_descr: db  0xFF,0xFF,0x0,0x0,0x0,10011010b,11001111b,0x0

    ; descriptor of 32 bit data segment, base 0, size ffffffff
    DATA_descr: db 0xFF,0xFF,0x0,0x0,0x0,10010010b,11001111b,0x0

    ; descriptor of video buffer, base 0x000B8000, size ffff
    VIDEO_descr: db 0xFF,0xFF,0x0,0x80,0x0B,10010010b,01000000b,0x0
GDT_END:

GDTR dw GDT_END-GDT-1            ; Size of GDT (minus 1)
     dd 0x0                      ; address of beginning of GDT, loaded in code

在创建自修改代码时,您还需要关注clearing the instruction prefetch queue,以确保处理器看到代码的更改。处理器可能已经预读了您要修改的FAR JMP指令,并且不知道您对代码所做的更改。修改指令后,只需在代码中插入一个JMP,即可解决此问题。用计算的地址更新指令后,您可以执行以下操作:

    mov [ENTRY_OFF],eax
    jmp clear_prefetch          ; Clear the instruction prefetch queue
                                ;     by jumping to next instruction
clear_prefetch:

工作代码(我整理了一下格式)看起来像:

bits 16
org 0x7c00

start:
    xor eax,eax
    mov ds, ax                  ; Explicitly set DS to zero

    add eax,ENTRY_POINT_32      ; address to plug to far jmp
    mov [ENTRY_OFF],eax
    jmp clear_prefetch          ; Clear the instruction prefetch queue
                                ;     by jumping to next instruction
clear_prefetch:

    xor eax,eax
    mov eax,GDT                 ; load GDT label address
    mov [GDTR+2],eax            ; load it into address space in GDTR
    lgdt [GDTR]                 ; load GDTR

    cli                         ; turn off masked interrupts
    in al,0x70
    or al,0x80
    out 0x70,al                 ; turn off nonmasked interrupts
    in al,0x92
    or al,2
    out 0x92, al                ; enable A20 line
    mov eax,cr0
    or al,1
    mov cr0,eax                 ; switch to protected mode

    db 0x66                     ; prefix of opcode to change bitness
    db 0xEA                     ; opcode of jmp far
ENTRY_OFF:
    dd 0x0                      ; 32 bit offset of 32 bit instructions
    dw 00001000b                ; selector 1st descriptor CODE_descr,=1

bits 32
ENTRY_POINT_32:
    jmp $                       ; infinite jump to the same location

GDT:
    NULL_descr: dd 0x0,0x0      ; must be first entry in GDT

    ; descriptor of 32 bit code segment, base 0, size ffffffff
    CODE_descr: db  0xFF,0xFF,0x0,0x0,0x0,10011010b,11001111b,0x0

    ; descriptor of 32 bit data segment, base 0, size ffffffff
    DATA_descr: db 0xFF,0xFF,0x0,0x0,0x0,10010010b,11001111b,0x0

    ; descriptor of video buffer, base 0x000B8000, size ffff
    VIDEO_descr: db 0xFF,0xFF,0x0,0x80,0x0B,10010010b,01000000b,0x0
GDT_END:

GDTR dw GDT_END-GDT-1            ; Size of GDT (minus 1)
     dd 0x0                      ; address of beginning of GDT, loaded in code

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

无需在引导程序中运行FAR JMP的运行时间

在这种情况下,您的代码过于复杂。 x86上的旧版BIOS始终将引导加载程序加载到物理地址0x07c00。使用ORG 0x7c00并将段设置为0x0000的一个优点是0x0000:0x7c00和线性地址(与实模式下的物理地址相同)与内存起始位置的偏移量为0x07c00。您可以利用它来发挥自己的优势,并避免在运行时进行不必要的计算。代码看起来像这样:

bits 16
org 0x7c00

start:
    xor ax,ax
    mov ds,ax                   ; Explicitly set DS to zero

    lgdt [GDTR]                 ; load GDTR

    cli                         ; turn off masked interrupts
    in al,0x70
    or al,0x80
    out 0x70,al                 ; turn off nonmasked interrupts
    in al,0x92
    or al,2
    out 0x92, al                ; enable A20 line

    ; Enter protected mode
    mov eax,cr0
    or al,1
    mov cr0,eax                 ; switch to protected mode
    jmp CODE32_SEL:ENTRY_POINT_32

bits 32
ENTRY_POINT_32:
    mov eax, DATA32_SEL         ; Set the protected mode selector
    mov ds, ax
    mov fs, ax
    mov gs, ax
    mov ss, ax
    mov esp, 0x9C000            ; Set protected mode stack below EBDA

    mov eax, VIDEO32_SEL        ; Set the video memory selector
    mov es, ax

    ; Print some characters to top left of the screen in white on magenta
    xor ebx, ebx
    mov word [es:ebx],   0x57 << 8 | 'M'
    mov word [es:ebx+2], 0x57 << 8 | 'D'
    mov word [es:ebx+4], 0x57 << 8 | 'P'

    jmp $                       ; infinite jump to the same location

GDT:
    NULL_descr: dd 0x0,0x0      ; must be first entry in GDT

    ; descriptor of 32 bit code segment, base 0, size ffffffff
    CODE_descr: db  0xFF,0xFF,0x0,0x0,0x0,10011010b,11001111b,0x0

    ; descriptor of 32 bit data segment, base 0, size ffffffff
    DATA_descr: db 0xFF,0xFF,0x0,0x0,0x0,10010010b,11001111b,0x0

    VIDEO_descr: db 0xFF,0xFF,0x0,0x80,0x0B,10010010b,01000000b,0x0
    ; descriptor of video buffer, base 0x000B8000, size ffff
GDT_END:
CODE32_SEL  equ CODE_descr-GDT
DATA32_SEL  equ DATA_descr-GDT
VIDEO32_SEL equ VIDEO_descr-GDT

GDTR dw GDT_END-GDT-1            ; Size of GDT (minus 1)
     dd GDT                      ; address of beginning of GDT

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

此代码在汇编时计算CODE和DATA选择器。它还在组装时计算GDTR,并对FAR JMP进行硬编码。应该注意的是,由于引导加载程序和32位入口点完全位于内存的前64KiB之内,因此在FAR JMP进入保护模式时,可以使用16位偏移而不是32位。无需自我修改代码。

注意:无需为视频存储器创建选择器。您始终可以使用32位4GiB平面数据选择器来寻址该内存。


什么时候使用在运行时计算地址的代码?

建立FAR JMP并在运行时生成GDTR记录的概念并非一无是处。在将代码放置在内存中不同段的环境中,则需要在运行时计算GDTR的FAR JMP和GDT线性地址。如果您试图通过COM或EXE程序从DOS进入保护模式,就会出现这种情况。 DOS加载器决定将内容放置在哪个段中。在这种情况下,您必须在运行时计算地址。几年前,我为IRC上的某个人写了一些代码。我的代码不会(应该)禁用NMI,也不会修改FAR JMP。我要做的是在堆栈上构建FAR JMP地址,然后通过堆栈上的地址执行间接FAR JMP。原理与执行自修改代码相同。

一个示例DOS COM程序,该程序在运行时为堆栈上的FAR JMP地址生成并在GDTR中生成GDT地址,如下所示:

; Assemble with NASM as
;     nasm -f bin enterpm.asm -o enterpm.com

STACK32_TOP EQU 0x200000
CODE32_REL  EQU 0x110000
VIDEOMEM    EQU 0x0b8000

use16
; COM program CS=DS=SS
org 100h

    call check_pmode    ; Check if we are already in protected mode
                        ;    This may be the case if we are in a VM8086 task.
                        ;    EMM386 and other expanded memory manager often
                        ;    run DOS in a VM8086 task. DOS extenders will have
                        ;    the same effect

    jz not_prot_mode    ; If not in protected mode proceed to switch
    mov dx, in_pmode_str;    otherwise print an error and exit back to DOS
    mov ah, 0x9
    int 0x21            ; Print Error
    ret

not_prot_mode:
    call a20_on         ; Enable A20 gate (uses Fast method as proof of concept)
    cli

    ; Compute linear address of label gdt_start
    ; Using (segment << 4) + offset
    mov eax,cs          ; EAX = CS
    shl eax,4           ; EAX = (CS << 4)
    mov ebx,eax         ; Make a copy of (CS << 4)
    add [gdtr+2],eax    ; Add base linear address to gdt_start address
                        ;     in the gdtr
    lgdt [gdtr]         ; Load gdt

    ; Compute linear address of label code_32bit
    ; Using (segment << 4) + offset
    add ebx,code_32bit  ; EBX = (CS << 4) + code_32bit

    push dword 0x08     ; CS Selector
    push ebx            ; Linear offset of code_32bit
    mov bp, sp          ; m16:32 address on top of stack, point BP to it

    mov eax,cr0
    or eax,1
    mov cr0,eax         ; Set protected mode flag

    jmp dword far [bp]  ; Indirect m16:32 FAR jmp with
                        ;    m16:32 constructed at top of stack
                        ;    DWORD allows us to use a 32-bit offset in 16-bit code

; 16-bit functions that run in real mode

; Check if protected mode is enabled, effectively checkign if we are
; in in a VM8086 task. Set ZF to 1 if in protected mode

check_pmode:
    smsw ax
    test ax, 0x1
    ret


; Enable a20 (fast method). This may not work on all hardware
a20_on:
    cli
    in al, 0x92         ; Read System Control Port A
    test al, 0x02       ; Test current a20 value (bit 1)
    jnz .skipfa20       ; If already 1 skip a20 enable
    or al, 0x02         ; Set a20 bit (bit 1) to 1
    and al, 0xfe        ; Always write a zero to bit 0 to avoid
                        ;     a fast reset into real mode
    out 0x92, al        ; Enable a20
.skipfa20:
    sti
    ret

in_pmode_str: db "Processor already in protected mode - exiting",0x0a,0x0d,"$"

align 4
gdtr:
    dw gdt_end-gdt_start-1
    dd gdt_start

gdt_start:
    ; First entry is always the Null Descriptor
    dd 0
    dd 0

gdt_code:
    ; 4gb flat r/w/executable code descriptor
    dw 0xFFFF           ; limit low
    dw 0                ; base low
    db 0                ; base middle
    db 0b10011010       ; access
    db 0b11001111       ; granularity
    db 0                ; base high

gdt_data:
    ; 4gb flat r/w data descriptor
    dw 0xFFFF           ; limit low
    dw 0                ; base low
    db 0                ; base middle
    db 0b10010010       ; access
    db 0b11001111       ; granularity
    db 0                ; base high
gdt_end:

; Code that will run in 32-bit protected mode
; Align code to 4 byte boundary. code_32bit label is
; relative to the origin point 100h
align 4
code_32bit:
use32
; Set virtual memory address of pm code/data to CODE32_REL
; We will be relocating this section from low memory where DOS
; originally loaded it.
section protectedmode vstart=CODE32_REL, valign=4
start_32:
    cld                 ; Direction flag forward
    mov eax,0x10        ; 0x10 is flat selector for data
    mov ds,eax
    mov es,eax
    mov fs,eax
    mov gs,eax
    mov ss,eax
    mov esp,STACK32_TOP ; Should set ESP to a usable memory location
                        ; Stack will be grow down from this location

    mov edi,start_32    ; EDI = linear address where PM code will be copied
    mov esi,ebx         ; ESI = linear address of code_32bit
    mov ecx,PMSIZE_LONG ; ECX = number of DWORDs to copy
    rep movsd           ; Copy all code/data from code_32bit to CODE32_REL
    jmp 0x08:.relentry  ; Absolute jump to relocated code

.relentry:
    mov ah, 0x57        ; Attribute white on magenta

    ; Print a string to display
    mov esi,str         ; ESI = address of string to print
    mov edi,VIDEOMEM    ; EDI = base address of video memory
    call print_string_attr

    cli
endloop:
    hlt                 ; Halt CPU with infinite loop
    jmp endloop

print_string_attr:
    push ecx
    xor ecx,ecx         ; ECX = 0 current video offset
    jmp .loopentry
.printloop:
    mov [edi+ecx*2],ax  ; Copy attr and character to display
    inc ecx             ; Next word position
.loopentry:
    mov al,[esi+ecx]    ; Get next character to print
    test al,al
    jnz .printloop      ; If it's not NUL continue
.endprint:
    pop ecx
    ret

str: db "Protected Mode",0

PMSIZE_LONG equ ($-$$+3)>>2
                        ; Number of DWORDS that the protected mode
                        ;    code and data takes up (rounded up)

此代码比我认为的要复杂一些。感兴趣的部分将是not_prot_mode中的指针计算,这与您的代码正在执行的计算类型相似。进入保护模式后,代码将自身重​​新定位在DOS之上的0x00110000。那是最初问我有关进入保护模式的人的要求。

注意:此代码仅在尚未启用保护模式的环境中运行。如果在VM8086任务中运行,它将显示错误并退出。