【问题标题】:Segmentation fault when using printf in nasm 64bit [duplicate]在 nasm 64bit 中使用 printf 时出现分段错误 [重复]
【发布时间】:2021-10-16 09:35:54
【问题描述】:

我正在尝试在 nasm 64 位 linux 中调用 printf。但是当我运行它时它会输出分段错误。我对齐堆栈,在字符串末尾添加一个 0 转义字符。但它仍然输出段错误。

代码:

section .data
_DATA1 db "aa", 0

section .text
global main
extern printf
main:
sub rsp, 16
lea r13, [_DATA1]
mov rdi, r13
call printf
add rsp, 16
mov rax, 0
ret 

组装和链接

nasm -f elf64 a.asm
gcc -no-pie a.o

我哪里做错了?

【问题讨论】:

  • 要对齐堆栈,您必须使用sub rsp, 8

标签: gcc segmentation-fault printf x86-64 nasm


【解决方案1】:

好的,我明白了。 原来我需要在main 之后添加:

push rbp
mov rbp, rsp

所以代码看起来像这样:

section .data
_DATA1 db "aa", 0

section .text
global main
extern printf
main:
push rbp
mov rbp, rsp
sub rsp, 16
lea r13, [_DATA1]
mov rdi, r13
call printf
add rsp, 16
mov rax, 0
mov rsp, rbp
pop rbp
ret 

我意识到这也是 gcc 所做的

【讨论】:

  • 将 RSP 转移到 RBP 不是原因。
  • 即使在当前的 glibc 版本中 AL=0,printf 是否关心堆栈对齐? scanf 有一阵子了:glibc scanf Segmentation faults when called from a function that doesn't align RSP
  • @MichaelPetch 好吧,我想知道,但不知何故,它神奇地起作用了......
  • 如果你也将 RBP 推到顶部并在 ret 之前弹出它,我可以理解它的工作原理
  • @michael 啊,是的,我确实推送了 rbp 并在 ret 之前将其弹出。这可能就是原因。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-12-27
  • 1970-01-01
  • 2011-02-27
  • 2013-12-23
  • 1970-01-01
  • 2018-06-06
相关资源
最近更新 更多