Run function defined as variable
I have a program written in C, which includes 2 functions, one function is main()
and the other function is a pre-compiled function which stored as byte array (let's call it varFunc()
). The pointer to the array is casted in the main
function to a function pointer and then it is called from the main
function. (see code below)
Now, I know that there are operating systems and some processors that won't allow executing code from data section, and my varFunc
should be just there...
Is there a way using C language to make C compiler to add some variables to code/text section? if not, is there a way to enforce that by compiler in most compilers?
char varFuncArr[] = { 0xDE, 0x67, 0x6F, 0x6F, 0xAC, 0x13, 0x05, 0x01, 0xDA, 0xF0, 0xBD, 0x79, 0xA9, 0x10, 0x00, 0x00, 0xB8, 0x74, 0x00, 0x00, 0x00, 0x3F, 0x58, 0x13, 0xEA, 0x0A, 0x2E, 0xEE, 0xC7, 0x01, 0x05, 0xD0, 0x6E, 0xB8, 0x9E};
typedef unsigned long (*funcPtr)(void* d[]);
int main(int argc, char** argv)
{
unsigned int ra[8];
funcPtr varFunc;
for (i=0; i<8; i++)
ra[i] = 0;
varFunc = (funcPtr)varFuncArr;
return varFunc(ra);
}
Note 1: I know that this is a very clumsy way to call a function and it also make it super platform and compiler, but I show this example to make it simpler, actual use include an encrypted function instead of varFuncArr()
.
开发者_如何学运维Note 2: Don't try to run this code, varFuncArr is encrypted in this example :)
Thanks, Binyamin
On GCC, you can use __attribute__((section("text")))
to put something in a particular section; see here for documentation. Visual C++ has __declspec(allocate("section"))
; see here for documentation.
Alternatively to Jeremiah Willcock's suggestion of using compiler attributes, you could mmap
a bit of memory and request execute permission on it, then copy your data there before calling it.
You'll trade platform portability (Posix/Windows) for compiler portability (gcc/...), as it does not depend on a specific compiler, but instead on a standard Posix function.
精彩评论