Bins & Memory Allocations

Basic Information

In order to improve the efficiency on how chunks are stored every chunk is not just in one linked list, but there are several types. These are the bins and there are 5 type of bins: 62 small bins, 63 large bins, 1 unsorted bin, 10 fast bins and 64 tcache bins per thread.

The initial address to each unsorted, small and large bins is inside the same array. The index 0 is unused, 1 is the unsorted bin, bins 2-64 are small bins and bins 65-127 are large bins.

Tcache (Per-Thread Cache) Bins

Even though threads try to have their own heap (see Arenas and Subheaps), there is the possibility that a process with a lot of threads (like a web server) will end sharing the heap with another threads. In this case, the main solution is the use of lockers, which might slow down significantly the threads.

Therefore, a tcache is similar to a fast bin per thread in the way that it's a single linked list that doesn't merge chunks. Each thread has 64 singly-linked tcache bins. Each bin can have a maximum of 7 same-size chunks ranging from 24 to 1032B on 64-bit systems and 12 to 516B on 32-bit systems.

When a thread frees a chunk, if it isn't too big to be allocated in the tcache and the respective tcache bin isn't full (already 7 chunks), it'll be allocated in there. If it cannot go to the tcache, it'll need to wait for the heap lock to be able to perform the free operation globally.

When a chunk is allocated, if there is a free chunk of the needed size in the Tcache it'll use it, if not, it'll need to wait for the heap lock to be able to find one in the global bins or create a new one. There's also an optimization, in this case, while having the heap lock, the thread will fill his Tcache with heap chunks (7) of the requested size, so in case it needs more, it'll find them in Tcache.

Add a tcache chunk example
#include <stdlib.h>
#include <stdio.h> 

int main(void) 
{
  char *chunk;
  chunk = malloc(24);
  printf("Address of the chunk: %p\n", (void *)chunk);
  gets(chunk);
  free(chunk);
  return 0;
}

Compile it and debug it with a breakpoint in the ret opcode from main function. then with gef you can see the tcache bin in use:

gef➤  heap bins
──────────────────────────────────────────────────────────────────────────────── Tcachebins for thread 1 ────────────────────────────────────────────────────────────────────────────────
Tcachebins[idx=0, size=0x20, count=1]   Chunk(addr=0xaaaaaaac12a0, size=0x20, flags=PREV_INUSE | IS_MMAPPED | NON_MAIN_ARENA) 

Tcache Structs & Functions

In the following code it's possible to see the max bins and chunks per index, the tcache_entry struct created to avoid double frees and tcache_perthread_struct, a struct that each thread uses to store the addresses to each index of the bin.

tcache_entry and tcache_perthread_struct

The function __tcache_init is the function that creates and allocates the space for the tcache_perthread_struct obj

tcache_init code

Tcache Indexes

The tcache have several bins depending on the size an the initial pointers to the first chunk of each index and the amount of chunks per index are located inside a chunk. This means that locating the chunk with this information (usually the first), it's possible to find all the tcache initial points and the amount of Tcache chunks.

Fast bins

Fast bins are designed to speed up memory allocation for small chunks by keeping recently freed chunks in a quick-access structure. These bins use a Last-In, First-Out (LIFO) approach, which means that the most recently freed chunk is the first to be reused when there's a new allocation request. This behaviour is advantageous for speed, as it's faster to insert and remove from the top of a stack (LIFO) compared to a queue (FIFO).

Additionally, fast bins use singly linked lists, not double linked, which further improves speed. Since chunks in fast bins aren't merged with neighbours, there's no need for a complex structure that allows removal from the middle. A singly linked list is simpler and quicker for these operations.

Basically, what happens here is that the header (the pointer to the first chunk to check) is always pointing to the latest freed chunk of that size. So:

  • When a new chunk is allocated of that size, the header is pointing to a free chunk to use. As this free chunk is pointing to the next one to use, this address is stored in the header so the next allocation knows where to get an available chunk

  • When a chunk is freed, the free chunk will save the address to the current available chunk and the address to this newly freed chunk will be put in the header

The maximum size of a linked list is 0x80 and they are organized so a chunk of size 0x20 will be in index 0, a chunk of size 0x30 would be in index 1...

Add a fastbin chunk example

Note how we allocate and free 8 chunks of the same size so they fill the tcache and the eight one is stored in the fast chunk.

Compile it and debug it with a breakpoint in the ret opcode from main function. then with gef you can see that the tcache bin is full and one chunk is in the fast bin:

Unsorted bin

The unsorted bin is a cache used by the heap manager to make memory allocation quicker. Here's how it works: When a program frees a chunk, and if this chunk cannot be allocated in a tcache or fast bin and is not colliding with the top chunk, the heap manager doesn't immediately put it in a specific small or large bin. Instead, it first tries to merge it with any neighbouring free chunks to create a larger block of free memory. Then, it places this new chunk in a general bin called the "unsorted bin."

When a program asks for memory, the heap manager checks the unsorted bin to see if there's a chunk of enough size. If it finds one, it uses it right away. If it doesn't find a suitable chunk in the unsorted bin, it moves all the chunks in this list to their corresponding bins, either small or large, based on their size.

Note that if a larger chunk is split in 2 halves and the rest is larger than MINSIZE, it'll be paced back into the unsorted bin.

So, the unsorted bin is a way to speed up memory allocation by quickly reusing recently freed memory and reducing the need for time-consuming searches and merges.

Add a unsorted chunk example

Note how we allocate and free 9 chunks of the same size so they fill the tcache and the eight one is stored in the unsorted bin because it's too big for the fastbin and the nineth one isn't freed so the nineth and the eighth don't get merged with the top chunk.

Compile it and debug it with a breakpoint in the ret opcode from main function. Then with gef you can see that the tcache bin is full and one chunk is in the unsorted bin:

Small Bins

Small bins are faster than large bins but slower than fast bins.

Each bin of the 62 will have chunks of the same size: 16, 24, ... (with a max size of 504 bytes in 32bits and 1024 in 64bits). This helps in the speed on finding the bin where a space should be allocated and inserting and removing of entries on these lists.

This is how the size of the small bin is calculated according to the index of the bin:

  • Smallest size: 2*4*index (e.g. index 5 -> 40)

  • Biggest size: 2*8*index (e.g. index 5 -> 80)

Function to choose between small and large bins:

Add a small chunk example

Note how we allocate and free 9 chunks of the same size so they fill the tcache and the eight one is stored in the unsorted bin because it's too big for the fastbin and the ninth one isn't freed so the ninth and the eights don't get merged with the top chunk. Then we allocate a bigger chunk of 0x110 which makes the chunk in the unsorted bin goes to the small bin.

Compile it and debug it with a breakpoint in the ret opcode from main function. then with gef you can see that the tcache bin is full and one chunk is in the small bin:

Large bins

Unlike small bins, which manage chunks of fixed sizes, each large bin handle a range of chunk sizes. This is more flexible, allowing the system to accommodate various sizes without needing a separate bin for each size.

In a memory allocator, large bins start where small bins end. The ranges for large bins grow progressively larger, meaning the first bin might cover chunks from 512 to 576 bytes, while the next covers 576 to 640 bytes. This pattern continues, with the largest bin containing all chunks above 1MB.

Large bins are slower to operate compared to small bins because they must sort and search through a list of varying chunk sizes to find the best fit for an allocation. When a chunk is inserted into a large bin, it has to be sorted, and when memory is allocated, the system must find the right chunk. This extra work makes them slower, but since large allocations are less common than small ones, it's an acceptable trade-off.

There are:

  • 32 bins of 64B range (collide with small bins)

  • 16 bins of 512B range (collide with small bins)

  • 8bins of 4096B range (part collide with small bins)

  • 4bins of 32768B range

  • 2bins of 262144B range

  • 1bin for remaining sizes

Large bin sizes code
Add a large chunk example

2 large allocations are performed, then on is freed (putting it in the unsorted bin) and a bigger allocation in made (moving the free one from the usorted bin ro the large bin).

Compile it and debug it with a breakpoint in the ret opcode from main function. then with gef you can see that the tcache bin is full and one chunk is in the large bin:

Top Chunk

Basically, this is a chunk containing all the currently available heap. When a malloc is performed, if there isn't any available free chunk to use, this top chunk will be reducing its size giving the necessary space. The pointer to the Top Chunk is stored in the malloc_state struct.

Moreover, at the beginning, it's possible to use the unsorted chunk as the top chunk.

Observe the Top Chunk example

After compiling and debugging it with a break point in the ret opcode of main I saw that the malloc returned the address 0xaaaaaaac12a0 and these are the chunks:

Where it can be seen that the top chunk is at address 0xaaaaaaac1ae0. This is no surprise because the last allocated chunk was in 0xaaaaaaac12a0 with a size of 0x410 and 0xaaaaaaac12a0 + 0x410 = 0xaaaaaaac1ae0 . It's also possible to see the length of the Top chunk on its chunk header:

Last Remainder

When malloc is used and a chunk is divided (from the unsorted bin or from the top chunk for example), the chunk created from the rest of the divided chunk is called Last Remainder and it's pointer is stored in the malloc_state struct.

Allocation Flow

Check out:

malloc & sysmalloc

Free Flow

Check out:

free

Heap Functions Security Checks

Check the security checks performed by heavily used functions in heap in:

Heap Functions Security Checks

References

Last updated