8a8cfb
commit 58d2672f64176fcb323859d3bd5240fb1cf8f25c
8a8cfb
Author: Wilco Dijkstra <wdijkstr@arm.com>
8a8cfb
Date:   Fri May 10 16:38:21 2019 +0100
8a8cfb
8a8cfb
    Fix tcache count maximum (BZ #24531)
8a8cfb
    
8a8cfb
    The tcache counts[] array is a char, which has a very small range and thus
8a8cfb
    may overflow.  When setting tcache_count tunable, there is no overflow check.
8a8cfb
    However the tunable must not be larger than the maximum value of the tcache
8a8cfb
    counts[] array, otherwise it can overflow when filling the tcache.
8a8cfb
    
8a8cfb
            [BZ #24531]
8a8cfb
            * malloc/malloc.c (MAX_TCACHE_COUNT): New define.
8a8cfb
            (do_set_tcache_count): Only update if count is small enough.
8a8cfb
            * manual/tunables.texi (glibc.malloc.tcache_count): Document max value.
8a8cfb
    
8a8cfb
    (cherry picked from commit 5ad533e8e65092be962e414e0417112c65d154fb)
8a8cfb
8a8cfb
diff --git a/malloc/malloc.c b/malloc/malloc.c
8a8cfb
index 723d393f529bdb4c..92239b3324584060 100644
8a8cfb
--- a/malloc/malloc.c
8a8cfb
+++ b/malloc/malloc.c
8a8cfb
@@ -2919,6 +2919,8 @@ typedef struct tcache_perthread_struct
8a8cfb
   tcache_entry *entries[TCACHE_MAX_BINS];
8a8cfb
 } tcache_perthread_struct;
8a8cfb
 
8a8cfb
+#define MAX_TCACHE_COUNT 127	/* Maximum value of counts[] entries.  */
8a8cfb
+
8a8cfb
 static __thread bool tcache_shutting_down = false;
8a8cfb
 static __thread tcache_perthread_struct *tcache = NULL;
8a8cfb
 
8a8cfb
@@ -5124,8 +5126,11 @@ static inline int
8a8cfb
 __always_inline
8a8cfb
 do_set_tcache_count (size_t value)
8a8cfb
 {
8a8cfb
-  LIBC_PROBE (memory_tunable_tcache_count, 2, value, mp_.tcache_count);
8a8cfb
-  mp_.tcache_count = value;
8a8cfb
+  if (value <= MAX_TCACHE_COUNT)
8a8cfb
+    {
8a8cfb
+      LIBC_PROBE (memory_tunable_tcache_count, 2, value, mp_.tcache_count);
8a8cfb
+      mp_.tcache_count = value;
8a8cfb
+    }
8a8cfb
   return 1;
8a8cfb
 }
8a8cfb
 
8a8cfb
diff --git a/manual/tunables.texi b/manual/tunables.texi
8a8cfb
index bb4819bdf1de273e..9dccf2ee7f8eec17 100644
8a8cfb
--- a/manual/tunables.texi
8a8cfb
+++ b/manual/tunables.texi
8a8cfb
@@ -188,8 +188,8 @@ per-thread cache.  The default (and maximum) value is 1032 bytes on
8a8cfb
 
8a8cfb
 @deftp Tunable glibc.malloc.tcache_count
8a8cfb
 The maximum number of chunks of each size to cache. The default is 7.
8a8cfb
-There is no upper limit, other than available system memory.  If set
8a8cfb
-to zero, the per-thread cache is effectively disabled.
8a8cfb
+The upper limit is 127.  If set to zero, the per-thread cache is effectively
8a8cfb
+disabled.
8a8cfb
 
8a8cfb
 The approximate maximum overhead of the per-thread cache is thus equal
8a8cfb
 to the number of bins times the chunk count in each bin times the size