be0c12
From 58cdc09af08e065c85b2f8834ee9848c010f5afe Mon Sep 17 00:00:00 2001
be0c12
From: Yu Watanabe <watanabe.yu+github@gmail.com>
be0c12
Date: Mon, 16 Dec 2019 19:47:48 +0900
be0c12
Subject: [PATCH] random-util: call initialize_srand() after fork()
be0c12
be0c12
(cherry picked from commit a0f11d1d11a546f791855ec9c47c2ff830e6a5aa)
be0c12
be0c12
Related: #2005008
be0c12
---
be0c12
 src/basic/random-util.c | 14 +++++++++++++-
be0c12
 1 file changed, 13 insertions(+), 1 deletion(-)
be0c12
be0c12
diff --git a/src/basic/random-util.c b/src/basic/random-util.c
be0c12
index 91481559db..801f6ad131 100644
be0c12
--- a/src/basic/random-util.c
be0c12
+++ b/src/basic/random-util.c
be0c12
@@ -4,6 +4,7 @@
be0c12
 #include <errno.h>
be0c12
 #include <fcntl.h>
be0c12
 #include <linux/random.h>
be0c12
+#include <pthread.h>
be0c12
 #include <stdbool.h>
be0c12
 #include <stdint.h>
be0c12
 #include <stdlib.h>
be0c12
@@ -26,6 +27,8 @@
be0c12
 #include "random-util.h"
be0c12
 #include "time-util.h"
be0c12
 
be0c12
+static bool srand_called = false;
be0c12
+
be0c12
 int acquire_random_bytes(void *p, size_t n, bool high_quality_required) {
be0c12
         static int have_syscall = -1;
be0c12
 
be0c12
@@ -81,8 +84,12 @@ int acquire_random_bytes(void *p, size_t n, bool high_quality_required) {
be0c12
         return loop_read_exact(fd, (uint8_t*) p + already_done, n - already_done, true);
be0c12
 }
be0c12
 
be0c12
+static void clear_srand_initialization(void) {
be0c12
+        srand_called = false;
be0c12
+}
be0c12
+
be0c12
 void initialize_srand(void) {
be0c12
-        static bool srand_called = false;
be0c12
+        static bool pthread_atfork_registered = false;
be0c12
         unsigned x;
be0c12
 #if HAVE_SYS_AUXV_H
be0c12
         void *auxv;
be0c12
@@ -109,6 +116,11 @@ void initialize_srand(void) {
be0c12
 
be0c12
         srand(x);
be0c12
         srand_called = true;
be0c12
+
be0c12
+        if (!pthread_atfork_registered) {
be0c12
+                (void) pthread_atfork(NULL, NULL, clear_srand_initialization);
be0c12
+                pthread_atfork_registered = true;
be0c12
+        }
be0c12
 }
be0c12
 
be0c12
 /* INT_MAX gives us only 31 bits, so use 24 out of that. */