Part 5 of 7 · 2 min read
Memory map
In plain words: The kernel keeps a list of the memory regions of every process, and /proc/PID/maps (see Level 0) displays it. Each line shows an address range, the permissions, and what the region holds. This program prints its own map, keeping only the interesting lines:
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *f = fopen("/proc/self/maps", "r");
char line[256];
while (fgets(line, sizeof line, f)) {
if (strstr(line, "[heap]") || strstr(line, "[stack]") || strstr(line, "m2"))
fputs(line, stdout);
}
fclose(f);
return 0;
}
On the test machine (the program file was called m2; paths shortened here):
5627ec6d1000-5627ec6d2000 r--p ... m2
5627ec6d2000-5627ec6d3000 r-xp ... m2
5627ec6d3000-5627ec6d4000 r--p ... m2
5627ec6d4000-5627ec6d5000 r--p ... m2
5627ec6d5000-5627ec6d6000 rw-p ... m2
562807f6a000-562807f8b000 rw-p ... [heap]
7ffcff630000-7ffcff655000 rw-p ... [stack]
The permission letters mean read (r), write (w) and execute (x). The line with r-xp is the text: it may be read and run but not changed. The line with rw-p right after the program's own lines is the data and BSS: it may be read and written but not run. The [heap] and [stack] lines are readable and writable. Each region is a multiple of 4,096 bytes, the size of a memory page (Level 6). For example, the stack region is 0x7ffcff655000 − 0x7ffcff630000 = 0x25000 = 151,552 bytes, which is 37 pages of 4,096 bytes.
Separating the permissions is a protection (Level 0, page 2). A program that tries to write into its text, or to run code from its stack, is stopped by the hardware, and the kernel ends it with a segmentation fault.
Check yourself:
1. What do the letters r-xp mean?
2. Why is the text region not writable?
3. How many pages are in a region of 0x25000 bytes, if a page is 4,096 bytes?