How can i execute something from memory?

I want to embed an executable program in my app.
My question is whether I can run this app directly from memory without writing it to the disk and going through spawn?

So you have a chunk of memory which contains instructions in binary?

Just jump to it:

let func_addr = 0x8000;
let func: fn() = unsafe { std::mem::transmute(func_addr) };
func();

Needless to say, this is highly dangerous, but that's what the unsafe is for :wink:

4 Likes

How about the command line arguments and stuff they arent exactly function arguments i believe

Oh, I see.
It's possible the easiest to extract it to the filesystem and then let the OS handle it.
I'm not entirely sure if you can load an ELF from memory. I highly doubt that :confused:

I see thanks for the answer

Isn't this likely to be complicated if the memory in question has been flagged as non-executable by the OS? How would you prevent this happening?

Well, it's... complicated.

TBH: The solution I gave is mainly focus on embedded devices, e.g. an updater which is loaded via UART and then jumped to.
If you have an OS, let the OS handle it.
There's a reason why execve and friends only take paths to files, and not some memory chunks.

-<| Quoting Nikos Efthias via The Rust Programming Language Forum rust_lang+8eefbc752ac1c987ab7c384776f384b0@discoursemail.com, on Friday, 2019-10-18 08:25:10 AM |>-

I want to embed an executable program in my app.
My question is whether I can run this app directly from memory without writing it to the disk and going through spawn?

The libc crate has definitions for fexecve(2),
shm_open(2), andSYS_memfd_create (no wrapper). So the
primitives are there. You may have to copy the file though.