Programming Search⌘K

Conceptcore

Memory layout of a process

Also called memory layout of a program, memory segments, text segment, data segment, bss segment, address space layout.

A running process sees its memory as regions: code, data, bss, heap, stack and mapped files. Each region has its own use and its own permissions.

Applies to
core-languages

Idea

A running program does not see one flat block of memory. Its address space is split into regions, and each region holds one kind of thing: the machine code, the global variables, the heap, the call stack, and files and libraries mapped into memory. Each region has its own permissions, so the code can be run but not written, and the data can be written but not run. On Linux, a program can list its own regions in the file /proc/self/maps.

def regions():
    """Yield (start, perms, path) for each region in /proc/self/maps."""
    with open("/proc/self/maps") as f:
        for line in f:
            fields = line.split(maxsplit=5)
            start = int(fields[0].split("-")[0], 16)
            path = fields[5].strip() if len(fields) > 5 else ""
            yield start, fields[1], path


found = {}
for start, perms, path in regions():
    if path in ("[heap]", "[stack]", "[vdso]") and path not in found:
        found[path] = start
        print(path, perms)

print("the heap is below the stack:", str(found["[heap]"] < found["[stack]"]).lower())
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true

The heap and the stack can be read and written (rw) but not run. The [vdso] region is "The virtual dynamically linked shared object"1, and it can be run (x) but not written. The heap is at a lower address than the stack. The addresses themselves change from run to run, so the program prints only the order.

How it works

Code. The code segment, "also known as a text segment or simply as text", is the part of the address space "that contains executable instructions"2. "The code segment in memory is typically read-only and has a fixed size"2.

Data and read-only data. The data segment "contains initialized static variables, that is, global variables and static local variables"3. "The data segment is read/write"3. Constants go in a separate read-only data segment, .rodata, "which contains static constants rather than variables"3.

BSS. Static variables with no initial value go in the bss segment. "Typically only the length of the bss section, but no data, is stored in the object file"4. The ELF format says that .bss "holds uninitialized data that contributes to the program's memory image. By definition, the system initializes the data with zeros when the program begins to run"5.

Heap. "The heap segment contains dynamically allocated memory, commonly begins at the end of the BSS segment and grows to larger addresses from there"3. The end of this region is the program break: brk and sbrk "change the location of the program break, which defines the end of the process's data segment"6. A program rarely calls them itself. "Normally, malloc() allocates memory from the heap, and adjusts the size of the heap as required, using sbrk(2)"7.

Stack. "The stack segment contains the call stack, a LIFO structure, typically located in the higher parts of memory"3. "On the standard PC x86 architecture the stack grows toward address zero"3, so a deeper call has a lower address. "The stack segment traditionally adjoined the heap segment and they grew towards each other"3. With virtual memory, the two regions "tend to be placed more freely, but they still typically grow in a converging direction"3.

Mapped regions. Not all memory comes from the heap. mmap makes a mapping "in the virtual address space of the calling process"8. A mapping can show a file in memory: a memory-mapped file "has been assigned a direct byte-for-byte correspondence with some portion of a file or file-like resource"9. The example in the maps man page shows the C library file, libc-2.15.so, mapped in this way1. An anonymous mapping "is not backed by any file; its contents are initialized to zero"8. The C library uses anonymous mappings for large blocks: "When allocating blocks of memory larger than MMAP_THRESHOLD bytes, the glibc malloc() implementation allocates the memory as a private anonymous mapping using mmap(2)"7.

How to see it. On Linux, /proc/pid/maps lists the "mapped memory regions and their access permissions"1. Each line has an address range, the permissions, an offset, a device, an inode and a path1. The permissions are "r = read w = write x = execute s = shared p = private (copy on write)"1. Some paths are names, not files: [stack] is "The initial process's (also known as the main thread's) stack", and [heap] is "The process's heap"1. "If the pathname field is blank, this is an anonymous mapping as obtained via mmap(2)"1. An inode of 0 means that no file is behind the region, "as would be the case with BSS (uninitialized data)"1.

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaNative
CNative
C#Native
JavaScriptNative
TypeScriptNative
GoNative
RustNative
KotlinNativeKotlin on the JVM runs in a process with the same regions as Java, and it can read /proc/self/maps as a file. No example file exists because kotlinc is not installed.
SQLDoes not applyA query does not see memory.
BashNative
PowerShellNativePowerShell runs on .NET in a process with the same regions, and Get-Content can read /proc/self/maps. No example file exists because pwsh is not installed.
HTMLDoes not applyA document does not see memory.
CSSDoes not applyA style sheet does not see memory.
Regular expressionsDoes not applyA regular expression does not see memory.
Language Verdict What the program can see of the layout
Python native no addresses; the program can read /proc/self/maps as a file
JavaScript native no addresses; Node.js can read /proc/self/maps as a file
TypeScript native as in JavaScript
Java native no addresses; the program can read /proc/self/maps as a file
Kotlin native as in Java
C# native unsafe code can take the address of a local or a field
Go native unsafe.Pointer turns a pointer into an address
Rust native a reference converts to a raw pointer and then to an address
C native & gives the address of a function, a global or a local
C++ native as in C
Bash native /proc/$$/maps lists the regions of the shell
PowerShell native runs on .NET, in a process with the same regions
SQL n/a a query does not see memory
Regex n/a a pattern does not see memory
HTML n/a a document does not see memory
CSS n/a a style sheet does not see memory

The example files read /proc/self/maps in each language. Python, JavaScript, TypeScript, Java, C# and Bash print the heap, stack and vdso regions. C, C++ and Rust also find the region of a function, a global, a local, a small heap block and a large heap block. Go does the same, but its heap and its goroutine stacks are in anonymous mappings, not in [heap] and [stack].

PythonGitHub
def regions():
    """Yield (start, perms, path) for each region in /proc/self/maps."""
    with open("/proc/self/maps") as f:
        for line in f:
            fields = line.split(maxsplit=5)
            start = int(fields[0].split("-")[0], 16)
            path = fields[5].strip() if len(fields) > 5 else ""
            yield start, fields[1], path


found = {}
for start, perms, path in regions():
    if path in ("[heap]", "[stack]", "[vdso]") and path not in found:
        found[path] = start
        print(path, perms)

print("the heap is below the stack:", str(found["[heap]"] < found["[stack]"]).lower())
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true
  • Verdict: native. Python does not give the address of a region, but the program runs in a process with the usual layout, and it can read /proc/self/maps as a text file.
#include <cstdint>
#include <filesystem>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

int counter = 42; // a global with a value: the data segment

// Prints the permissions and the kind of the region that holds addr.
void where(const std::string& name, std::uintptr_t addr) {
    const std::string exe = std::filesystem::read_symlink("/proc/self/exe").string();
    std::ifstream maps("/proc/self/maps");
    for (std::string line; std::getline(maps, line);) {
        std::istringstream in(line);
        std::string range, perms, offset, dev, inode, path;
        in >> range >> perms >> offset >> dev >> inode;
        std::getline(in >> std::ws, path);
        const auto dash = range.find('-');
        const auto start = std::stoull(range.substr(0, dash), nullptr, 16);
        const auto end = std::stoull(range.substr(dash + 1), nullptr, 16);
        if (addr >= start && addr < end) {
            std::string kind = path;
            if (path == exe) kind = "the program file";
            else if (path.empty() || path.rfind("[anon", 0) == 0) kind = "an anonymous mapping";
            std::cout << std::left << std::setw(8) << name << " " << perms << " " << kind << "\n";
            return;
        }
    }
}

int main() {
    int here = 1;                             // a local: the stack
    auto small = std::make_unique<int>(7);    // a small block: the heap
    std::vector<char> big(1 << 20);           // 1 MiB, over MMAP_THRESHOLD

    where("code", reinterpret_cast<std::uintptr_t>(&where));
    where("global", reinterpret_cast<std::uintptr_t>(&counter));
    where("local", reinterpret_cast<std::uintptr_t>(&here));
    where("small", reinterpret_cast<std::uintptr_t>(small.get()));
    where("big", reinterpret_cast<std::uintptr_t>(big.data()));
}
Output
code     r-xp the program file
global   rw-p the program file
local    rw-p [stack]
small    rw-p [heap]
big      rw-p an anonymous mapping
  • Verdict: native. As in C, a pointer is an address. new and std::vector get their memory from the C library, so the small block is in [heap] and the 1 MiB block is in an anonymous mapping.
JavaGitHub
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws Exception {
        Map<String, Long> found = new LinkedHashMap<>();
        for (String line : Files.readAllLines(Path.of("/proc/self/maps"))) {
            String[] fields = line.trim().split("\\s+");
            String path = fields.length > 5 ? fields[5] : "";
            if (List.of("[heap]", "[stack]", "[vdso]").contains(path) && !found.containsKey(path)) {
                found.put(path, Long.parseUnsignedLong(fields[0].split("-")[0], 16));
                System.out.println(path + " " + fields[1]);
            }
        }
        boolean below = Long.compareUnsigned(found.get("[heap]"), found.get("[stack]")) < 0;
        System.out.println("the heap is below the stack: " + below);
    }
}
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true
  • Verdict: native. Java has no addresses, but the JVM runs in a process with the usual layout, and the program can read /proc/self/maps as a file.
#define _POSIX_C_SOURCE 200112L /* for readlink */
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

int counter = 42; /* a global with a value: the data segment */

/* Prints the permissions and the kind of the region that holds addr. */
static void where(const char *name, uintptr_t addr) {
    char exe[4096] = "";
    ssize_t len = readlink("/proc/self/exe", exe, sizeof exe - 1);
    if (len > 0) exe[len] = '\0';

    FILE *maps = fopen("/proc/self/maps", "r");
    char line[8192];
    while (maps && fgets(line, sizeof line, maps)) {
        unsigned long start, end;
        char perms[5], path[4096] = "";
        if (sscanf(line, "%lx-%lx %4s %*s %*s %*s %4095[^\n]", &start, &end, perms, path) < 3) continue;
        if (addr >= start && addr < end) {
            const char *kind = path;
            if (strcmp(path, exe) == 0) kind = "the program file";
            else if (path[0] == '\0' || strncmp(path, "[anon", 5) == 0) kind = "an anonymous mapping";
            printf("%-8s %s %s\n", name, perms, kind);
            break;
        }
    }
    if (maps) fclose(maps);
}

int main(void) {
    int here = 1;                      /* a local: the stack */
    int *small = malloc(sizeof *small); /* a small block: the heap */
    char *big = malloc(1 << 20);       /* 1 MiB, over MMAP_THRESHOLD */

    where("code", (uintptr_t)&where);
    where("global", (uintptr_t)&counter);
    where("local", (uintptr_t)&here);
    where("small", (uintptr_t)small);
    where("big", (uintptr_t)big);

    free(big);
    free(small);
    return 0;
}
Output
code     r-xp the program file
global   rw-p the program file
local    rw-p [stack]
small    rw-p [heap]
big      rw-p an anonymous mapping
  • Verdict: native. A pointer is an address, so the program can find the region of each thing. The code is in a region of the program file that can be run, and counter is in a region of the file that can be written.
  • The 1 MiB block is larger than MMAP_THRESHOLD, so malloc takes it from an anonymous mapping, not from [heap].
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;

static class Demo
{
    static void Main()
    {
        var found = new Dictionary<string, ulong>();
        foreach (var line in File.ReadLines("/proc/self/maps"))
        {
            var fields = line.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            var path = fields.Length > 5 ? fields[5] : "";
            if ((path == "[heap]" || path == "[stack]" || path == "[vdso]") && !found.ContainsKey(path))
            {
                found[path] = ulong.Parse(fields[0].Split('-')[0], NumberStyles.HexNumber);
                Console.WriteLine($"{path} {fields[1]}");
            }
        }
        var below = found["[heap]"] < found["[stack]"];
        Console.WriteLine($"the heap is below the stack: {below.ToString().ToLowerInvariant()}");
    }
}
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true
  • Verdict: native. The .NET runtime runs in a process with the usual layout. Safe C# code has no addresses, and the program reads /proc/self/maps as a file.
JavaScriptGitHub
const fs = require("node:fs");

const found = new Map();
for (const line of fs.readFileSync("/proc/self/maps", "utf8").trim().split("\n")) {
  const fields = line.trim().split(/\s+/);
  const path = fields[5] ?? "";
  if (["[heap]", "[stack]", "[vdso]"].includes(path) && !found.has(path)) {
    found.set(path, BigInt("0x" + fields[0].split("-")[0])); // addresses need more than 53 bits
    console.log(path, fields[1]);
  }
}
console.log("the heap is below the stack:", found.get("[heap]") < found.get("[stack]"));
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true
  • Verdict: native. JavaScript has no addresses, but Node.js runs in a process with the usual layout, and it can read /proc/self/maps as a file.
  • An address can be larger than Number.MAX_SAFE_INTEGER, so the program compares them as BigInt values.
TypeScriptGitHub
const fs = require("node:fs");

const found = new Map<string, bigint>();
const text: string = fs.readFileSync("/proc/self/maps", "utf8");
for (const line of text.trim().split("\n")) {
  const fields: string[] = line.trim().split(/\s+/);
  const path: string = fields[5] ?? "";
  if (["[heap]", "[stack]", "[vdso]"].includes(path) && !found.has(path)) {
    found.set(path, BigInt("0x" + fields[0].split("-")[0])); // addresses need more than 53 bits
    console.log(path, fields[1]);
  }
}
console.log("the heap is below the stack:", found.get("[heap]")! < found.get("[stack]")!);
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true
  • Verdict: native. The program runs as JavaScript in Node.js, so it sees the same regions.
package main

import (
	"fmt"
	"os"
	"reflect"
	"strconv"
	"strings"
	"unsafe"
)

var counter = 42 // a global with a value: the data segment

// where prints the permissions and the kind of the region that holds addr.
func where(name string, addr uintptr) {
	exe, _ := os.Executable()
	data, _ := os.ReadFile("/proc/self/maps")
	for _, line := range strings.Split(strings.TrimSpace(string(data)), "\n") {
		fields := strings.Fields(line)
		lo, hi, _ := strings.Cut(fields[0], "-")
		start, _ := strconv.ParseUint(lo, 16, 64)
		end, _ := strconv.ParseUint(hi, 16, 64)
		if uint64(addr) >= start && uint64(addr) < end {
			path := strings.Join(fields[min(5, len(fields)):], " ")
			kind := path
			if path == exe {
				kind = "the program file"
			} else if path == "" || strings.HasPrefix(path, "[anon") {
				kind = "an anonymous mapping"
			}
			fmt.Printf("%-8s %s %s\n", name, fields[1], kind)
			return
		}
	}
}

func main() {
	here := 1                 // a local: the stack of the goroutine
	small := new(int)         // a small block
	big := make([]byte, 1<<20) // 1 MiB: too large for the stack

	where("code", reflect.ValueOf(where).Pointer())
	where("global", uintptr(unsafe.Pointer(&counter)))
	where("local", uintptr(unsafe.Pointer(&here)))
	where("small", uintptr(unsafe.Pointer(small)))
	where("big", uintptr(unsafe.Pointer(&big[0])))
}
Output
code     r-xp the program file
global   rw-p the program file
local    rw-p an anonymous mapping
small    rw-p an anonymous mapping
big      rw-p an anonymous mapping
  • Verdict: native. unsafe.Pointer turns a pointer into an address. The code and the global are in the program file, as in C.
  • The Go runtime takes its memory with mmap. The stack of a goroutine and the heap of Go are both in anonymous mappings, so this program has nothing in [heap] or [stack].
RustGitHub
use std::fs;
use std::sync::atomic::AtomicI32;

static COUNTER: AtomicI32 = AtomicI32::new(42); // a global that can change: the data segment

// Prints the permissions and the kind of the region that holds addr.
fn where_is(name: &str, addr: usize) {
    let exe = fs::read_link("/proc/self/exe").unwrap();
    let exe = exe.to_string_lossy().into_owned();
    let maps = fs::read_to_string("/proc/self/maps").unwrap();
    for line in maps.lines() {
        let fields: Vec<&str> = line.splitn(6, ' ').collect();
        let path = fields.get(5).map_or("", |s| s.trim());
        let (lo, hi) = fields[0].split_once('-').unwrap();
        let start = usize::from_str_radix(lo, 16).unwrap();
        let end = usize::from_str_radix(hi, 16).unwrap();
        if addr >= start && addr < end {
            let kind = if path == exe {
                "the program file"
            } else if path.is_empty() || path.starts_with("[anon") {
                "an anonymous mapping"
            } else {
                path
            };
            println!("{:<8} {} {}", name, fields[1], kind);
            return;
        }
    }
}

fn main() {
    let here = 1i32;              // a local: the stack
    let small = Box::new(7i32);   // a small block: the heap
    let big = vec![1u8; 1 << 20]; // 1 MiB, over MMAP_THRESHOLD

    where_is("code", where_is as fn(&str, usize) as usize);
    where_is("global", &COUNTER as *const AtomicI32 as usize);
    where_is("local", &here as *const i32 as usize);
    where_is("small", &*small as *const i32 as usize);
    where_is("big", big.as_ptr() as usize);
}
Output
code     r-xp the program file
global   rw-p the program file
local    rw-p [stack]
small    rw-p [heap]
big      rw-p an anonymous mapping
  • Verdict: native. A reference converts to a raw pointer, and the pointer to an address. Box and Vec use the system allocator by default, so the blocks go where malloc puts them.
  • An immutable static with a plain value can be put in read-only data. AtomicI32 can change, so COUNTER is in a region that can be written.
BashGitHub
heap="" stack=""
while read -r range perms _ _ _ path; do
  start=$((16#${range%%-*}))
  case $path in
    "[heap]")  [[ -z $heap ]] && heap=$start && echo "$path $perms" ;;
    "[stack]") [[ -z $stack ]] && stack=$start && echo "$path $perms" ;;
    "[vdso]")  echo "$path $perms" ;;
  esac
done < /proc/$$/maps # $$ is the process ID of this shell
if (( heap < stack )); then
  echo "the heap is below the stack: true"
fi
Output
[heap] rw-p
[stack] rw-p
[vdso] r-xp
the heap is below the stack: true
  • Verdict: native. $$ is the process ID of the shell, so /proc/$$/maps lists the regions of the shell itself.
  • Address space layout randomization. "ASLR randomly arranges the address space positions of key data areas of a process, including the base of the executable and the positions of the stack, heap and libraries"10. This makes it harder for an attack to guess an address10. The order of the regions stays the same, but the addresses change on each run.
  • Threads. Each thread has its own stack. Only the stack of the main thread is named [stack]1. Some kernels named the stack of a thread [stack:tid], but the man page says that this field was removed, because it is expensive for a process with many threads1.
  • A runtime with its own heap. A runtime can take memory with mmap and keep its own heap there. The Go example shows its heap blocks and its goroutine stack in anonymous mappings, not in [heap] and [stack].
  • Segments in hardware. "The Intel 8086 family of CPUs provided four segments: the code segment, the data segment, the stack segment and the extra segment"3. Wikipedia calls the memory segment "a historical approach to memory management that has been succeeded by paging"2.

Pitfalls

  • Addresses are not stable. Because of ASLR, the address of a global or a function can change on each run. Do not store an address in a file or compare addresses from two runs.
  • The heap is more than [heap]. A large malloc goes to an anonymous mapping, not to the [heap] region7. A tool that only measures [heap] misses those blocks.
  • Writes to code. The code segment is read-only on most systems, and "If the code segment is not read-only, then the particular architecture allows self-modifying code"2.
  • brk in a program. The brk man page says "Avoid using brk() and sbrk(): the malloc(3) memory allocation package is the portable and comfortable way of allocating memory"6.

Cost

The bss segment saves space in the file: "By placing variables with no value in the .bss section, instead of the .data or .rodata section which require initial value data, the size of the object file is reduced"4. It also costs little at run time, because "Operating systems may use a technique called zero-fill-on-demand to efficiently implement the bss segment"4. The C library uses mmap only for blocks larger than MMAP_THRESHOLD, which "is 128 kB by default, but is adjustable using mallopt(3)"7.

History

The name bss comes from an assembler of the 1950s: "BSS (from Block Started by Symbol) is a pseudo-operation in UA-SAP (United Aircraft Symbolic Assembly Program), the assembler developed in the mid-1950s for the IBM 704"4. The segments of the Intel 8086 let a 16-bit address register reach more memory: "This allowed a 16-bit address register, which would normally be able to access 64 KB of memory space, to access 1 MB of memory space"3. Address space layout randomization came later. The PaX project "published the first design and implementation of ASLR in July 2001 as a patch for the Linux kernel"10, and "The first mainstream operating system to support ASLR by default was OpenBSD version 3.4 in 2003"10.

References

  1. proc_pid_maps(5), Linux manual page, DESCRIPTION
  2. Code segment, Wikipedia, Introduction; Segment
  3. Data segment, Wikipedia, Introduction; Program memory; Code; Data; BSS; Heap; Stack
  4. .bss, Wikipedia, Introduction; Origin
  5. elf(5), Linux manual page, Section header, special sections (.bss, .data, .rodata, .text)
  6. brk(2), Linux manual page, DESCRIPTION; NOTES
  7. malloc(3), Linux manual page, NOTES
  8. mmap(2), Linux manual page, DESCRIPTION; MAP_ANONYMOUS
  9. Memory-mapped file, Wikipedia, Introduction
  10. Address space layout randomization, Wikipedia, Introduction; History; Linux

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/T638CX/text.yaml