OpenTTD Source 20261112-master-gbcbec5e63f
random_func.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "../stdafx.h"
11#include "random_func.hpp"
12#include "../debug.h"
13
14#ifdef RANDOM_DEBUG
15#include "../network/network.h"
18#include "../company_func.h"
20#endif /* RANDOM_DEBUG */
21
22#if defined(_WIN32)
23# include <windows.h>
24# include <bcrypt.h>
25#elif defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__)
26/* No includes required. */
27#elif defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 25)))
28# include <sys/random.h>
29#elif defined(__EMSCRIPTEN__)
30# include <emscripten.h>
31#endif
32
33#include "../safeguards.h"
34
36
42{
43 const uint32_t s = this->state[0];
44 const uint32_t t = this->state[1];
45
46 this->state[0] = s + std::rotr(t ^ 0x1234567F, 7) + 1;
47 return this->state[1] = std::rotr(s, 3) - 1;
48}
49
54void Randomizer::SetSeed(uint32_t seed)
55{
56 this->state[0] = seed;
57 this->state[1] = seed;
58}
59
64void SetRandomSeed(uint32_t seed)
65{
66 _random.SetSeed(seed);
67 _interactive_random.SetSeed(seed * 0x1234567);
68}
69
70#ifdef RANDOM_DEBUG
71uint32_t Random(const std::source_location location)
72{
73 if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::ClientStatus::Inactive))) {
74 Debug(Facility::Random, Severity::Critical, "{:08x}; {:02x}; {:04x}; {:02x}; {}:{}", TimerGameEconomy::date, TimerGameEconomy::date_fract, _frame_counter, _current_company, location.file_name(), location.line());
75 }
76
77 return _random.Next();
78}
79#endif /* RANDOM_DEBUG */
80
93void RandomBytesWithFallback(std::span<uint8_t> buf)
94{
95#if defined(_WIN32)
96 auto res = BCryptGenRandom(nullptr, static_cast<PUCHAR>(buf.data()), static_cast<ULONG>(buf.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG);
97 if (res >= 0) return;
98#elif defined(__APPLE__) || defined(__NetBSD__) || defined(__FreeBSD__) || defined(__OpenBSD__)
99 arc4random_buf(buf.data(), buf.size());
100 return;
101#elif defined(__GLIBC__) && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 25)))
102 auto res = getrandom(buf.data(), buf.size(), 0);
103 if (res > 0 && static_cast<size_t>(res) == buf.size()) return;
104#elif defined(__EMSCRIPTEN__)
105 auto res = EM_ASM_INT({
106 var buf = $0;
107 var bytes = $1;
108
109 var crypto = window.crypto;
110 if (crypto === undefined || crypto.getRandomValues === undefined) {
111 return -1;
112 }
113
114 crypto.getRandomValues(Module.HEAPU8.subarray(buf, buf + bytes));
115 return 1;
116 }, buf.data(), buf.size());
117 if (res > 0) return;
118#else
119# warning "No cryptographically-strong random generator available; using a fallback instead"
120#endif
121
122 static Severity severity = Severity::Critical;
123 Debug(Facility::Misc, severity, "Cryptographically-strong random generator unavailable; using fallback");
124 severity = Severity::Error;
125
126 for (uint i = 0; i < buf.size(); i++) {
127 buf[i] = static_cast<uint8_t>(InteractiveRandom());
128 }
129}
static Date date
Current date in days (day counter).
static DateFract date_fract
Fractional part of the day.
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
Functions related to debugging.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Random
Random message facility.
Definition debug_type.h:43
@ Misc
Misc message facility.
Definition debug_type.h:32
Severity
Debug message severity levels.
Definition debug_type.h:14
@ Critical
Critical, user should know about this.
Definition debug_type.h:15
@ Error
Error, but we are recovering.
Definition debug_type.h:16
uint32_t _frame_counter
The current frame.
Definition network.cpp:76
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_server
network-server is active
Definition network.cpp:64
Basic functions/variables used all over the place.
Variables and function used internally.
Server part of the network protocol.
Randomizer _random
Random used in the game state calculations.
void RandomBytesWithFallback(std::span< uint8_t > buf)
Fill the given buffer with random bytes.
Randomizer _interactive_random
Random used everywhere else, where it does not (directly) influence the game state.
void SetRandomSeed(uint32_t seed)
(Re)set the state of the random number generators.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
Definition of base types and functions in a cross-platform compatible way.
Structure to encapsulate the pseudo random number generators.
void SetSeed(uint32_t seed)
(Re)set the state of the random number generator.
uint32_t state[2]
The state of the randomizer.
uint32_t Next()
Generate the next pseudo random number.
Definition of the game-economy-timer.