[PATCH] malloc: check tcachebin size when allocating.

dudududumaxver@gmail.com dudududumaxver@gmail.com
Tue Apr 1 03:00:56 GMT 2025


From: dbgbgtf <dudududuMaxVer@outlook.com>

check if `tcache mem size == request size` to avoid arbitrary tcachebin
allocation.
---
 malloc/malloc.c | 13 +++++++++++--
 1 file changed, 11 insertions(+), 2 deletions(-)

diff --git a/malloc/malloc.c b/malloc/malloc.c
index a0bc733482..e746335a29 100644
--- a/malloc/malloc.c
+++ b/malloc/malloc.c
@@ -1294,6 +1294,9 @@ nextchunk-> +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
 /* Convert a user mem pointer to a chunk address and extract the right tag.  */
 #define mem2chunk(mem) ((mchunkptr)tag_at (((char*)(mem) - CHUNK_HDR_SZ)))
 
+/* Convert a user mem pointer to chunk size */
+#define mem2size(mem) ((*(INTERNAL_SIZE_T*)((char*)mem - SIZE_SZ)) & ~MALLOC_ALIGN_MASK )
+
 /* The smallest possible chunk */
 #define MIN_CHUNK_SIZE        (offsetof(struct malloc_chunk, fd_nextsize))
 
@@ -3429,10 +3432,16 @@ void *
 __libc_malloc (size_t bytes)
 {
 #if USE_TCACHE
-  size_t tc_idx = csize2tidx (checked_request2size (bytes));
+  size_t tbytes = checked_request2size (bytes);
+  size_t tc_idx = csize2tidx (tbytes);
 
   if (tcache_available (tc_idx))
-    return tag_new_usable (tcache_get (tc_idx));
+  {
+    void *memptr = tag_new_usable (tcache_get (tc_idx));
+    if (__glibc_unlikely(mem2size(memptr)) != tbytes)
+      malloc_printerr("malloc(): tcache mem size vs request2 size");
+    return memptr;
+  }
 #endif
 
   return __libc_malloc2 (bytes);
-- 
2.49.0



More information about the Libc-alpha mailing list