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