On May 9, 3:08 pm, "all.ju...@gmail.com" <p.compass...@gmail.com>
wrote:
> Hi,
>
> Let's say I'm in function foo.
> I am trying to find the function(or return address) which called foo.
>
> Initially, I thought I could use stack base pointer(ebp+4) to find the
> return address.
> However, my compiler(vs7) would go through so many function call and
> ebp+4 points to somewhere in kernel32.
ebp+4 just points to return address, you have to dereference it in
order to obtain one.
But, generaly it depends when you obtained ebp.
ebp usually points to stack frame of previous function when entering
routine and of course esp points to return address.
so each function does this first:
push ebp; saves frame
mov ebp,esp;
sub esp, size; alloc mem for locals
now [ebp+4] points to return address,
and [ebp] to previous frame. (valid only for 32 bit)
But if omit frame pointer optimization is enabled you don;t get
frame from prev function in ebp. Actually without frame pointer
I can;t see how to do frame walk at all.
>
> I can use the address of parameter and obtain the return address.
> When the function call is cdecl, the return address is at
> [&firstparameter -4]
Use compiler instrinsics for these things, or inline assembly.
(for example gcc has intrinsics for getting frame pointer and return
address,
and it is portable to different platforms, though only level 0 frame
is promised to work and if frame optimizations are disabled)
> I can use this but it depends on the calling convention.
Calling convention and CPU and optimizations

for example what I said is not true any more for
64 bit windows (both assembly and frame set up are different).
>
> I feel there must be a more general way to get a return address. (any
> api?)
There can't be general way as code to set up stack frame
is not required to exist. This is CPU, OS and compiler
specific thing.
Greetings, Branimir.