user2923535
user2923535

Reputation: 594

How to use the stack in x86-64 Assembly?

I'm having a bit of trouble how to access variables in the stack. Here is what I'm doing:

.data
.text
input:
    .string "%ld"   #format for input
output:
    .string "%ld.\n"    #format for output

.global main
pushq   %rbp                    #push base pointer, also known as frame pointer
movq    %rsp, %rbp              #set base pointer to stack pointer, reference off of rbp for locals

subq    $8, %rsp                #allocate 16 bytes for local use
movq    $input, %rdi            #calls scanf in the format of input
movq    %rsp, %rsi
movq    $0, %rax
call    scanf


subq    $8, %rsp
movq    $input, %rdi            #calls scanf in the format of input
movq    %rsp, %rsi
movq    $0, %rax
call    scanf

movq    -8(%rsp), %rbx          #stores first number into reg rbx
movq    (%rbx),%rbx
movq    -16(%rsp), %rcx         #stores second number into reg rcx
movq    (%rcx),%rcx


movq    $output,%rdi            #prints in format input
movq    $0, %rax
movq    %rcx, %rsi
call    printf

addq $16, %rsp
popq %rbp
ret

I read in two integers with scanf and then try to store them into rbx and rcx registers. However, when I try to print one of them out, it just prints out some random integer.

Upvotes: 0

Views: 2673

Answers (1)

Jester
Jester

Reputation: 58762

If you follow through your own operations on rsp it should be obvious that the second number is still at address (%rsp) since nothing has changed and the first number is at 8(%rsp) because you have subtracted 8 from rsp since you have read it. Also, as @EOF said, you do not need the indirection:

movq    8(%rsp), %rbx        #stores first number into reg rbx
movq    (%rsp), %rcx         #stores second number into reg rcx

Note that calling convention mandates rbx to be preserved so it's a bad idea to destroy that. x86-64 has plenty of other registers to choose from ;) (But beware, some others need to be preserved too).

Upvotes: 2

Related Questions