76b6d9
From 0e00b35704e67c499c3abfbd5b6224a13d38b012 Mon Sep 17 00:00:00 2001
76b6d9
From: "W. Hashimoto" <ssmallkirby@gmail.com>
76b6d9
Date: Fri, 11 Dec 2020 16:59:10 -0500
76b6d9
Subject: malloc: Detect infinite-loop in _int_free when freeing tcache
76b6d9
 [BZ#27052]
76b6d9
76b6d9
If linked-list of tcache contains a loop, it invokes infinite
76b6d9
loop in _int_free when freeing tcache. The PoC which invokes
76b6d9
such infinite loop is on the Bugzilla(#27052). This loop
76b6d9
should terminate when the loop exceeds mp_.tcache_count and
76b6d9
the program should abort. The affected glibc version is
76b6d9
2.29 or later.
76b6d9
76b6d9
Reviewed-by: DJ Delorie <dj@redhat.com>
76b6d9
76b6d9
diff --git a/malloc/malloc.c b/malloc/malloc.c
76b6d9
index 5b87bdb081..ec2d934595 100644
76b6d9
--- a/malloc/malloc.c
76b6d9
+++ b/malloc/malloc.c
76b6d9
@@ -4224,11 +4224,14 @@ _int_free (mstate av, mchunkptr p, int have_lock)
76b6d9
 	if (__glibc_unlikely (e->key == tcache))
76b6d9
 	  {
76b6d9
 	    tcache_entry *tmp;
76b6d9
+	    size_t cnt = 0;
76b6d9
 	    LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
76b6d9
 	    for (tmp = tcache->entries[tc_idx];
76b6d9
 		 tmp;
76b6d9
-		 tmp = REVEAL_PTR (tmp->next))
76b6d9
+		 tmp = REVEAL_PTR (tmp->next), ++cnt)
76b6d9
 	      {
76b6d9
+		if (cnt >= mp_.tcache_count)
76b6d9
+		  malloc_printerr ("free(): too many chunks detected in tcache");
76b6d9
 		if (__glibc_unlikely (!aligned_OK (tmp)))
76b6d9
 		  malloc_printerr ("free(): unaligned chunk detected in tcache 2");
76b6d9
 		if (tmp == e)