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