Ok so I want to learn what is the problem in the following code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
|
typedef int (*foo_ptr)(void);
static int foo()
{
return 20;
}
static void after_foo(){}
void main(int argc, char **argv)
{
size_t foo_size = (LPBYTE)after_foo - (LPBYTE)foo;
foo_ptr p_foo = (foo_ptr) VirtualAlloc(0, foo_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
CopyMemory(p_foo, &foo, foo_size);
int res = (*p_foo)();
}
|
Now it works perfectly as this but it crashes as soon as i insert printf("something") in the foo function. so the code that fails is the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
|
typedef int (*foo_ptr)(void);
static int foo()
{
// this is the only modification
printf("test to print");
return 20;
}
static void after_foo(){}
void main(int argc, char **argv)
{
size_t foo_size = (LPBYTE)after_foo - (LPBYTE)foo;
foo_ptr p_foo = (foo_ptr) VirtualAlloc(0, foo_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
CopyMemory(p_foo, &foo, foo_size);
int res = (*p_foo)();
}
|
What i have noticed is that it crushes each time i insert a code that access the heap memory in the foo function. If i insert a code that allocates a heap it is not a problem (example int x; ). I think it is something with the static functions and their address translation (absolute vs relative)...
Any answer would be appreciated
P.S. Please note that i do not want to do some mallware code.. i mean i know how to inject the code in the address space of another process i just cant figure it out how to insert it in the address space of the same process...... I have done a data management component which i use to share data between processes (IPC). The data management component works on a File mapped memory and uses custom heap implementation over that memory (using offsets since the memory is mapped differently in each process) to store the data. Now i want to boost it to share not only data between processes but also a code. The idea is that i do not want to inject the code from another process instead to inject the code in a shared memory space then from another process to copy the function in the local memory space and execute it from there.
Example:
App1 -> store foo() in DM
App2 -> read foo() from DM
App2 -> write foo() in local memory space (with PAGE_EXECUTE_READWRITE protection flag set)
App2 -> execute foo()
* DM is already created and works fine with data
* I understand that foo must not call functions from libraries that are not loaded in App2
Uffff tooo long post... sorry Smile
regards
Nikola