How to call a function from binary data
I have some binary data that contains a bunch of functions and wants to call one of them. I know the signature of these functions along with the offset from the start of the file. Calling convention is the standard: __cdecl
. The file has already been loaded into the memory page with permissions being executed.
For example ( A
, B
, C
- some types)
void myFunction (A *arg1, B arg2, C arg3); // Signature
int myOffset = 0x42; // Offset
How can I indicate what is myOffset
pointing to myFunction
?
source to share
I'm not really sure what you are asking. I am assuming you are trying to declare a function pointer and assign the pointer to some arbitrary address.
To declare a function pointer,
void (*p)(A*,B,C);
To assign it,
p = (void (*)(A*,B,C)))0x42;
To call a function,
p(a,b,c) or (*p)(a,b,c);
source to share
For the question itself: you just need to add the address to the memory where you loaded the binary into. That is, if you downloaded the binary to the address myLoadAddress
, just add it to the myOffset
. However, this will prevent you from calling the function easily. If you want to do this, you must treat it as a library file (and if in fact it is a library file, check the system function to load libraries such as LoadLibrary on Windows, then use GetProcAddress to get the function pointer).
// create a type for your function signature
typedef void (*myFunc)(A *arg1, B arg2, C arg3);
// create a pointer to your function
myFunc myFuncPointer;
// set the address of the function in memory
myFuncPointer = myLoadAddress + myOffset;
// invoke function
myFuncPointer(A, B, C);
When loading a DLL, you load it with LoadLibrary and then use GetProcAddress and assign the address returned to your function pointer - ie myFuncPointer = (myFunc)GetProcAddress(hmodule, "myFunc");
in this example.
On POSIX it works much the same, but the functions are slightly different: use dlopen
to load dynamic link library and dlsym
to get symbol. The Howto Programming Library describes this in more detail, or looks at the man pages for dlopen and dlsym . The basics are the same.
source to share