sav0h
sav0h

Reputation: 391

What is the value of esp after a function returns?

In C / x86, when returning from a function we typically:

  1. pop ebp to restore the previous function's frame pointer
  2. ret which (as I understand) contains an implicit pop eip so that the calling function can continue to execute from the return address

At this point, what can I expect esp to contain? Will it be a pointer to whatever was directly above the return address, or is the value of esp also implicitly changed by ret ?

Thanks :)

Upvotes: 3

Views: 2624

Answers (3)

Matt
Matt

Reputation: 15091

Will it be a pointer to whatever was directly above the return address, or is the value of esp also implicitly changed by ret ?

There are two forms of ret: just ret and ret N. The first form simply pops eip (which as usual means both "take eip and add esp,4") from stack and continues execution, so esp points at the last parameter pushed when calling the function - this means that caller must deal with this by subsequent add esp, N.

ret N means that after popping eip, esp is added by value N in the same instruction, so there's no need for the caller to do that. The drawback is that you can't use variable number of args, because 'N' can only be constant value.

Upvotes: 9

lostbard
lostbard

Reputation: 5220

After the ret, sp should be the same as it was at the point where the call to the function occured.

So it would point to whatever was last pushed to the stack.

Upvotes: 1

fuz
fuz

Reputation: 93014

After a ret, esp should contain the same value it had right before the corresponding call if no shenanigans happened in between. The call instruction pushes the return value on the stack, the ret instruction pops it off. So yes, your intuition is correct.

Upvotes: 2

Related Questions