Raj
Raj

Reputation: 31

how to execute a piece of code from a malloc'ed region

I am trying to malloc some heap space (size of the file bytes) and copy the contents of a binary file into the allocated memory. Once the binary is copied, I would like to execute that piece of code.

So as a part of this, I tried to write some assembly code to jump to that location(virt address returned from malloc). I am facing a seg fault, I am not sure is this the correct way to do it??

can someone help me in this scenario?

any help/pointers is appreciated! P.S: I don't want to do exec calls to run those binaries.

Upvotes: 0

Views: 1507

Answers (2)

Peter Cordes
Peter Cordes

Reputation: 364408

If you're trying to JIT-compile something, search for / ask about that directly. It's a common enough thing to want to do that you don't need to implement the mmap / memory protection yourself.

Even if the file you loaded did start with machine code, rather than ELF headers, you'd still segfault because malloc()ed memory is not marked as executable, as an extra layer of defence against bugs turning into security exploits. You'd have to mprotect the memory, as Nominal Animal says in comments.

If this isn't for JIT-compiling, but rather runtime loading of modules / libraries, then you can use dlopen / dlsym to load a library and get a function pointer to a function it contains. This should be much easier than implementing it yourself.

Upvotes: 1

Chris Beck
Chris Beck

Reputation: 16204

The only way I can think to do anything like this is described in this answer: https://stackoverflow.com/a/5602143/3598119

I think you can't simply load a binary into memory and then hope to run it. First of all it has some kind of header to find dynamic libraries in it (in linux this is ELF, in other platforms it's different), and you need to process that yourself (hard, you need to duplicate DLL lookup in your application!) or expect it to crash.

If you want to run external binaries, either use exec or some related OS function, or make them DLL's and link with them dynamically, load their symbols and call them. (Or compile them to assembly by hand and hard code them into executable and cast them as function pointers and call them, and get fired :p )

Upvotes: 2

Related Questions