gpt4 book ai didi

c - 什么是 TCACHE?

转载 作者:行者123 更新时间:2023-12-03 21:24:05 25 4
gpt4 key购买 nike

我在 linux 上玩了很长时间的二进制开发,最近我正在写一些基于 的堆开发笔记。 ptmalloc ,所以我回去查看我解决过的过去安全挑战中的一些有效载荷,令人惊讶的是它们不再起作用了。

比如基本的double free corruption(不是fastbin)

char *chunk1 = malloc(0xc0);
free(chunk1);
free(chunk1);

我希望看到类似的东西
*** Error in `main': double free or corruption (top): 0x0000000000c85010 ***  

但是没有,什么也没有发生,程序正常退出。

为此,我去检查与我的机器对应的 glibc 源代码 - Debian GLIBC 2.27-2 , 发现 malloc.c 有很大不同.
void *
__libc_malloc (size_t bytes)
{
...
#if USE_TCACHE
/* int_free also calls request2size, be careful to not pad twice. */
size_t tbytes;
checked_request2size (bytes, tbytes);
size_t tc_idx = csize2tidx (tbytes);

MAYBE_INIT_TCACHE ();

DIAG_PUSH_NEEDS_COMMENT;
if (tc_idx < mp_.tcache_bins
/*&& tc_idx < TCACHE_MAX_BINS*/ /* to appease gcc */
&& tcache
&& tcache->entries[tc_idx] != NULL)
{
return tcache_get (tc_idx);
}
DIAG_POP_NEEDS_COMMENT;
#endif
USE_TCACHE也出现在许多其他地方。

然后我回到上面的程序,发现 chunk1未放入 small bin但在 tcache_entry .
TCACHE的目的是什么| ?我搜索了很多,仍然很困惑。

最佳答案

线程本地缓存(tcache)是 glibc 中的性能优化。不幸的是,它以牺牲安全性为代价,并使某些攻击变得更加容易,正如您后来发现的那样。
来自 https://sourceware.org/glibc/wiki/MallocInternals#Thread_Local_Cache_.28tcache.29

While this malloc is aware of multiple threads, that's pretty much the extent of its awareness - it knows there are multiple threads. There is no code in this malloc to optimize it for NUMA architectures, coordinate thread locality, sort threads by core, etc. It is assumed that the kernel will handle those issues sufficiently well.

Each thread has a thread-local variable that remembers which arena it last used. If that arena is in use when a thread needs to use it the thread will block to wait for the arena to become free. If the thread has never used an arena before then it may try to reuse an unused one, create a new one, or pick the next one on the global list.

Each thread has a per-thread cache (called the tcache) containing a small collection of chunks which can be accessed without needing to lock an arena. These chunks are stored as an array of singly-linked lists, like fastbins, but with links pointing to the payload (user area) not the chunk header. Each bin contains one size chunk, so the array is indexed (indirectly) by chunk size. Unlike fastbins, the tcache is limited in how many chunks are allowed in each bin (tcache_count). If the tcache bin is empty for a given requested size, the next larger sized chunk is not used (could cause internal fragmentation), instead the fallback is to use the normal malloc routines i.e. locking the thread's arena and working from there.

关于c - 什么是 TCACHE?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49636591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com