-1

I'm learning assembly and I have one question. Example:

int main()
{
    foo(a);
}

int foo (x)
{
    return 0;
}

when the foo function returns to main the ret instruction is executed. How does the ret instruction knows where the pushed EIP register is saved?

I know that before the foo function is called the EIP is pushed to the stack, but when ret in foo is executed, what the ret really does?

Thanks for your help

2
  • 3
    That is all over the Intel manuals. Short answer (those manuals are quite long): there is only one place where such a value is stored, the stack.
    – Jongware
    Jan 15 '17 at 13:02
  • felixcloutier.com/x86/ret
    – phuclv
    Feb 29 '20 at 12:22
4

The ret instruction actually performs quite a simple task.

It is composed of two operations in the CPU:

  1. It pops the topmost value off the stack.
  2. It sets the eip register to that popped value.

Therefore, the ret instruction never really "knows" or "finds out" where the previous eip value is stored. ret just assumes the topmost stack variable is the previous eip.

It is the responsibility for the developer (or, more commonly now - the compiler) to make sure that assumption is met whenever a ret instruction is executed by the CPU.

Making sure that assumption is valid is one of what some might say is the worst constraint enforced on the stack, and the reason why every function must make sure it leaves the stack in the same state it entered it.

It also makes some assembly tricks (such as hooking) a bit more complex, but I won't go into that here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.