使用RIP相对的OSX的x64汇编处理 [英] Using RIP-relative addressing in OSX x64 assembly
问题描述
我试图做一个基本的的printf
例如,在x86-64的组装$ C $下OSX,这是我的第一个版本:
I was trying to make a basic printf
example in x86-64 assembly code for OSX, here's my first version:
section .data
msg db 'hello', 0Ah
section .text
extern _printf
global _main
_main:
sub rsp, 8
mov rdi, msg
mov rax, 0
call _printf
add rsp, 8
ret
所以这个code为移动信息
的绝对地址为 RDI
的第一个参数 _printf
,和gcc再抱怨缺少位置无关code。二进制仍然有效,但:
So this code is moving the absolute address of msg
into rdi
for the first argument to _printf
, and gcc then complains about the lack of position-independent code. The binary still works though:
→ nasm -f macho64 new.asm && gcc -m64 -o new new.o && ./new
ld: warning: PIE disabled. Absolute addressing (perhaps -mdynamic-no-pic) not allowed in code signed PIE, but used in _main from new.o. To fix this warning, don't compile with -mdynamic-no-pic or link with -Wl,-no_pie
hello
所以,当我改变code使用RIP相对寻址,使用 [REL ...]
NASM语法,报警消失,但可执行现在赛格故障:
So when I change the code to use RIP-relative addressing, using the [rel ...]
nasm syntax, the warning disappears but the executable now seg faults:
section .data
msg db 'hello', 0Ah
section .text
extern _printf
global _main
_main:
sub rsp, 8
mov rdi, [rel msg]
mov rax, 0
call _printf
add rsp, 8
ret
当我编译并运行它:
And when I compile and run it:
→ nasm -f macho64 new.asm && gcc -m64 -o new new.o && ./new
zsh: segmentation fault ./new
有谁知道是怎么回事了?
Does anyone know what's going wrong?
推荐答案
现在的问题是,原来的 MOV偏下,味精
加载信息
到 RDI
的组装时间。
The problem is that the original mov rdi, msg
loaded the memory address of msg
into rdi
at assemble time.
当它被更改为 MOV偏下,[REL味精]
,由此产生它用的值code 信息
作为相对地址,在调试的时候看到的:
When it was changed to mov rdi, [rel msg]
, this produced code which used the value in msg
as the relative address, as seen when debugging:
Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x00000a6f6c6c6568
请注意如何地址包含字节从信息
, 0x00000a< olleh>
正确的解决办法是使用 LEA
指令在运行时加载信息
的有效RIP-相对地址,像这样:
The correct solution is to use the lea
instruction to load the effective RIP-relative address of msg
at runtime, like so:
lea rdi, [rel msg]
这篇关于使用RIP相对的OSX的x64汇编处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!