Part 3 of 6 · 2 min read
Protection
In plain words: With paging, each page has its own permission bits (page 3): read, write, execute, and a user/supervisor bit. The hardware checks them on every access, in the same step as the translation. The kernel sets them when it maps memory, in line with the regions of the process:
| Region | Permissions | Why |
|---|---|---|
| Code | read, execute | A program must not change its own instructions by mistake |
| Read-only data | read | Constants stay constant |
| Data, heap, stack | read, write (not execute) | Prevents running injected data as code |
| Guard page | none | A trap that catches an overflow |
| Kernel memory | not user-accessible | Protects the kernel from every process |
The check can fail in several ways: writing a read-only page, reading a page that has no permission, running code from a no-execute page, or using an address with no mapping at all. In each case the hardware raises a trap, and the kernel sends the process the signal SIGSEGV. By default this ends the process, with the message "Segmentation fault". The name comes from the age of segmentation, and it stuck.
A test makes it concrete. A program maps one page, writes to it, and then calls mprotect to make it read-only. A write after that is trapped, and a handler for SIGSEGV reports it:
char *p = mmap(0, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
p[0] = 1; /* allowed */
mprotect(p, 4096, PROT_READ); /* the page is now read-only */
p[0] = 3; /* trap */
The output was SIGSEGV: write to a read-only page, printed by the handler. Without a handler, the process would have been killed at the last line. The hardware, not the compiler, made the decision, at the moment of the write.
The same machinery gives a guard page: the kernel leaves a page with no permissions between the stack and other memory, so a stack that grows too far hits the guard and traps at once, and not silently over other data (Level 7). Also, because the stack and heap are not executable, an attack that writes machine code into a buffer cannot run it directly.
Segmentation fault
A segmentation fault is the error that occurs when a program accesses memory in a way the page table does not allow, for example by writing a read-only page or using an unmapped address; the kernel delivers the signal SIGSEGV, which by default ends the process.
Example: writing to a page after mprotect(p, 4096, PROT_READ) caused SIGSEGV at the write.
Check yourself:
1. Which permission bits does the code region of a process have, and why?
2. Name three kinds of access that cause SIGSEGV.
3. What does a guard page protect against?