分段错误在内部如何工作(内核/硬件)? [英] How does a segmentation fault work internally (kernel/hardware)?

查看:20
本文介绍了分段错误在内部如何工作(内核/硬件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从广义上讲,我想知道内核(或 CPU)如何知道一个进程试图访问它没有权限的内存位置,以及称为 MMU 的神秘硬件如何帮助做到这一点.

Broadly speaking, I am wondering how the kernel (or the CPU) knows that a process has tried to access a memory location for which it lacks permission, and how the mysterious piece of hardware called MMU helps in doing that.

特别是:在我看来,MMU 对操作系统内核的内存管理模型(分页、内存区域、进程地址空间......)不可知(我认为 Linux 和 Windows 页面不完全是例如,相同.如果我错了,请纠正我).但是,我的 CPU 如何知道当前代码是否可以访问位置 x?它如何向内核发出信号?

In particular: It seems to me that the MMU is agnostic towards the memory management model of the OS kernel (paging, memory zones, process adress spaces...) (I would presume that Linux and Windows pages are not exactly the same, for example. Correct me if I'm wrong). But then, how does my CPU find out whether the current code may access location x? And how does it signal this to the kernel?

推荐答案

这可能是一个太大的话题,无法在这里完全满意地回答;您最好搜索一些讨论虚拟内存实现背后的硬件的论文/文章/书籍(可能从特定架构开始,因为 x86、x86_64、sparc 等之间存在显着差异......).

This is probably too big a topic to completely answer satisfactorily here; you'll do better to search for some papers/articles/books that discuss the hardware behind virtual memory implementations (probably starting with a specific architecture, since there are significant differences between e.g. x86, x86_64, sparc, etc...).

不过,简短的回答是硬件通过页表处理这个问题.要求 MMU 处理的每个内存访问都通过页表结构进行验证.如果描述包含被请求地址的页面的页表条目没有被标记为允许被请求的访问类型(读/写/执行/...),硬件会生成一个陷阱,Linux 最终将其称为分段错误".其他操作系统以不同的方式命名它们(例如一般保护故障,...).操作系统内核然后必须找出故障的原因以及是否可以对其采取任何措施(内核处理许多陷阱以从磁盘交换新页面,映射新的空页面等,但有些,例如空指针取消引用,内核能做的最好的事情就是把它扔给应用程序说你做了坏事").

The short answer, though, is that the hardware handles this through the page tables. Every memory access that the MMU is asked to handle is verified through the page table structures. If the page table entry describing the page containing the address being requested is not marked to allow the type of access being requested (read/write/execute/...), the hardware generates a trap that Linux eventually calls a "segmentation fault". Other OSes name them differently (e.g. general protection fault, ...). The OS kernel then has to figure out the reason for the fault and whether anything can be done about it (many traps are handled by the kernel to swap in new pages from disk, map a new empty page, etc., but some, like null-pointer dereferences, the best thing the kernel can do is throw it at the application to say "you did something bad").

这篇关于分段错误在内部如何工作(内核/硬件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆