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