【发布时间】:2021-03-25 02:47:56
【问题描述】:
这更像是一项学术练习,但我希望在汇编中编写一个递归函数,如果它接收到“中断信号”并返回到主函数,而不仅仅是调用的函数它(通常是相同的递归函数)。
对于这个测试,我正在做一个基本的倒计时并打印一个字符的数字(8...7...6...等)。为了模拟一个“中断”,我使用了数字7,所以当函数达到7(如果它从上面开始),它将返回一个1,表示它被中断了,如果它没有被中断,它会倒计时到零。到目前为止,这是我所拥有的:
.globl _start
_start:
# countdown(9);
mov $8, %rdi
call countdown
# return 0;
mov %eax, %edi
mov $60, %eax
syscall
print:
push %rbp
mov %rsp, %rbp
# write the value to a memory location
pushq %rdi # now 16-byte aligned
add $'0', -8(%rbp)
movb $'\n', -7(%rbp)
# do a write syscall
mov $1, %rax # linux syscall write
mov $1, %rdi # file descriptor: stdout=1
lea -8(%rbp), %rsi # memory location of string goes in rsi
mov $2, %rdx # length: 1 char + newline
syscall
# restore the stack
pop %rdi
pop %rbp
ret;
countdown:
# this is the handler to call the recursive function so it can
# pass the address to jump back to in an interrupt as one of the
# function parameters
# (%rsp) currntly holds the return address, and let's pass that as the second argument
mov %rdi, %rdi # redundant, but for clarity
mov (%rsp), %rsi # return address to jump
call countdown_recursive
countdown_recursive:
# bool countdown(int n: n<10, return_address)
# ...{
push %rbp
mov %rsp, %rbp
# if (num<0) ... return
cmp $0, %rdi
jz end
# imaginary interrupt on num=7
cmp $7, %rdi
jz fast_ret
# else...printf("%d\n", num);
push %rsi
push %rdi
call print
pop %rdi
pop %rsi
# --num
dec %rdi
# countdown(num)
call countdown_recursive
end:
# ...}
mov $0, %eax
mov %rbp, %rsp
pop %rbp
ret
fast_ret:
mov $1, %eax
jmp *%rsi
上面的方法看起来像一个有效的方法吗,在rsi 中传递我想要返回的内存地址?这个函数对我来说写起来非常棘手,但我认为主要是因为我对汇编非常陌生/原始。
【问题讨论】:
标签: recursion assembly x86 x86-64 setjmp