Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use function pointers across processes?

Tags:

c++

boost

ipc

I'm aware that each process creates it's own memory address space, however I was wondering,

If Process A was to have a function like :

int DoStuff() { return 1; }

and a pointer typedef like :

typedef int(DoStuff_f*)();

and a getter function like :

DoStuff_f * getDoStuff() { return DoStuff; }

and a magical way to communicate with Process B via... say boost::interprocess

would it be possible to pass the function pointer to process B and call

Process A's DoStuff from Process B directly?

like image 416
Maciek Avatar asked Oct 13 '09 17:10

Maciek


2 Answers

No. All a function pointer is is an address in your process's address space. It has no intrinsic marker that is unique to different processes. So, even if your function pointer just happened to still be valid once you've moved it over to B, it would call that function on behalf of process B.

For example, if you had

////PROCESS A////
int processA_myfun() { return 3; }
// get a pointer to pA_mf and pass it to process B

////PROCESS B////
int processB_myfun() { return 4; } // This happens to be at the same virtual address as pA_myfun
// get address from process A
int x = call_myfun(); // call via the pointer
x == 4;  // x is 4, because we called process B's version!

If process A and B are running the same code, you might end up with identical functions at identical addresses - but you'll still be working with B's data structures and global memory! So the short answer is, no, this is not how you want to do this!

Also, security measures such as address space layout randomization could prevent these sort of "tricks" from ever working.

You're confusing IPC and RPC. IPC is for communicating data, such as your objects or a blob of text. RPC is for causing code to be executed in a remote process.

like image 55
Steven Schlansker Avatar answered Oct 08 '22 01:10

Steven Schlansker


In short, you cannot use function pointer that passed to another process.

Codes of function are located in protected pages of memory, you cannot write to them. And each process has isolated virtual address space, so address of function is not valid in another process. In Windows you could use technique described in this article to inject your code in another process, but latest version of Windows rejects it.

Instead of passing function pointer, you should consider creating a library which will be used in both processes. In this case you could send message to another process when you need to call that function.

like image 33
Kirill V. Lyadvinsky Avatar answered Oct 08 '22 03:10

Kirill V. Lyadvinsky