Razvan
Razvan

Reputation: 2596

How can I load an external file/program in memory and then execute it (C++ and Unix)?

Let's say I have an executable file called "execfile". I want to read that file using a C++ program (on Unix) and then execute it from memory. I know this is possible on Windows but I was not able to find a solution for Unix.

In pseudo-code it would be something like this:

declare buffer (char *)
readfile "execfile" in buffer
execute buffer

Just to make it clear: obviously I could just execute the file using system("execfile"), but, as I said, this is not what I intend to do.

Thank you.

EDIT 1: To make it even more clear (and the reason why I can't use dlopen): the reason I need this functionality is because the executable files are going to be generated dynamically and so I cannot just build all of them at once in a single library. To be more precise I'm building a tool that will first encrypt an executable file with a key and then it will be able to execute that encrypted file, first decrypting it and then executing it (and I don't want to have a copy of the decrypted file on the file system).

Upvotes: 0

Views: 1018

Answers (2)

pwes
pwes

Reputation: 2040

The solution to load-and-run -- not necessarily in C++ -- is to use dlopen+dlsym to load dynamic library and obtain a pointer to function defined in the library.

See C++ dlopen mini HOWTO for description of solving problems with C++ symbols in dynamic libraries.

Upvotes: 0

bmargulies
bmargulies

Reputation: 99993

You cannot without writing a mountain of code. Loading and linking an a.out is a kernel facility, not a user mode facility, on linux.

You'd be better off making a shared library and loading it with dlopen.

Upvotes: 2

Related Questions