在linux x86-64和换行符中添加两个数字

时间:2014-10-05 15:41:42

标签: assembly x86-64 att

我目前正在尝试学习汇编语言。我想我会尝试试错,但我不能理解为我能够做到这一点。我想写一个简单的程序,允许我输入2个数字,然后将两个数字打印在一起,所以只需添加。

我试着开始尝试输入两个数字而不是打印这两个数字,但是当我输入第二个数字时,我得到了分段错误。

我想知道的另一件事是当我输入“%d \ n”而不是“%d”时,我必须连续两次输入一个数字。我想打印单独行的数量,但是当我尝试这样做时,我必须连续两次输入数字。我想知道为什么会发生这种情况以及如何解决它。

如果之前有人询问,我很抱歉。我之前可能遇到过这个帖子,但我发现很难理解解决方案以及其他人的代码。

.text

    string: .asciz "Your first program\n"
    number1: .asciz "%u"
    number2: .asciz "%d"

.global main

main:

    movq $0, %rax
    movq $string, %rdi
    call printf
    call adding
    call end

adding:

    movq %rsp, %rbp
    subq $8, %rsp
    leaq -8(%rbp), %rsi
    movq $number1, %rdi
    movq $0, %rax
    call scanf
    popq %rsi
    movq $number1, %rdi
    movq $0, %rax
    call printf
    movq $0, %rdi
    subq $8, %rsp
    leaq -8(%rbp), %rsi
    movq $number2, %rdi
    movq $0, %rax
    call scanf
    popq %rsi
    movq $number2, %rdi
    movq $0, %rax
    call printf
    movq -16(%rbp), %rax
    movq %rbp, %rsp
    popq %rbp
    movq -16(%rbp), %rax
    movq %rbp, %rsp
    popq %rbp
    ret

end:

    movq $0, %rdi
    call exit

1 个答案:

答案 0 :(得分:0)

以下是一些适用于您的计划的修补程序:

.text

    string: .asciz "Your first program\n"
    number1in: .asciz "%u"     #use different format strings for input and output
    number2in: .asciz "%d"
    number1out: .asciz "%u\n"  #added "\n" to flush stdout.
    number2out: .asciz "%d\n"  #same

.global main

main:
    movq $0, %rax
    movq $string, %rdi
    push %rbp            #dummy push to satisfy 16-byte alignment requirements
    call printf
    call adding
    call end

adding:
    pushq %rbp           #must preserve %rbp before...
    movq %rsp, %rbp      #...%rbp is overwritten here
    subq $16, %rsp       #must subtract 16 from %rsp to satisfy 16-byte alignment
    leaq -8(%rbp), %rsi
    movq $number1in, %rdi
    movq $0, %rax
    call scanf
    movq -8(%rbp), %rsi  #this line must be edited...
    movq $number1out, %rdi
    movq $0, %rax
    call printf
    movq $0, %rdi
    leaq -8(%rbp), %rsi
    movq $number2in, %rdi
    movq $0, %rax
    call scanf
    movq -8(%rbp), %rsi  #as must this...
    movq $number2out, %rdi
    movq $0, %rax
    call printf
    movq %rbp, %rsp
    popq %rbp
    ret

end:
    pushq %rbp           #dummy push to satisfy 16-byte alignment
    movq $0, %rdi
    call exit