summaryrefslogtreecommitdiff
path: root/targets/heap.c
blob: 7f999e97b44ea7facab1411bb2d064f7a67e356e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// glibc's malloc a step at a time, for `ztrace record --heap -b heap_step`: each
// call of `heap_step` follows one change to the heap. Seventeen chunks of one
// size fill its tcache bin (7 before glibc 2.42, 16 by default since) and
// pass the rest on, to a fastbin where there are fastbins; a chunk too large
// for the tcache, freed beside one in use, goes to the unsorted bin; a
// larger request sorts it into a large bin (2.40 consolidates the fastbins
// first) and is served from the top, to which it returns when freed.
#include <stdlib.h>

// Volatile, or the compiler proves the allocations away.
static void *volatile small[17], *volatile big, *volatile guard, *volatile larger;

__attribute__((noinline)) void heap_step(int n) { __asm__ volatile("" : : "r"(n) : "memory"); }

int main(void) {
    for (int i = 0; i < 17; i++) small[i] = malloc(0x28);
    big = malloc(0x500);
    guard = malloc(0x18);
    heap_step(1);
    for (int i = 0; i < 17; i++) free(small[i]);
    heap_step(2);
    free(big);
    heap_step(3);
    larger = malloc(0x1000);
    heap_step(4);
    free(larger);
    heap_step(5);
    return 0;
}