Posix 中的后卫尺寸是多少?

What is guard size in Posix?

这个问题的灵感来自 pthread API 中的 pthread_attr_setguardsizepthread_attr_getguardsize 方法。可以在 here.

中找到该方法的文档

在这些方法的文档中,我找到的最接近实际保护大小的解释是:

The guardsize attribute controls the size of the guard area for the created thread's stack. The guardsize attribute provides protection against overflow of the stack pointer. If a thread's stack is created with guard protection, the implementation allocates extra memory at the overflow end of the stack as a buffer against stack overflow of the stack pointer. If an application overflows into this buffer an error shall result (possibly in a SIGSEGV signal being delivered to the thread).

我相信这对某些人来说非常有意义,但我还是有点迷茫。

我理解守卫是栈尾的溢出缓冲区,是为了防止栈溢出而设计的。但是我还有两个问题:

  1. 为什么有一个特殊的溢出缓冲区比简单地使用更大的堆栈更可取?
  2. 如果溢出守卫仍然向线程发送错误,那么拥有溢出缓冲区的意义何在?

我确信有一些简短的、概念性的东西可以回答这两个问题,我希望这里有人能够提供它。感谢大家!

P.S。我终于可以用 "stack-overflow".

标记问题了,这也非常有趣

下一个问题是线程的栈之后是什么。

可以是任何东西。它可能是另一个线程的栈顶,堆的一部分。一些内存映射文件等

如果没有保护内存,线程可能会溢出其堆栈到该区域,如果该内存是可写的,则没有什么可以阻止线程覆盖该内存而不生成任何 error/trap/signal。

您可以分配更大的堆栈。但多大才足够大?如果分配太大,则意味着用于其他任何东西的可用内存更少(尤其是在内存 space 非常有限的 32 位系统上)

保护区试图解决这个问题。该区域将被标记为不可写,因此如果有人试图写入该区域(即线程溢出其堆栈),内核将在硬件协助下得到通知,向进程发送信号并(默认情况下)终止它。

与让线程无声地破坏不应该破坏内存的风险相比,终止进程通常更好。