微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

nasm:在运行时从 rip指令指针获取重定位二进制文​​件的偏移量

如何解决nasm:在运行时从 rip指令指针获取重定位二进制文​​件的偏移量

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

因为 GRUB 不支持 multiboot2 + 一个可重定位的 ELF(至少在 2021 年 7 月 [3]),我想自己解决一些重定位来解决这个问题,只需加载一个静态 ELF。>

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

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

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

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

我该如何解决这个问题?

解决方法

访问 rip 中的 nasm 的唯一方法是通过 rel 关键字 [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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?