调试技巧

1. QEMU + GDB 调试

启动调试

# 终端1: 启动QEMU(-s 开启GDB端口, -S 启动时暂停)
qemu-system-x86_64 -drive format=raw,file=boot.bin -s -S
 
# 终端2: 启动GDB
gdb
(gdb) target remote localhost:1234
(gdb) set architecture i8086        # 设置为16位模式
(gdb) break *0x7C00                 # 在引导扇区入口设断点
(gdb) continue                      # 继续执行到断点

常用GDB命令

info registers          # 查看所有寄存器
stepi                   # 单步执行一条指令
nexti                   # 单步(跳过函数调用)
x/10i $pc              # 查看接下来10条指令
x/16xb 0x7C00          # 查看0x7C00处的16个字节
x/1xh 0x7DFE           # 查看引导签名(应该是0xAA55)

2. 查看二进制文件

# 查看完整的十六进制内容
xxd boot.bin
 
# 只看前32字节(代码部分)
xxd boot.bin | head -2
 
# 只看最后16字节(包含引导签名)
xxd boot.bin | tail -1
 
# 使用 hexdump
hexdump -C boot.bin

3. 确认引导签名

# 查看最后两字节
xxd -s 510 -l 2 boot.bin
# 应该输出: 000001fe: 55aa

4. QEMU Monitor

在QEMU运行时,按 Ctrl+Alt+2 进入QEMU Monitor:

info registers      # 查看CPU寄存器
xp /10i 0x7C00     # 反汇编0x7C00处的代码
xp /16xb 0x7C00    # 查看内存
q                   # 退出QEMU

按 Ctrl+Alt+1 返回正常显示。