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