Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to load a function into some allocated memory and run it from there?

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.

like image 895
Nick Strupat Avatar asked Dec 22 '22 00:12

Nick Strupat


1 Answers

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:

  • Call a function or method.
  • Pass a pointer (or reference)
    • No object that contains a pointer or a reference will work either.
  • Use globals.
  • You could pass a method pointer:
    • But object it is used on must be passed by value.

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).

Silly Example

#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;

}
like image 119
Martin York Avatar answered Dec 27 '22 21:12

Martin York