Caspian Ahlberg
Caspian Ahlberg

Reputation: 976

Assembly function call using stack-based calling conventions

I am confused. I am looking at this page to work on understanding how to use the stack to pass parameters to functions. However, my code is not working as expected. Given that I'm putting the computed result in rax, I'm expecting the exit code to be 9 but this is not the case; instead, my exit code is 150. Does someone who understands this calling convention with the stack in x86 know what I am doing wrong, and how to achieve what I'm trying to solve? I'm assembling with GAS on a Mac like this: gcc -masm=intel stack_frames.asm

    .global _main
    .text
_main:
    push 4  # arg 2
    push 5  # arg 1
    call plus

    mov rdi, rax  # exit code = result in rax, which I'm expecting to be 9
    mov rax, 0x2000001
    syscall

plus:
    push rbp
    mov rbp, rsp

    mov rsi, [rbp + 12]  # param 1
    mov rdi, [rbp + 8]  # param 2
    add rdi, rsi  # sum in rdi
    mov rax, rdi  # move sum to rax

    mov rsp, rbp
    pop rbp
    ret

Upvotes: 1

Views: 279

Answers (1)

You're on x86-64, which is 64 bits, not the 32-bit x86. You know this because you were able to use 64-bit registers like rax. As such, push and call push 8 bytes, not 4, so your parameters will be at [rbp + 24] and [rbp + 16], not [rbp + 12] and [rbp + 8].

Upvotes: 2

Related Questions