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