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

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

问题描述

广义上讲,我想知道内核(或CPU)如何知道某个进程试图访问其未获得许可的内存位置,以及神秘的MMU硬件如何帮助实现这一点.

尤其是:在我看来,MMU对OS内核的内存管理模型(分页,内存区域,进程地址空间……)是不可知的(我想Linux和Windows页面并非完全相同).例如,如果错误,请纠正我).但是,然后我的CPU如何确定当前代码是否可以访问位置x?以及它如何向内核发出信号?

解决方案

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

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

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.

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?

解决方案

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...).

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天全站免登陆