Hasty Briefsbeta

Bilingual

A Friendly Tour of Process Memory on Linux

6 months ago
  • #linux
  • #kernel
  • #memory-management
  • Linux creates an illusion of continuous memory for processes by managing memory in pages, not as a single block.
  • Process memory is managed through virtual memory areas (VMAs), which are contiguous ranges with specific permissions and backing sources.
  • Memory mappings can be changed using `mmap`, `mprotect`, and `munmap`, with actual memory allocation happening on first access (lazy allocation).
  • Page faults occur when accessing unmapped memory, triggering the kernel to allocate or load the required pages.
  • Copy-on-write (CoW) is used during `fork()` and with `MAP_PRIVATE` mappings to share memory until modifications are made.
  • Transparent Huge Pages (THP) improve performance by using larger pages (e.g., 2 MiB) to reduce TLB pressure.
  • The kernel defends against Meltdown using Page Table Isolation (PTI), which separates user and kernel page tables.
  • Tools like `/proc/<pid>/maps` and `/proc/<pid>/smaps` provide insights into process memory usage and mappings.
  • Memory permissions (e.g., W^X) and TLB invalidations can introduce small delays, especially during `mprotect` calls.
  • Common issues include misaligned mappings (`EINVAL`), out-of-memory errors (`ENOMEM`), and `SIGBUS` when accessing beyond file boundaries.