0

When trying to use external C function in assembly, I have segfaults without knowing why. Does it have something to do with stack alignement ? I can't find the right documentation (a link will be highy appreciated).

My code :

extern printf

section .data
int_string: db "hey, your result is %d", 10, 0
global main
main:
    push rbp
    mov rbp, rsp
    mov rax, 78
    push rbp
    mov rdi, int_string
    mov rsi, rax ; 78 in rsi
    call printf
    pop rbp
    mov rax, 1
    leave
    ret

I compile using :

nasm -f elf64 test.asm 
gcc -no-pie -fno-pie test.o -o test
./test

Note that this sometimes works.

My working environment : Linux (ubuntu) Intel i7

  • 1
    Yep, classic stack alignment problem. Will link you to an appropriate duplicate. – fuz Oct 19 '22 at 11:41
  • 1
    "Sometimes works" sounds very unlikely, unless you're talking about changing the source. If this segfaults at all, it should segfault every time you run the program, as RSP % 16 == 8 is guaranteed on entry to any function, including `main`. (And thus RSP%16 == 0 is required *before* a call) – Peter Cordes Oct 19 '22 at 12:05
  • @fuz I had already seen that thread and still can't fix my problem. Since the syntax is different, I don't get to make it work. – user13123535 Oct 19 '22 at 18:24
  • 1
    In simplest terms, change your code to have an **odd** number of `push` instructions before the call to printf. You currently have 2. Remove the second push, which is unnecessary, and remove the corresponding pop. – prl Oct 19 '22 at 23:23

0 Answers0