Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does an arbitrary instruction pointer reside in a specific function?

Tags:

c++

c

I have a very difficult problem I'm trying to solve: Let's say I have an arbitrary instruction pointer. I need to find out if that instruction pointer resides in a specific function (let's call it "Foo").

One approach to this would be to try to find the start and ending bounds of the function and see if the IP resides in it. The starting bound is easy to find:

    void *start = &Foo;

The problem is, I don't know how to get the ending address of the function (or how "long" the function is, in bytes of assembly).

Does anyone have any ideas how you would get the "length" of a function, or a completely different way of doing this?

Let's assume that there is no SEH or C++ exception handling in the function. Also note that I am on a win32 platform, and have full access to the win32 api.

like image 915
LCC Avatar asked Jul 09 '26 12:07

LCC


1 Answers

This won't work. You're presuming functions are contigous in memory and that one address will map to one function. The optimizer has a lot of leeway here and can move code from functions around the image.

If you have PDB files, you can use something like the dbghelp or DIA API's to figure this out. For instance, SymFromAddr. There may be some ambiguity here as a single address can map to multiple functions.

I've seen code that tries to do this before with something like:

#pragma optimize("", off)
void Foo()
{
}

void FooEnd()
{
}
#pragma optimize("", on)

And then FooEnd-Foo was used to compute the length of function Foo. This approach is incredibly error prone and still makes a lot of assumptions about exactly how the code is generated.

like image 185
Michael Avatar answered Jul 12 '26 01:07

Michael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!