I'm messing around with some interprocess communication stuff and I am curious if it's possible to copy a function into some shared memory and run it from there from either process.
Something like:
memcpy(shared_memory_address, &func, &func + sizeof(func));
I realize you can't take the size of the function but that was what popped into my head.
That was fun.
But it seems like you can. Though I would NEVER do this:
Compiled on lenovo:T61p running Windows 7: using g++ 4.3.4
I would note that some types of hardware will prevent this as you can only execute code from specific memory area (the program area) which is marked in the hardware memory map file as read only (to prevent self modifying code).
Note also that the type of function is very limited:
In this example func() does very a little and therefore works.
But if you do any of the following it will not be portable to another processes:
None of the above work because the address space of one process bares no resemblance to the address space of another processes (As it is mapped at the hardware level to physical memory).
#include <vector>
#include <iostream>
#include <string.h>
int func(int x)
{
return x+1;
}
typedef int (*FUNC)(int);
int main()
{
std::vector<char> buffer(5000);
::memcpy(&buffer[0],reinterpret_cast<char*>(&func),5000);
FUNC func = reinterpret_cast<FUNC>(&buffer[0]);
int result = (*func)(5);
std::cout << result << std::endl;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With