How does a segmentation fault work internally (kernel/hardware)?

后端 未结 2 1364
迷失自我
迷失自我 2020-12-24 08:31

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

2条回答
  •  感动是毒
    2020-12-24 08:55

    The MMU is configured (by design of its logic and/or option bits set by the kernel) to be the hardware part of the implementation of the paging model.

    The MMU must ordinarily translate logical addresses to the mapped physical addresses; when it cannot do so because there is no corresponding physical address for the requested logical address, it generates a fault (often as a type of interrupt) which runs handler code in the kernel.

    If the fault was an attempt to request something that theoretically exists - say part of a mapped file - but in not currently present in physical ram, the operating system's virtual memory implementation can solve the problem by allocating some physical ram and copying the appropriate disk blocks into it.

    However, if it is a request for something that does not exist, it cannot be satisfied and will have to be handled as a program fault.

    A request to write to something where writing is not allowed would be handled in a similar manner.

    Off the top of my head, I'm not sure if attempts to execute non-executable information are detected in the MMU or more in the CPU itself; how an instruction cache if present fits into that could also complicate things. However, the end result would be similar - a fault condition to the kernel that an illegal execution attempt has occurred, which the kernel would typically treat as a program fault.

    In summary, the model is that the simpler hardware layers tell the kernel that something unusual has happened, which the hardware cannot deal with by itself using its current configuration. The operating system then decides if what was attempted can and should occur - if so it updates the hardware configuration to make this possible. Or if what was attempted should not be permitted, a program fault is declared. And there are additional possibilities too, for example, a virtualization layer could decide to emulate the requested operation rather than literally performing it, preserving some isolation from the hardware.

提交回复
热议问题