Assembly return address

I want to get the return address of a function in an assembly, and then compare that return address value with another value without distorting the stack or changing anything on the stack.

how can this be done in assembly?

I am using x86


source to share

3 answers

Typically on x86, if the stdcall return address is used, it is stored in the contents of the ebp +4 register. So I cmp ebp, whatever;

have to do the job. It does not actually depend on the calling convention, but rather whether your compiler puts push ebp as the first instruction of your function, which it usually does. The Generaly function looks like this:

push ebp
mov ebp,esp
sub esp,size_of_local_variables
somehting something something
mov esp, ebp
pop ebp




You can create a wrapper function.

int the_real_function ( unsigned int a, unsigned int b )


Create some lines of assembler:

  save registers if needed
  grab the return address here
  if passed on stack copy parameters
  call the_real_function
  if return is stack based place it where needed
  restore registers if needed


Not real asm code, obviously. The function you want to test will rename, then asm will have the function name, compilation and reference and all function calls will go through the wrapper. To write the above, you must know the calling convention for this purpose, the compiler, compiler options, etc.



In general, you will need to disassemble this function manually or with the help of some of your code and analyze the disassembly (again, manually or with some heuristic in your code) to see the behavior of the stack pointer and any associated registers (e.g. ebp ) or variables in that function until your code starts that needs a return address.

If you do everything by hand, it will be easy for you to find out the location of the return address and its hardcoded, but the resulting code will be very fragile as any code changes and changes in how you compile it could break it.

OTOH, implementing a solution in code that will always (or almost always) work despite code changes and compilation changes will be very tedious and difficult.

Can you tell us why you need a return address? What is the problem you are trying to solve with this?



All Articles