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?
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..
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 09:07 PM.|