2020-05-27 13:25:46 +03:00
|
|
|
/*
|
|
|
|
* Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
|
|
|
|
*
|
2021-04-22 11:24:48 +03:00
|
|
|
* SPDX-License-Identifier: BSD-2-Clause
|
2020-05-27 13:25:46 +03:00
|
|
|
*/
|
|
|
|
|
|
|
|
#pragma once
|
|
|
|
|
|
|
|
#include <AK/Platform.h>
|
|
|
|
#include <AK/Types.h>
|
|
|
|
|
2022-10-10 00:23:23 +03:00
|
|
|
#if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID)
|
2020-05-27 13:25:46 +03:00
|
|
|
# include <stdlib.h>
|
|
|
|
#endif
|
|
|
|
|
2020-10-17 23:25:13 +03:00
|
|
|
#if defined(__unix__)
|
2020-05-27 13:25:46 +03:00
|
|
|
# include <unistd.h>
|
|
|
|
#endif
|
|
|
|
|
2021-09-12 19:06:33 +03:00
|
|
|
#if defined(AK_OS_MACOS)
|
2020-05-29 23:22:01 +03:00
|
|
|
# include <sys/random.h>
|
|
|
|
#endif
|
|
|
|
|
2022-09-20 10:15:12 +03:00
|
|
|
#if defined(AK_OS_WINDOWS)
|
|
|
|
# include <random>
|
|
|
|
# include <unistd.h>
|
|
|
|
#endif
|
|
|
|
|
2020-05-27 13:25:46 +03:00
|
|
|
namespace AK {
|
|
|
|
|
2020-12-21 02:09:48 +03:00
|
|
|
inline void fill_with_random([[maybe_unused]] void* buffer, [[maybe_unused]] size_t length)
|
2020-05-27 13:25:46 +03:00
|
|
|
{
|
2022-10-10 00:23:23 +03:00
|
|
|
#if defined(AK_OS_SERENITY) || defined(AK_OS_ANDROID)
|
2020-05-27 13:25:46 +03:00
|
|
|
arc4random_buf(buffer, length);
|
2020-11-28 01:57:02 +03:00
|
|
|
#elif defined(OSS_FUZZ)
|
2021-09-12 19:06:33 +03:00
|
|
|
#elif defined(__unix__) or defined(AK_OS_MACOS)
|
2020-12-21 02:09:48 +03:00
|
|
|
[[maybe_unused]] int rc = getentropy(buffer, length);
|
2022-09-20 10:15:12 +03:00
|
|
|
#else
|
|
|
|
char* char_buffer = static_cast<char*>(buffer);
|
|
|
|
for (size_t i = 0; i < length; i++) {
|
|
|
|
char_buffer[i] = std::rand();
|
|
|
|
}
|
2020-05-27 13:25:46 +03:00
|
|
|
#endif
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
inline T get_random()
|
|
|
|
{
|
|
|
|
T t;
|
|
|
|
fill_with_random(&t, sizeof(T));
|
|
|
|
return t;
|
|
|
|
}
|
|
|
|
|
2021-05-14 18:16:06 +03:00
|
|
|
u32 get_random_uniform(u32 max_bounds);
|
|
|
|
|
2020-05-27 13:25:46 +03:00
|
|
|
}
|
2020-10-16 22:59:53 +03:00
|
|
|
|
2022-11-26 14:18:30 +03:00
|
|
|
#if USING_AK_GLOBALLY
|
2020-10-16 22:59:53 +03:00
|
|
|
using AK::fill_with_random;
|
|
|
|
using AK::get_random;
|
2021-05-14 18:16:06 +03:00
|
|
|
using AK::get_random_uniform;
|
2022-11-26 14:18:30 +03:00
|
|
|
#endif
|