1

我有一个适用于 x86_64 的 multiboot2 兼容 ELF 文件,其中开始符号在start.asmNASM 程序集文件中定义。multiboot2 标头包含relocatable标记。

因为 GRUB 不支持 multiboot2 + 可重定位的 ELF(至少在 2021 年 7 月 [ 3 ]),所以我想自己解决一些重定位问题以解决此问题并仅加载静态 ELF。

为此,我需要在运行时在我的第一个条目符号(在 ELF 标头中指定)中获取偏移量,以便手动解决重定位问题。偏移量是指 GRUB 在内存中定位二进制文​​件的位置与 ELF 文件中符号的静态地址之间的差异。

在我的输入符号中,我处于 ​​64 位长模式。无法直接rip以 NASM 语法访问,因此我需要某种解决方法。

[ 1 ] [ 2 ] 之类的解决方案不起作用,因为rip关键字/寄存器在 NASM 中不可用。因此我不能使用

lea    rax,[rip+0x1020304]
; rax contains offset
sub    rax,0x1020304

我该如何解决这个问题?

4

1 回答 1

2

访问ripin的唯一方法nasm是通过rel-keyword [ 1 ]。如果没有一个奇怪的解决方法,它不能立即接受,而只能接受一个符号。要使用符号解决它,以下代码有效:

; the function we want to jump to. We need to calculate the runtime
; address manually, because the ELF file is not relocatable, therefore static.
EXTERN entry_64_bit

; start symbol must be globally available (linker must find it, don't discard it)
; Referenced in ELF-Header.
GLOBAL start

SECTION .text

; always produce x-bit x86 code (even if this would be compiled to an ELF-32 file)
[BITS 64]

    ; very first entry point; this is the address where GRUB loads the binary
    start:
        ; save values provided by multiboot2 bootloader (removed here)
        ; ...

        ; Set stack top (removed here)
        ; ...

        ; rbx: static link address
        mov     rbx, .eff_addr_magic_end

        ; rax: runtime address (relative to instruction pointer)
        lea     rax, [rel + .eff_addr_magic_end]
    
    .eff_addr_magic_end:
        ; subtract address difference => offset
        sub     rax, rbx
        ; rax: address of Rust entry point (static link address + runtime offset)
        add     rax, entry_64_bit
        jmp     rax

请注意,这确实很棘手,需要对几个低级主题有深入的专业知识。谨慎使用。

于 2021-07-21T15:38:15.233 回答