1/****************************************************************************
2**
3** Copyright (C) 2019 Intel Corporation.
4** Contact: https://www.qt.io/licensing/
5**
6** This file is part of the QtCore module of the Qt Toolkit.
7**
8** $QT_BEGIN_LICENSE:LGPL$
9** Commercial License Usage
10** Licensees holding valid commercial Qt licenses may use this file in
11** accordance with the commercial license agreement provided with the
12** Software or, alternatively, in accordance with the terms contained in
13** a written agreement between you and The Qt Company. For licensing terms
14** and conditions see https://www.qt.io/terms-conditions. For further
15** information use the contact form at https://www.qt.io/contact-us.
16**
17** GNU Lesser General Public License Usage
18** Alternatively, this file may be used under the terms of the GNU Lesser
19** General Public License version 3 as published by the Free Software
20** Foundation and appearing in the file LICENSE.LGPL3 included in the
21** packaging of this file. Please review the following information to
22** ensure the GNU Lesser General Public License version 3 requirements
23** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
24**
25** GNU General Public License Usage
26** Alternatively, this file may be used under the terms of the GNU
27** General Public License version 2.0 or (at your option) the GNU General
28** Public license version 3 or any later version approved by the KDE Free
29** Qt Foundation. The licenses are as published by the Free Software
30** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
31** included in the packaging of this file. Please review the following
32** information to ensure the GNU General Public License requirements will
33** be met: https://www.gnu.org/licenses/gpl-2.0.html and
34** https://www.gnu.org/licenses/gpl-3.0.html.
35**
36** $QT_END_LICENSE$
37**
38****************************************************************************/
39
40// for rand_s
41#define _CRT_RAND_S
42
43#include "qrandom.h"
44#include "qrandom_p.h"
45#include <qobjectdefs.h>
46#include <qmutex.h>
47#include <qthreadstorage.h>
48
49#include <errno.h>
50
51#if !QT_CONFIG(getentropy) && (!defined(Q_OS_BSD4) || defined(__GLIBC__)) && !defined(Q_OS_WIN)
52# include "qdeadlinetimer.h"
53# include "qhashfunctions.h"
54
55# if QT_CONFIG(getauxval)
56# include <sys/auxv.h>
57# endif
58#endif // !QT_CONFIG(getentropy)
59
60#ifdef Q_OS_UNIX
61# include <fcntl.h>
62# include <private/qcore_unix_p.h>
63#else
64# include <qt_windows.h>
65
66// RtlGenRandom is not exported by its name in advapi32.dll, but as SystemFunction036
67// See https://msdn.microsoft.com/en-us/library/windows/desktop/aa387694(v=vs.85).aspx
68// Implementation inspired on https://hg.mozilla.org/mozilla-central/file/722fdbff1efc/security/nss/lib/freebl/win_rand.c#l146
69// Argument why this is safe to use: https://bugzilla.mozilla.org/show_bug.cgi?id=504270
70extern "C" {
71DECLSPEC_IMPORT BOOLEAN WINAPI SystemFunction036(PVOID RandomBuffer, ULONG RandomBufferLength);
72}
73#endif
74
75#if defined(Q_OS_ANDROID) && !defined(Q_OS_ANDROID_EMBEDDED)
76# include <private/qjni_p.h>
77#endif
78
79// This file is too low-level for regular Q_ASSERT (the logging framework may
80// recurse back), so use regular assert()
81#undef NDEBUG
82#undef Q_ASSERT_X
83#undef Q_ASSERT
84#define Q_ASSERT(cond) assert(cond)
85#define Q_ASSERT_X(cond, x, msg) assert(cond && msg)
86#if defined(QT_NO_DEBUG) && !defined(QT_FORCE_ASSERTS)
87# define NDEBUG 1
88#endif
89#include <assert.h>
90
91QT_BEGIN_NAMESPACE
92
93enum {
94 // may be "overridden" by a member enum
95 FillBufferNoexcept = true
96};
97
98struct QRandomGenerator::SystemGenerator
99{
100#if QT_CONFIG(getentropy)
101 static qsizetype fillBuffer(void *buffer, qsizetype count) noexcept
102 {
103 // getentropy can read at most 256 bytes, so break the reading
104 qsizetype read = 0;
105 while (count - read > 256) {
106 // getentropy can't fail under normal circumstances
107 int ret = getentropy(buffer: reinterpret_cast<uchar *>(buffer) + read, length: 256);
108 Q_ASSERT(ret == 0);
109 Q_UNUSED(ret);
110 read += 256;
111 }
112
113 int ret = getentropy(buffer: reinterpret_cast<uchar *>(buffer) + read, length: count - read);
114 Q_ASSERT(ret == 0);
115 Q_UNUSED(ret);
116 return count;
117 }
118
119#elif defined(Q_OS_UNIX)
120 enum { FillBufferNoexcept = false };
121
122 QBasicAtomicInt fdp1; // "file descriptor plus 1"
123 int openDevice()
124 {
125 int fd = fdp1.loadAcquire() - 1;
126 if (fd != -1)
127 return fd;
128
129 fd = qt_safe_open("/dev/urandom", O_RDONLY);
130 if (fd == -1)
131 fd = qt_safe_open("/dev/random", O_RDONLY | O_NONBLOCK);
132 if (fd == -1) {
133 // failed on both, set to -2 so we won't try again
134 fd = -2;
135 }
136
137 int opened_fdp1;
138 if (fdp1.testAndSetOrdered(0, fd + 1, opened_fdp1))
139 return fd;
140
141 // failed, another thread has opened the file descriptor
142 if (fd >= 0)
143 qt_safe_close(fd);
144 return opened_fdp1 - 1;
145 }
146
147#ifdef Q_CC_GNU
148 // If it's not GCC or GCC-like, then we'll leak the file descriptor
149 __attribute__((destructor))
150#endif
151 static void closeDevice()
152 {
153 int fd = self().fdp1.loadRelaxed() - 1;
154 if (fd >= 0)
155 qt_safe_close(fd);
156 }
157
158 Q_DECL_CONSTEXPR SystemGenerator() : fdp1 Q_BASIC_ATOMIC_INITIALIZER(0) {}
159
160 qsizetype fillBuffer(void *buffer, qsizetype count)
161 {
162 int fd = openDevice();
163 if (Q_UNLIKELY(fd < 0))
164 return 0;
165
166 qint64 n = qt_safe_read(fd, buffer, count);
167 return qMax<qsizetype>(n, 0); // ignore any errors
168 }
169
170#elif defined(Q_OS_WIN) && !defined(Q_OS_WINRT)
171 qsizetype fillBuffer(void *buffer, qsizetype count) noexcept
172 {
173 auto RtlGenRandom = SystemFunction036;
174 return RtlGenRandom(buffer, ULONG(count)) ? count: 0;
175 }
176#elif defined(Q_OS_WINRT)
177 qsizetype fillBuffer(void *, qsizetype) noexcept
178 {
179 // always use the fallback
180 return 0;
181 }
182#endif // Q_OS_WINRT
183
184 static SystemGenerator &self();
185 typedef quint32 result_type;
186 void generate(quint32 *begin, quint32 *end) noexcept(FillBufferNoexcept);
187
188 // For std::mersenne_twister_engine implementations that use something
189 // other than quint32 (unsigned int) to fill their buffers.
190 template <typename T> void generate(T *begin, T *end)
191 {
192 Q_STATIC_ASSERT(sizeof(T) >= sizeof(quint32));
193 if (sizeof(T) == sizeof(quint32)) {
194 // Microsoft Visual Studio uses unsigned long, but that's still 32-bit
195 generate(begin: reinterpret_cast<quint32 *>(begin), end: reinterpret_cast<quint32 *>(end));
196 } else {
197 // Slow path. Fix your C++ library.
198 std::generate(begin, end, [this]() {
199 quint32 datum;
200 generate(begin: &datum, end: &datum + 1);
201 return datum;
202 });
203 }
204 }
205};
206
207#if defined(Q_OS_WIN)
208static void fallback_update_seed(unsigned) {}
209static void fallback_fill(quint32 *ptr, qsizetype left) noexcept
210{
211 // on Windows, rand_s is a high-quality random number generator
212 // and it requires no seeding
213 std::generate(ptr, ptr + left, []() {
214 unsigned value;
215 rand_s(&value);
216 return value;
217 });
218}
219#elif QT_CONFIG(getentropy)
220static void fallback_update_seed(unsigned) {}
221static void fallback_fill(quint32 *, qsizetype) noexcept
222{
223 // no fallback necessary, getentropy cannot fail under normal circumstances
224 Q_UNREACHABLE();
225}
226#elif defined(Q_OS_BSD4) && !defined(__GLIBC__)
227static void fallback_update_seed(unsigned) {}
228static void fallback_fill(quint32 *ptr, qsizetype left) noexcept
229{
230 // BSDs have arc4random(4) and these work even in chroot(2)
231 arc4random_buf(ptr, left * sizeof(*ptr));
232}
233#else
234static QBasicAtomicInteger<unsigned> seed = Q_BASIC_ATOMIC_INITIALIZER(0U);
235static void fallback_update_seed(unsigned value)
236{
237 // Update the seed to be used for the fallback mechansim, if we need to.
238 // We can't use QtPrivate::QHashCombine here because that is not an atomic
239 // operation. A simple XOR will have to do then.
240 seed.fetchAndXorRelaxed(value);
241}
242
243Q_NEVER_INLINE
244#ifdef Q_CC_GNU
245__attribute__((cold)) // this function is pretty big, so optimize for size
246#endif
247static void fallback_fill(quint32 *ptr, qsizetype left) noexcept
248{
249 quint32 scratch[12]; // see element count below
250 quint32 *end = scratch;
251
252 auto foldPointer = [](quintptr v) {
253 if (sizeof(quintptr) == sizeof(quint32)) {
254 // For 32-bit systems, we simply return the pointer.
255 return quint32(v);
256 } else {
257 // For 64-bit systems, we try to return the variable part of the
258 // pointer. On current x86-64 and AArch64, the top 17 bits are
259 // architecturally required to be the same, but in reality the top
260 // 24 bits on Linux are likely to be the same for all processes.
261 return quint32(v >> (32 - 24));
262 }
263 };
264
265 Q_ASSERT(left);
266
267 *end++ = foldPointer(quintptr(&seed)); // 1: variable in this library/executable's .data
268 *end++ = foldPointer(quintptr(&scratch)); // 2: variable in the stack
269 *end++ = foldPointer(quintptr(&errno)); // 3: veriable either in libc or thread-specific
270 *end++ = foldPointer(quintptr(reinterpret_cast<void*>(strerror))); // 4: function in libc (and unlikely to be a macro)
271
272#ifndef QT_BOOTSTRAPPED
273 quint64 nsecs = QDeadlineTimer::current(Qt::PreciseTimer).deadline();
274 *end++ = quint32(nsecs); // 5
275#endif
276
277 if (quint32 v = seed.loadRelaxed())
278 *end++ = v; // 6
279
280#if QT_CONFIG(getauxval)
281 // works on Linux -- all modern libc have getauxval
282# ifdef AT_RANDOM
283 // ELF's auxv AT_RANDOM has 16 random bytes
284 // (other ELF-based systems don't seem to have AT_RANDOM)
285 ulong auxvSeed = getauxval(AT_RANDOM);
286 if (auxvSeed) {
287 memcpy(end, reinterpret_cast<void *>(auxvSeed), 16);
288 end += 4; // 7 to 10
289 }
290# endif
291
292 // Both AT_BASE and AT_SYSINFO_EHDR have some randomness in them due to the
293 // system's ASLR, even if many bits are the same. They also have randomness
294 // between them.
295# ifdef AT_BASE
296 // present at least on the BSDs too, indicates the address of the loader
297 ulong base = getauxval(AT_BASE);
298 if (base)
299 *end++ = foldPointer(base); // 11
300# endif
301# ifdef AT_SYSINFO_EHDR
302 // seems to be Linux-only, indicates the global page of the sysinfo
303 ulong sysinfo_ehdr = getauxval(AT_SYSINFO_EHDR);
304 if (sysinfo_ehdr)
305 *end++ = foldPointer(sysinfo_ehdr); // 12
306# endif
307#endif
308
309 Q_ASSERT(end <= std::end(scratch));
310
311 // this is highly inefficient, we should save the generator across calls...
312 std::seed_seq sseq(scratch, end);
313 std::mt19937 generator(sseq);
314 std::generate(ptr, ptr + left, generator);
315
316 fallback_update_seed(*ptr);
317}
318#endif
319
320Q_NEVER_INLINE void QRandomGenerator::SystemGenerator::generate(quint32 *begin, quint32 *end)
321 noexcept(FillBufferNoexcept)
322{
323 quint32 *buffer = begin;
324 qsizetype count = end - begin;
325
326 if (Q_UNLIKELY(uint(qt_randomdevice_control.loadAcquire()) & SetRandomData)) {
327 uint value = uint(qt_randomdevice_control.loadAcquire()) & RandomDataMask;
328 std::fill_n(first: buffer, n: count, value: value);
329 return;
330 }
331
332 qsizetype filled = 0;
333 if (qHasHwrng() && (uint(qt_randomdevice_control.loadAcquire()) & SkipHWRNG) == 0)
334 filled += qRandomCpu(buffer, count);
335
336 if (filled != count && (uint(qt_randomdevice_control.loadAcquire()) & SkipSystemRNG) == 0) {
337 qsizetype bytesFilled =
338 fillBuffer(buffer: buffer + filled, count: (count - filled) * qsizetype(sizeof(*buffer)));
339 filled += bytesFilled / qsizetype(sizeof(*buffer));
340 }
341 if (filled)
342 fallback_update_seed(*buffer);
343
344 if (Q_UNLIKELY(filled != count)) {
345 // failed to fill the entire buffer, try the faillback mechanism
346 fallback_fill(buffer + filled, count - filled);
347 }
348}
349
350struct QRandomGenerator::SystemAndGlobalGenerators
351{
352 // Construction notes:
353 // 1) The global PRNG state is in a different cacheline compared to the
354 // mutex that protects it. This avoids any false cacheline sharing of
355 // the state in case another thread tries to lock the mutex. It's not
356 // a common scenario, but since sizeof(QRandomGenerator) >= 2560, the
357 // overhead is actually acceptable.
358 // 2) We use both Q_DECL_ALIGN and std::aligned_storage<..., 64> because
359 // some implementations of std::aligned_storage can't align to more
360 // than a primitive type's alignment.
361 // 3) We don't store the entire system QRandomGenerator, only the space
362 // used by the QRandomGenerator::type member. This is fine because we
363 // (ab)use the common initial sequence exclusion to aliasing rules.
364 QBasicMutex globalPRNGMutex;
365 struct ShortenedSystem { uint type; } system_;
366 SystemGenerator sys;
367 Q_DECL_ALIGN(64) std::aligned_storage<sizeof(QRandomGenerator64), 64>::type global_;
368
369#ifdef Q_COMPILER_CONSTEXPR
370 constexpr SystemAndGlobalGenerators()
371 : globalPRNGMutex{}, system_{.type: 0}, sys{}, global_{}
372 {}
373#endif
374
375 void confirmLiteral()
376 {
377#if defined(Q_COMPILER_CONSTEXPR) && !defined(Q_CC_MSVC) && !defined(Q_OS_INTEGRITY)
378 // Currently fails to compile with MSVC 2017, saying QBasicMutex is not
379 // a literal type. Disassembly with MSVC 2013 and 2015 shows it is
380 // actually a literal; MSVC 2017 has a bug relating to this, so we're
381 // withhold judgement for now. Integrity's compiler is unable to
382 // guarantee g's alignment for some reason.
383
384 constexpr SystemAndGlobalGenerators g = {};
385 Q_UNUSED(g);
386 Q_STATIC_ASSERT(std::is_literal_type<SystemAndGlobalGenerators>::value);
387#endif
388 }
389
390 static SystemAndGlobalGenerators *self()
391 {
392 static SystemAndGlobalGenerators g;
393 Q_STATIC_ASSERT(sizeof(g) > sizeof(QRandomGenerator64));
394 return &g;
395 }
396
397 static QRandomGenerator64 *system()
398 {
399 // Though we never call the constructor, the system QRandomGenerator is
400 // properly initialized by the zero initialization performed in self().
401 // Though QRandomGenerator is has non-vacuous initialization, we
402 // consider it initialized because of the common initial sequence.
403 return reinterpret_cast<QRandomGenerator64 *>(&self()->system_);
404 }
405
406 static QRandomGenerator64 *globalNoInit()
407 {
408 // This function returns the pointer to the global QRandomGenerator,
409 // but does not initialize it. Only call it directly if you meant to do
410 // a pointer comparison.
411 return reinterpret_cast<QRandomGenerator64 *>(&self()->global_);
412 }
413
414 static void securelySeed(QRandomGenerator *rng)
415 {
416 // force reconstruction, just to be pedantic
417 new (rng) QRandomGenerator{System{}};
418
419 rng->type = MersenneTwister;
420 new (&rng->storage.engine()) RandomEngine(self()->sys);
421 }
422
423 struct PRNGLocker {
424 const bool locked;
425 PRNGLocker(const QRandomGenerator *that)
426 : locked(that == globalNoInit())
427 {
428 if (locked)
429 self()->globalPRNGMutex.lock();
430 }
431 ~PRNGLocker()
432 {
433 if (locked)
434 self()->globalPRNGMutex.unlock();
435 }
436 };
437};
438
439inline QRandomGenerator::SystemGenerator &QRandomGenerator::SystemGenerator::self()
440{
441 return SystemAndGlobalGenerators::self()->sys;
442}
443
444/*!
445 \class QRandomGenerator
446 \inmodule QtCore
447 \reentrant
448 \since 5.10
449
450 \brief The QRandomGenerator class allows one to obtain random values from a
451 high-quality Random Number Generator.
452
453 QRandomGenerator may be used to generate random values from a high-quality
454 random number generator. Like the C++ random engines, QRandomGenerator can
455 be seeded with user-provided values through the constructor.
456 When seeded, the sequence of numbers generated by this
457 class is deterministic. That is to say, given the same seed data,
458 QRandomGenerator will generate the same sequence of numbers. But given
459 different seeds, the results should be considerably different.
460
461 QRandomGenerator::securelySeeded() can be used to create a QRandomGenerator
462 that is securely seeded with QRandomGenerator::system(), meaning that the
463 sequence of numbers it generates cannot be easily predicted. Additionally,
464 QRandomGenerator::global() returns a global instance of QRandomGenerator
465 that Qt will ensure to be securely seeded. This object is thread-safe, may
466 be shared for most uses, and is always seeded from
467 QRandomGenerator::system()
468
469 QRandomGenerator::system() may be used to access the system's
470 cryptographically-safe random generator. On Unix systems, it's equivalent
471 to reading from \c {/dev/urandom} or the \c {getrandom()} or \c
472 {getentropy()} system calls.
473
474 The class can generate 32-bit or 64-bit quantities, or fill an array of
475 those. The most common way of generating new values is to call the generate(),
476 generate64() or fillRange() functions. One would use it as:
477
478 \snippet code/src_corelib_global_qrandom.cpp 0
479
480 Additionally, it provides a floating-point function generateDouble() that
481 returns a number in the range [0, 1) (that is, inclusive of zero and
482 exclusive of 1). There's also a set of convenience functions that
483 facilitate obtaining a random number in a bounded, integral range.
484
485 \section1 Seeding and determinism
486
487 QRandomGenerator may be seeded with specific seed data. When that is done,
488 the numbers generated by the object will always be the same, as in the
489 following example:
490
491 \snippet code/src_corelib_global_qrandom.cpp 1
492
493 The seed data takes the form of one or more 32-bit words. The ideal seed
494 size is approximately equal to the size of the QRandomGenerator class
495 itself. Due to mixing of the seed data, QRandomGenerator cannot guarantee
496 that distinct seeds will produce different sequences.
497
498 QRandomGenerator::global(), like all generators created by
499 QRandomGenerator::securelySeeded(), is always seeded from
500 QRandomGenerator::system(), so it's not possible to make it produce
501 identical sequences.
502
503 \section1 Bulk data
504
505 When operating in deterministic mode, QRandomGenerator may be used for bulk
506 data generation. In fact, applications that do not need
507 cryptographically-secure or true random data are advised to use a regular
508 QRandomGenerator instead of QRandomGenerator::system() for their random
509 data needs.
510
511 For ease of use, QRandomGenerator provides a global object that can
512 be easily used, as in the following example:
513
514 \snippet code/src_corelib_global_qrandom.cpp 2
515
516 \section1 System-wide random number generator
517
518 QRandomGenerator::system() may be used to access the system-wide random
519 number generator, which is cryptographically-safe on all systems that Qt
520 runs on. This function will use hardware facilities to generate random
521 numbers where available. On such systems, those facilities are true Random
522 Number Generators. However, if they are true RNGs, those facilities have
523 finite entropy sources and thus may fail to produce any results if their
524 entropy pool is exhausted.
525
526 If that happens, first the operating system then QRandomGenerator will fall
527 back to Pseudo Random Number Generators of decreasing qualities (Qt's
528 fallback generator being the simplest). Whether those generators are still
529 of cryptographic quality is implementation-defined. Therefore,
530 QRandomGenerator::system() should not be used for high-frequency random
531 number generation, lest the entropy pool become empty. As a rule of thumb,
532 this class should not be called upon to generate more than a kilobyte per
533 second of random data (note: this may vary from system to system).
534
535 If an application needs true RNG data in bulk, it should use the operating
536 system facilities (such as \c{/dev/random} on Linux) directly and wait for
537 entropy to become available. If the application requires PRNG engines of
538 cryptographic quality but not of true randomness,
539 QRandomGenerator::system() may still be used (see section below).
540
541 If neither a true RNG nor a cryptographically secure PRNG are required,
542 applications should instead use PRNG engines like QRandomGenerator's
543 deterministic mode and those from the C++ Standard Library.
544 QRandomGenerator::system() can be used to seed those.
545
546 \section2 Fallback quality
547
548 QRandomGenerator::system() uses the operating system facilities to obtain
549 random numbers, which attempt to collect real entropy from the surrounding
550 environment to produce true random numbers. However, it's possible that the
551 entropy pool becomes exhausted, in which case the operating system will
552 fall back to a pseudo-random engine for a time. Under no circumstances will
553 QRandomGenerator::system() block, waiting for more entropy to be collected.
554
555 The following operating systems guarantee that the results from their
556 random-generation API will be of at least cryptographically-safe quality,
557 even if the entropy pool is exhausted: Apple OSes (Darwin), BSDs, Linux,
558 Windows. Barring a system installation problem (such as \c{/dev/urandom}
559 not being readable by the current process), QRandomGenerator::system() will
560 therefore have the same guarantees.
561
562 On other operating systems, QRandomGenerator will fall back to a PRNG of
563 good numeric distribution, but it cannot guarantee proper seeding in all
564 cases. Please consult the OS documentation for more information.
565
566 Applications that require QRandomGenerator not to fall back to
567 non-cryptographic quality generators are advised to check their operating
568 system documentation or restrict their deployment to one of the above.
569
570 \section1 Reentrancy and thread-safety
571
572 QRandomGenerator is reentrant, meaning that multiple threads can operate on
573 this class at the same time, so long as they operate on different objects.
574 If multiple threads need to share one PRNG sequence, external locking by a
575 mutex is required.
576
577 The exceptions are the objects returned by QRandomGenerator::global() and
578 QRandomGenerator::system(): those objects are thread-safe and may be used
579 by any thread without external locking. Note that thread-safety does not
580 extend to copying those objects: they should always be used by reference.
581
582 \section1 Standard C++ Library compatibility
583
584 QRandomGenerator is modeled after the requirements for random number
585 engines in the C++ Standard Library and may be used in almost all contexts
586 that the Standard Library engines can. Exceptions to the requirements are
587 the following:
588
589 \list
590 \li QRandomGenerator does not support seeding from another seed
591 sequence-like class besides std::seed_seq itself;
592 \li QRandomGenerator is not comparable (but is copyable) or
593 streamable to \c{std::ostream} or from \c{std::istream}.
594 \endlist
595
596 QRandomGenerator is also compatible with the uniform distribution classes
597 \c{std::uniform_int_distribution} and \c{std:uniform_real_distribution}, as
598 well as the free function \c{std::generate_canonical}. For example, the
599 following code may be used to generate a floating-point number in the range
600 [1, 2.5):
601
602 \snippet code/src_corelib_global_qrandom.cpp 3
603
604 \sa QRandomGenerator64, qrand()
605 */
606
607/*!
608 \enum QRandomGenerator::System
609 \internal
610*/
611
612/*!
613 \fn QRandomGenerator::QRandomGenerator(quint32 seedValue)
614
615 Initializes this QRandomGenerator object with the value \a seedValue as
616 the seed. Two objects constructed or reseeded with the same seed value will
617 produce the same number sequence.
618
619 \sa seed(), securelySeeded()
620 */
621
622/*!
623 \fn template <qsizetype N> QRandomGenerator::QRandomGenerator(const quint32 (&seedBuffer)[N])
624 \overload
625
626 Initializes this QRandomGenerator object with the values found in the
627 array \a seedBuffer as the seed. Two objects constructed or reseeded with
628 the same seed value will produce the same number sequence.
629
630 \sa seed(), securelySeeded()
631 */
632
633/*!
634 \fn QRandomGenerator::QRandomGenerator(const quint32 *seedBuffer, qsizetype len)
635 \overload
636
637 Initializes this QRandomGenerator object with \a len values found in
638 the array \a seedBuffer as the seed. Two objects constructed or reseeded
639 with the same seed value will produce the same number sequence.
640
641 This constructor is equivalent to:
642 \snippet code/src_corelib_global_qrandom.cpp 4
643
644 \sa seed(), securelySeeded()
645 */
646
647/*!
648 \fn QRandomGenerator::QRandomGenerator(const quint32 *begin, const quint32 *end)
649 \overload
650
651 Initializes this QRandomGenerator object with the values found in the range
652 from \a begin to \a end as the seed. Two objects constructed or reseeded
653 with the same seed value will produce the same number sequence.
654
655 This constructor is equivalent to:
656 \snippet code/src_corelib_global_qrandom.cpp 5
657
658 \sa seed(), securelySeeded()
659 */
660
661/*!
662 \fn QRandomGenerator::QRandomGenerator(std::seed_seq &sseq)
663 \overload
664
665 Initializes this QRandomGenerator object with the seed sequence \a
666 sseq as the seed. Two objects constructed or reseeded with the same seed
667 value will produce the same number sequence.
668
669 \sa seed(), securelySeeded()
670 */
671
672/*!
673 \fn QRandomGenerator::QRandomGenerator(const QRandomGenerator &other)
674
675 Creates a copy of the generator state in the \a other object. If \a other is
676 QRandomGenerator::system() or a copy of that, this object will also read
677 from the operating system random-generating facilities. In that case, the
678 sequences generated by the two objects will be different.
679
680 In all other cases, the new QRandomGenerator object will start at the same
681 position in the deterministic sequence as the \a other object was. Both
682 objects will generate the same sequence from this point on.
683
684 For that reason, it is not adviseable to create a copy of
685 QRandomGenerator::global(). If one needs an exclusive deterministic
686 generator, consider instead using securelySeeded() to obtain a new object
687 that shares no relationship with the QRandomGenerator::global().
688 */
689
690/*!
691 \fn bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
692 \relates QRandomGenerator
693
694 Returns true if the two the two engines \a rng1 and \a rng2 are at the same
695 state or if they are both reading from the operating system facilities,
696 false otherwise.
697*/
698
699/*!
700 \fn bool operator!=(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
701 \relates QRandomGenerator
702
703 Returns true if the two the two engines \a rng1 and \a rng2 are at
704 different states or if one of them is reading from the operating system
705 facilities and the other is not, false otherwise.
706*/
707
708/*!
709 \typedef QRandomGenerator::result_type
710
711 A typedef to the type that operator() returns. That is, quint32.
712
713 \sa operator()
714 */
715
716/*!
717 \fn result_type QRandomGenerator::operator()()
718
719 Generates a 32-bit random quantity and returns it.
720
721 \sa generate(), generate64()
722 */
723
724/*!
725 \fn quint32 QRandomGenerator::generate()
726
727 Generates a 32-bit random quantity and returns it.
728
729 \sa {QRandomGenerator::operator()}{operator()()}, generate64()
730 */
731
732/*!
733 \fn quint64 QRandomGenerator::generate64()
734
735 Generates a 64-bit random quantity and returns it.
736
737 \sa {QRandomGenerator::operator()}{operator()()}, generate()
738 */
739
740/*!
741 \fn result_type QRandomGenerator::min()
742
743 Returns the minimum value that QRandomGenerator may ever generate. That is, 0.
744
745 \sa max(), QRandomGenerator64::min()
746 */
747
748/*!
749 \fn result_type QRandomGenerator::max()
750
751 Returns the maximum value that QRandomGenerator may ever generate. That is,
752 \c {std::numeric_limits<result_type>::max()}.
753
754 \sa min(), QRandomGenerator64::max()
755 */
756
757/*!
758 \fn void QRandomGenerator::seed(quint32 seed)
759
760 Reseeds this object using the value \a seed as the seed.
761 */
762
763/*!
764 \fn void QRandomGenerator::seed(std::seed_seq &seed)
765 \overload
766
767 Reseeds this object using the seed sequence \a seed as the seed.
768 */
769
770/*!
771 \fn void QRandomGenerator::discard(unsigned long long z)
772
773 Discards the next \a z entries from the sequence. This method is equivalent
774 to calling generate() \a z times and discarding the result, as in:
775
776 \snippet code/src_corelib_global_qrandom.cpp 6
777*/
778
779/*!
780 \fn template <typename ForwardIterator> void QRandomGenerator::generate(ForwardIterator begin, ForwardIterator end)
781
782 Generates 32-bit quantities and stores them in the range between \a begin
783 and \a end. This function is equivalent to (and is implemented as):
784
785 \snippet code/src_corelib_global_qrandom.cpp 7
786
787 This function complies with the requirements for the function
788 \l{http://en.cppreference.com/w/cpp/numeric/random/seed_seq/generate}{\c std::seed_seq::generate},
789 which requires unsigned 32-bit integer values.
790
791 Note that if the [begin, end) range refers to an area that can store more
792 than 32 bits per element, the elements will still be initialized with only
793 32 bits of data. Any other bits will be zero. To fill the range with 64 bit
794 quantities, one can write:
795
796 \snippet code/src_corelib_global_qrandom.cpp 8
797
798 If the range refers to contiguous memory (such as an array or the data from
799 a QVector), the fillRange() function may be used too.
800
801 \sa fillRange()
802 */
803
804/*!
805 \fn void QRandomGenerator::generate(quint32 *begin, quint32 *end)
806 \overload
807 \internal
808
809 Same as the other overload, but more efficiently fills \a begin to \a end.
810 */
811
812/*!
813 \fn template <typename UInt> void QRandomGenerator::fillRange(UInt *buffer, qsizetype count)
814
815 Generates \a count 32- or 64-bit quantities (depending on the type \c UInt)
816 and stores them in the buffer pointed by \a buffer. This is the most
817 efficient way to obtain more than one quantity at a time, as it reduces the
818 number of calls into the Random Number Generator source.
819
820 For example, to fill a vector of 16 entries with random values, one may
821 write:
822
823 \snippet code/src_corelib_global_qrandom.cpp 9
824
825 \sa generate()
826 */
827
828/*!
829 \fn template <typename UInt, size_t N> void QRandomGenerator::fillRange(UInt (&buffer)[N])
830
831 Generates \c N 32- or 64-bit quantities (depending on the type \c UInt) and
832 stores them in the \a buffer array. This is the most efficient way to
833 obtain more than one quantity at a time, as it reduces the number of calls
834 into the Random Number Generator source.
835
836 For example, to fill generate two 32-bit quantities, one may write:
837
838 \snippet code/src_corelib_global_qrandom.cpp 10
839
840 It would have also been possible to make one call to generate64() and then split
841 the two halves of the 64-bit value.
842
843 \sa generate()
844 */
845
846/*!
847 \fn qreal QRandomGenerator::generateDouble()
848
849 Generates one random qreal in the canonical range [0, 1) (that is,
850 inclusive of zero and exclusive of 1).
851
852 This function is equivalent to:
853 \snippet code/src_corelib_global_qrandom.cpp 11
854
855 The same may also be obtained by using
856 \l{http://en.cppreference.com/w/cpp/numeric/random/uniform_real_distribution}{\c std::uniform_real_distribution}
857 with parameters 0 and 1.
858
859 \sa generate(), generate64(), bounded()
860 */
861
862/*!
863 \fn double QRandomGenerator::bounded(double highest)
864
865 Generates one random double in the range between 0 (inclusive) and \a
866 highest (exclusive). This function is equivalent to and is implemented as:
867
868 \snippet code/src_corelib_global_qrandom.cpp 12
869
870 If the \a highest parameter is negative, the result will be negative too;
871 if it is infinite or NaN, the result will be infinite or NaN too (that is,
872 not random).
873
874 \sa generateDouble(), bounded()
875 */
876
877/*!
878 \fn quint32 QRandomGenerator::bounded(quint32 highest)
879 \overload
880
881 Generates one random 32-bit quantity in the range between 0 (inclusive) and
882 \a highest (exclusive). The same result may also be obtained by using
883 \l{http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution}{\c std::uniform_int_distribution}
884 with parameters 0 and \c{highest - 1}. That class can also be used to obtain
885 quantities larger than 32 bits.
886
887 For example, to obtain a value between 0 and 255 (inclusive), one would write:
888
889 \snippet code/src_corelib_global_qrandom.cpp 13
890
891 Naturally, the same could also be obtained by masking the result of generate()
892 to only the lower 8 bits. Either solution is as efficient.
893
894 Note that this function cannot be used to obtain values in the full 32-bit
895 range of quint32. Instead, use generate().
896
897 \sa generate(), generate64(), generateDouble()
898 */
899
900/*!
901 \fn int QRandomGenerator::bounded(int highest)
902 \overload
903
904 Generates one random 32-bit quantity in the range between 0 (inclusive) and
905 \a highest (exclusive). \a highest must be positive.
906
907 Note that this function cannot be used to obtain values in the full 32-bit
908 range of int. Instead, use generate() and cast to int.
909
910 \sa generate(), generate64(), generateDouble()
911 */
912
913/*!
914 \fn quint32 QRandomGenerator::bounded(quint32 lowest, quint32 highest)
915 \overload
916
917 Generates one random 32-bit quantity in the range between \a lowest
918 (inclusive) and \a highest (exclusive). The \a highest parameter must be
919 greater than \a lowest.
920
921 The same result may also be obtained by using
922 \l{http://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution}{\c std::uniform_int_distribution}
923 with parameters \a lowest and \c{\a highest - 1}. That class can also be used to
924 obtain quantities larger than 32 bits.
925
926 For example, to obtain a value between 1000 (incl.) and 2000 (excl.), one
927 would write:
928
929 \snippet code/src_corelib_global_qrandom.cpp 14
930
931 Note that this function cannot be used to obtain values in the full 32-bit
932 range of quint32. Instead, use generate().
933
934 \sa generate(), generate64(), generateDouble()
935 */
936
937/*!
938 \fn int QRandomGenerator::bounded(int lowest, int highest)
939 \overload
940
941 Generates one random 32-bit quantity in the range between \a lowest
942 (inclusive) and \a highest (exclusive), both of which may be negative, but
943 \a highest must be greater than \a lowest.
944
945 Note that this function cannot be used to obtain values in the full 32-bit
946 range of int. Instead, use generate() and cast to int.
947
948 \sa generate(), generate64(), generateDouble()
949 */
950
951/*!
952 \fn QRandomGenerator *QRandomGenerator::system()
953 \threadsafe
954
955 Returns a pointer to a shared QRandomGenerator that always uses the
956 facilities provided by the operating system to generate random numbers. The
957 system facilities are considered to be cryptographically safe on at least
958 the following operating systems: Apple OSes (Darwin), BSDs, Linux, Windows.
959 That may also be the case on other operating systems.
960
961 They are also possibly backed by a true hardware random number generator.
962 For that reason, the QRandomGenerator returned by this function should not
963 be used for bulk data generation. Instead, use it to seed QRandomGenerator
964 or a random engine from the <random> header.
965
966 The object returned by this function is thread-safe and may be used in any
967 thread without locks. It may also be copied and the resulting
968 QRandomGenerator will also access the operating system facilities, but they
969 will not generate the same sequence.
970
971 \sa securelySeeded(), global()
972*/
973
974/*!
975 \fn QRandomGenerator *QRandomGenerator::global()
976 \threadsafe
977
978 Returns a pointer to a shared QRandomGenerator that was seeded using
979 securelySeeded(). This function should be used to create random data
980 without the expensive creation of a securely-seeded QRandomGenerator
981 for a specific use or storing the rather large QRandomGenerator object.
982
983 For example, the following creates a random RGB color:
984
985 \snippet code/src_corelib_global_qrandom.cpp 15
986
987 Accesses to this object are thread-safe and it may therefore be used in any
988 thread without locks. The object may also be copied and the sequence
989 produced by the copy will be the same as the shared object will produce.
990 Note, however, that if there are other threads accessing the global object,
991 those threads may obtain samples at unpredictable intervals.
992
993 \sa securelySeeded(), system()
994*/
995
996/*!
997 \fn QRandomGenerator QRandomGenerator::securelySeeded()
998
999 Returns a new QRandomGenerator object that was securely seeded with
1000 QRandomGenerator::system(). This function will obtain the ideal seed size
1001 for the algorithm that QRandomGenerator uses and is therefore the
1002 recommended way for creating a new QRandomGenerator object that will be
1003 kept for some time.
1004
1005 Given the amount of data required to securely seed the deterministic
1006 engine, this function is somewhat expensive and should not be used for
1007 short-term uses of QRandomGenerator (using it to generate fewer than 2600
1008 bytes of random data is effectively a waste of resources). If the use
1009 doesn't require that much data, consider using QRandomGenerator::global()
1010 and not storing a QRandomGenerator object instead.
1011
1012 \sa global(), system()
1013 */
1014
1015/*!
1016 \class QRandomGenerator64
1017 \inmodule QtCore
1018 \since 5.10
1019
1020 \brief The QRandomGenerator64 class allows one to obtain 64-bit random values
1021 from a high-quality, seed-less Random Number Generator.
1022
1023 QRandomGenerator64 is a simple adaptor class around QRandomGenerator, making the
1024 QRandomGenerator::generate64() function the default for operator()(), instead of the
1025 function that returns 32-bit quantities. This class is intended to be used
1026 in conjunction with Standard Library algorithms that need 64-bit quantities
1027 instead of 32-bit ones.
1028
1029 In all other aspects, the class is the same. Please refer to
1030 QRandomGenerator's documentation for more information.
1031
1032 \sa QRandomGenerator
1033*/
1034
1035/*!
1036 \typedef QRandomGenerator64::result_type
1037
1038 A typedef to the type that operator() returns. That is, quint64.
1039
1040 \sa operator()
1041 */
1042
1043/*!
1044 \fn quint64 QRandomGenerator64::generate()
1045
1046 Generates one 64-bit random value and returns it.
1047
1048 Note about casting to a signed integer: all bits returned by this function
1049 are random, so there's a 50% chance that the most significant bit will be
1050 set. If you wish to cast the returned value to qint64 and keep it positive,
1051 you should mask the sign bit off:
1052
1053 \snippet code/src_corelib_global_qrandom.cpp 16
1054
1055 \sa QRandomGenerator, QRandomGenerator::generate64()
1056 */
1057
1058/*!
1059 \fn result_type QRandomGenerator64::operator()()
1060
1061 Generates a 64-bit random quantity and returns it.
1062
1063 \sa QRandomGenerator::generate(), QRandomGenerator::generate64()
1064 */
1065
1066Q_DECL_CONSTEXPR QRandomGenerator::Storage::Storage()
1067 : dummy(0)
1068{
1069 // nothing
1070}
1071
1072inline QRandomGenerator64::QRandomGenerator64(System s)
1073 : QRandomGenerator(s)
1074{
1075}
1076
1077QRandomGenerator64 *QRandomGenerator64::system()
1078{
1079 auto self = SystemAndGlobalGenerators::system();
1080 Q_ASSERT(self->type == SystemRNG);
1081 return self;
1082}
1083
1084QRandomGenerator64 *QRandomGenerator64::global()
1085{
1086 auto self = SystemAndGlobalGenerators::globalNoInit();
1087
1088 // Yes, this is a double-checked lock.
1089 // We can return even if the type is not completely initialized yet:
1090 // any thread trying to actually use the contents of the random engine
1091 // will necessarily wait on the lock.
1092 if (Q_LIKELY(self->type != SystemRNG))
1093 return self;
1094
1095 SystemAndGlobalGenerators::PRNGLocker locker(self);
1096 if (self->type == SystemRNG)
1097 SystemAndGlobalGenerators::securelySeed(rng: self);
1098
1099 return self;
1100}
1101
1102QRandomGenerator64 QRandomGenerator64::securelySeeded()
1103{
1104 QRandomGenerator64 result(System{});
1105 SystemAndGlobalGenerators::securelySeed(rng: &result);
1106 return result;
1107}
1108
1109/*!
1110 \internal
1111*/
1112inline QRandomGenerator::QRandomGenerator(System)
1113 : type(SystemRNG)
1114{
1115 // don't touch storage
1116}
1117
1118QRandomGenerator::QRandomGenerator(const QRandomGenerator &other)
1119 : type(other.type)
1120{
1121 Q_ASSERT(this != system());
1122 Q_ASSERT(this != SystemAndGlobalGenerators::globalNoInit());
1123
1124 if (type != SystemRNG) {
1125 SystemAndGlobalGenerators::PRNGLocker lock(&other);
1126 storage.engine() = other.storage.engine();
1127 }
1128}
1129
1130QRandomGenerator &QRandomGenerator::operator=(const QRandomGenerator &other)
1131{
1132 if (Q_UNLIKELY(this == system()) || Q_UNLIKELY(this == SystemAndGlobalGenerators::globalNoInit()))
1133 qFatal(msg: "Attempted to overwrite a QRandomGenerator to system() or global().");
1134
1135 if ((type = other.type) != SystemRNG) {
1136 SystemAndGlobalGenerators::PRNGLocker lock(&other);
1137 storage.engine() = other.storage.engine();
1138 }
1139 return *this;
1140}
1141
1142QRandomGenerator::QRandomGenerator(std::seed_seq &sseq) noexcept
1143 : type(MersenneTwister)
1144{
1145 Q_ASSERT(this != system());
1146 Q_ASSERT(this != SystemAndGlobalGenerators::globalNoInit());
1147
1148 new (&storage.engine()) RandomEngine(sseq);
1149}
1150
1151QRandomGenerator::QRandomGenerator(const quint32 *begin, const quint32 *end)
1152 : type(MersenneTwister)
1153{
1154 Q_ASSERT(this != system());
1155 Q_ASSERT(this != SystemAndGlobalGenerators::globalNoInit());
1156
1157 std::seed_seq s(begin, end);
1158 new (&storage.engine()) RandomEngine(s);
1159}
1160
1161void QRandomGenerator::discard(unsigned long long z)
1162{
1163 if (Q_UNLIKELY(type == SystemRNG))
1164 return;
1165
1166 SystemAndGlobalGenerators::PRNGLocker lock(this);
1167 storage.engine().discard(z: z);
1168}
1169
1170bool operator==(const QRandomGenerator &rng1, const QRandomGenerator &rng2)
1171{
1172 if (rng1.type != rng2.type)
1173 return false;
1174 if (rng1.type == SystemRNG)
1175 return true;
1176
1177 // Lock global() if either is it (otherwise this locking is a no-op)
1178 using PRNGLocker = QRandomGenerator::SystemAndGlobalGenerators::PRNGLocker;
1179 PRNGLocker locker(&rng1 == QRandomGenerator::global() ? &rng1 : &rng2);
1180 return rng1.storage.engine() == rng2.storage.engine();
1181}
1182
1183/*!
1184 \internal
1185
1186 Fills the range pointed by \a buffer and \a bufferEnd with 32-bit random
1187 values. The buffer must be correctly aligned.
1188 */
1189void QRandomGenerator::_fillRange(void *buffer, void *bufferEnd)
1190{
1191 // Verify that the pointers are properly aligned for 32-bit
1192 Q_ASSERT(quintptr(buffer) % sizeof(quint32) == 0);
1193 Q_ASSERT(quintptr(bufferEnd) % sizeof(quint32) == 0);
1194 quint32 *begin = static_cast<quint32 *>(buffer);
1195 quint32 *end = static_cast<quint32 *>(bufferEnd);
1196
1197 if (type == SystemRNG || Q_UNLIKELY(uint(qt_randomdevice_control.loadAcquire()) & (UseSystemRNG|SetRandomData)))
1198 return SystemGenerator::self().generate(begin, end);
1199
1200 SystemAndGlobalGenerators::PRNGLocker lock(this);
1201 std::generate(first: begin, last: end, gen: [this]() { return storage.engine()(); });
1202}
1203
1204namespace {
1205struct QRandEngine
1206{
1207 std::minstd_rand engine;
1208 QRandEngine() : engine(1) {}
1209
1210 int generate()
1211 {
1212 std::minstd_rand::result_type v = engine();
1213 if (std::numeric_limits<int>::max() != RAND_MAX)
1214 v %= uint(RAND_MAX) + 1;
1215
1216 return int(v);
1217 }
1218
1219 void seed(std::minstd_rand::result_type q)
1220 {
1221 engine.seed(s: q);
1222 }
1223};
1224}
1225
1226#if defined(Q_OS_WIN)
1227// On Windows srand() and rand() already use Thread-Local-Storage
1228// to store the seed between calls
1229static inline QRandEngine *randTLS()
1230{
1231 return nullptr;
1232}
1233#elif defined(Q_COMPILER_THREAD_LOCAL)
1234static inline QRandEngine *randTLS()
1235{
1236 thread_local QRandEngine r;
1237 return &r;
1238}
1239#else
1240Q_GLOBAL_STATIC(QThreadStorage<QRandEngine>, g_randTLS)
1241static inline QRandEngine *randTLS()
1242{
1243 auto tls = g_randTLS();
1244 if (!tls)
1245 return nullptr;
1246 return &tls->localData();
1247
1248}
1249#endif
1250
1251/*!
1252 \relates <QtGlobal>
1253 \deprecated
1254 \since 4.2
1255
1256 Thread-safe version of the standard C++ \c srand() function.
1257
1258 Sets the argument \a seed to be used to generate a new random number sequence of
1259 pseudo random integers to be returned by qrand().
1260
1261 The sequence of random numbers generated is deterministic per thread. For example,
1262 if two threads call qsrand(1) and subsequently call qrand(), the threads will get
1263 the same random number sequence.
1264
1265 \note This function is deprecated. In new applications, use
1266 QRandomGenerator instead.
1267
1268 \sa qrand(), QRandomGenerator
1269*/
1270void qsrand(uint seed)
1271{
1272 auto prng = randTLS();
1273 if (prng)
1274 prng->seed(q: seed);
1275 else
1276 srand(seed: seed);
1277}
1278
1279/*!
1280 \relates <QtGlobal>
1281 \deprecated
1282 \since 4.2
1283
1284 Thread-safe version of the standard C++ \c rand() function.
1285
1286 Returns a value between 0 and \c RAND_MAX (defined in \c <cstdlib> and
1287 \c <stdlib.h>), the next number in the current sequence of pseudo-random
1288 integers.
1289
1290 Use \c qsrand() to initialize the pseudo-random number generator with a
1291 seed value. Seeding must be performed at least once on each thread. If that
1292 step is skipped, then the sequence will be pre-seeded with a constant
1293 value.
1294
1295 \note This function is deprecated. In new applications, use
1296 QRandomGenerator instead.
1297
1298 \sa qsrand(), QRandomGenerator
1299*/
1300int qrand()
1301{
1302 auto prng = randTLS();
1303 if (prng)
1304 return prng->generate();
1305 else
1306 return rand();
1307}
1308
1309QT_END_NAMESPACE
1310

source code of qtbase/src/corelib/global/qrandom.cpp