Possible Duplicate:
How to get the length of a function in bytes?
I’m making a Hooking program that will be used to insert a method into the specified section of memory.
I need to get the length of a local C++ function, I’ve used a cast to get the location of a function, but how would I get the length?
would
int GetFuncLen()
{
int i = 0;
while((DWORD*)Function+i<max)
{
if((DWORD*)Function+i==0xC3)
{
return i;
}
i++;
}
}
work?
Your code seems to be operating system, compiler, and machine architecture specific.
(I know nothing about Windows)
It could be wrong if
maxis not defined.It is operating system specific (probably Windows only) because
DWORDis not a standard C++ type. You could useintptr_t(from<cstdint>header).Your code is compiler specific, because you assume that every compiled function has a well defined unique end, and don’t share any code with some other functions. (Some compilers are able to do such optimizations, and e.g. make two functions sharing a common epilogue or code chunk, using jump instructions).
Your code is machine specific, because you assume that the last instruction would be a
RETcoded0xC3and this is specific to x86 & x86-64 (won’t work on Alpha or ARM, on which Windows is rumored to have been or to be ported). Also, that byte could appear inside other instructions or inlined constants (as Mat commented).I am not sure that the notion of where a binary function ends has a well defined meaning. But if it does, I would expect that the linker may know about it. On some systems, for example on Linux with ELF executable, the compiler and the linker produces the size of each function.
Perhaps you better need to find the symbol near to a given address. I don’t know if Windows has such a functionality (on Linux, the dladdr GNU function from
<dlfcn.h>could be useful). Perhaps your operating system provides an equivalent?