Tcache
The Basics
Thread Local Caching is built within ptmalloc to speed up repeated (small) allocations in a single thread. Implemetned as a singly-linked list, with each thread having a list ehader for different sized allocations.
typedef struct tcache_perthread_struct
{
char counts[TCACHE_MAX_BINS];
tcache_entry *entries[TCACHE_MAX_BINS];
} tcache_perthread_struct;
typedef struct tcache_entry
{
struct tcache_entry *next;
struct tcache_perthread_struct *key;
} tcache_entry;
The structure contains to the two pointers, one to the original value and one to the next value in the linked list.
Tcache comes into play when we are freeing memory. When something, it gets put into the tstruct_perthread_struct. More specifically, the element it goes into is based on the size of the data we freed. If another element is freed, it goes to the top of the list; however, it also points to previous one that is freed. Example:



How does it work on free?
1) Select the right bin based on its size
2) Chheck to make sure the entry hasn't already been freed
- Double free check
3) Push the freed allocation ot the front of the list
4) Record the tcache_perthread_struct association with the freed allocation
How does it work on allocation?
1) Select the bin number based on the requested size
2) Check the appropriate cache for available entries
3) Reuse the allocation in the front of the list available
More specifically, it will pop the first entry off of the list, and put the entry considered to be next in the tcache_perthread_struct.
Things that are not done:
- Clearing all sensitive pointers
- Checking if the next (return[0]) address makes sense
Does not NULL out next pointer in tcache entry, but does null out key.
Does not perform any checks.
Photos of allocations below needs to be inserted
Dangers of the Heap
Double Free Errors
Ubuntu 18.04 had no security checks, but now in Ubuntu 20.04, it will detect it.
- This is done by checking whether the
tcache_entry->keyis pointing to a validtcache_perthread_struct.
To bypass this, you need to corrupt the key (the second set of bytes in the tcache_entry).