[PATCH v2 04/14] KVM: selftests: Reproduce tests that rely on randomization

Josh Hilke
2026-03-31T19:41:30Z

Seed srand() using the KVM_RANDOM_SEED environment variable during
selftest initialization. If KVM_RANDOM_SEED is not set, seed srand()
using the current time. In order to reproduce a test that relies on
values that are set using rand(), the test must not call srand(), as
this will override the call to srand() during test initialization.

To test this, run a selftest:
$ ./selftest

The first line of test output should look like:
Guest random seed: <guest_seed> (srand: <seed>)

Then to reproduce, run:
$ KVM_RANDOM_SEED=<seed> ./selftest

The test output should show the same value for the `srand` seed.

Signed-off-by: Josh Hilke <jrhilke@google.com>
---
tools/testing/selftests/kvm/lib/kvm_util.c | 11 ++++++++++-
1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/tools/testing/selftests/kvm/lib/kvm_util.c b/tools/testing/selftests/kvm/lib/kvm_util.c
index 1959bf556e88..63c882b5f743 100644
--- a/tools/testing/selftests/kvm/lib/kvm_util.c
+++ b/tools/testing/selftests/kvm/lib/kvm_util.c
@@ -2349,6 +2349,8 @@ void __attribute((constructor)) kvm_selftest_init(void)
struct sigaction sig_sa = {
.sa_handler = report_unexpected_signal,
};
+ char *env_seed = getenv("KVM_RANDOM_SEED");
+ int random_seed;

/* Tell stdout not to buffer its content. */
setbuf(stdout, NULL);
@@ -2358,8 +2360,15 @@ void __attribute((constructor)) kvm_selftest_init(void)
sigaction(SIGILL, &sig_sa, NULL);
sigaction(SIGFPE, &sig_sa, NULL);

+ if (env_seed)
+ random_seed = strtol(env_seed, NULL, 0);
+ else
+ random_seed = time(NULL);
+
+ srand(random_seed);
guest_random_seed = last_guest_seed = random();
- pr_info("Random seed: 0x%x\n", guest_random_seed);
+ pr_info("Guest random seed: 0x%x (srand: 0x%x)\n",
+ guest_random_seed, random_seed);

kvm_selftest_arch_init();
}
--
2.53.0.1118.gaef5881109-goog