0

I'm trying to call printf in nasm 64 bit linux. But it outputs segmentation fault when i run it. I alligned the stack, add a 0 escape character to the end of the string. But it still output segfault.

The code:

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 

assemble and link with

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

Where did i do something wrong?

Michael Petch
  • 46,082
  • 8
  • 107
  • 198

1 Answers1

0

Ok, i got it. It turns out i need to add after main :

push rbp
mov rbp, rsp

So the code looks like this:

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 

I realise that this is also what gcc do

  • 1
    Moving RSP to RBP isn't the reason. – Michael Petch Aug 13 '21 at 12:14
  • Does printf care about stack alignment even with AL=0 in current builds of glibc? Scanf has for a while: [glibc scanf Segmentation faults when called from a function that doesn't align RSP](https://stackoverflow.com/q/51070716) – Peter Cordes Aug 13 '21 at 12:52
  • @MichaelPetch well, idk but somehow, it magically works... – blend_smile Aug 13 '21 at 13:40
  • 1
    I could understand it working if you also pushed RBP at the top and popped it before the ret – Michael Petch Aug 13 '21 at 21:11
  • @michael ah yes, i do pushed rbp and popped it before ret. That's probably why. – blend_smile Aug 13 '21 at 23:45
  • That makes sense. Pushing an 8 byte value has the effect of subtracting 8 from RSP which aligned the stack. When `main` is initially called the stack was 16 byte aligned but the call itself placed the 8 byte return address on the stack misaligning the stack by 8. To realign you'd have to subtract 8, 24, 40 etc – Michael Petch Aug 14 '21 at 07:47
  • 1
    You should have been able to get it to work without the push and use of rbp altogether by subtracting 8 from RSP in our original question. – Michael Petch Aug 14 '21 at 17:11