The following code doesn’t work as intended but hopefully illustrates my attempt:
long foo (int a, int b) {
return a + b;
}
void call_foo_from_stack (void) {
/* reserve space on the stack to store foo's code */
char code[sizeof(*foo)];
/* have a pointer to the beginning of the code */
long (*fooptr)(int, int) = (long (*)(int, int)) code;
/* copy foo's code to the stack */
memcpy(code, foo, sizeof(*foo));
/* execute foo from the stack */
fooptr(3, 5);
}
Obviously, sizeof(*foo) doesn’t return the size of the code of the foo() function.
I am aware that executing the stack is restricted on some CPUs (or at least if a restriction flag is set). Apart from GCC’s nested functions that can eventually be stored on the stack, is there a way to do that in standard C?
sizeof(*foo)isn’t the size of the functionfoo, it’s the size of a pointer to foo (which will usually be the same size as every other pointer on your platform).sizeofcan’t measure the size of a function. The reason is thatsizeofis a static operator, and the size of a function is not known at compile time.Since the size of a function is not known at compile time, that also means that you can’t define a statically-size array that is large enough to contain a function.
You might be able to do something horrible using
allocaand some nasty hacks, but the short answer is no, I don’t think you can do this with standard C.It should also be noted that the stack is not executable on modern, secure operating systems. In some cases you might be able to make it executable, but that is a very bad idea that will leave your program wide open to stack smashing attacks and horrible bugs.