d8307d
commit affec03b713c82c43a5b025dddc21bde3334f41e
d8307d
Author: Florian Weimer <fweimer@redhat.com>
d8307d
Date:   Mon Nov 26 20:06:37 2018 +0100
d8307d
d8307d
    malloc: tcache: Validate tc_idx before checking for double-frees [BZ #23907]
d8307d
    
d8307d
    The previous check could read beyond the end of the tcache entry
d8307d
    array.  If the e->key == tcache cookie check happened to pass, this
d8307d
    would result in crashes.
d8307d
d8307d
diff --git a/malloc/malloc.c b/malloc/malloc.c
d8307d
index c6b0282e783eaeea..13c52f376859562d 100644
d8307d
--- a/malloc/malloc.c
d8307d
+++ b/malloc/malloc.c
d8307d
@@ -4159,33 +4159,33 @@ _int_free (mstate av, mchunkptr p, int have_lock)
d8307d
 #if USE_TCACHE
d8307d
   {
d8307d
     size_t tc_idx = csize2tidx (size);
d8307d
-
d8307d
-    /* Check to see if it's already in the tcache.  */
d8307d
-    tcache_entry *e = (tcache_entry *) chunk2mem (p);
d8307d
-
d8307d
-    /* This test succeeds on double free.  However, we don't 100%
d8307d
-       trust it (it also matches random payload data at a 1 in
d8307d
-       2^<size_t> chance), so verify it's not an unlikely coincidence
d8307d
-       before aborting.  */
d8307d
-    if (__glibc_unlikely (e->key == tcache && tcache))
d8307d
+    if (tcache != NULL && tc_idx < mp_.tcache_bins)
d8307d
       {
d8307d
-	tcache_entry *tmp;
d8307d
-	LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
d8307d
-	for (tmp = tcache->entries[tc_idx];
d8307d
-	     tmp;
d8307d
-	     tmp = tmp->next)
d8307d
-	  if (tmp == e)
d8307d
-	    malloc_printerr ("free(): double free detected in tcache 2");
d8307d
-	/* If we get here, it was a coincidence.  We've wasted a few
d8307d
-	   cycles, but don't abort.  */
d8307d
-      }
d8307d
+	/* Check to see if it's already in the tcache.  */
d8307d
+	tcache_entry *e = (tcache_entry *) chunk2mem (p);
d8307d
+
d8307d
+	/* This test succeeds on double free.  However, we don't 100%
d8307d
+	   trust it (it also matches random payload data at a 1 in
d8307d
+	   2^<size_t> chance), so verify it's not an unlikely
d8307d
+	   coincidence before aborting.  */
d8307d
+	if (__glibc_unlikely (e->key == tcache))
d8307d
+	  {
d8307d
+	    tcache_entry *tmp;
d8307d
+	    LIBC_PROBE (memory_tcache_double_free, 2, e, tc_idx);
d8307d
+	    for (tmp = tcache->entries[tc_idx];
d8307d
+		 tmp;
d8307d
+		 tmp = tmp->next)
d8307d
+	      if (tmp == e)
d8307d
+		malloc_printerr ("free(): double free detected in tcache 2");
d8307d
+	    /* If we get here, it was a coincidence.  We've wasted a
d8307d
+	       few cycles, but don't abort.  */
d8307d
+	  }
d8307d
 
d8307d
-    if (tcache
d8307d
-	&& tc_idx < mp_.tcache_bins
d8307d
-	&& tcache->counts[tc_idx] < mp_.tcache_count)
d8307d
-      {
d8307d
-	tcache_put (p, tc_idx);
d8307d
-	return;
d8307d
+	if (tcache->counts[tc_idx] < mp_.tcache_count)
d8307d
+	  {
d8307d
+	    tcache_put (p, tc_idx);
d8307d
+	    return;
d8307d
+	  }
d8307d
       }
d8307d
   }
d8307d
 #endif