Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a process from memory within another process?

Tags:

c++

c

linux

memory

I would like to have a small "application loader" program that receives other binary application files over TCP from an external server and runs them.

I could do this by saving the transmitted file to the hard disk and using the system() call to run it. However, I am wondering if it would be possible to launch the new application from memory without it ever touching the hard drive.

The state of the loader application does not matter after loading a new application. I prefer to stick to C, but C++ solutions are welcome as well. I would also like to stick to standard Linux C functions and not use any external libraries, if possible.

like image 988
Flip Avatar asked May 09 '12 20:05

Flip


People also ask

Can a process read another process memory?

That processes can read/write memory of other processes of the same user is a fact.

Can processes share memory?

Processes don't share memory with other processes. Threads share memory with other threads of the same process.

How do I share data between processes?

To share big data: named shared-memory The fastest way to handle this is to create a file mapping object, map the file object into memory space, notify the parent process of the file mapping handle and data size, and then dump the data to the mapped buffer for the parent process to read.

Is heap shared between processes?

Every process can use heap memory to store and share data within the process.


1 Answers

Short answer: no.

Long answer: It's possible but rather tricky to do this without writing it out to disk. You can theoretically write your own elf loader that reads the binary, maps some memory, handles the dynamic linking as required, and then transfers control but that's an awful lot of work, that's hardly ever going to be worth the effort.

The next best solution is to write it to disk and call unlink ASAP. The disk doesn't even have to be "real" disk, it can be tmpfs or similar.

The alternative I've been using recently is to not pass complete compiled binaries around, but to pass LLVM bytecode instead, which can then be JIT'd/interpreted/saved as fit. This also has the advantage of making your application work in heterogeneous environments.

It may be tempting to try a combination of fmemopen, fileno and fexecve, but this won't work for two reasons:

  1. From fexecve() manpage:

    "The file descriptor fd must be opened read-only, and the caller must have permission to execute the file that it refers to"

    I.e. it needs to be a fd that refers to a file.

  2. From fmemopen() manpage:

    "There is no file descriptor associated with the file stream returned by these functions (i.e., fileno(3) will return an error if called on the returned stream)"

like image 66
Flexo Avatar answered Sep 22 '22 06:09

Flexo