基于nasm编写 x86 裸金属汇编程序

计算机启动是这样一个过程

  1. 通电
  2. 读取ROM里面的BIOS,用来检查硬件
  3. 硬件检查通过
  4. BIOS根据指定的顺序,检查引导设备的第一个扇区(即主引导记录),加载在内存地址 0x7C00
  5. 主引导记录把操作权交给操作系统

为什么主引导记录的内存地址是0x7C00?

https://www.ruanyifeng.com/blog/2015/09/0x7c00.html
https://www.glamenv-septzen.net/en/view/6

实模式(real mode),也称为实地址模式(real address mode),是所有x86兼容CPU下的一种操作模式。 实模式的特点是20 bit分段内存(segmented memory)地址空间(精确到1 MB的可寻址内存)以及 对所有可寻址内存,I/O地址和外设硬件的无限制直接软件访问。 实模式不支持内存保护(memory protection),多任务处理(multitasking)或 代码权限级别(code privilege levels)。

最早期的8086 CPU只有一种工作方式,那就是实模式,而且数据总线为16位,地址总线为20位,实模式下所有寄存器都是16位。而从80286开始就有了保护模式,从80386开始CPU数据总线和地址总线均为32位,而且寄存器都是32位。80386以及现在的奔腾,酷睿等等CPU为了向前兼容都保留了实模式,x86 CPU在重置(reset)时都以实模式启动。

汇编代码

[BITS 16]                               ; 16 bits program
[ORG 0x7C00]                            ; starts from 0x7c00, where MBR lies in memory

mov si, OSH                             ; si points to string OSH
print_str:
    lodsb                               ; load char to al
    cmp al, 0                           ; is it the end of the string?
    je halt                             ; if true, then halt the system
    mov ah, 0x0e                        ; if false, then set AH = 0x0e 
    int 0x10                            ; call BIOS interrupt procedure, print a char to screen
    jmp print_str                      ; loop over to print all chars

halt:
    hlt

OSH db `Hello, OSH 2020 Lab1!`, 0       ; our string, null-terminated

TIMES 510 - ($ - $) db 0               ; the size of MBR is 512 bytes, fill remaining bytes to 0
DW 0xAA55                               ; magic number, mark it as a valid bootloader to BIOS

编译:

nasm -f bin exa.asm -o exa.img



qemu运行

qemu-system-x86_64 -hda exa

bochs运行

配置bochs



点击start运行


virtualbox运行

配置



运行


参考

https://cee.github.io/NASM-Tutorial/
https://www.nasm.us/xdoc/2.15.05/html/nasmdoc0.html
https://www.cs.virginia.edu/~evans/cs216/guides/x86.html
发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章