简体   繁体   English

如何在x86-64 Assembly中使用堆栈?

[英]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. 我用scanf读了两个整数,然后尝试将它们存储到rbxrcx寄存器中。 However, when I try to print one of them out, it just prints out some random integer. 但是,当我尝试打印其中之一时,它只是打印出一些随机整数。

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. 如果您对rsp自己的操作,那么很明显第二个数字仍在地址(%rsp)因为没有任何变化,而第一个数字为8(%rsp)因为您已经从rsp减去了8阅读。 Also, as @EOF said, you do not need the indirection: 另外,正如@EOF所说,您不需要间接调用:

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. 请注意,调用约定要求保留rbx ,因此销毁它是个坏主意。 x86-64 has plenty of other registers to choose from ;) (But beware, some others need to be preserved too). x86-64还有很多其他寄存器可供选择;)(但是请注意,还需要保留其他一些寄存器)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM