检测堆栈溢出
操作系统如何检测用户空间程序的堆栈溢出[然后将 SIGTERM 或 SIGSEGV 发送到这些用户空间程序]?
How do operating systems detect stack overflows of user-space programs [and then send SIGTERM or SIGSEGV to those userspace programs] ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
防护页。当操作系统为程序创建堆栈时,它将分配比指定的多一点的空间。内存按页分配(通常每页 4KB),并且额外的页将进行设置,以便任何访问它的尝试都将导致抛出异常。
Guard pages. When the OS creates the stack for the program it will allocate a little bit more than is specified. The memory is allocated in pages (usually 4KB each), and the extra page will have settings such that any attempt to access it will result in an exception being thrown.
答案将取决于目标架构和特定操作系统。由于问题被标记为Linux,因此您对这个问题有相当的偏见,从表面上看,这个问题似乎更普遍。
在复杂的操作系统或 RTOS(例如 Linux 或 QNX Neutrino)中,具有 MMU 保护支持,可以使用内存保护机制,例如已经提到的保护页。当然,此类操作系统需要带有 MMU 的目标。
没有 MMU 支持的更简单的操作系统和典型的 RTOS 调度内核可以使用多种方法。最简单的方法是在堆栈顶部放置一个保护签名,在调度程序运行时检查其是否有修改。这有点偶然,它要求堆栈溢出实际修改签名,并且所产生的损坏不会在调度程序下次运行之前导致崩溃。一些具有片上调试资源的系统可能能够在签名字上放置访问断点,并在命中时引发异常。
在开发过程中,一种常见的技术是首先用签名填充每个线程堆栈,并让线程定期检查“高潮”,并在超过一定百分比水平时发出警告。
The answer will depend on the target architecture and the particular OS. Since the question is tagged Linux, you have rather biased the question which on the face of it seems more general.
In a sophisticated OS or RTOS such as Linux or QNX Neutrino, with MMU protection support, memory protection mechanisms may be used such as the guard pages already mentioned. Such OSs require a target with an MMU of course.
Simpler OSs and typical RTOS scheduling kernels without MMU support may use a number of methods. The simplest is to place a guard signature at the top of the stack, which is checked for modification when the scheduler runs. This is a bit hit-and-miss, it requires that the stack-overflow actually modifies the signature, and that the resulting corruption does not cause a crash before the scheduler next runs. Some systems with on-chip debug resources may be able to place an access break-point on the signature word and cause an exception when it is hit.
In development a common technique is to initially fill each thread stack with a signature and to have a thread periodically check for the "high-tide" and issue a warning if it exceeds a certain percentage level.
除了另一个答案中提到的保护页之外,一些较小的(无 MMU)嵌入式微控制器对于堆栈溢出(和下溢)也有特定的例外情况。
As well as guard pages mentioned in another answer, some smaller (MMU-less) embedded microcontrollers have specific exceptions for stack overflow (and underflow).