You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

GAS x86 16位汇编无法解析符号地址,如何实现自动地址解析?

问题:GAS编写16位Bootloader时无法解析符号地址?

我尝试用GAS编写x86的16位小型Bootloader,程序加载到0x7C00地址时能正常运行:

.code16   
.text

 .globl main
main:
    mov $0xb800, %ax
    mov %ax, %es
    
    mov $0x7c0f, %si
    movb (%si), %al
    mov %al, %es:0
hlt

string:
    .byte 'A'

    .section    .note.GNU-stack,"",@progbits
    .section    .note.gnu.property,"x"

但这里string的地址被硬编码成了$0x7C0F。当我把该行替换为:

#mov $0x7c0f, %si
    mov string, %si

编译时报错:

/usr/bin/ld: /tmp/cctVBx2h.o: relocation R_X86_64_16 against `.text' can not be used when making a PIE object; recompile with -fPIE
/usr/bin/ld: failed to set dynamic section sizes: bad value

如何让GAS像在32位或64位模式下那样自动解析地址?

补充
我在Linux源码的arch/x86/realmode/rm/realmode.h中看到这样的注释:

This must be open-coded since gas will choke on using a relocatable symbol for the segment portion.

这是否意味着GAS确实无法正常完成该操作?


解决方法

1. 禁用PIE并指定链接地址

GAS默认会生成PIE(位置无关可执行文件),但16位Bootloader需要固定地址的代码。你需要在编译链接时明确指定链接地址为0x7C00,同时禁用PIE。

编译命令示例:

as --32 boot.s -o boot.o
ld -m elf_i386 -Ttext=0x7C00 --oformat binary boot.o -o boot.bin
  • --32:告诉GAS生成32位目标文件(兼容16位模式)
  • -m elf_i386:让ld使用32位ELF链接器
  • -Ttext=0x7C00:指定代码段加载地址为0x7C00
  • --oformat binary:输出纯二进制文件,符合Bootloader要求

2. 调整汇编代码中的符号引用

修改后的汇编代码可以直接使用符号地址,无需硬编码:

.code16   
.text

.globl main
main:
    mov $0xb800, %ax
    mov %ax, %es
    
    mov $string, %si  # 直接引用符号
    movb (%si), %al
    mov %al, %es:0
hlt

string:
    .byte 'A'

.section    .note.GNU-stack,"",@progbits
.section    .note.gnu.property,"x"

关于Linux源码注释的说明

那个注释说的是实模式下使用符号作为段地址部分的情况会触发GAS的问题,而你这里是用符号作为代码段内的偏移地址,只要通过正确的链接参数指定加载地址,GAS完全可以正常解析符号地址。注释里的场景和你的需求不同,不用担心。

内容的提问来源于stack exchange,提问作者performancematters

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:55:10