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