From b3407f04e7a98f2c24feb03ec436f3f3f80a5dea Mon Sep 17 00:00:00 2001 From: Alberto Escolar Piedras Date: Mon, 30 Dec 2024 10:26:20 +0100 Subject: [PATCH] drivers: entropy: fix native_posix driver for more than 3 byte requests Fix the native_posix fake entropy driver for more than 3 byte requests, and specially for native_sim//64 builds. The host random() provides a number between 0 and 2**31-1 (INT_MAX), so bit 32 was always 0. So when filling a buffer with more than 3 bytes we would be filling each 4th byte with a byte which always had its MSbit as 0. For LP64 native_sim//64 builds, this was even worse, as the driver had another bug where we assumed random() returned the whole long filled, and therefore all 4 upper bytes would be 0. Signed-off-by: Alberto Escolar Piedras --- drivers/entropy/fake_entropy_native_posix.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/drivers/entropy/fake_entropy_native_posix.c b/drivers/entropy/fake_entropy_native_posix.c index 1b7e457fca6..04f25b2e62d 100644 --- a/drivers/entropy/fake_entropy_native_posix.c +++ b/drivers/entropy/fake_entropy_native_posix.c @@ -42,7 +42,10 @@ static int entropy_native_posix_get_entropy(const struct device *dev, */ long value = nsi_host_random(); - size_t to_copy = MIN(length, sizeof(long int)); + /* The host random() provides a number between 0 and 2**31-1. Bit 32 is always 0. + * So let's just use the lower 3 bytes discarding the upper 7 bits + */ + size_t to_copy = MIN(length, 3); memcpy(buffer, &value, to_copy); buffer += to_copy;