From d5c1bca9153d8f4a548eb3552ae20d9c8322e373 Mon Sep 17 00:00:00 2001 From: Daniel Micay Date: Tue, 9 Apr 2019 16:36:01 -0400 Subject: [PATCH] use round-robin assignment to arenas The initial implementation was a temporary hack rather than a serious implementation of random arena selection. It may still make sense to offer it but it should be implemented via the CSPRNG instead of this silly hack. It would also make sense to offer dynamic load balancing, particularly with sched_getcpu(). This results in a much more predictable spread across arenas. This is one place where randomization probably isn't a great idea because it makes the benefits of arenas unpredictable in programs not creating a massive number of threads. The security benefits of randomization for this are also quite small. It's not certain that randomization is even a net win for security since it's not random enough and can result in a more interesting mix of threads in the same arena for an attacker if they're able to attempt multiple attacks. --- h_malloc.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/h_malloc.c b/h_malloc.c index b35330c..dfedd0c 100644 --- a/h_malloc.c +++ b/h_malloc.c @@ -56,6 +56,7 @@ static_assert(N_ARENA <= 4, "currently only support up to 4 arenas (as an initia #if N_ARENA > 1 __attribute__((tls_model("initial-exec"))) static thread_local unsigned thread_arena = N_ARENA; +static _Atomic unsigned thread_arena_counter = 0; #else static const unsigned thread_arena = 0; #endif @@ -469,7 +470,7 @@ static inline void *allocate_small(size_t requested_size) { #if N_ARENA > 1 if (unlikely(thread_arena == N_ARENA)) { - thread_arena = hash_page(&thread_arena) % N_ARENA; + thread_arena = thread_arena_counter++ % N_ARENA; } #endif