aboutsummaryrefslogtreecommitdiff
path: root/lib/libc
diff options
context:
space:
mode:
authorAlexander Motin <mav@FreeBSD.org>2021-07-20 17:15:08 +0000
committerAlexander Motin <mav@FreeBSD.org>2021-07-20 17:30:28 +0000
commit28d70deaafa62c5d1602de5272c0aad0fcca8aff (patch)
tree62088f6d9989f20fa730684edec255c76f86e66f /lib/libc
parent5a9e5a5111af59dbc96383fcd73129e31648e017 (diff)
downloadsrc-28d70deaafa62c5d1602de5272c0aad0fcca8aff.tar.gz
src-28d70deaafa62c5d1602de5272c0aad0fcca8aff.zip
Fix race between first rand(3) calls.
Before this patch there was a chance for thread that called rand(3) slightly later to see rand3_state already allocated, but not yet initialized. While this API is not expected to be thread-safe, it is not expected to crash. ztest on 64-thread system reproduced it reliably for me. MFC after: 1 month
Diffstat (limited to 'lib/libc')
-rw-r--r--lib/libc/stdlib/rand.c9
1 files changed, 7 insertions, 2 deletions
diff --git a/lib/libc/stdlib/rand.c b/lib/libc/stdlib/rand.c
index bddb0f040302..353f59349e1d 100644
--- a/lib/libc/stdlib/rand.c
+++ b/lib/libc/stdlib/rand.c
@@ -44,6 +44,7 @@ __FBSDID("$FreeBSD$");
#include <stdbool.h>
#include <stdlib.h>
#include <syslog.h>
+#include <machine/atomic.h>
#include "un-namespace.h"
#include "random.h"
@@ -68,11 +69,15 @@ static struct __random_state *rand3_state;
static void
initialize_rand3(void)
{
+ struct __random_state *state;
int error;
- rand3_state = allocatestate(TYPE_3);
- error = initstate_r(rand3_state, 1, rand3_state->rst_randtbl, BREAK_3);
+ state = allocatestate(TYPE_3);
+ error = initstate_r(state, 1, state->rst_randtbl, BREAK_3);
assert(error == 0);
+ if (!atomic_cmpset_rel_ptr((volatile uintptr_t *)&rand3_state,
+ (uintptr_t)NULL, (uintptr_t)state))
+ free(state);
}
int