ElP*_*roo 5 assembly callstack riscv
我把一个很简单的C程序转成汇编文件(这里是RISC-V ISA),在堆栈指针上做了一些我不明白的操作。
C程序:
int main()
{
int a = 10;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
相关的汇编代码:
.file "alternating_branches_2.c"
.option nopic
.text
.align 1
.globl main
.type main, @function
main:
addi sp,sp,-32
sd s0,24(sp)
addi s0,sp,32
li a5,10
sw a5,-20(s0)
li a5,0
mv a0,a5
ld s0,24(sp)
addi sp,sp,32
jr ra
.size main, .-main
.ident "GCC: (GNU) 8.3.0"
Run Code Online (Sandbox Code Playgroud)
这是我的理解。
sp 包含堆栈内存的最后一个地址。因此,压入堆栈会降低 sp 的值。s0 是帧指针,指向 sp 的前一个值。
在第一行中,从堆栈指针开始减少 32 的偏移量。这是要创建堆栈帧吗?通常,在堆栈中,推送操作会减少堆栈指针。但是,既然已经创建了一个栈帧,现在sp指向栈的下层内存,push会增加sp的值吗?
-------------| <--sp
-------------|
-------------|
-------------|
-------------|
-------------|
-------------|
Run Code Online (Sandbox Code Playgroud)
创建堆栈帧后:
-------------| <--s0
-------------|
-------------|
-------------|
-------------|
-------------|
-------------| <--sp
Run Code Online (Sandbox Code Playgroud)
现在,推入堆栈必须导致 sp 增加,对吗?或者也可以使用帧指针 s0 进行推送?如果这是一个非常基本的问题,我深表歉意。谢谢你。
Unlike the x86 ISA \xe2\x80\x93 which has dedicated instructions for pushing onto and popping from the stack, the RISC-V ISA can only access memory through load and store instructions. It has no push and pop instructions that access the stack \xe2\x80\x93 which is the memory \xe2\x80\x93 and modify the stack pointer.
\n\nSince the stack grows downwards, decreasing the stack pointer, sp, allocates space on the stack, whereas increasing it deallocates space. That is, addi sp,sp,-32 allocates 32 bytes on the stack and addi sp,sp,32 deallocates 32 bytes from the stack. The former creates the new stack frame, and the latter destroys it.
寄存器\xe2\x80\x93与\xe2\x80\x93s0相同,是帧指针,指向堆栈帧的开头。它的当前值保存在新创建的堆栈帧 ( ) 的最开始处。然后,它被设置为指向堆栈帧开头的地址()。最后,在离开函数之前,帧指针将恢复为其先前的值 ( )。fpsd s0,24(sp)addi s0,sp,32ld s0,24(sp)
堆栈帧创建和帧指针设置后堆栈的表示为:
\n\n| ... |\n|-------------|<- s0 | beginning of stack frame\n| previous s0 |\n|-------------|<- sp-24\n|-------------|\n|-------------|\n|-------------|\n|-------------|\n|-------------|\n|-------------|\n|-------------|<- sp | end of stack frame\nRun Code Online (Sandbox Code Playgroud)\n