是否有可能从标准C堆栈执行code

是否有可能从标准C堆栈执行code

本文介绍了是否有可能从标准C堆栈执行code?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下code不工作打算,但希望我的说明尝试:

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的code()的大小功能。

我知道在执行堆栈上某些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(*富)不是该函数的大小,它的尺寸的指针以富(通常将是大小的平台上的所有其他指针一样)。

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 和一些讨厌的黑客,但简单的答案是,我不认为做一些可怕你可以用标准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堆栈执行code?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 09:18