我有一个适用于 x86_64 的 multiboot2 兼容 ELF 文件,其中启动符号定义在start.asm
,NASM 汇编文件。 multiboot2 标头包含relocatable
tag.
因为 GRUB 不支持 multiboot2 + 可重定位的 ELF(至少在 2021 年 7 月 [3 https://github.com/rhboot/grub2/blame/a53e530f8ad3770c3b03c208c08ae4162f68e3b1/grub-core/loader/multiboot_elfxx.c#L247]),我想自己解决一些重定位来解决这个问题并加载一个静态ELF。
为此,我需要在运行时获取第一个条目符号(在 ELF 标头中指定)中的偏移量,以便手动解决重定位问题。对于偏移量,我指的是 GRUB 在内存中定位二进制文件与 ELF 文件中符号的静态地址相比的差异。
在我的输入符号中,我处于 64 位长模式。无法直接访问rip
在 NASM 语法中,因此我需要某种解决方法。
解决方案如[1 https://stackoverflow.com/questions/8333413/why-cant-you-set-the-instruction-pointer-directly] [2 https://stackoverflow.com/questions/52049481/how-to-get-the-instruction-pointer-in-x86-64-without-0x00-or-0xff-bytes] 不起作用,因为rip
关键字/寄存器在 NASM 中不可用。因此我不能使用
lea rax,[rip+0x1020304]
; rax contains offset
sub rax,0x1020304
我该如何解决这个问题?
唯一的访问方式rip
in nasm
是通过rel
-关键字[1 https://stackoverflow.com/questions/68470114/]。如果没有奇怪的解决方法,它就不能直接使用而只能使用符号。要使用符号解决该问题,可以使用以下代码:
; 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
请注意,这确实很棘手,需要对几个低级主题有深入的专业知识。谨慎使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)