Skip to main content
Be Bitwise

Dangling Pointers & the tcache

Heap Vulnerabilities & Use-After-Free · Exploitation Fundamentals track

12 min read

In this module

The Pointer That Outlives Its Data

When a program frees a block of heap memory, the allocator takes the chunk back. What about the pointer variable that still holds its address? Nothing happens to it. The pointer keeps its old value, and it still "works" in the sense that the CPU will happily dereference it. The data behind it, though, now belongs to the allocator.

This lesson follows one dangling pointer through glibc 2.35 (Ubuntu 22.04) on x86-64, and uses it as a window into the two caches that freed small chunks land in first: tcache and the fastbins. By the end you'll be able to read the bytes free leaves behind and explain why, since glibc 2.32, half of them look like nonsense.

A Dangling Pointer in Action

Here's the bug in its natural habitat:

c
struct session {
void (*on_close)(struct session *);
char user[0x38];
};
struct session *s = malloc(sizeof *s); /* 0x40 bytes -> 0x50 chunk */
s->on_close = log_close;
strcpy(s->user, "alice");
free(s); /* s is now dangling */
/* ... later, on some other code path ... */
s->on_close(s); /* use after free */

After free(s), the variable s still says 0x55555555b2a0 (addresses in this lesson are illustrative, and match the layout from lesson 1). That address isn't the program's any more. Whatever the last line reads could be the old function pointer, garbage, or a field belonging to a completely different object that has since landed in the same chunk.

Here's the part most textbook descriptions skip: on glibc, the first option almost never happens. free itself overwrites the start of the object.

Dangling Pointer

A dangling pointer is a pointer that references memory that has been deallocated. The pointer itself is not invalid in any hardware sense; the CPU will still read from or write to that address. The danger is that the memory may now belong to the allocator's free lists, or to a different allocation, leading to data corruption, crashes, or exploitable vulnerabilities.

Why the CPU Cannot Help

As you learned in earlier modules, memory is a flat array of bytes addressed by numbers. The CPU has no concept of "ownership". A mov rax, [rdi] fetches whatever eight bytes sit at the address in rdi. There's no check for whether your program still owns that address, or whether it was freed a microsecond ago. The page is still mapped, the permissions still say read-write, so the access succeeds.

That's a basic property of the hardware, and it's why dangling pointers exist at all. Rust heads the problem off at compile time with ownership rules that stop a reference outliving its data. In C and C++, the responsibility falls on the programmer, and on the allocator's checks, which as you'll see are thinner than you'd hope.

What free Writes: the tcache

Since glibc 2.26, the first stop for a freed small chunk is the tcache (thread cache). Each thread has a tcache_perthread_struct, the 0x290-byte chunk at the very start of the heap from lesson 1. In glibc 2.35 it looks like this:

c
#define TCACHE_MAX_BINS 64
typedef struct tcache_entry {
struct tcache_entry *next;
uintptr_t key; /* used to detect double frees */
} tcache_entry;
typedef struct tcache_perthread_struct {
uint16_t counts[TCACHE_MAX_BINS];
tcache_entry *entries[TCACHE_MAX_BINS];
} tcache_perthread_struct;

There's one bin per chunk size, from 0x20 (index 0) to 0x410 (index 63), so the index for a chunk of size sz is (sz - 0x20) / 0x10. A 0x50 chunk goes in bin 3. Each bin holds at most 7 chunks by default (the glibc.malloc.tcache_count tunable can change that).

The crucial detail is where a tcache_entry lives. It doesn't get allocated separately. glibc casts the freed chunk's user pointer to tcache_entry * and writes the two fields straight into the first 16 bytes of your old object. Here's tcache_put from 2.35, lightly trimmed:

c
static __always_inline void
tcache_put (mchunkptr chunk, size_t tc_idx)
{
tcache_entry *e = (tcache_entry *) chunk2mem (chunk);
e->key = tcache_key;
e->next = PROTECT_PTR (&e->next, tcache->entries[tc_idx]);
tcache->entries[tc_idx] = e;
++(tcache->counts[tc_idx]);
}

So after free(s), the on_close slot holds a list pointer (in an encoded form, explained below) and the first eight bytes of user hold tcache_key. Call s->on_close(s) now and the program jumps to an address that isn't code. Most of the time that's a crash. The next lesson is about the times it isn't.

The tcache list is LIFO: the most recently freed chunk is the head, and malloc pops the head. Free a 0x50 chunk, then ask for 0x40 bytes, and you get the same address straight back. That predictability is the whole foundation of use-after-free exploitation.

Reading a tcache Dump

Free two 0x50 chunks, a at 0x55555555b2a0 and then b at 0x55555555b2f0, and dump the heap. This is what 2.35 leaves behind:

text
0x55555555b010: 0x0002000000000000 0x0000000000000000 <- counts[0..3], counts[4..7]
...
0x55555555b0a0: 0x0000000000000000 0x000055555555b2f0 <- entries[2], entries[3]
...
0x55555555b290: 0x0000000000000000 0x0000000000000051 <- chunk a header
0x55555555b2a0: 0x000000055555555b 0x5d8c1e3fa7b2c491 <- a: next, key
0x55555555b2b0: 0x4141414141414141 0x4141414141414141 <- old data, untouched
...
0x55555555b2e0: 0x0000000000000000 0x0000000000000051 <- chunk b header
0x55555555b2f0: 0x000055500000e7fb 0x5d8c1e3fa7b2c491 <- b: next, key

Work through it line by line.

  • Counts. counts is an array of 16-bit values starting at 0x55555555b010. x86-64 is little-endian, so the first qword holds counts[0] in its lowest two bytes and counts[3] in its highest two. 0x0002... means bin 3 holds two chunks.
  • Head. entries starts 0x80 bytes later at 0x55555555b090, so entries[3] is at 0x55555555b0a8. It holds b's user pointer, unencoded. b was freed last, so it's the head.
  • Size fields. Both chunks still read 0x51. tcache doesn't touch the header, and the chunk after each one keeps PREV_INUSE set. As far as the rest of the allocator is concerned, these chunks are still in use.
  • Key. Both chunks hold the same 8-byte value at offset 8. That's tcache_key, a random number glibc picks once per process (since 2.34; from 2.29 to 2.33 it was the address of the tcache_perthread_struct itself, which leaked a heap address to anyone who could read a freed chunk).
  • Old data. Everything past the first 16 bytes is untouched. A stale read of s->user + 8 still returns the old string. Stale reads of the first two words don't.

And then the next fields, which look nothing like heap addresses. That's safe-linking.

Safe-Linking (glibc 2.32 and Later)

Before 2.32, next held a plain pointer. An attacker with a use-after-free write could overwrite it with any address, and two malloc calls later the allocator would hand that address back. Eyal Itkin of Check Point Research proposed safe-linking to make that harder, and it shipped in glibc 2.32 in 2020. Every singly linked pointer, in tcache and in the fastbins, is now stored mangled:

c
#define PROTECT_PTR(pos, ptr) \
((__typeof (ptr)) ((((size_t) pos) >> 12) ^ ((size_t) ptr)))
#define REVEAL_PTR(ptr) PROTECT_PTR (&ptr, ptr)

pos is the address where the pointer is stored, ptr is the pointer itself. Shifting pos right by 12 throws away the page offset and keeps the randomised bits ASLR put into the heap address. XOR is its own inverse, so applying the same operation decodes it.

Check it against the dump:

  • a was freed into an empty bin, so ptr was NULL. The stored value is 0x55555555b2a0 >> 12, which is 0x55555555b. That's what sits at 0x55555555b2a0.
  • b's next is a. The stored value is (0x55555555b2f0 >> 12) ^ 0x55555555b2a0, which is 0x55555555b ^ 0x55555555b2a0 = 0x55500000e7fb.

When tcache_get pops an entry it calls REVEAL_PTR on the stored value to find the new head, and it first checks that the entry it's about to return is 16-byte aligned. A misaligned entry aborts the program with malloc(): unaligned tcache chunk detected.

Predict: the program frees a single 0x30 chunk at 0x55555555c3d0 into an empty tcache bin, then a use-after-free prints the first 8 bytes of it. What gets printed, and why does that matter to an attacker?

Answer. 0x55555555c. The bin was empty, so the stored value is (0x55555555c3d0 >> 12) ^ 0, which is just the chunk's own address shifted right by 12. Shift it back left and you have the heap's page address, which defeats heap ASLR. It's also exactly the value an attacker needs to mangle pointers of their own for any chunk on the same page, which the next lesson uses.

What Safe-Linking Changes, and What It Doesn't

Safe-linking does three useful things. An attacker who overwrites next without knowing the heap address now produces a random-looking pointer after decoding, which will usually fail the alignment check and abort. Partial overwrites, where an attacker changes only the low byte or two of a pointer to steer it somewhere nearby, stop working, because the low bits are XORed with ASLR-derived bits. And random heap corruption from ordinary bugs tends to be caught earlier, which helps developers too.

It doesn't stop an attacker who has a heap leak. With the address of the chunk being edited, mangling a chosen pointer is one XOR. As the predict block showed, a single use-after-free read of the first entry in a bin hands that leak over for free. Even without that, when a stored pointer and the place it's stored sit close together on the heap, the mangled value can be unpicked 12 bits at a time, because the top 12 bits of pos >> 12 are always zero.

It also only covers the singly linked lists. The unsorted, small and large bins use doubly linked fd/bk pointers stored in plain form, and the entries heads in tcache_perthread_struct are plain too. Lesson 4 makes use of the first of those.

Double-Free Detection

The key field exists for one reason. When free sees a chunk whose offset-8 word equals tcache_key, it suspects a double free and walks the whole bin. If it finds the chunk, it aborts with free(): double free detected in tcache 2. The walk also aborts on a misaligned entry (free(): unaligned chunk detected in tcache 2) or if it finds more chunks than the bin can hold.

That check arrived in glibc 2.29. It's cheap, because the full walk only happens when the key matches, and it's easy to dodge: a use-after-free write that changes even one byte of key makes the chunk look never-freed, and a second free goes through. malloc clears the key to zero when it hands a chunk out, so legitimately reused chunks never trip it.

Fastbins: the Second Cache

Once a tcache bin has 7 chunks, the next free of that size goes elsewhere. For chunks up to 0x80 bytes, that's a fastbin. Fastbins are older than tcache, singly linked, LIFO, and live in the arena (main_arena.fastbinsY[]) instead of per thread. The index is (size >> 4) - 2, so a 0x50 chunk goes in fastbin 3.

Fastbins differ from tcache in ways that matter when you read a dump or plan an attack:

  • The fd link is at offset 0x10 of the chunk, the same place as tcache's next, but it points to the next chunk header, not the next user pointer. Mix those up and every address you compute is 16 bytes off.
  • fd is mangled with the same PROTECT_PTR, so safe-linking applies.
  • There's no key field. The double-free check only compares the chunk being freed with the current head of the bin, aborting with double free or corruption (fasttop). Freeing x, then y, then x again passes, which is the classic "fastbin dup".
  • When malloc takes a chunk from a fastbin, it checks that the chunk's size field matches the bin, aborting with malloc(): memory corruption (fast) if not. tcache does no such check, which is a large part of why attackers prefer it.
  • When malloc serves a request from a fastbin and the tcache bin for that size has room, it moves the remaining fastbin chunks into tcache.

Neither cache merges chunks with their neighbours or clears the next chunk's PREV_INUSE. Fastbin chunks only merge when malloc_consolidate runs, which happens on large requests and in a few other situations.

Stale Reads and Silent Corruption

The most insidious thing about dangling pointers is that they often appear to work. Only the first 16 bytes of a tcache chunk get overwritten, so a stale read of any later field returns the old value, and the program chugs along happily. The bug only shows itself once the chunk gets handed out again, and by then the symptoms are unpredictable, hard to reproduce, and miles from the mistake.

Stale writes are worse. A write through a dangling pointer into the first 16 bytes edits the allocator's own linked list. Writing to s->on_close after free(s) changes where tcache thinks the next free chunk is.

That window between "the memory is freed" and "the memory is reused" is what attackers target, and the next lesson turns it into an arbitrary write.