From f685123e5f8e7c84648b2de810ba20e85b7d1504 Mon Sep 17 00:00:00 2001
From: Yuzhuo Jing <yzjing@jhu.edu>
Date: Sat, 29 May 2021 12:05:16 -0700
Subject: [PATCH] random: Fix behavior of kernel option "-rs".
MIME-Version: 1.0
Content-Type: text/plain; charset=utf8
Content-Transfer-Encoding: 8bit

In init.c at line 275:
  random_init (rtc_get_time ());

The comments claim that "This has no effect if an "-rs" option was
specified." However, this line actually overrides the initialization at
“-rs”.

To see the effect, we can try generating some random bytes after parsing
the arguments. Apply the patch file randprint.patch, I get the following
group of output w/ and w/o "-rs", and w/ and w/o simulator RTC:

Kernel command line: -q
Unix epoch is 9
 10 c4 c3 f4 1a 18 b0 cb 5f 2a 4d d5 d8 73 42 66

Kernel command line: -q -rs=1
Unix epoch is 9
 10 c4 c3 f4 1a 18 b0 cb 5f 2a 4d d5 d8 73 42 66

Kernel command line: -q -rs=1
Unix epoch is 1621759823
 60 4a 91 29 c3 d4 f5 16 96 7e c8 05 37 6f 79 4e

Kernel command line: -q -rs=1
Unix epoch is 1621759824
 c1 ac a2 a1 3c e7 83 a3 31 a9 31 3f 2d 1c fa f9

Expected output is that the last three ones has the same output, and
they should differ from the first output.

This commit fixes the problem. We check `inited` variable at the
beginning of the random_init function.

New output:

Kernel command line: -q
Unix epoch is 9
 10 c4 c3 f4 1a 18 b0 cb 5f 2a 4d d5 d8 73 42 66

Kernel command line: -q -rs=1
Unix epoch is 9
 01 48 10 d0 18 1c 6a 43 a4 19 73 08 d7 cc d3 39

Kernel command line: -q -rs=1
Unix epoch is 1621760373
 01 48 10 d0 18 1c 6a 43 a4 19 73 08 d7 cc d3 39

Kernel command line: -q -rs=1
Unix epoch is 1621760377
 01 48 10 d0 18 1c 6a 43 a4 19 73 08 d7 cc d3 39
---
 src/lib/random.c | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/src/lib/random.c b/src/lib/random.c
index a4761b6..6a963e2 100644
--- a/src/lib/random.c
+++ b/src/lib/random.c
@@ -37,6 +37,9 @@ random_init (unsigned seed)
   int i;
   uint8_t j;
 
+  if (inited)
+    return;
+
   for (i = 0; i < 256; i++) 
     s[i] = i;
   for (i = j = 0; i < 256; i++) 
-- 
2.30.2