我目前正在使用 x86 Assembler,以提高我的低级编程技能。目前,我在 32 位保护模式下的寻址方案遇到了一个小问题。
情况如下:
我在 0x7e0 加载了一个程序,它将 CPU 切换到保护模式并跳转到代码中的相应标签:
[...]
code to switch CPU in Protected Mode
[...]
jmp ProtectedMode
[...]
bits 32
ProtectedMode:
.halt:
hlt
jmp .halt
到目前为止,这工作得非常好。 “jmp ProtectedMode”无需显式远跳转即可清除预取队列 - 因为该程序以偏移量 0(开头为 org 0)加载 - 导致代码段指向正确的位置。
我现在的问题是,在“ProtectedMode”标签中,我想跳转到在 0x8000 处加载的另一个程序(我用内存转储检查了这一点,加载函数确实工作正常,并且程序正确加载到 0x8000) 。
由于 CPU 现在处于保护模式而不是实模式,因此寻址模式有所不同。 ProtectedMode 使用描述符选择器在描述符表中查找基地址和限制,以添加给定的偏移量并检索物理地址(据我所知)。因此,在进入保护模式之前需要安装GDT。
我的看起来像下面这样:
%ifndef __GDT_INC_INCLUDED__
%define __GDT_INC_INCLUDED__
;*********************************
;* Global Descriptor Table (GDT) *
;*********************************
NULL_DESC:
dd 0 ; null descriptor
dd 0
CODE_DESC:
dw 0xFFFF ; limit low
dw 0 ; base low
db 0 ; base middle
db 10011010b ; access
db 11001111b ; granularity
db 0 ; base high
DATA_DESC:
dw 0xFFFF ; data descriptor
dw 0 ; limit low
db 0 ; base low
db 10010010b ; access
db 11001111b ; granularity
db 0 ; base high
gdtr:
Limit dw 24 ; length of GDT
Base dd NULL_DESC ; base of GDT
%endif ;__GDT_INC_INCLUDED__
并通过以下方式加载到 GDT 寄存器
lgdt [gdtr]
到目前为止我不明白的是,我现在如何使用GPT在保护模式下跳转到物理地址0x8000?
我的第一个想法是选择代码描述符(CODE_DESC),它应该指向 0x7e00(当前程序已加载)并使用到达 0x8000(512 字节)所需的偏移量,从而产生跳转指令:
jmp CODE_DESC:0x200
但这是行不通的。
jmp 0x7e0:0x200
也不起作用...
你知道我在这里缺少什么吗?也许我不明白 32 位保护模式寻址方案和 GDT 的用法中的一些基本内容。
[编辑]完整代码:
bits 16
org 0 ; loaded with offset 0000 (phys addr: 0x7e00)
jmp Start
Start:
xor ax, ax
mov ax, cs
mov ds, ax ; update data segment
cli ; clear interrupts
lgdt [gdtr] ; load GDT from GDTR (see gdt_32.inc)
call OpenA20Gate ; open the A20 gate
call EnablePMode ; jumps to ProtectedMode
;******************
;* Opens A20 Gate *
;******************
OpenA20Gate:
in al, 0x93 ; switch A20 gate via fast A20 port 92
or al, 2 ; set A20 Gate bit 1
and al, ~1 ; clear INIT_NOW bit
out 0x92, al
ret
;**************************
;* Enables Protected Mode *
;**************************
EnablePMode:
mov eax, cr0
or eax, 1
mov cr0, eax
jmp ProtectedMode ; this works (jumps to label and halts)
;jmp (CODE_DESC-NULL_DESC):ProtectedMode ; => does not work
;jmp 08h:ProtectedMode , => does not work
;***************
;* data fields *
;* &includes *
;***************
%include "gdt_32.inc"
;******************
;* Protected Mode *
;******************
bits 32
ProtectedMode:
;here I want to jump to physical addr 0x8000 (elf64 asm program)
.halt:
hlt
jmp .halt