user2304942
user2304942

Reputation: 51

return to call after jumps in assembly

this is probably an easy one, but I'm confused about this for some time:

Suppose I have something like

main:
...
call some_fun
...

some_fun:
...
jmp op
...

op:
...
ret

would this ret correctly return to where the call starts? if not, then how would the ret returns correctly?

Upvotes: 2

Views: 7797

Answers (2)

ady
ady

Reputation: 173

If it still crashes then try out

move dword[stak],esp ;at the very start

and end with

mov esp,[stak]

ret

kinda thing

gl

Upvotes: 1

Sparky
Sparky

Reputation: 14057

If in the provided example, you want the next instruction it executes after it returns to be the instruction after call some_fun, then yes it will do exactly as you want provided that you clean up your stack frame before returning.

Assuming that you are using x86 assembly, here is what is going on.

  1. When call some_fun is executed, it pushes the return address onto the stack and then changes the program counter/instruction pointer to point to some_fun so it continues execution there.
  2. The jmp op instruction does not modify the stack. It only modifies the program counter/instruction pointer.
  3. The ret instruction pops a value off the stack and dumps it into the program counter/instruction pointer. The value it pops off the stack is known as the return address. It is vitally important that anything some_fun and op have pushed onto the stack be popped off before issuing ret. Otherwise, you will return to the wrong return address.

Hope this helps.

Upvotes: 8

Related Questions