Reputation: 43
i am reading the csapp and some codes (x86-64) confuse me.
the book says "pushq %rbp" equals :
subq $8,%rsp
movq %rbp,(%rsp)
The c code is :
long P(long x,long y)
{
long u = Q(y);
long v = Q(x);
return u + v;
}
And the a part of the assembly code the book gives is :
pushq %rbp
pushq %rbx
subq $8,%rsp
The 'subq' confuse me.
Why it is like this?
Upvotes: 1
Views: 522
Reputation: 4369
Stack is a block of memory which grows down. There is a point in memory indicated by rsp
/esp
register which is a stack top. All memory above it is occupied by things placed on stack and all memory below it is free.
If you want to put something on stack you need to decrease rsp
register (that is what sub
instruction does) by number of bytes you need and rsp
will point now to the newly reserver area you needed.
Lets look at this simple example:
rsp
points to address 100. As said - whole memory above address 100 is used, and memory below 100 is free. So if you need 4 bytes you decrease rsp
by 4 so it points to 96. As you have just decreased rsp
you are aware that memory cells 96, 97, 98 and 99 are yours and you can use them. When you need more bytes on stack, then you again can decrease rsp
to get it more.
There are two ways puting things on stack.
1. you can decrease rsp
as shown above.
2. you can use push
instruction which does exactly the same but in one step: push rax
will decrease rsp
by 8 bytes (size of rax
register) and then will save its value in reserved area.
Sometimes also rbp
register is being used to operate on stack.
If you need a bigger area on stack, for example for local variables, you reserve required amount on stack and then you save current rsp
value into rbp
. So rbp
is a kind of bookmark remembering where your area is. Then you can push
more things on stack, without loosing information where the allocated area was.
Before leaving function all things placed on stack need to be taken from it. It is done by pop
instruction which is opposite to push
- takes value from stack and moves it to register and then increases rsp
. Or you can just increase rsp
if you do not need to restore register values.
Upvotes: 2