Skip site navigation (1)Skip section navigation (2)
Date:      Wed, 21 Jul 2021 15:32:28 GMT
From:      Alexander Motin <mav@FreeBSD.org>
To:        src-committers@FreeBSD.org, dev-commits-src-all@FreeBSD.org, dev-commits-src-main@FreeBSD.org
Subject:   git: 3a57f08b5042 - main - Fix race between first rand(3) calls with _once().
Message-ID:  <202107211532.16LFWS55025500@gitrepo.freebsd.org>

next in thread | raw e-mail | index | archive | help
The branch main has been updated by mav:

URL: https://cgit.FreeBSD.org/src/commit/?id=3a57f08b5042f15bb8ffb2fcce99d082d225d4cf

commit 3a57f08b5042f15bb8ffb2fcce99d082d225d4cf
Author:     Alexander Motin <mav@FreeBSD.org>
AuthorDate: 2021-07-21 15:25:46 +0000
Commit:     Alexander Motin <mav@FreeBSD.org>
CommitDate: 2021-07-21 15:32:22 +0000

    Fix race between first rand(3) calls with _once().
    
    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.
    
    Submitted by:   avg@
    MFC after:      1 month
---
 lib/libc/stdlib/rand.c | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/lib/libc/stdlib/rand.c b/lib/libc/stdlib/rand.c
index bddb0f040302..e448d1b1fd14 100644
--- a/lib/libc/stdlib/rand.c
+++ b/lib/libc/stdlib/rand.c
@@ -41,11 +41,13 @@ __FBSDID("$FreeBSD$");
 #include <sys/param.h>
 #include <sys/sysctl.h>
 #include <assert.h>
+#include <pthread.h>
 #include <stdbool.h>
 #include <stdlib.h>
 #include <syslog.h>
 #include "un-namespace.h"
 
+#include "libc_private.h"
 #include "random.h"
 
 /*
@@ -64,6 +66,7 @@ __FBSDID("$FreeBSD$");
  * the advantage of being the one already in the tree.
  */
 static struct __random_state *rand3_state;
+static pthread_once_t rand3_state_once = PTHREAD_ONCE_INIT;
 
 static void
 initialize_rand3(void)
@@ -78,16 +81,14 @@ initialize_rand3(void)
 int
 rand(void)
 {
-	if (rand3_state == NULL)
-		initialize_rand3();
+	_once(&rand3_state_once, initialize_rand3);
 	return ((int)random_r(rand3_state));
 }
 
 void
 srand(unsigned seed)
 {
-	if (rand3_state == NULL)
-		initialize_rand3();
+	_once(&rand3_state_once, initialize_rand3);
 	srandom_r(rand3_state, seed);
 }
 



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?202107211532.16LFWS55025500>