LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Execute code from memory? (https://www.linuxquestions.org/questions/programming-9/execute-code-from-memory-419553/)

thedevilsjester 02-25-2006 06:11 PM

Execute code from memory?
 
Is there any way that I can take an executable, fread() it into a byte array, and have it executed purely from memory? Would any of the exec*() functions have a way of doing this?

(Linux)

aluser 02-25-2006 06:38 PM

Yes it can be done, but it's rough.

I've done it with the following conditions:

* The read executable was staticly linked.
* The read executable was linked into addresses which weren't used by the executable which loaded it. (You can do this by tweaking the linker script; my default one is /usr/lib/ldscripts/elf_i386.x and you use the -T argument to ld to use a different one.)

You can man 5 elf to read about the format of an executable. The important points are that an executable is a series of sections, each of which has an offset and length in the file, and an address and length in memory. Your job is to load it there.

To begin execution of the thing you read in, see the e_entry field in the elf format and the getcontext()/setcontext() libc functions.


You could roll dynamic linking yourself somehow, but it probably wouldn't be fun.

----

The "normal" way to do this sort of thing is to have the code you were going to read into memory be a shared library instead, and use dlopen() on it.

If you've got more questions, ask away..

aluser 02-25-2006 06:39 PM

oh yeah, you'll have to use mmap to get memory allocated where you want it


All times are GMT -5. The time now is 08:22 AM.