2019-12-10 07:50:47 +00:00
|
|
|
/*
|
2021-10-04 19:59:10 +00:00
|
|
|
* Copyright (c) Atmosphère-NX
|
2019-12-10 07:50:47 +00:00
|
|
|
*
|
|
|
|
* This program is free software; you can redistribute it and/or modify it
|
|
|
|
* under the terms and conditions of the GNU General Public License,
|
|
|
|
* version 2, as published by the Free Software Foundation.
|
|
|
|
*
|
|
|
|
* This program is distributed in the hope it will be useful, but WITHOUT
|
|
|
|
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
|
|
|
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
|
|
|
|
* more details.
|
|
|
|
*
|
|
|
|
* You should have received a copy of the GNU General Public License
|
|
|
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
*/
|
|
|
|
#include <stratosphere.hpp>
|
|
|
|
#include "impl/os_random_impl.hpp"
|
|
|
|
|
|
|
|
namespace ams::os {
|
|
|
|
|
|
|
|
namespace {
|
|
|
|
|
2021-10-23 22:25:20 +00:00
|
|
|
constinit util::TinyMT g_random{util::ConstantInitialize};
|
2021-05-02 17:33:15 +00:00
|
|
|
constinit os::SdkMutex g_random_mutex;
|
|
|
|
constinit bool g_initialized_random;
|
2019-12-10 07:50:47 +00:00
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
inline T GenerateRandomTImpl(T max) {
|
|
|
|
static_assert(std::is_integral<T>::value && std::is_unsigned<T>::value);
|
|
|
|
const T EffectiveMax = (std::numeric_limits<T>::max() / max) * max;
|
|
|
|
T cur_rnd;
|
|
|
|
while (true) {
|
2021-10-09 21:49:53 +00:00
|
|
|
os::GenerateRandomBytes(std::addressof(cur_rnd), sizeof(T));
|
2019-12-10 07:50:47 +00:00
|
|
|
if (cur_rnd < EffectiveMax) {
|
|
|
|
return cur_rnd % max;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
void GenerateRandomBytes(void *dst, size_t size) {
|
|
|
|
std::scoped_lock lk(g_random_mutex);
|
|
|
|
|
2020-03-16 20:08:20 +00:00
|
|
|
if (AMS_UNLIKELY(!g_initialized_random)) {
|
2021-10-09 21:49:53 +00:00
|
|
|
impl::InitializeRandomImpl(std::addressof(g_random));
|
2019-12-10 07:50:47 +00:00
|
|
|
g_initialized_random = true;
|
|
|
|
}
|
|
|
|
|
|
|
|
g_random.GenerateRandomBytes(dst, size);
|
|
|
|
}
|
|
|
|
|
|
|
|
u32 GenerateRandomU32(u32 max) {
|
|
|
|
return GenerateRandomTImpl<u32>(max);
|
|
|
|
}
|
|
|
|
|
|
|
|
u64 GenerateRandomU64(u64 max) {
|
|
|
|
return GenerateRandomTImpl<u64>(max);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|