Glibc Scanf Segmentation Faults When Called from a Function That Doesn't Align Rsp

Segmentation fault when calling printf from C function called from assembly

You're not maintaining stack alignment. The ABI says that %rsp must always be a multiple of 16 right before a call instruction. call itself pushes one 8-byte quantity (the return address), so the stack pointer is always congruent to 8 (mod 16) at function entry, and it's your responsibility to fix that before you make another call.

This only causes a crash when the call to fprintf is uncommented because fprintf is actually doing something that takes advantage of this ABI requirement (specifically, using some of the x86-64 vector instructions, probably to accelerate binary-to-decimal conversion). partition by itself doesn't do anything that cares.

The easiest way for you to fix it will be to junk the frame pointer. It's not required on x86-64 and that way you will be pushing an odd number of registers, which gives you the proper stack alignment as a side effect.

Segmentation fault when using printf in nasm 64bit

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



Related Topics



Leave a reply



Submit