是否可以在标准 C 中从堆栈中执行代码? [英] Is it possible to execute code from the stack in standard C?
问题描述
以下代码无法按预期工作,但希望能说明我的尝试:
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);
}
显然,sizeof(*foo)
不会返回 foo()
函数的代码大小.
Obviously, sizeof(*foo)
doesn't return the size of the code of the foo()
function.
我知道在某些 CPU 上执行堆栈受到限制(或者至少在设置了限制标志的情况下).除了 GCC 的嵌套函数最终可以存储在堆栈中之外,在标准 C 中是否有办法做到这一点?
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)
不是函数 foo
的大小,而是函数的大小指向 foo 的指针(通常与您平台上的所有其他指针大小相同).
sizeof(*foo)
isn’t the size of the function foo
, it’s the size of a pointer to foo (which will usually be the same size as every other pointer on your platform).
sizeof
无法测量函数的大小.原因是 sizeof
是静态运算符,函数的大小在编译时是未知的.
sizeof
can’t measure the size of a function. The reason is that sizeof
is 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.
您也许可以使用 alloca
和一些讨厌的 hack 来做一些可怕的事情,但简短的回答是 no,我认为您不能使用标准来做到这一点C.
You might be able to do something horrible using alloca
and 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.
这篇关于是否可以在标准 C 中从堆栈中执行代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!