Memory Layout and Linking (OS Core #6)
A process’s address space is not one flat blob. It is a set of mappings with different permissions, different backing stores, and different lifetimes. Once you can read the layout, questions like “why is this global zero?”, “why does the binary shrink when I move data around?”, and “why did the address change between runs?” answer themselves.
The address-space map
\begin{tikzpicture}[font=\rmfamily, >=stealth,
r/.style={draw, thick, minimum width=5.2cm, minimum height=0.52cm, font=\scriptsize}]
\node[r, fill=gray!12] (k) at (0,3.5) {kernel (upper half, user-inaccessible)};
\node[r, fill=green!18] (s) at (0,2.85) {stack \hfill rw-};
\node[r, fill=gray!5] (g) at (0,2.3) {guard page};
\node[r, fill=orange!15] (h) at (0,1.75) {heap \hfill rw-};
\node[r, fill=blue!10] (b) at (0,1.2) {.bss \hfill rw-};
\node[r, fill=blue!10] (d) at (0,0.65) {.data \hfill rw-};
\node[r, fill=blue!10] (rd) at (0,0.1) {.rodata \hfill r--};
\node[r, fill=blue!10] (t) at (0,-0.45) {.text \hfill r-x};
\node[font=\scriptsize, anchor=west] at (2.8,1.75) {mmap: shared libs, files};
\node[font=\scriptsize, anchor=west] at (2.8,2.85) {one per thread};
\end{tikzpicture}
The exact addresses differ per binary, architecture, and run, but the order is
stable: code at the bottom, then read-only data, then writable data, then the heap
growing up, then a large gap used for shared libraries and mmap, then the stack
growing down, then the kernel.
Each region has permissions. The MMU enforces them; a write to .text is a
segmentation fault, not a silent modification.
ASolution
So both can grow without colliding. The gap is virtual address space, not physical memory; it costs nothing until pages are mapped.
Text, rodata, initialized data, and BSS
The compiler sorts globals by how they are initialized.
#include <cstdio>
int g_init = 42; // .data: initialized, writable
int g_zero; // .bss: zero-initialized, writable
const int g_const = 7; // .rodata (usually): read-only
static int g_static; // .bss
int main() {
static int s_init = 5; // .data
int local = 1; // stack
int* heap = new int(2); // heap
const char* lit = "hi"; // pointer on stack, characters in .rodata
std::printf("text %p\n", (void*)main);
std::printf("data %p\n", (void*)&g_init);
std::printf("bss %p\n", (void*)&g_zero);
std::printf("rodata%p\n", (void*)lit);
std::printf("heap %p\n", (void*)heap);
std::printf("stack %p\n", (void*)&local);
delete heap;
}
| Segment | Contents | Permissions | Stored in file? |
|---|---|---|---|
.text |
machine code | r-x |
yes |
.rodata |
string literals, const globals |
r-- |
yes |
.data |
initialized globals/statics | rw- |
yes |
.bss |
zero-initialized globals/statics | rw- |
no (size only) |
| heap | new/malloc |
rw- |
no |
| stack | locals, frames | rw- |
no |
.data is the initialized data segment; .bss is the zeroed one. .bss is the
trick that saves disk space. A global array of 10 million zeroed ints
occupies 40 MB of address space, but the executable only records its size. The
kernel maps zero pages and allocates real frames only when the program writes.
size a.out prints the three file-backed sizes:
$ size a.out
text data bss dec hex filename
1420 552 40016 41988 a404 a.out
data is .data plus .rodata; bss is the zeroed part.
int big[10'000'000]; at file scope barely change theexecutable size?
ASolution
It goes into .bss, which is stored as a size, not as bytes. The kernel maps
zero pages and allocates them on first write.
Stack
The stack holds function frames: return address, saved registers, parameters,
locals. It grows downward on x86-64 and is usually limited to 8 MB per thread
(ulimit -s).
void f() {
int local[1000]; // 4 KB in this frame
f(); // no base case: stack overflow
}
A guard page sits below the stack. Touching it raises a fault, which the kernel
turns into SIGSEGV instead of silently corrupting other memory. The kernel grows
the stack mapping only for accesses close to the current stack pointer; a wild
pointer far below gets a segfault.
Stack frames are reused, so an uninitialized local contains whatever the previous call left behind. That is the source of many “why is this value garbage” bugs.
std::vector isfine?
ASolution
The array is allocated in the stack frame, which is limited to a few megabytes. The vector allocates on the heap and only stores a small header on the stack.
Heap
The heap is memory allocated at runtime. Two mechanisms on Linux:
brk/sbrk: move the program break, growing the main heap. Simple, but the heap must stay contiguous.mmap: map a new region for large allocations.mallocuses this above a threshold (128 KB by default in glibc) and for thread arenas.
void* p = std::malloc(64);
std::free(p);
int* q = new int[100]; // calls operator new, usually malloc
delete[] q;
malloc manages free blocks with headers and free lists. Fragmentation, alignment,
and per-thread arenas are its problem; the kernel only sees page-granularity
mappings.
ASolution
The allocator keeps freed blocks for reuse. The process’s RSS stays high until
the allocator decides to release whole arenas back with madvise/munmap.
Static and dynamic linking
Linking resolves symbols. Static linking copies library code into the executable; dynamic linking records a dependency and resolves it at load time.
g++ main.cpp util.cpp -o app # static link of your objects
g++ main.cpp -o app -static # static libc, if available
g++ -shared -fPIC util.cpp -o libutil.so # shared library
g++ main.cpp -L. -lutil -o app # link against it
ldd app # show dependencies
| Static | Dynamic | |
|---|---|---|
| Code in executable | yes | no (pointer to .so) |
| Executable size | larger | smaller |
| Startup | faster (no loader work) | loader maps libraries |
| Updates | relink required | replace the .so |
| Memory use | each process has its own copy | one copy shared by all processes |
| Failure mode | self-contained | missing library, ABI mismatch |
Static binaries are common in containers and recovery tools because they have no runtime dependencies. Dynamic linking is the default because it saves memory and lets a security patch fix every program at once.
run many times?
ASolution
The library’s code pages are mapped from the same file and shared by every process. Only the writable data is private.
Shared libraries
A shared library is an ELF file loaded by the dynamic linker (ld-linux.so). Key
details:
- SONAME: the library’s runtime name (
libfoo.so.1), recorded in the binary, so the loader can find the right major version. - Search path:
DT_RPATH,LD_LIBRARY_PATH,/etc/ld.so.cache, default directories. - PIC: shared libraries must be position-independent (
-fPIC), because they are mapped at an address chosen at load time. - PLT/GOT: calls to library functions go through a procedure linkage table and
a global offset table. The first call may resolve the symbol lazily (unless
LD_BIND_NOWor-Wl,-z,now). - ABI: name mangling, struct layout, exception handling, and standard library ABI must match. Mixing compilers can break at runtime.
readelf -d app | grep NEEDED # which libraries
objdump -d app | less # PLT stubs
LD_DEBUG=libs ./app # loader trace
ASolution
The SONAME includes the major version (libfoo.so.1 vs libfoo.so.2), and each
binary records the one it was built against. The loader keeps both mapped.
Address-space layout and ASLR
Without randomization, a non-PIE executable loads at a fixed address (often
0x400000 on x86-64 Linux), and libraries and the stack land at predictable
places. That makes exploitation easy: an attacker knows where to jump.
ASLR (address space layout randomization) randomizes the base of the executable
(if PIE), the heap, the mmap region, and the stack at each run. Linux exposes the
entropy through /proc/sys/kernel/randomize_va_space (0, 1, 2).
$ cat /proc/self/maps
55f3c1a2d000-55f3c1a2e000 r--p 00000000 08:01 1234567 /usr/bin/cat
7ffd9f3a2000-7ffd9f3c3000 rw-p 00000000 00:00 0 [stack]
Each run shows different numbers. PIE (position-independent executable) is the
default for modern distros; -no-pie produces the old fixed layout.
ASLR is not encryption. It raises the cost of an attack by making addresses unpredictable, but a leak of one address defeats it.
run?
ASolution
No. Within a run, addresses are fixed. ASLR changes the base at load time; it does not move objects afterwards.
Memory-mapped files
mmap maps a file’s contents into the address space. Reads and writes go through
the page cache, and the kernel handles the I/O on demand.
int fd = open("data.bin", O_RDWR);
void* p = mmap(nullptr, len, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
char* bytes = static_cast<char*>(p);
bytes[0] = 'x'; // writes the page cache; msync or munmap flushes
msync(p, len, MS_SYNC);
munmap(p, len);
close(fd);
| Flag | Meaning |
|---|---|
MAP_SHARED |
writes are visible to other mappings and the file |
MAP_PRIVATE |
copy-on-write; changes are not written back |
MAP_ANONYMOUS |
no file, zero-filled (used by malloc for large blocks) |
MAP_FIXED |
map at an exact address (dangerous) |
mmap avoids a copy between kernel and user buffers, which is why databases and
loaders use it. The cost is page faults on first touch and the need to handle
SIGBUS if the file is truncated underneath the mapping.
mmap slower than read?ASolution
For small, sequential, one-shot reads. read copies bytes directly; mmap pays
page-fault and TLB costs. For large or random access, mmap usually wins.
Memory protection
Protection is per-page and lives in the PTE:
- Read/write/execute bits, enforced by the MMU.
- User/supervisor bit, the kernel/user boundary.
- NX (no-execute): data pages cannot run code, which blocks classic stack-smashing attacks.
- W^X: a page should be writable or executable, not both.
mprotect(page, 4096, PROT_READ); // make read-only
mprotect(page, 4096, PROT_NONE); // guard page
The kernel uses protection for COW (shared pages are read-only until written) and for guard pages. User programs use it for JITs (switch between write and execute), sandboxes, and debuggers.
page?
ASolution
W^X policies forbid pages that are both writable and executable. The JIT writes
to a read/write page, then calls mprotect to make it executable (and often
clears the write permission).
Bugs and edge cases
- Writing past the end of
.bssor.data. Corrupts adjacent globals;-fstack-protectordoes not help for globals. - Assuming zeroed heap.
mallocreturns uninitialized memory. - Returning pointers to locals. The frame is reused after return.
mmaplength not page-aligned. The kernel rounds up; touching the rounded part of a file mapping can raiseSIGBUS.- Leaked mappings. Every
mmapneeds amunmap;/proc/self/mapsgrows. - ASLR expectations in tests. Address comparisons differ between runs; do not assert on them.
- Static linking with
getpwnam. Name-service libraries may not work without dynamic NSS modules. - Mixing
-fPICand non-PIC. Relocation errors at link time. - Assuming
.rodatais a specific address. PIE and ASLR move it.
object file” from a different directory. Why?
ASolution
The dynamic loader cannot find a library. The binary records a SONAME, not a full
path (unless RPATH is set), so the search path matters: LD_LIBRARY_PATH,
ld.so.cache, or an RPATH/$ORIGIN entry.
Next: File Systems and I/O (OS Core #7) — inodes, descriptors, caches, and journaling.