views:

103

answers:

4

I have some binary data which contains a bunch of functions and want to call one of it. I know the signature of these functions along with the offset relative to the start of the file. Calling convention is the default one: __cdecl. The file was already loaded into a memory page with executing permissions.

For example (A, B, C being some types)

void myFunction (A *arg1, B arg2, C arg3); // Signature
int myOffset = 0x42; // Offset

How can I specify that myOffset points to myFunction?

+1  A: 
( (void(*)(A*,B,C))0x42 )(a,b,c);

Or something like that. Always had troubles getting that at the first time. That is if I understand your question right, anyway.

Michael Krelin - hacker
+4  A: 

I am not quite sure what you are asking. I assume that you try to declare a function pointer, and assign a function 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 the function,

p(a,b,c) or (*p)(a,b,c);
leiz
+5  A: 
// define a function pointer
typedef __cdecl void (*your_function) (A *arg1, B arg2, C arg3); 
your_function ftr;

char * memory = 0x123456; // base segment address

fptr = (your_function)(memory + 0x42); //calculate memory address

(*ftpr)(a,b,b); // call function
ebo
+3  A: 

For the question itself: you simply need to add the address in memory you loaded the binary to. I.e. if you loaded the binary to address myLoadAddress just add that to myOffset. This won't enable you to easily call the function, however. If you want to do that, you should treat it like a library file (and if it in fact is a library file check for a system function for loading libraries like LoadLibrary on Windows, then use GetProcAddress to retrieve a pointer to the function).

// 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 using LoadLibrary, then use GetProcAddress and typecast the address returned to your function pointer -- i.e. myFuncPointer = (myFunc)GetProcAddress(hmodule, "myFunc"); in the example.

On POSIX it works pretty much the same, but the functions are slightly different: use dlopen to load the dynamic library, and dlsym to retrieve the symbol. The Programming Library Howto describes this in more detail, or see the man pages for dlopen and dlsym. The basics are the same.

bluebrother
+1 for an excellent example, if you are familiar with posix you should update your answer
mtasic