I've been working on a (C++) project, which requires completely dynamically allocated functions, which means malloc/new and mprotect and then modify the buffer manually to assembly code. Because of this I've wondered exactly, what is required in this "buffer" of mine, for it to be a replicate of any other _cdecl function. For example:
int ImAcDeclFunc(int a, int b)
{
return a + b;
}
If I would like to literally create a duplicate of this function, but completely dynamically, what would that require (and remember it's C++ with inline assembly)? For starters, I guess I would have to do something like this (or a similiar solution):
// My main....
byte * ImAcDeclFunc = new byte[memory];
mprotect(Align(ImAcDeclFunc), pageSize, PROT_EXEC | PROT_READ | PROT_WRITE);
After this I would have to find out the assembly code for the ImAcDeclFunc(int a, int b);
. Now I'm still lousy at assembly, so how would this function be in AT&T syntax? Here's my bold attempt:
push %ebp
movl %%ebp, %%esp
movl 8(%ebp), %%eax
movl 12(%ebp), %%edx
addl edx, eax
pop ebp
ret
Now if this code is correct (which I highly doubt, please correct me) would I only need to find this code's value in hex (for example, 'jmp' is 0xE9 and 'inc' is 0xFE), and use these values directly in C++? If I continue my previous C++ code:
*ImAcDeclFunc = 'hex value for push'; // This is 'push' from the first line
*(uint)(ImAcDeclFunc + 1) = 'address to push'; // This is %ebp from the first line
*(ImAcDeclFunc + 5) = 'hex value for movl' // This is movl from the second line
// and so on...
After I've done this for the whole code/buffer, would that be enough for a completely dynamic _cdecl function (i.e could I just cast it to a function pointer and do int result = ((int (*)(int, int))ImAcDeclFunc)(firstArg, secondArg)
?).
And I'm not interested in using boost::function or something similiar, I need the function to be completely dynamic, therefore my interest :)
NOTE: This question is a continuation on my previous one, but with far more specifics.