1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-25 20:27:45 +00:00

Kernel: Add a more expressive API for getting random bytes

We now have these API's in <Kernel/Random.h>:

    - get_fast_random_bytes(u8* buffer, size_t buffer_size)
    - get_good_random_bytes(u8* buffer, size_t buffer_size)
    - get_fast_random<T>()
    - get_good_random<T>()

Internally they both use x86 RDRAND if available, otherwise they fall
back to the same LCG we had in RandomDevice all along.

The main purpose of this patch is to give kernel code a way to better
express its needs for random data.

Randomness is something that will require a lot more work, but this is
hopefully a step in the right direction.
This commit is contained in:
Andreas Kling 2020-01-03 12:36:30 +01:00
parent 24cc67d199
commit 9026598999
11 changed files with 87 additions and 48 deletions

View file

@ -31,6 +31,7 @@
#include <Kernel/ProcessTracer.h>
#include <Kernel/Profiling.h>
#include <Kernel/RTC.h>
#include <Kernel/Random.h>
#include <Kernel/Scheduler.h>
#include <Kernel/SharedBuffer.h>
#include <Kernel/StdLib.h>
@ -3612,25 +3613,7 @@ int Process::sys$getrandom(void* buffer, size_t buffer_size, unsigned int flags
if (!validate_write(buffer, buffer_size))
return -EFAULT;
// We prefer to get whole words of entropy.
// If the length is unaligned, we can work with bytes instead.
// Mask out the bottom two bits for words.
size_t words_len = buffer_size & ~3;
if (words_len) {
uint32_t* words = (uint32_t*)buffer;
for (size_t i = 0; i < words_len / 4; i++)
words[i] = RandomDevice::random_value();
}
// The remaining non-whole word bytes we can fill in.
size_t bytes_len = buffer_size & 3;
if (bytes_len) {
uint8_t* bytes = (uint8_t*)buffer + words_len;
// Get a whole word of entropy to use.
uint32_t word = RandomDevice::random_value();
for (size_t i = 0; i < bytes_len; i++)
bytes[i] = ((uint8_t*)&word)[i];
}
get_good_random_bytes((u8*)buffer, buffer_size);
return 0;
}