This is going to sound super hackish but does anyone know of a way to combine method bodies at runtime in C++? I’m currently on the path of grabbing the address of the functions then memcopy to executable memory but it has the problem of unwanted prolog/epilog.
Essentially I’ve got a few dozen simple operations that take the same arguments and return nothing and i want to build a function at runtime out of these simple operations.
I can’t see any practical use for this, except for the heck of it 🙂
So first you should decide for a platform.
There is no way in hell you can do this in a cross-platform way.
It might actually be quite difficult to do it in a way that works across several compilers, even on the same platform.
Then the processor type, of course 🙂
Then you should somehow check that the code you are copying can be relocated. Not everything can be moved around as you feel like.
You have to understand very well the calling conventions, so that you make sure you don’t mess up the stack.
Know how the prolog/epilog generated by your compiler. You can probably cheat by adding at the beginning and end of the functions some code sequences that does nothing, but you can use as signature then look for (ie. nop; nop; nop; xor ax, ax; nop; push ax; pop ax; nop; nop; nop; ). Make sure is not optimized-out by the compiler 🙂
Make sure you can write/execute that code. The modern CPUs and OSes don’t normally allow one to write in a code segment, or to execute a non-code segment. So you will have to find out what are the ways to change the rights (100% OS specific).
Then have fun fighting stuff like “Address space layout randomization,” “Stack Randomization,” “Data Execution Prevention,” “Heap Randomization.”
Anyway, a lot of work. And pointless, except to enjoy a good challenge and in the process learn some assembly and OS internals.
Or for proving yourself as “1337,” but then, asking on stackoverflow how to do it is not quite “1337,” if you ask me 🙂
Anyway, good luck.