I was looking how call and malloc works, and was wondering what if I wanted to malloc space to inject code and run it, how would I go about it? Thanks.
Asked
Active
Viewed 152 times
-1
-
1Wrong question. :) a better one would be: _how do I allocate memory for storing or generating code to?_ - don't use `malloc`, use `mmap`. Although, it depends on your OS as to what will be possible. Also, what parts are problematic for you? Have you _tried_ using `malloc` for this? – davmac Oct 09 '18 at 12:56
-
1My answer on [The repetitive byte counter](https://codegolf.stackexchange.com/a/160236) on codegolf has a complete working example that stores x86 machine code into a `malloc`ed buffer (which is executable because I compiled with `gcc -z execstack` (which affects `.data` and the heap as well), and uses `__builtin___clear_cache` to get gcc not to optimize away the stores. – Peter Cordes Oct 09 '18 at 13:31
1 Answers
-1
To put it simple. Really hard, and you should not do it. The malloc
function allocates space on the heap. Which is marked "Unexecutable" by some Linux distributions. So in that case this would be impossible. The whole idea of the stack is to store data. Not to store instructions. Even if you want to execute program in a malloc space, it would require quite some hacks that moves them into executable memory. So my suggestion is don't do it.

Codetector
- 694
- 6
- 16
-
2_"The malloc function allocates space on the stack."_ You mean the _heap_ (?) – Michael Oct 09 '18 at 12:15
-
-
Yes, it requires system-specific functions / system calls. That's what this question is asking for. – Peter Cordes Oct 09 '18 at 13:32