2014-12-02 256 views
0

我在如何訪問堆棧中的變量時遇到了一些問題。下面是我在做什麼:如何在x86-64 Assembly中使用堆棧?

.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 

我在兩個整數與scanf讀取,然後嘗試將其存儲到rbxrcx寄存器。但是,當我嘗試打印其中的一個時,它只是打印出一些隨機整數。

+3

單級太多間接:'movq(%rbx),%rbx','movq(%rcx),%rcx'需要消失。 – EOF 2014-12-02 01:08:35

+0

@EOF它仍然打印出一個隨機整數。 – user2923535 2014-12-02 01:14:12

+3

哦,對。你從錯誤的地方加載。 'movq -8($ rsp),%rbx'應該是'movq(%rsp),%rbx'和'movq -16(%rsp),%rcx'應該是'movq 8(%rsp),%rcx' 。 – EOF 2014-12-02 01:17:16

回答

3

如果按照通過的rsp你自己的操作應該是顯而易見的是,第二個數字仍然在地址(%rsp)因爲一切都沒有改變,第一個數字是在8(%rsp)因爲你是從rsp減去8,因爲您已經閱讀它。此外,作爲@EOF說,你不需要間接:

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

注意調用約定強制要求rbx被保存所以這是一個壞主意摧毀。 x86-64有很多其他的寄存器可供選擇;)(但要小心,其他一些寄存器也需要保存)。

+0

謝謝!這就是訣竅!我會用r10和r11代替:) – user2923535 2014-12-02 01:22:14